/** * AgoraWebSDK_N-v4.22.1-0-g1c8e27e9 Copyright AgoraInc. */ import{isValidString as e,AgoraRTCErrorCode as t,isEmpty as s,checkValidNumber as n,checkValidBoolean as E,checkValidEnum as r,checkValidString as i,checkValidArray as o,IS_GLOBAL_VERSION as _,EventEmitter as c,PromiseMutex as R,NETWORK_STATE as a,networkIndicator as A,NETWORK_INDICATOR_EVENTS as I,createDefer as N,getParameter as S,AgoraRTCError as T,getRetryWaitTime as d,wait as h,emitAsPromise as O,emitAsInvokerNoResponse as L,noop as C,VERSION as l,getUTF8StringByteLength as u,getMultiUnilbsFormDataByteLength as g,retryable as D,DEFAULT_RETRY_CONFIG as w}from"@agora-js/shared";import{AgoraRTCError as U,logger as M,report as m,AgoraRTCErrorCode as V}from"@agora-js/report";import P from"axios";import"formdata-polyfill";function f(e,t,s){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var n=s.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function p(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,n)}return s}function v(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?p(Object(s),!0).forEach((function(t){f(e,t,s[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):p(Object(s)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))}))}return e}let b=function(e){return e[e.ACCESS_POINT=101]="ACCESS_POINT",e[e.UNILBS=201]="UNILBS",e[e.STRING_UID_ALLOCATOR=901]="STRING_UID_ALLOCATOR",e}({}),y=function(e){return e[e.IIIEGAL_APPID=1]="IIIEGAL_APPID",e[e.IIIEGAL_UID=2]="IIIEGAL_UID",e[e.INTERNAL_ERROR=3]="INTERNAL_ERROR",e}({}),k=function(e){return e[e.INVALID_VENDOR_KEY=5]="INVALID_VENDOR_KEY",e[e.INVALID_CHANNEL_NAME=7]="INVALID_CHANNEL_NAME",e[e.INTERNAL_ERROR=8]="INTERNAL_ERROR",e[e.NO_AUTHORIZED=9]="NO_AUTHORIZED",e[e.DYNAMIC_KEY_TIMEOUT=10]="DYNAMIC_KEY_TIMEOUT",e[e.NO_ACTIVE_STATUS=11]="NO_ACTIVE_STATUS",e[e.DYNAMIC_KEY_EXPIRED=13]="DYNAMIC_KEY_EXPIRED",e[e.STATIC_USE_DYNAMIC_KEY=14]="STATIC_USE_DYNAMIC_KEY",e[e.DYNAMIC_USE_STATIC_KEY=15]="DYNAMIC_USE_STATIC_KEY",e[e.USER_OVERLOAD=16]="USER_OVERLOAD",e[e.FORBIDDEN_REGION=18]="FORBIDDEN_REGION",e[e.CANNOT_MEET_AREA_DEMAND=19]="CANNOT_MEET_AREA_DEMAND",e}({}),B=function(e){return e[e.NO_FLAG_SET=100]="NO_FLAG_SET",e[e.FLAG_SET_BUT_EMPTY=101]="FLAG_SET_BUT_EMPTY",e[e.INVALID_FALG_SET=102]="INVALID_FALG_SET",e[e.FLAG_SET_BUT_NO_RE=103]="FLAG_SET_BUT_NO_RE",e[e.INVALID_SERVICE_ID=104]="INVALID_SERVICE_ID",e[e.NO_SERVICE_AVAILABLE=200]="NO_SERVICE_AVAILABLE",e[e.NO_SERVICE_AVAILABLE_P2P=201]="NO_SERVICE_AVAILABLE_P2P",e[e.NO_SERVICE_AVAILABLE_VOICE=202]="NO_SERVICE_AVAILABLE_VOICE",e[e.NO_SERVICE_AVAILABLE_WEBRTC=203]="NO_SERVICE_AVAILABLE_WEBRTC",e[e.NO_SERVICE_AVAILABLE_CDS=204]="NO_SERVICE_AVAILABLE_CDS",e[e.NO_SERVICE_AVAILABLE_CDN=205]="NO_SERVICE_AVAILABLE_CDN",e[e.NO_SERVICE_AVAILABLE_TDS=206]="NO_SERVICE_AVAILABLE_TDS",e[e.NO_SERVICE_AVAILABLE_REPORT=207]="NO_SERVICE_AVAILABLE_REPORT",e[e.NO_SERVICE_AVAILABLE_APP_CENTER=208]="NO_SERVICE_AVAILABLE_APP_CENTER",e[e.NO_SERVICE_AVAILABLE_ENV0=209]="NO_SERVICE_AVAILABLE_ENV0",e[e.NO_SERVICE_AVAILABLE_VOET=210]="NO_SERVICE_AVAILABLE_VOET",e[e.NO_SERVICE_AVAILABLE_STRING_UID=211]="NO_SERVICE_AVAILABLE_STRING_UID",e[e.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS=212]="NO_SERVICE_AVAILABLE_WEBRTC_UNILBS",e[e.NO_SERVICE_AVAILABLE_UNILBS_FLV=213]="NO_SERVICE_AVAILABLE_UNILBS_FLV",e}({}),W=function(e){return e[e.K_TIMESTAMP_EXPIRED=2]="K_TIMESTAMP_EXPIRED",e[e.K_CHANNEL_PERMISSION_INVALID=3]="K_CHANNEL_PERMISSION_INVALID",e[e.K_CERTIFICATE_INVALID=4]="K_CERTIFICATE_INVALID",e[e.K_CHANNEL_NAME_EMPTY=5]="K_CHANNEL_NAME_EMPTY",e[e.K_CHANNEL_NOT_FOUND=6]="K_CHANNEL_NOT_FOUND",e[e.K_TICKET_INVALID=7]="K_TICKET_INVALID",e[e.K_CHANNEL_CONFLICTED=8]="K_CHANNEL_CONFLICTED",e[e.K_SERVICE_NOT_READY=9]="K_SERVICE_NOT_READY",e[e.K_SERVICE_TOO_HEAVY=10]="K_SERVICE_TOO_HEAVY",e[e.K_UID_BANNED=14]="K_UID_BANNED",e[e.K_IP_BANNED=15]="K_IP_BANNED",e[e.K_CHANNEL_BANNED=16]="K_CHANNEL_BANNED",e[e.K_AUTO_REBALANCE=28]="K_AUTO_REBALANCE",e[e.WARN_NO_AVAILABLE_CHANNEL=103]="WARN_NO_AVAILABLE_CHANNEL",e[e.WARN_LOOKUP_CHANNEL_TIMEOUT=104]="WARN_LOOKUP_CHANNEL_TIMEOUT",e[e.WARN_LOOKUP_CHANNEL_REJECTED=105]="WARN_LOOKUP_CHANNEL_REJECTED",e[e.WARN_OPEN_CHANNEL_TIMEOUT=106]="WARN_OPEN_CHANNEL_TIMEOUT",e[e.WARN_OPEN_CHANNEL_REJECTED=107]="WARN_OPEN_CHANNEL_REJECTED",e[e.WARN_REQUEST_DEFERRED=108]="WARN_REQUEST_DEFERRED",e[e.ERR_DYNAMIC_KEY_TIMEOUT=109]="ERR_DYNAMIC_KEY_TIMEOUT",e[e.ERR_NO_AUTHORIZED=110]="ERR_NO_AUTHORIZED",e[e.ERR_VOM_SERVICE_UNAVAILABLE=111]="ERR_VOM_SERVICE_UNAVAILABLE",e[e.ERR_NO_CHANNEL_AVAILABLE_CODE=112]="ERR_NO_CHANNEL_AVAILABLE_CODE",e[e.ERR_MASTER_VOCS_UNAVAILABLE=114]="ERR_MASTER_VOCS_UNAVAILABLE",e[e.ERR_INTERNAL_ERROR=115]="ERR_INTERNAL_ERROR",e[e.ERR_NO_ACTIVE_STATUS=116]="ERR_NO_ACTIVE_STATUS",e[e.ERR_INVALID_UID=117]="ERR_INVALID_UID",e[e.ERR_DYNAMIC_KEY_EXPIRED=118]="ERR_DYNAMIC_KEY_EXPIRED",e[e.ERR_STATIC_USE_DYANMIC_KE=119]="ERR_STATIC_USE_DYANMIC_KE",e[e.ERR_DYNAMIC_USE_STATIC_KE=120]="ERR_DYNAMIC_USE_STATIC_KE",e[e.ERR_NO_VOCS_AVAILABLE=2e3]="ERR_NO_VOCS_AVAILABLE",e[e.ERR_NO_VOS_AVAILABLE=2001]="ERR_NO_VOS_AVAILABLE",e[e.ERR_JOIN_CHANNEL_TIMEOUT=2002]="ERR_JOIN_CHANNEL_TIMEOUT",e[e.ERR_REPEAT_JOIN_CHANNEL=2003]="ERR_REPEAT_JOIN_CHANNEL",e[e.ERR_JOIN_BY_MULTI_IP=2004]="ERR_JOIN_BY_MULTI_IP",e[e.ERR_NOT_JOINED=2011]="ERR_NOT_JOINED",e[e.ERR_REPEAT_JOIN_REQUEST=2012]="ERR_REPEAT_JOIN_REQUEST",e[e.ERR_INVALID_VENDOR_KEY=2013]="ERR_INVALID_VENDOR_KEY",e[e.ERR_INVALID_CHANNEL_NAME=2014]="ERR_INVALID_CHANNEL_NAME",e[e.ERR_INVALID_STRINGUID=2015]="ERR_INVALID_STRINGUID",e[e.ERR_TOO_MANY_USERS=2016]="ERR_TOO_MANY_USERS",e[e.ERR_SET_CLIENT_ROLE_TIMEOUT=2017]="ERR_SET_CLIENT_ROLE_TIMEOUT",e[e.ERR_SET_CLIENT_ROLE_NO_PERMISSION=2018]="ERR_SET_CLIENT_ROLE_NO_PERMISSION",e[e.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE=2019]="ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",e[e.ERR_PUBLISH_REQUEST_INVALID=2020]="ERR_PUBLISH_REQUEST_INVALID",e[e.ERR_SUBSCRIBE_REQUEST_INVALID=2021]="ERR_SUBSCRIBE_REQUEST_INVALID",e[e.ERR_NOT_SUPPORTED_MESSAGE=2022]="ERR_NOT_SUPPORTED_MESSAGE",e[e.ERR_ILLEAGAL_PLUGIN=2023]="ERR_ILLEAGAL_PLUGIN",e[e.ERR_REJOIN_TOKEN_INVALID=2024]="ERR_REJOIN_TOKEN_INVALID",e[e.ERR_REJOIN_USER_NOT_JOINED=2025]="ERR_REJOIN_USER_NOT_JOINED",e[e.ERR_INVALID_OPTIONAL_INFO=2027]="ERR_INVALID_OPTIONAL_INFO",e[e.ILLEGAL_AES_PASSWORD=2028]="ILLEGAL_AES_PASSWORD",e[e.ILLEGAL_CLIENT_ROLE_LEVEL=2029]="ILLEGAL_CLIENT_ROLE_LEVEL",e[e.ERR_TOO_MANY_BROADCASTERS=2031]="ERR_TOO_MANY_BROADCASTERS",e[e.ERR_TOO_MANY_SUBSCRIBERS=2032]="ERR_TOO_MANY_SUBSCRIBERS",e[e.ERR_LICENSE_MISSING=32769]="ERR_LICENSE_MISSING",e[e.ERR_LICENSE_EXPIRED=32771]="ERR_LICENSE_EXPIRED",e[e.ERR_LICENSE_MINUTES_EXCEEDED=32773]="ERR_LICENSE_MINUTES_EXCEEDED",e[e.ERR_LICENSE_PERIOD_INVALID=32774]="ERR_LICENSE_PERIOD_INVALID",e[e.ERR_LICENSE_MULTIPLE_SDK_SERVICE=32778]="ERR_LICENSE_MULTIPLE_SDK_SERVICE",e[e.ERR_LICENSE_ILLEGAL=32783]="ERR_LICENSE_ILLEGAL",e[e.ERR_TEST_RECOVER=9e3]="ERR_TEST_RECOVER",e[e.ERR_TEST_TRYNEXT=9001]="ERR_TEST_TRYNEXT",e[e.ERR_TEST_RETRY=9002]="ERR_TEST_RETRY",e}({}),H=function(e){return e.CONNECTED="websocket:connected",e.RECONNECTING="websocket:reconnecting",e.WILL_RECONNECT="websocket:will_reconnect",e.CLOSED="websocket:closed",e.FAILED="websocket:failed",e.ON_MESSAGE="websocket:on_message",e.REQUEST_NEW_URLS="websocket:request_new_urls",e.RECONNECT_WAITTING_FINISH="websocket:reconnect_waitting_finish",e.RECONNECT_CREATE_CONNECTION="websocket:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="websocket:on_token_privilege_did_expire",e}({});function G(s){if(!(n=s,"number"==typeof n&&Math.floor(n)===n&&0<=n&&n<=4294967295||e(s,1,255)))throw new U(t.INVALID_PARAMS,"[String uid] Length of the string: [1,255]. ASCII characters only. [Number uid] The value range is [0,10000]");var n;"string"==typeof s&&M.warn("You input a string as the user ID, to ensure better end-user experience, Agora highly suggests not using a string as the user ID.")}let K=function(e){return e.TRANSCODE="mix_streaming",e.RAW="raw_streaming",e}({});const Y={alpha:1,height:640,width:360,x:0,y:0,zOrder:0,audioChannel:0},F={x:0,y:0,width:160,height:160,zOrder:255,alpha:1};function x(e,t){i(e.url,"".concat(t,".url"),1,1e3,!1),s(e.x)||n(e.x,"".concat(t,".x"),0,1e4),s(e.y)||n(e.y,"".concat(t,".y"),0,1e4),s(e.width)||n(e.width,"".concat(t,".width"),0,1e4),s(e.height)||n(e.height,"".concat(t,".height"),0,1e4),s(e.zOrder)||n(e.zOrder,"".concat(t,".zOrder"),0,255),s(e.alpha)||n(e.alpha,"".concat(t,".alpha"),0,1,!1)}const J={audioBitrate:48,audioChannels:1,audioSampleRate:48e3,backgroundColor:0,height:360,lowLatency:!1,videoBitrate:400,videoCodecProfile:100,videoCodecType:1,videoFrameRate:15,videoGop:30,width:640,images:[],userConfigs:[],userConfigExtraInfo:""};let q=function(e){return e.WARNING="@live_uap-warning",e.ERROR="@line_uap-error",e.PUBLISH_STREAM_STATUS="@live_uap-publish-status",e.WORKER_STATUS="@live_uap-worker-status",e.REQUEST_NEW_ADDRESS="@live_uap-request-address",e}({}),X=function(e){return e.REQUEST_WORKER_MANAGER_LIST="@live_req_worker_manager",e}({}),Q=function(e){return e[e.LIVE_STREAM_RESPONSE_SUCCEED=200]="LIVE_STREAM_RESPONSE_SUCCEED",e[e.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM=454]="LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM",e[e.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR=450]="LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR",e[e.LIVE_STREAM_RESPONSE_BAD_STREAM=451]="LIVE_STREAM_RESPONSE_BAD_STREAM",e[e.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR=400]="LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR",e[e.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST=404]="LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST",e[e.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED=456]="LIVE_STREAM_RESPONSE_NOT_AUTHORIZED",e[e.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE=457]="LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE",e[e.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN=429]="LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN",e[e.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH=452]="LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH",e[e.LIVE_STREAM_RESPONSE_NOT_SUPPORTED=453]="LIVE_STREAM_RESPONSE_NOT_SUPPORTED",e[e.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM=455]="LIVE_STREAM_RESPONSE_MAX_STREAM_NUM",e[e.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR=500]="LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR",e[e.LIVE_STREAM_RESPONSE_WORKER_LOST=501]="LIVE_STREAM_RESPONSE_WORKER_LOST",e[e.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT=502]="LIVE_STREAM_RESPONSE_RESOURCE_LIMIT",e[e.LIVE_STREAM_RESPONSE_WORKER_QUIT=503]="LIVE_STREAM_RESPONSE_WORKER_QUIT",e[e.ERROR_FAIL_SEND_MESSAGE=504]="ERROR_FAIL_SEND_MESSAGE",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE=30]="PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT=31]="PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH=32]="PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH",e[e.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN=33]="PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN",e}({}),j=function(e){return e.CHINA="CHINA",e.ASIA="ASIA",e.NORTH_AMERICA="NORTH_AMERICA",e.EUROPE="EUROPE",e.JAPAN="JAPAN",e.INDIA="INDIA",e.KOREA="KOREA",e.HKMC="HKMC",e.US="US",e.OCEANIA="OCEANIA",e.SOUTH_AMERICA="SOUTH_AMERICA",e.AFRICA="AFRICA",e.OVERSEA="OVERSEA",e.GLOBAL="GLOBAL",e.EXTENSIONS="EXTENSIONS",e}({});j.AFRICA,j.ASIA,j.CHINA,j.EUROPE,j.GLOBAL,j.INDIA,j.JAPAN,j.NORTH_AMERICA,j.OCEANIA,j.OVERSEA,j.SOUTH_AMERICA;let z=function(e){return e.CHINA="CN",e.ASIA="AS",e.NORTH_AMERICA="NA",e.EUROPE="EU",e.JAPAN="JP",e.INDIA="IN",e.KOREA="KR",e.HKMC="HK",e.US="US",e.OCEANIA="OC",e.SOUTH_AMERICA="SA",e.AFRICA="AF",e.OVERSEA="OVERSEA",e.GLOBAL="GLOBAL",e.EXTENSIONS="GLOBAL",e}({});z.ASIA,z.NORTH_AMERICA,z.EUROPE,z.JAPAN,z.INDIA,z.KOREA,z.HKMC,z.US,z.OVERSEA,z.GLOBAL,z.OCEANIA,z.SOUTH_AMERICA,z.AFRICA,_&&z.CHINA;let Z=function(e){return e.CONNECTED="transmitter:connected",e.RECONNECTING="transmitter:reconnecting",e.WILL_RECONNECT="transmitter:will_reconnect",e.CLOSED="transmitter:closed",e.FAILED="transmitter:failed",e.ON_MESSAGE="transmitter:on_message",e.REQUEST_NEW_URLS="transmitter:request_new_urls",e.RECONNECT_WAITTING_FINISH="transmitter:reconnect_waitting_finish",e.RECONNECT_CREATE_CONNECTION="transmitter:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="transmitter:on_token_privilege_did_expire",e.TO_CONNECT_DATACHANNEL="transmitter:to_connect_datachannel",e.FAILBACK="transmitter:failback",e.PRE_CONNECT_PC="transmitter:pre_connect_pc",e}({});class $ extends c{get url(){return this.websocket&&this.websocket.url||null}get reconnectMode(){return this._reconnectMode}set reconnectMode(e){["tryNext","recover"].includes(e)&&this.resetReconnectCount(e),this._reconnectMode=e}get state(){return this._state}set state(e){e!==this._state&&(this._state=e,"reconnecting"===this._state?this.emit(H.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(H.CONNECTED):"closed"===this._state?this.emit(H.CLOSED):"failed"===this._state&&this.emit(H.FAILED))}resetReconnectCount(e){M.debug("websocket reset reconnect count, reason: "+e),this.reconnectCount=0}constructor(e,t){let s=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],E=arguments.length>4&&void 0!==arguments[4]&&arguments[4],r=arguments.length>5?arguments[5]:void 0;super(),this.connectionID=0,this.currentURLIndex=0,this.urls=[],this._reconnectMode="tryNext",this.reconnectReason=void 0,this._initMutex=new R("websocket"),this.name=void 0,this._state="closed",this.reconnectInterrupter=void 0,this.websocket=void 0,this.retryConfig=void 0,this.reconnectCount=0,this.forceCloseTimeout=5e3,this.onlineReconnectListener=void 0,this.useCompress=void 0,this.tryDoubleDomain=!1,this.use443PortOnly=!1,this.wsInflateLength=0,this.wsDeflateLength=0,this.closeEstablishingWs=()=>{},this.store=void 0,this.joinGatewayRecordIndex=void 0,this.store=r,this.name=e,this.retryConfig=v({},t),this.useCompress=s,this.tryDoubleDomain=n,this.use443PortOnly=E;const{timeout:i,timeoutFactor:o}=t,_=Math.max(300,Math.floor(3*i/5)),c=Math.max(1.2,Math.floor(8*o)/10);a.ONLINE&&(this.retryConfig.timeout=_,this.retryConfig.timeoutFactor=c),A.on(I.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===a.ONLINE?(this.retryConfig.timeout=_,this.retryConfig.timeoutFactor=c):(this.retryConfig.timeout=i,this.retryConfig.timeoutFactor=o))}))}getConnection(){return this.websocket||void 0}async init(e){let s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const n=await this._initMutex.lock();this.forceCloseTimeout=s,this.urls=e,this.state="connecting";try{const e=N(),s=this.urls[this.currentURLIndex];S("ENABLE_PREALLOC_PC")&&this.emit(Z.PRE_CONNECT_PC),this.createWebSocketConnection(s).then(e.resolve).catch(e.reject),this.once(H.CLOSED,(()=>{e.reject(new T(t.WS_DISCONNECT))})),this.once(H.CONNECTED,e.resolve),await e.promise}catch(e){}finally{n()}}close(e,t){if(this.currentURLIndex=0,this.resetReconnectCount("close"),this.reconnectInterrupter&&this.reconnectInterrupter(),this.websocket){this.websocket.onclose=null,this.websocket.onopen=null,this.websocket.onmessage=null;const e=this.websocket;t?setTimeout((()=>e.close()),500):e.close(),this.websocket=void 0}this.state=e?"failed":"closed",this.closeEstablishingWs&&this.closeEstablishingWs()}reconnect(e,t){if(!this.websocket)return void M.warning("[".concat(this.name,"] can not reconnect, no websocket"));void 0!==e&&(this.reconnectMode=e),M.debug("[".concat(this.name,"] reconnect is triggered initiative")),"number"==typeof this.joinGatewayRecordIndex&&this.store&&this.store.recordJoinChannelService({status:"error",errors:[new Error(t)]},this.joinGatewayRecordIndex);const s=this.websocket.onclose;this.websocket.onclose=null,this.websocket.close(),s&&s.bind(this.websocket)({code:9999,reason:t})}sendMessage(e){let s=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new T(t.WS_ABORT,"websocket is not ready");try{s||(e=JSON.stringify(e)),this.websocket.send(e)}catch(e){throw new T(t.WS_ERR,"send websocket message error"+e.toString())}}setWsInflateData(e){this.wsDeflateLength=this.wsDeflateLength+e.originLength,this.wsInflateLength=this.wsInflateLength+e.compressedLength}getWsInflateData(){const e=this.wsInflateLength,t=this.wsDeflateLength;return this.clearWsInflateData(),{wsInflateLength:e,wsDeflateLength:t}}clearWsInflateData(){this.wsInflateLength=0,this.wsDeflateLength=0}async createWebSocketConnection(e){var s;const n=N();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const E=e=>{var t;null===(t=this.store)||void 0===t||t.signalChannelOpen(),M.debug("[".concat(this.name,"] websocket opened:"),e),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),n.resolve()},r=async e=>{var s;if(M.debug("[".concat(this.name,"] websocket close ").concat(null===(s=this.websocket)||void 0===s?void 0:s.url,", code: ").concat(e.code,", reason: ").concat(e.reason,", current mode: ").concat(this.reconnectMode)),this.reconnectCount>=this.retryConfig.maxRetryCount)n.reject(new T(t.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close();else{"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");const s=L(this,H.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,E=await this.reconnectWithAction(s);if("closed"===this.state)return void M.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!E)return n.reject(new T(t.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);n.resolve()}},i=e=>{this.emit(H.ON_MESSAGE,e)},o=e=>{M.warn("[".concat(this.connectionID,"] ws open error ").concat(e))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),S("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(e=S("GATEWAY_WSS_ADDRESS")),M.debug("[".concat(this.name,"] start connect, url:"),e);const _=null===(s=this.store)||void 0===s?void 0:s.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});try{var c;const t=await this.chooseBestWebsocketConnection(e);this.websocket=t,E&&E(this.websocket.url),this.websocket.onclose=r,this.websocket.onmessage=i,this.websocket.onerror=o,null===(c=this.store)||void 0===c||c.recordJoinChannelService({endTs:Date.now(),status:"success"},_),this.joinGatewayRecordIndex=_}catch(e){const s="closed"===this.state,E=e instanceof T,i=E&&e.code===t.WS_ABORT,o=E&&e.code===t.WS_ERR,c=E?e.message:e&&(e.reason||e.toString());M.warning("[choose-best-ws] chooseBestWebsocket error: ".concat(c)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:i?"aborted":"error",errors:[e]},_),s||o?(n.reject(s?new T(t.WS_DISCONNECT,"websocket is closed: ".concat(c)):new T(t.WS_ERR,"init websocket failed: ".concat(c))),o&&M.error("[".concat(this.name,"] init websocket failed: ").concat(c))):r&&r(e)}return n.promise}async reconnectWithAction(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(this.reconnectCount>=this.retryConfig.maxRetryCount)return!1;if(0===this.urls.length)return!1;if("closed"===this.state)return!1;M.warning("[choose-best-ws] action: =>",e),this.onlineReconnectListener||A.isOnline||!A.onlineWaiter||(this.onlineReconnectListener=A.onlineWaiter.then((()=>{this.onlineReconnectListener=void 0})));let s=!0;if(this.reconnectInterrupter=()=>s=!1,t){const t=d(this.reconnectCount,this.retryConfig);M.debug("[".concat(this.name,"] wait ").concat(t,"ms to reconnect websocket, mode: ").concat(e)),await Promise.race([h(t),this.onlineReconnectListener||new Promise((()=>{}))])}if("closed"===this._state||!s)return!1;this.reconnectCount+=1;const n=async(e,t)=>{this.emit(H.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e)};try{if("retry"===e)this.emit(H.RECONNECT_WAITTING_FINISH,e),await n(this.urls[this.currentURLIndex],e);else if("tryNext"===e){if(this.currentURLIndex+=1,this.currentURLIndex>=this.urls.length)return this.reconnectWithAction("recover",!1);M.debug("[".concat(this.name,"] websocket url length: ").concat(this.urls.length," current index: ").concat(this.currentURLIndex)),this.emit(H.RECONNECT_WAITTING_FINISH,e),await n(this.urls[this.currentURLIndex],e)}else"recover"===e&&(M.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.emit(H.RECONNECT_WAITTING_FINISH,e),this.urls=await O(this,H.REQUEST_NEW_URLS),this.currentURLIndex=0,await n(this.urls[this.currentURLIndex],e))}catch(s){var E;M.error("[".concat(this.name,"] reconnect failed ").concat(s&&s.toString()));const n=null==s||null===(E=s.data)||void 0===E?void 0:E.desc;return Array.isArray(n)&&n.includes("dynamic key expired")?(this.emit(H.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):this.reconnectWithAction(e,t)}return!0}}class ee extends ${constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3&&void 0!==arguments[3]&&arguments[3],arguments.length>4&&void 0!==arguments[4]&&arguments[4],arguments.length>5?arguments[5]:void 0)}async chooseBestWebsocketConnection(e,s){return new Promise(((n,E)=>{let r=!1;const i=[];this.closeEstablishingWs=()=>{M.debug("[choose-best-ws] close establishing websockets"),i.forEach((e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close()})),E(new T(t.WS_ABORT,"choose best websocket aborted"))};const o=S("GATEWAY_DOMAINS");let _;const c=e.indexOf("?h="),R=o.find((t=>-1!==c?e.includes(t,c):e.includes(t)));M.debug("[choose-best-ws] currentDomain: ",R,", domains: ",o);let a=!this.tryDoubleDomain||!R;if(!a&&R){var A;const t=Date.now();try{o.forEach((t=>{const s=-1===c?e.replace(R,t):e.substr(0,c)+e.substr(c).replace(R,t),n=new WebSocket(s);n.binaryType="arraybuffer",i.push(n),M.debug("[choose-best-ws] ws is connecting:",n.url)}))}catch(e){for(M.debug("[choose-best-ws] ws create failed, fallback to single url"),i.forEach((e=>e.close()));i.length;)i.pop();a=!0}null===(A=this.store)||void 0===A||A.recordJoinChannelService({urls:i.map((e=>e.url)),service:"gateway"},s),i.forEach((e=>{e.onopen=()=>{if(r)return;const s=Date.now()-t;M.debug("[choose-best-ws] ws open cost ".concat(s,"ms")),i.filter((t=>t!==e)).forEach((e=>{M.debug("[choose-best-ws]close backup websocket: ".concat(e.url)),e.close()})),r=!0,n(e)},e.onclose=e=>{if(_=e,r)return;i.find((e=>!(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)))||(M.debug("[choose-best-ws] all websocket is closed"),r=!0,E(_))},e.onmessage=t=>{M.debug("[choose-best-ws]".concat(e.url," onmessage: ").concat(t.data))}})),h(this.forceCloseTimeout).then((()=>{i.forEach((e=>{e.readyState!==WebSocket.OPEN&&e.close()}))}))}if(a){var I;let r;M.debug("[choose-best-ws] use single url: ",e),null===(I=this.store)||void 0===I||I.recordJoinChannelService({urls:[e],service:"gateway"},s);try{r=new WebSocket(e),i.push(r),r.binaryType="arraybuffer"}catch(e){const s=new T(t.WS_ERR,"init websocket failed! Error: ".concat(e.toString()));return M.error("[".concat(this.name,"]").concat(s)),void E(s)}r.onopen=()=>{n(r)},r.onclose=e=>{E(e)},r.onmessage=e=>{M.debug("[choose-best-ws]".concat(r.url," onmessage: ").concat(e.data))},h(this.forceCloseTimeout).then((()=>{r&&r.readyState!==WebSocket.OPEN&&r.close()}))}})).then((e=>(this.closeEstablishingWs=void 0,e))).catch((e=>{throw this.closeEstablishingWs=void 0,e}))}}class te extends c{constructor(e,t,s,n){super(),this.spec=void 0,this.token=void 0,this.websocket=void 0,this.pingpongTimer=void 0,this.reconnectMode="retry",this.serviceMode=void 0,this.reqId=0,this.commandReqId=0,this.handleWebSocketOpen=()=>{this.reconnectMode="retry",this.startPingPong()},this.handleWebSocketMessage=e=>{if(!e.data)return;const t=JSON.parse(e.data);t.requestId?this.emit("@".concat(t.requestId,"-").concat(t.sid),t):(m.workerEvent(this.spec.sid,{actionType:"status",serverCode:t.code,workerType:this.serviceMode===K.TRANSCODE?1:2}),this.emit(q.PUBLISH_STREAM_STATUS,t))},this.spec=t,this.token=e,this.serviceMode=n,this.websocket=new ee("live-streaming",s),this.websocket.on(H.CONNECTED,this.handleWebSocketOpen),this.websocket.on(H.ON_MESSAGE,this.handleWebSocketMessage),this.websocket.on(H.REQUEST_NEW_URLS,((e,t)=>{O(this,q.REQUEST_NEW_ADDRESS).then(e).catch(t)})),this.websocket.on(H.RECONNECTING,(()=>{this.websocket.reconnectMode=this.reconnectMode}))}init(e){return this.websocket.init(e)}async request(e,t,s,n){this.reqId+=1,"request"===e&&(this.commandReqId+=1);const E=this.commandReqId,r=this.reqId;if(!r||!this.websocket)throw new U(V.UNEXPECTED_ERROR);const i=v({command:e,sdkVersion:"4.22.1"===l?"0.0.1":l,seq:r,requestId:r,allocate:s,cname:this.spec.cname,appId:this.spec.appId,sid:this.spec.sid,uid:this.spec.uid.toString(),ts:Math.floor(Date.now()/1e3)},t);if("closed"===this.websocket.state)throw new U(V.WS_DISCONNECT);const o=()=>new Promise(((e,t)=>{this.websocket.once(H.CLOSED,(()=>t(new U(V.WS_ABORT)))),this.websocket.once(H.CONNECTED,e)}));"connected"!==this.websocket.state&&await o(),i.clientRequest&&(i.clientRequest.workerToken=this.token);const _=new Promise(((e,t)=>{const s=()=>{t(new U(V.WS_ABORT))};this.websocket.once(H.RECONNECTING,s),this.websocket.once(H.CLOSED,s),this.once("@".concat(r,"-").concat(this.spec.sid),(t=>{e(t)}))}));n&&m.workerEvent(this.spec.sid,v(v({},n),{},{requestId:E,actionType:"request",payload:JSON.stringify(t.clientRequest),serverCode:0,code:0}));const c=Date.now();this.websocket.sendMessage(i);let R=null;try{R=await _}catch(n){if("closed"===this.websocket.state)throw n;return await o(),await this.request(e,t,s)}return n&&m.workerEvent(this.spec.sid,v(v({},n),{},{requestId:E,actionType:"response",payload:JSON.stringify(R.serverResponse),serverCode:R.code,success:200===R.code,responseTime:Date.now()-c})),200!==R.code&&this.handleResponseError(R),R}tryNextAddress(){this.reconnectMode="tryNext",this.websocket.reconnect("tryNext")}close(){const e="4.22.1"===l?"0.0.1":l;this.reqId+=1,"connected"===this.websocket.state?(this.websocket.sendMessage({command:"request",appId:this.spec.appId,cname:this.spec.cname,uid:this.spec.uid.toString(),sdkVersion:e,sid:this.spec.sid,seq:this.reqId,ts:Math.floor(Date.now()/1e3),requestId:this.reqId,clientRequest:{command:"DestroyWorker"}}),this.websocket.close(!1,!0)):this.websocket.close(!1),this.pingpongTimer&&(window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0)}handleResponseError(e){switch(e.code){case Q.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM:return void M.warning("live stream response already exists stream");case Q.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR:case Q.LIVE_STREAM_RESPONSE_BAD_STREAM:case Q.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR:return new U(V.LIVE_STREAMING_INVALID_ARGUMENT,"",{code:e.code}).throw();case Q.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST:if("UnpublishStream"===e.serverResponse.command)return;throw new U(V.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case Q.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED:return new U(V.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED,"",{code:e.code}).throw();case Q.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const t=new U(V.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE);return this.emit(q.WARNING,t,e.serverResponse.url)}case Q.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN:{const t=new U(V.LIVE_STREAMING_WARN_FREQUENT_REQUEST);return this.emit(q.WARNING,t,e.serverResponse.url)}case Q.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH:throw new U(V.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case Q.LIVE_STREAM_RESPONSE_NOT_SUPPORTED:return new U(V.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED,"",{code:e.code}).throw();case Q.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM:{const t=new U(V.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT);return this.emit(q.WARNING,t,e.serverResponse.url)}case Q.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR:return new U(V.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code}).throw();case Q.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT:throw new U(V.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream resource limit",{retry:!0,changeAddress:!0});case Q.LIVE_STREAM_RESPONSE_WORKER_LOST:case Q.LIVE_STREAM_RESPONSE_WORKER_QUIT:if("UnpublishStream"===e.serverResponse.command)return;throw new U(V.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case Q.ERROR_FAIL_SEND_MESSAGE:if("UnpublishStream"===e.serverResponse.command)return;if("UpdateTranscoding"===e.serverResponse.command||"ControlStream"===e.serverResponse.command)return new U(V.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{code:e.code}).throw();throw new U(V.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case Q.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case Q.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case Q.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case Q.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:return new U(V.LIVE_STREAMING_CDN_ERROR,"",{code:e.code}).throw()}}startPingPong(){this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval((()=>{"connected"===this.websocket.state&&this.request("ping",{}).catch(C)}),6e3)}}let se=0,ne=0;const Ee={[b.ACCESS_POINT]:{[B.NO_FLAG_SET]:{desc:"flag is zero",retry:!1},[B.FLAG_SET_BUT_EMPTY]:{desc:"flag is empty",retry:!1},[B.INVALID_FALG_SET]:{desc:"invalid flag",retry:!1},[B.FLAG_SET_BUT_NO_RE]:{desc:"flag set unilbs but no request",retry:!1},[B.INVALID_SERVICE_ID]:{desc:"invalid service id",retry:!1},[B.NO_SERVICE_AVAILABLE]:{desc:"no service available",retry:!0},[B.NO_SERVICE_AVAILABLE_P2P]:{desc:"no unilbs p2p service available",retry:!0},[B.NO_SERVICE_AVAILABLE_VOICE]:{desc:"no unilbs voice service available",retry:!0},[B.NO_SERVICE_AVAILABLE_WEBRTC]:{desc:"no unilbs webrtc service available",retry:!0},[B.NO_SERVICE_AVAILABLE_CDS]:{desc:"no cds service available",retry:!0},[B.NO_SERVICE_AVAILABLE_CDN]:{desc:"no cdn dispatcher service available",retry:!0},[B.NO_SERVICE_AVAILABLE_TDS]:{desc:"no tds service available",retry:!0},[B.NO_SERVICE_AVAILABLE_REPORT]:{desc:"no unilbs report service available",retry:!0},[B.NO_SERVICE_AVAILABLE_APP_CENTER]:{desc:"no app center service available",retry:!0},[B.NO_SERVICE_AVAILABLE_ENV0]:{desc:"no unilbs sig env0 service available",retry:!0},[B.NO_SERVICE_AVAILABLE_VOET]:{desc:"no unilbs voet service available",retry:!0},[B.NO_SERVICE_AVAILABLE_STRING_UID]:{desc:"no string uid service available",retry:!0},[B.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS]:{desc:"no webrtc unilbs service available",retry:!0}},[b.UNILBS]:{[k.INVALID_VENDOR_KEY]:{desc:"invalid vendor key, can not find appid",retry:!1},[k.INVALID_CHANNEL_NAME]:{desc:"invalid channel name",retry:!1},[k.INTERNAL_ERROR]:{desc:"unilbs internal error",retry:!1},[k.NO_AUTHORIZED]:{desc:"invalid token, authorized failed",retry:!1},[k.DYNAMIC_KEY_TIMEOUT]:{desc:"dynamic key or token timeout",retry:!1},[k.NO_ACTIVE_STATUS]:{desc:"no active status",retry:!1},[k.DYNAMIC_KEY_EXPIRED]:{desc:"dynamic key expired",retry:!1},[k.STATIC_USE_DYNAMIC_KEY]:{desc:"static use dynamic key",retry:!1},[k.DYNAMIC_USE_STATIC_KEY]:{desc:"dynamic use static key",retry:!1},[k.USER_OVERLOAD]:{desc:"amount of users over load",retry:!1},[k.FORBIDDEN_REGION]:{desc:"the request is forbidden in this area",retry:!1},[k.CANNOT_MEET_AREA_DEMAND]:{desc:"unable to allocate services in this area",retry:!1}},[b.STRING_UID_ALLOCATOR]:{[y.IIIEGAL_APPID]:{desc:"invalid appid",retry:!1},[y.IIIEGAL_UID]:{desc:"invalid string uid",retry:!1},[y.INTERNAL_ERROR]:{desc:"string uid allocator internal error",retry:!0}}};function re(e){const t=Ee[Math.floor(e/1e4)];if(!t)return{desc:"unknown error",retry:!1};const s=t[e%1e4];if(!s){if(Math.floor(e/1e4)===b.ACCESS_POINT){const t=e%1e4;if("1"===t.toString()[0])return{desc:e.toString(),retry:!1};if("2"===t.toString()[0])return{desc:e.toString(),retry:!0}}return{desc:"unknown error",retry:!1}}return s}W.K_TIMESTAMP_EXPIRED,W.K_CHANNEL_PERMISSION_INVALID,W.K_CERTIFICATE_INVALID,W.K_CHANNEL_NAME_EMPTY,W.K_CHANNEL_NOT_FOUND,W.K_TICKET_INVALID,W.K_CHANNEL_CONFLICTED,W.K_SERVICE_NOT_READY,W.K_SERVICE_TOO_HEAVY,W.K_UID_BANNED,W.K_IP_BANNED,W.K_AUTO_REBALANCE,W.ERR_INVALID_VENDOR_KEY,W.ERR_INVALID_CHANNEL_NAME,W.WARN_NO_AVAILABLE_CHANNEL,W.WARN_LOOKUP_CHANNEL_TIMEOUT,W.WARN_LOOKUP_CHANNEL_REJECTED,W.WARN_OPEN_CHANNEL_TIMEOUT,W.WARN_OPEN_CHANNEL_REJECTED,W.WARN_REQUEST_DEFERRED,W.ERR_DYNAMIC_KEY_TIMEOUT,W.ERR_NO_AUTHORIZED,W.ERR_VOM_SERVICE_UNAVAILABLE,W.ERR_NO_CHANNEL_AVAILABLE_CODE,W.ERR_MASTER_VOCS_UNAVAILABLE,W.ERR_INTERNAL_ERROR,W.ERR_NO_ACTIVE_STATUS,W.ERR_INVALID_UID,W.ERR_DYNAMIC_KEY_EXPIRED,W.ERR_STATIC_USE_DYANMIC_KE,W.ERR_DYNAMIC_USE_STATIC_KE,W.ERR_NO_VOCS_AVAILABLE,W.ERR_NO_VOS_AVAILABLE,W.ERR_JOIN_CHANNEL_TIMEOUT,W.ERR_JOIN_BY_MULTI_IP,W.ERR_NOT_JOINED,W.ERR_REPEAT_JOIN_REQUEST,W.ERR_REPEAT_JOIN_CHANNEL,W.ERR_INVALID_STRINGUID,W.ERR_TOO_MANY_USERS,W.ERR_SET_CLIENT_ROLE_TIMEOUT,W.ERR_SET_CLIENT_ROLE_NO_PERMISSION,W.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE,W.ERR_PUBLISH_REQUEST_INVALID,W.ERR_SUBSCRIBE_REQUEST_INVALID,W.ERR_NOT_SUPPORTED_MESSAGE,W.ERR_ILLEAGAL_PLUGIN,W.ILLEGAL_CLIENT_ROLE_LEVEL,W.ERR_REJOIN_TOKEN_INVALID,W.ERR_REJOIN_USER_NOT_JOINED,W.ERR_INVALID_OPTIONAL_INFO,W.ERR_TEST_RECOVER,W.ERR_TEST_TRYNEXT,W.ERR_TEST_RETRY,W.ILLEGAL_AES_PASSWORD,W.ERR_TOO_MANY_BROADCASTERS,W.ERR_TOO_MANY_SUBSCRIBERS,W.ERR_LICENSE_ILLEGAL,W.ERR_LICENSE_MISSING,W.ERR_LICENSE_EXPIRED,W.ERR_LICENSE_MINUTES_EXCEEDED,W.ERR_LICENSE_PERIOD_INVALID,W.ERR_LICENSE_MULTIPLE_SDK_SERVICE;const ie={GLOBAL:{ASIA:[j.CHINA,j.JAPAN,j.INDIA,j.KOREA,j.HKMC],EUROPE:[],NORTH_AMERICA:[j.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}};async function oe(e,s,n,E,r){const i=Date.now(),o={sid:n.sid,opid:10,appid:n.appId,string_uid:s};let _=e[0];const c=await D((()=>function(e,s,n,E){return new Promise(((r,i)=>{s.timeout=s.timeout||S("HTTP_CONNECT_TIMEOUT"),s.responseType=s.responseType||"json",s.data&&!n?(s.data=JSON.stringify(s.data),se+=u(s.data)):n&&(s.data.size?se+=s.data.size:s.data instanceof FormData?se+=g(s.data):se+=u(JSON.stringify(s.data))),s.headers=s.headers||{},s.headers["Content-Type"]=s.headers["Content-Type"]||"application/json",s.method="POST",s.url=e,P.request(s).then((e=>{"string"==typeof e.data?ne+=u(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?ne+=e.data.byteLength:ne+=u(JSON.stringify(e.data)),E&&r({data:e.data,headers:e.headers}),r(e.data)})).catch((e=>{P.isCancel(e)?i(new U(t.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?i(new U(t.NETWORK_TIMEOUT,e.message)):e.response?i(new U(t.NETWORK_RESPONSE_ERROR,e.response.status)):i(new U(t.NETWORK_ERROR,e.message))}))}))}(_+"".concat(-1===_.indexOf("?")?"?":"&","action=stringuid"),{data:o,cancelToken:E,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":72}})),((t,n)=>{if(0===t.code){if(t.uid<=0||t.uid>=Math.pow(2,32))throw M.error("Invalid Uint Uid ".concat(s," => ").concat(t.uid),t),m.reqUserAccount(o.sid,{lts:i,success:!1,serverAddr:_,stringUid:o.string_uid,uid:t.uid,errorCode:V.INVALID_UINT_UID_FROM_STRING_UID,extend:o}),new U(V.INVALID_UINT_UID_FROM_STRING_UID);return m.reqUserAccount(o.sid,{lts:i,success:!0,serverAddr:_,stringUid:o.string_uid,uid:t.uid,errorCode:null,extend:o}),!1}const E=re(t.code);return E.retry&&(_=e[(n+1)%e.length]),m.reqUserAccount(o.sid,{lts:i,success:!1,serverAddr:_,stringUid:o.string_uid,uid:t.uid,errorCode:E.desc,extend:o}),E.retry}),((t,s)=>t.code!==V.OPERATION_ABORTED&&(m.reqUserAccount(o.sid,{lts:i,success:!1,serverAddr:_,stringUid:o.string_uid,uid:null,errorCode:t.code,extend:o}),_=e[(s+1)%e.length],!0)),r);if(0!==c.code){const e=re(c.code);throw new U(V.UNEXPECTED_RESPONSE,e.desc)}return c}Object.keys(ie[j.GLOBAL]),j.CHINA,j.NORTH_AMERICA,j.EUROPE,j.ASIA,j.JAPAN,j.INDIA,j.OCEANIA,j.SOUTH_AMERICA,j.AFRICA,j.KOREA,j.HKMC,j.US;class _e extends c{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:w,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:w;super(),this.onLiveStreamWarning=void 0,this.onLiveStreamError=void 0,this.spec=void 0,this.retryTimeout=1e4,this.connection=void 0,this.httpRetryConfig=void 0,this.wsRetryConfig=void 0,this.streamingTasks=new Map,this.isStartingStreamingTask=!1,this.taskMutex=new R("live-streaming"),this.cancelToken=P.CancelToken.source(),this.transcodingConfig=void 0,this.uapResponse=void 0,this.lastTaskId=1,this.statusError=new Map,this.spec=e,this.httpRetryConfig=s,this.wsRetryConfig=t}async setTranscodingConfig(e){const t=v(v({},J),e);66!==t.videoCodecProfile&&77!==t.videoCodecProfile&&100!==t.videoCodecProfile&&(M.debug("[".concat(this.spec.clientId,"] set transcoding config, fix video codec profile: ").concat(t.videoCodecProfile," -> 100")),t.videoCodecProfile=100),t.transcodingUsers||(t.transcodingUsers=t.userConfigs),t.transcodingUsers&&(t.transcodingUsers=t.transcodingUsers.map((e=>v(v(v({},Y),e),{},{zOrder:e.zOrder?e.zOrder+1:1})))),function(e){s(e.width)||n(e.width,"config.width",0,1e4),s(e.height)||n(e.height,"config.height",0,1e4),s(e.videoBitrate)||n(e.videoBitrate,"config.videoBitrate",1,1e6),s(e.videoFrameRate)||n(e.videoFrameRate,"config.videoFrameRate"),s(e.lowLatency)||E(e.lowLatency,"config.lowLatency"),s(e.audioSampleRate)||r(e.audioSampleRate,"config.audioSampleRate",[32e3,44100,48e3]),s(e.audioBitrate)||n(e.audioBitrate,"config.audioBitrate",1,128),s(e.audioChannels)||r(e.audioChannels,"config.audioChannels",[1,2,3,4,5]),s(e.videoGop)||n(e.videoGop,"config.videoGop"),s(e.videoCodecProfile)||r(e.videoCodecProfile,"config.videoCodecProfile",[66,77,100]),s(e.userCount)||n(e.userCount,"config.userCount",0,17),s(e.backgroundColor)||n(e.backgroundColor,"config.backgroundColor",0,16777215),s(e.userConfigExtraInfo)||i(e.userConfigExtraInfo,"config.userConfigExtraInfo",0,4096,!1),e.transcodingUsers&&!s(e.transcodingUsers)&&(o(e.transcodingUsers,"config.transcodingUsers"),e.transcodingUsers.forEach(((e,t)=>{G(e.uid),s(e.x)||n(e.x,"transcodingUser[".concat(t,"].x"),0,1e4),s(e.y)||n(e.y,"transcodingUser[".concat(t,"].y"),0,1e4),s(e.width)||n(e.width,"transcodingUser[".concat(t,"].width"),0,1e4),s(e.height)||n(e.height,"transcodingUser[".concat(t,"].height"),0,1e4),s(e.zOrder)||n(e.zOrder-1,"transcodingUser[".concat(t,"].zOrder"),0,100),s(e.alpha)||n(e.alpha,"transcodingUser[".concat(t,"].alpha"),0,1,!1)}))),s(e.watermark)||x(e.watermark,"watermark"),s(e.backgroundImage)||x(e.backgroundImage,"backgroundImage"),e.images&&!s(e.images)&&(o(e.images,"config.images"),e.images.forEach(((e,t)=>{x(e,"images[".concat(t,"]"))})))}(t);const _=[];t.images&&_.push(...t.images.map((e=>v(v(v({},F),e),{},{zOrder:255})))),t.backgroundImage&&(_.push(v(v(v({},F),t.backgroundImage),{},{zOrder:0})),delete t.backgroundImage),t.watermark&&(_.push(v(v(v({},F),t.watermark),{},{zOrder:255})),delete t.watermark),t.images=_,t.transcodingUsers&&(t.userConfigs=t.transcodingUsers.map((e=>v({},e))),t.userCount=t.transcodingUsers.length,delete t.transcodingUsers);const c=(t.userConfigs||[]).map((e=>"number"==typeof e.uid?Promise.resolve(e.uid):async function(e,t,s,n,E){const r=S("ACCOUNT_REGISTER").slice(0,S("AJAX_REQUEST_CONCURRENT"));let i=[];i=t.proxyServer?r.map((e=>"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1"))):r.map((e=>"https://".concat(e,"/api/v1")));const o=null==E?void 0:E.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"stringUID",urls:i});try{const r=await oe(i,e,t,s,n);return null==E||E.recordJoinChannelService({status:"success",endTs:Date.now()},o),r.uid}catch(e){throw null==E||E.recordJoinChannelService({status:"error",endTs:Date.now(),errors:[e]},o),e}}(e.uid,this.spec,this.cancelToken.token,this.httpRetryConfig)));if((await Promise.all(c)).forEach(((e,s)=>{t.userConfigs&&t.userConfigs[s]&&(t.userConfigs[s].uid=e)})),this.transcodingConfig=t,this.connection)try{const e=await this.connection.request("request",{clientRequest:{command:"UpdateTranscoding",transcodingConfig:this.transcodingConfig}},!1,{command:"UpdateTranscoding",workerType:1,requestByUser:!0,tid:Array.from(this.streamingTasks.values()).map((e=>e.taskId)).join("#")});M.debug("[".concat(this.spec.clientId,"] update live transcoding config success, code: ").concat(e.code,", config:"),JSON.stringify(this.transcodingConfig))}catch(e){if(!e.data||!e.data.retry)throw e;e.data.changeAddress&&this.connection.tryNextAddress(),this.streamingTasks.forEach((t=>{M.warning("[".concat(this.spec.clientId,"] live streaming receive error"),e.toString(),"try to republish",t.url),this.startLiveStreamingTask(t.url,t.mode,e).then((()=>{M.debug("[".concat(this.spec.clientId,"] live streaming republish ").concat(t.url," success"))})).catch((e=>{M.error("[".concat(this.spec.clientId,"] live streaming republish failed"),t.url,e.toString()),this.onLiveStreamError&&this.onLiveStreamError(t.url,e)}))}))}}async startLiveStreamingTask(e,t,s){if(!this.transcodingConfig&&t===K.TRANSCODE)throw new U(V.INVALID_OPERATION,"[LiveStreaming] no transcoding config found, can not start transcoding streaming task");const n={command:"PublishStream",ts:Date.now(),url:e,uid:this.spec.uid.toString(),autoDestroyTime:100,acceptImageTimeout:!0};M.debug("[".concat(this.spec.clientId,"] start live streaming ").concat(e,", mode: ").concat(t));const E=await this.taskMutex.lock();if(!this.connection&&s)return void E();if(this.streamingTasks.get(e)&&!s)return E(),new U(V.LIVE_STREAMING_TASK_CONFLICT).throw();try{this.connection||(this.connection=await this.connect(t))}catch(e){throw E(),e}switch(t){case K.TRANSCODE:n.transcodingConfig=v({},this.transcodingConfig);case K.RAW:}this.uapResponse&&this.uapResponse.vid&&(n.vid=this.uapResponse.vid),this.isStartingStreamingTask=!0;const r=this.lastTaskId++;try{const i=new Promise(((t,n)=>{h(this.retryTimeout).then((()=>{if(s)return n(s);const t=this.statusError.get(e);return t?(this.statusError.delete(e),n(t)):void 0}))})),o=await Promise.race([this.connection.request("request",{clientRequest:n},!0,{url:e,command:"PublishStream",workerType:t===K.TRANSCODE?1:2,requestByUser:!s,tid:r.toString()}),i]);this.isStartingStreamingTask=!1,M.debug("[".concat(this.spec.clientId,"] live streaming started, code: ").concat(o.code)),this.streamingTasks.set(e,{clientRequest:n,mode:t,url:e,taskId:r}),E()}catch(n){if(E(),this.isStartingStreamingTask=!1,!n.data||!n.data.retry||s)throw n;return n.data.changeAddress?(this.connection.tryNextAddress(),await this.startLiveStreamingTask(e,t,n)):await this.startLiveStreamingTask(e,t,n)}}stopLiveStreamingTask(e){return new Promise(((t,s)=>{const n=this.streamingTasks.get(e);if(!n||!this.connection)return new U(V.UNEXPECTED_ERROR,"can not find streaming task to stop").throw();const E=n.mode;n.abortTask=()=>{M.debug("[".concat(this.spec.clientId,"] stop live streaming success(worker exception)")),this.streamingTasks.delete(e),t()},this.connection.request("request",{clientRequest:{command:"UnpublishStream",url:n.url}},!1,{url:e,command:"UnPublishStream",workerType:E===K.TRANSCODE?1:2,requestByUser:!0,tid:(this.lastTaskId++).toString()}).then((s=>{M.debug("[".concat(this.spec.clientId,"] stop live streaming success, code: ").concat(s.code)),this.streamingTasks.delete(e),0===this.streamingTasks.size&&(this.connection&&this.connection.close(),this.connection=void 0),t()})).catch(s)}))}resetAllTask(){const e=Array.from(this.streamingTasks.values());this.terminate();for(const t of e)this.startLiveStreamingTask(t.url,t.mode).catch((e=>{this.onLiveStreamError&&this.onLiveStreamError(t.url,e)}))}terminate(){this.cancelToken&&this.cancelToken.cancel(),this.streamingTasks=new Map,this.isStartingStreamingTask=!1,this.statusError=new Map,this.cancelToken=P.CancelToken.source(),this.uapResponse=void 0,this.connection&&this.connection.close(),this.connection=void 0}async connect(e){if(this.connection)throw new U(V.UNEXPECTED_ERROR,"live streaming connection has already connected");const t=await O(this,X.REQUEST_WORKER_MANAGER_LIST,e);return this.uapResponse=t,this.connection=new te(t.workerToken,this.spec,this.wsRetryConfig,e),this.connection.on(q.WARNING,((e,t)=>this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e))),this.connection.on(q.PUBLISH_STREAM_STATUS,(e=>this.handlePublishStreamServer(e))),this.connection.on(q.REQUEST_NEW_ADDRESS,((t,s)=>{if(!this.connection)return s(new U(V.UNEXPECTED_ERROR,"can not get new live streaming address list"));O(this,X.REQUEST_WORKER_MANAGER_LIST,e).then((e=>{this.uapResponse=e,t(e.addressList)})).catch(s)})),await this.connection.init(t.addressList),this.connection}handlePublishStreamServer(e){const t=e.serverStatus&&e.serverStatus.url||"empty_url",s=this.streamingTasks.get(t),n=e.reason;switch(e.code){case Q.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case Q.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case Q.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case Q.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:{const n=new U(V.LIVE_STREAMING_CDN_ERROR,"",{code:e.code});if(s)return M.error(n.toString()),this.onLiveStreamError&&this.onLiveStreamError(t,n);if(!this.isStartingStreamingTask)return;this.statusError.set(t,n)}case Q.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const e=new U(V.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE,n);return this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e)}case Q.LIVE_STREAM_RESPONSE_WORKER_LOST:case Q.LIVE_STREAM_RESPONSE_WORKER_QUIT:{if(!this.connection)return;this.connection.tryNextAddress();const t=Array.from(this.streamingTasks.values());for(const s of t)s.abortTask?s.abortTask():(M.warning("[".concat(this.spec.clientId,"] publish stream status code"),e.code,"try to republish",s.url),this.startLiveStreamingTask(s.url,s.mode,new U(V.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code})).then((()=>{M.debug("[".concat(this.spec.clientId,"] republish live stream success"),s.url)})).catch((e=>{M.error(e.toString()),this.onLiveStreamError&&this.onLiveStreamError(s.url,e)})));return}}}hasUrl(e){return this.streamingTasks.has(e)}}const ce={name:"LiveStreaming",create:function(e){return new _e(e.joinInfo,e.websocketRetryConfig||w,e.httpRetryConfig||w)}};export{ce as LiveStreamingService};