agora-rtc-sdk-ng
Advanced tools
Comparing version 4.23.0 to 4.23.1
{ | ||
"name": "agora-rtc-sdk-ng", | ||
"version": "4.23.0", | ||
"version": "4.23.1", | ||
"module": "AgoraRTC_N-production.esm-bundler.mjs", | ||
@@ -5,0 +5,0 @@ "types": "rtc-sdk_en.esm.d.ts", |
{ | ||
"name": "agora-rtc-sdk-ng", | ||
"version": "4.23.0", | ||
"version": "4.23.1", | ||
"description": "Agora WebRTC SDK for JavaScript", | ||
@@ -65,5 +65,5 @@ "main": "AgoraRTC_N-production.js", | ||
"dependencies": { | ||
"@agora-js/shared": "4.23.0", | ||
"@agora-js/report": "4.23.0", | ||
"@agora-js/media": "4.23.0", | ||
"@agora-js/shared": "4.23.1", | ||
"@agora-js/report": "4.23.1", | ||
"@agora-js/media": "4.23.1", | ||
"agora-rte-extension": "^1.2.4", | ||
@@ -70,0 +70,0 @@ "axios": "^1.7.7", |
@@ -67,38 +67,2 @@ import { RTMConfiguration, TurnServerConfigWithMode, CloudProxyServerMode, EncryptionMode, EventEmitter, RetryConfiguration } from '@agora-js/shared'; | ||
interface JoinInfo extends Partial<RTMConfiguration> { | ||
clientId: string; | ||
appId: string; | ||
sid: string; | ||
cname: string; | ||
turnServer: TurnServerConfigWithMode; | ||
proxyServer?: string; | ||
token: string; | ||
cloudProxyServer: CloudProxyServerMode; | ||
uid?: number | null; | ||
stringUid?: string; | ||
aespassword?: string; | ||
aessalt?: string; | ||
aesmode?: EncryptionMode; | ||
multiIP?: MultiIpOptions; | ||
optionalInfo?: string; | ||
appScenario?: string; | ||
useLocalAccessPoint: boolean; | ||
apUrl?: string; | ||
defaultVideoStream?: RemoteStreamType; | ||
license?: string; | ||
setLocalAPVersion?: number; | ||
preload?: boolean; | ||
apRequestDetail?: string; | ||
role?: "host" | "audience"; | ||
} | ||
interface JoinInfoWithAPResponse extends JoinInfo { | ||
cid: number; | ||
uid: number; | ||
vid?: string; | ||
apResponse: ChooseServerResponse; | ||
apGatewayAddress?: GatewayAddress; | ||
gatewayAddrs: GatewayAddress[]; | ||
uni_lbs_ip?: string; | ||
} | ||
/** | ||
@@ -155,2 +119,38 @@ * Configurations of the media stream relay. | ||
interface JoinInfo extends Partial<RTMConfiguration> { | ||
clientId: string; | ||
appId: string; | ||
sid: string; | ||
cname: string; | ||
turnServer: TurnServerConfigWithMode; | ||
proxyServer?: string; | ||
token: string; | ||
cloudProxyServer: CloudProxyServerMode; | ||
uid?: number | null; | ||
stringUid?: string; | ||
aespassword?: string; | ||
aessalt?: string; | ||
aesmode?: EncryptionMode; | ||
multiIP?: MultiIpOptions; | ||
optionalInfo?: string; | ||
appScenario?: string; | ||
useLocalAccessPoint: boolean; | ||
apUrl?: string; | ||
defaultVideoStream?: RemoteStreamType; | ||
license?: string; | ||
setLocalAPVersion?: number; | ||
preload?: boolean; | ||
apRequestDetail?: string; | ||
role?: "host" | "audience"; | ||
} | ||
interface JoinInfoWithAPResponse extends JoinInfo { | ||
cid: number; | ||
uid: number; | ||
vid?: string; | ||
apResponse: ChooseServerResponse; | ||
apGatewayAddress?: GatewayAddress; | ||
gatewayAddrs: GatewayAddress[]; | ||
uni_lbs_ip?: string; | ||
} | ||
declare class AgoraChannelMediaRelayClient extends EventEmitter { | ||
@@ -157,0 +157,0 @@ private joinInfo; |
/** | ||
* AgoraWebSDK_N-v4.23.0-0-g98fcf352-dirty Copyright AgoraInc. | ||
* AgoraWebSDK_N-v4.23.1-0-gea45199f-dirty Copyright AgoraInc. | ||
*/ | ||
import{getParameter as e,getUTF8StringByteLength as t,getMultiUnilbsFormDataByteLength as s,AgoraRTCErrorCode as E,IS_GLOBAL_VERSION as n,VERSION as _,retryable as o,EventEmitter as i,PromiseMutex as r,NETWORK_STATE as c,networkIndicator as a,NETWORK_INDICATOR_EVENTS as R,createDefer as A,AgoraRTCError as I,getRetryWaitTime as N,wait as h,emitAsPromise as S,emitAsInvokerNoResponse as T,generateSessionID as C,DEFAULT_RETRY_CONFIG as O}from"@agora-js/shared";import{AgoraRTCError as L,AgoraRTCErrorCode as d,logger as l}from"@agora-js/report";import u from"axios";import"formdata-polyfill";function D(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 E=s.call(e,t||"default");if("object"!=typeof E)return E;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 w(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var E=Object.getOwnPropertySymbols(e);t&&(E=E.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,E)}return s}let V=0,g=0;let P=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}({}),U=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}({}),f=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}({}),M=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}({}),m=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.DATASTREAM2_NOT_AVAILABLE=27]="DATASTREAM2_NOT_AVAILABLE",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}({});P.ACCESS_POINT,M.NO_FLAG_SET,M.FLAG_SET_BUT_EMPTY,M.INVALID_FALG_SET,M.FLAG_SET_BUT_NO_RE,M.INVALID_SERVICE_ID,M.NO_SERVICE_AVAILABLE,M.NO_SERVICE_AVAILABLE_P2P,M.NO_SERVICE_AVAILABLE_VOICE,M.NO_SERVICE_AVAILABLE_WEBRTC,M.NO_SERVICE_AVAILABLE_CDS,M.NO_SERVICE_AVAILABLE_CDN,M.NO_SERVICE_AVAILABLE_TDS,M.NO_SERVICE_AVAILABLE_REPORT,M.NO_SERVICE_AVAILABLE_APP_CENTER,M.NO_SERVICE_AVAILABLE_ENV0,M.NO_SERVICE_AVAILABLE_VOET,M.NO_SERVICE_AVAILABLE_STRING_UID,M.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS,P.UNILBS,f.INVALID_VENDOR_KEY,f.INVALID_CHANNEL_NAME,f.INTERNAL_ERROR,f.NO_AUTHORIZED,f.DYNAMIC_KEY_TIMEOUT,f.NO_ACTIVE_STATUS,f.DYNAMIC_KEY_EXPIRED,f.STATIC_USE_DYNAMIC_KEY,f.DYNAMIC_USE_STATIC_KEY,f.USER_OVERLOAD,f.FORBIDDEN_REGION,f.CANNOT_MEET_AREA_DEMAND,P.STRING_UID_ALLOCATOR,U.IIIEGAL_APPID,U.IIIEGAL_UID,U.INTERNAL_ERROR,m.K_TIMESTAMP_EXPIRED,m.K_CHANNEL_PERMISSION_INVALID,m.K_CERTIFICATE_INVALID,m.K_CHANNEL_NAME_EMPTY,m.K_CHANNEL_NOT_FOUND,m.K_TICKET_INVALID,m.K_CHANNEL_CONFLICTED,m.K_SERVICE_NOT_READY,m.K_SERVICE_TOO_HEAVY,m.K_UID_BANNED,m.K_IP_BANNED,m.DATASTREAM2_NOT_AVAILABLE,m.K_AUTO_REBALANCE,m.ERR_INVALID_VENDOR_KEY,m.ERR_INVALID_CHANNEL_NAME,m.WARN_NO_AVAILABLE_CHANNEL,m.WARN_LOOKUP_CHANNEL_TIMEOUT,m.WARN_LOOKUP_CHANNEL_REJECTED,m.WARN_OPEN_CHANNEL_TIMEOUT,m.WARN_OPEN_CHANNEL_REJECTED,m.WARN_REQUEST_DEFERRED,m.ERR_DYNAMIC_KEY_TIMEOUT,m.ERR_NO_AUTHORIZED,m.ERR_VOM_SERVICE_UNAVAILABLE,m.ERR_NO_CHANNEL_AVAILABLE_CODE,m.ERR_MASTER_VOCS_UNAVAILABLE,m.ERR_INTERNAL_ERROR,m.ERR_NO_ACTIVE_STATUS,m.ERR_INVALID_UID,m.ERR_DYNAMIC_KEY_EXPIRED,m.ERR_STATIC_USE_DYANMIC_KE,m.ERR_DYNAMIC_USE_STATIC_KE,m.ERR_NO_VOCS_AVAILABLE,m.ERR_NO_VOS_AVAILABLE,m.ERR_JOIN_CHANNEL_TIMEOUT,m.ERR_JOIN_BY_MULTI_IP,m.ERR_NOT_JOINED,m.ERR_REPEAT_JOIN_REQUEST,m.ERR_REPEAT_JOIN_CHANNEL,m.ERR_INVALID_STRINGUID,m.ERR_TOO_MANY_USERS,m.ERR_SET_CLIENT_ROLE_TIMEOUT,m.ERR_SET_CLIENT_ROLE_NO_PERMISSION,m.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE,m.ERR_PUBLISH_REQUEST_INVALID,m.ERR_SUBSCRIBE_REQUEST_INVALID,m.ERR_NOT_SUPPORTED_MESSAGE,m.ERR_ILLEAGAL_PLUGIN,m.ILLEGAL_CLIENT_ROLE_LEVEL,m.ERR_REJOIN_TOKEN_INVALID,m.ERR_REJOIN_USER_NOT_JOINED,m.ERR_INVALID_OPTIONAL_INFO,m.ERR_TEST_RECOVER,m.ERR_TEST_TRYNEXT,m.ERR_TEST_RETRY,m.ILLEGAL_AES_PASSWORD,m.ERR_TOO_MANY_BROADCASTERS,m.ERR_TOO_MANY_SUBSCRIBERS,m.ERR_LICENSE_ILLEGAL,m.ERR_LICENSE_MISSING,m.ERR_LICENSE_EXPIRED,m.ERR_LICENSE_MINUTES_EXCEEDED,m.ERR_LICENSE_PERIOD_INVALID,m.ERR_LICENSE_MULTIPLE_SDK_SERVICE;let p=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}({});p.AFRICA,p.ASIA,p.CHINA,p.EUROPE,p.GLOBAL,p.INDIA,p.JAPAN,p.NORTH_AMERICA,p.OCEANIA,p.OVERSEA,p.SOUTH_AMERICA;let b=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}({});b.ASIA,b.NORTH_AMERICA,b.EUROPE,b.JAPAN,b.INDIA,b.KOREA,b.HKMC,b.US,b.OVERSEA,b.GLOBAL,b.OCEANIA,b.SOUTH_AMERICA,b.AFRICA,n&&b.CHINA;const v={GLOBAL:{ASIA:[p.CHINA,p.JAPAN,p.INDIA,p.KOREA,p.HKMC],EUROPE:[],NORTH_AMERICA:[p.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}};Object.keys(v[p.GLOBAL]),p.CHINA,p.NORTH_AMERICA,p.EUROPE,p.ASIA,p.JAPAN,p.INDIA,p.OCEANIA,p.SOUTH_AMERICA,p.AFRICA,p.KOREA,p.HKMC,p.US;let B=1;function y(n,i,r,c){const a={command:"convergeAllocateEdge",sid:i.sid,appId:i.appId,token:i.token,ts:Date.now(),version:_,cname:i.cname,uid:i.uid.toString(),requestId:B,seq:B};B+=1;const R={service_name:"tele_channel",json_body:JSON.stringify(a)};return o((async()=>{const _=await function(n,_,o,i){return new Promise(((r,c)=>{_.timeout=_.timeout||e("HTTP_CONNECT_TIMEOUT"),_.responseType=_.responseType||"json",_.data&&!o?(_.data=JSON.stringify(_.data),V+=t(_.data)):o&&(_.data.size?V+=_.data.size:_.data instanceof FormData?V+=s(_.data):V+=t(JSON.stringify(_.data))),_.headers=_.headers||{},_.headers["Content-Type"]=_.headers["Content-Type"]||"application/json",_.method="POST",_.url=n,u.request(_).then((e=>{"string"==typeof e.data?g+=t(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?g+=e.data.byteLength:g+=t(JSON.stringify(e.data)),i&&r({data:e.data,headers:e.headers}),r(e.data)})).catch((e=>{u.isCancel(e)?c(new L(E.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?c(new L(E.NETWORK_TIMEOUT,e.message)):e.response?c(new L(E.NETWORK_RESPONSE_ERROR,e.response.status)):c(new L(E.NETWORK_ERROR,e.message))}))}))}(n,{data:R,cancelToken:r,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":61}});if(0!==_.code){const e=new L(d.UNEXPECTED_RESPONSE,"cross channel ap error, code"+_.code,{retry:!0});throw l.error(e.toString()),e}const o=JSON.parse(_.json_body);if(200!==o.code){const e=new L(d.UNEXPECTED_RESPONSE,"cross channel app center error, code: ".concat(o.code,", reason: ").concat(o.reason));throw l.error(e.toString()),e}if(!o.servers||0===o.servers.length){const e=new L(d.UNEXPECTED_RESPONSE,"cross channel app center empty server");throw l.error(e.toString()),e}return{vid:o.vid,workerToken:o.workerToken,addressList:(e("CHANNEL_MEDIA_RELAY_SERVERS")||o.servers).map((t=>"wss://".concat(t.address.replace(/\./g,"-"),".").concat(e("WORKER_DOMAIN"),":").concat(t.wss)))}}),void 0,(e=>!!(e.code!==d.OPERATION_ABORTED&&e.code!==d.UNEXPECTED_RESPONSE||e.data&&e.data.retry)),c)}async function K(t,s,E){const n=e("UAP_AP").slice(0,e("AJAX_REQUEST_CONCURRENT")).map((e=>t.proxyServer?"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1?action=uap"):"https://".concat(e,"/api/v1?action=uap"))).map((e=>y(e,t,s,E)));try{const e=await(_=n,Promise.all(_.map((e=>e.then((e=>{throw e}),(e=>e))))).then((e=>{throw e}),(e=>e)));return n.forEach((e=>e.cancel())),e}catch(e){throw e[0]}var _}let k=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_CREATE_CONNECTION="websocket:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="websocket:on_token_privilege_did_expire",e}({}),H=function(e){return e[e.SetSdkProfile=0]="SetSdkProfile",e[e.SetSourceChannel=1]="SetSourceChannel",e[e.SetSourceUserId=2]="SetSourceUserId",e[e.SetDestChannel=3]="SetDestChannel",e[e.StartPacketTransfer=4]="StartPacketTransfer",e[e.StopPacketTransfer=5]="StopPacketTransfer",e[e.UpdateDestChannel=6]="UpdateDestChannel",e[e.Reconnect=7]="Reconnect",e[e.SetVideoProfile=8]="SetVideoProfile",e}({}),Y=function(e){return e.NETWORK_DISCONNECTED="NETWORK_DISCONNECTED",e.NETWORK_CONNECTED="NETWORK_CONNECTED",e.PACKET_JOINED_SRC_CHANNEL="PACKET_JOINED_SRC_CHANNEL",e.PACKET_JOINED_DEST_CHANNEL="PACKET_JOINED_DEST_CHANNEL",e.PACKET_SENT_TO_DEST_CHANNEL="PACKET_SENT_TO_DEST_CHANNEL",e.PACKET_RECEIVED_VIDEO_FROM_SRC="PACKET_RECEIVED_VIDEO_FROM_SRC",e.PACKET_RECEIVED_AUDIO_FROM_SRC="PACKET_RECEIVED_AUDIO_FROM_SRC",e.PACKET_UPDATE_DEST_CHANNEL="PACKET_UPDATE_DEST_CHANNEL",e.PACKET_UPDATE_DEST_CHANNEL_REFUSED="PACKET_UPDATE_DEST_CHANNEL_REFUSED",e.PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE="PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE",e}({}),W=function(e){return e.RELAY_STATE_IDLE="RELAY_STATE_IDLE",e.RELAY_STATE_CONNECTING="RELAY_STATE_CONNECTING",e.RELAY_STATE_RUNNING="RELAY_STATE_RUNNING",e.RELAY_STATE_FAILURE="RELAY_STATE_FAILURE",e}({}),G=function(e){return e.RELAY_OK="RELAY_OK",e.SERVER_CONNECTION_LOST="SERVER_CONNECTION_LOST",e.SRC_TOKEN_EXPIRED="SRC_TOKEN_EXPIRED",e.DEST_TOKEN_EXPIRED="DEST_TOKEN_EXPIRED",e}({}),F=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_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 J extends i{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(k.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(k.CONNECTED):"closed"===this._state?this.emit(k.CLOSED):"failed"===this._state&&this.emit(k.FAILED))}resetReconnectCount(e){l.debug("websocket reset reconnect count, reason: "+e),this.reconnectCount=0}constructor(e,t){let s=arguments.length>2&&void 0!==arguments[2]&&arguments[2],E=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=arguments.length>4&&void 0!==arguments[4]&&arguments[4],_=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=void 0,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=_,this.name=e,this.retryConfig=function(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?w(Object(s),!0).forEach((function(t){D(e,t,s[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):w(Object(s)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))}))}return e}({},t),this.useCompress=s,this.tryDoubleDomain=E,this.use443PortOnly=n,this._initMutex=new r("websocket",_?_.clientId:void 0);const{timeout:o,timeoutFactor:i}=t,A=Math.max(300,Math.floor(3*o/5)),I=Math.max(1.2,Math.floor(8*i)/10);c.ONLINE&&(this.retryConfig.timeout=A,this.retryConfig.timeoutFactor=I),a.on(R.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===c.ONLINE?(this.retryConfig.timeout=A,this.retryConfig.timeoutFactor=I):(this.retryConfig.timeout=o,this.retryConfig.timeoutFactor=i))}))}getConnection(){return this.websocket||void 0}async init(t){let s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const n=await this._initMutex.lock();this._reconnectMode="tryNext",this.forceCloseTimeout=s,this.urls=t,this.state="connecting";try{const t=A(),s=this.urls[this.currentURLIndex];e("ENABLE_PREALLOC_PC")&&this.emit(F.PRE_CONNECT_PC),this.createWebSocketConnection(s).then(t.resolve).catch(t.reject),this.once(k.CLOSED,(()=>{t.reject(new I(E.WS_DISCONNECT))})),this.once(k.CONNECTED,t.resolve),await t.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 l.warning("[".concat(this.name,"] can not reconnect, no websocket"));void 0!==e&&(this.reconnectMode=e),l.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 t=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new I(E.WS_ABORT,"websocket is not ready");try{t||(e=JSON.stringify(e)),this.websocket.send(e)}catch(e){throw new I(E.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(t){var s;const n=A();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const _=e=>{var t;null===(t=this.store)||void 0===t||t.signalChannelOpen(),l.debug("[".concat(this.name,"] websocket opened:"),e),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),n.resolve()},o=async e=>{var t;if(l.debug("[".concat(this.name,"] websocket close ").concat(null===(t=this.websocket)||void 0===t?void 0:t.url,", code: ").concat(e.code,", reason: ").concat(e.reason,", current mode: ").concat(this.reconnectMode)),this.reconnectCount>=this.retryConfig.maxRetryCount)n.reject(new I(E.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close();else{"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");const t=T(this,k.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,s=await this.reconnectWithAction(t);if("closed"===this.state)return void l.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!s)return n.reject(new I(E.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);n.resolve()}},i=e=>{this.emit(k.ON_MESSAGE,e)},r=e=>{l.warn("[".concat(this.connectionID,"] ws open error ").concat(e))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),e("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(t=e("GATEWAY_WSS_ADDRESS")),l.debug("[".concat(this.name,"] start connect, url:"),t);const c=null===(s=this.store)||void 0===s?void 0:s.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});try{var a;const e=await this.chooseBestWebsocketConnection(t);this.websocket=e,_&&_(this.websocket.url),this.websocket.onclose=o,this.websocket.onmessage=i,this.websocket.onerror=r,null===(a=this.store)||void 0===a||a.recordJoinChannelService({endTs:Date.now(),status:"success"},c),this.joinGatewayRecordIndex=c}catch(e){const t="closed"===this.state,s=e instanceof I,_=s&&e.code===E.WS_ABORT,i=s&&e.code===E.WS_ERR,r=s?e.message:e&&(e.reason||e.toString());l.warning("[choose-best-ws] chooseBestWebsocket error: ".concat(r)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:_?"aborted":"error",errors:[e]},c),t||i?(n.reject(t?new I(E.WS_DISCONNECT,"websocket is closed: ".concat(r)):new I(E.WS_ERR,"init websocket failed: ".concat(r))),i&&l.error("[".concat(this.name,"] init websocket failed: ").concat(r))):o&&o(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;l.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=N(this.reconnectCount,this.retryConfig);l.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 E=async(e,t)=>{this.emit(k.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e)};try{if("retry"===e)await E(this.urls[this.currentURLIndex],e);else if("tryNext"===e){if(this.currentURLIndex+=1,this.currentURLIndex>=this.urls.length)return this.reconnectWithAction("recover",!1);l.debug("[".concat(this.name,"] websocket url length: ").concat(this.urls.length," current index: ").concat(this.currentURLIndex)),await E(this.urls[this.currentURLIndex],e)}else"recover"===e&&(l.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.urls=await S(this,k.REQUEST_NEW_URLS),this.currentURLIndex=0,await E(this.urls[this.currentURLIndex],e))}catch(s){var n;l.error("[".concat(this.name,"] reconnect failed ").concat(s&&s.toString()));const E=null==s||null===(n=s.data)||void 0===n?void 0:n.desc;return Array.isArray(E)&&E.includes("dynamic key expired")?(this.emit(k.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):this.reconnectWithAction(e,t)}return!0}}class j extends J{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(t,s){return new Promise(((n,_)=>{let o=!1;const i=[];this.closeEstablishingWs=()=>{l.debug("[choose-best-ws] close establishing websockets"),i.forEach((e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close()})),_(new I(E.WS_ABORT,"choose best websocket aborted"))};const r=e("GATEWAY_DOMAINS");let c;const a=t.indexOf("?h="),R=r.find((e=>-1!==a?t.includes(e,a):t.includes(e)));l.debug("[choose-best-ws] currentDomain: ",R,", domains: ",r);let A=!this.tryDoubleDomain||!R;if(!A&&R){var N;const e=Date.now();try{r.forEach((e=>{const s=-1===a?t.replace(R,e):t.substr(0,a)+t.substr(a).replace(R,e),E=new WebSocket(s);E.binaryType="arraybuffer",i.push(E),l.debug("[choose-best-ws] ws is connecting:",E.url)}))}catch(e){for(l.debug("[choose-best-ws] ws create failed, fallback to single url"),i.forEach((e=>e.close()));i.length;)i.pop();A=!0}null===(N=this.store)||void 0===N||N.recordJoinChannelService({urls:i.map((e=>e.url)),service:"gateway"},s),i.forEach((t=>{t.onopen=()=>{if(o)return;const s=Date.now()-e;l.debug("[choose-best-ws] ws open cost ".concat(s,"ms")),i.filter((e=>e!==t)).forEach((e=>{l.debug("[choose-best-ws]close backup websocket: ".concat(e.url)),e.close()})),o=!0,n(t)},t.onclose=e=>{if(c=e,o)return;i.find((e=>!(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)))||(l.debug("[choose-best-ws] all websocket is closed"),o=!0,_(c))},t.onmessage=e=>{l.debug("[choose-best-ws]".concat(t.url," onmessage: ").concat(e.data))}})),h(this.forceCloseTimeout).then((()=>{i.forEach((e=>{e.readyState!==WebSocket.OPEN&&e.close()}))}))}if(A){var S;let e;l.debug("[choose-best-ws] use single url: ",t),null===(S=this.store)||void 0===S||S.recordJoinChannelService({urls:[t],service:"gateway"},s);try{e=new WebSocket(t),i.push(e),e.binaryType="arraybuffer"}catch(e){const t=new I(E.WS_ERR,"init websocket failed! Error: ".concat(e.toString()));return l.error("[".concat(this.name,"]").concat(t)),void _(t)}e.onopen=()=>{n(e)},e.onclose=e=>{_(e)},e.onmessage=t=>{l.debug("[choose-best-ws]".concat(e.url," onmessage: ").concat(t.data))},h(this.forceCloseTimeout).then((()=>{e&&e.readyState!==WebSocket.OPEN&&e.close()}))}})).then((e=>(this.closeEstablishingWs=void 0,e))).catch((e=>{throw this.closeEstablishingWs=void 0,e}))}}class q extends i{constructor(e,t,s){super(),this.ws=void 0,this.requestId=1,this.heartBeatTimer=void 0,this.joinInfo=void 0,this.clientId=void 0,this.onOpen=()=>{this.emit("open"),this.startHeartBeatCheck()},this.onClose=e=>{this.emit("close"),this.dispose()},this.onMessage=e=>{const t=JSON.parse(e.data);if(!t||"serverResponse"!==t.command||!t.requestId)return t&&"serverStatus"===t.command&&t.serverStatus&&t.serverStatus.command?(this.emit("status",t.serverStatus),void this.emit(t.serverStatus.command,t.serverStatus)):void 0;this.emit("req_".concat(t.requestId),t)},this.joinInfo=e,this.clientId=t,this.ws=new j("cross-channel-".concat(this.clientId),s),this.ws.on(k.RECONNECTING,(()=>{this.ws.reconnectMode="retry",this.emit("reconnecting")})),this.ws.on(k.CONNECTED,this.onOpen),this.ws.on(k.ON_MESSAGE,this.onMessage),this.ws.on(k.CLOSED,this.onClose)}isConnect(){return"connected"===this.ws.state}sendMessage(e){const t=this.requestId++;return e.requestId=t,e.seq=t,this.ws.sendMessage(e),t}waitStatus(e){return new Promise(((t,s)=>{const E=window.setTimeout((()=>{s(new L(d.TIMEOUT,"wait status timeout, status: ".concat(e)))}),5e3);this.once(e,(n=>{window.clearTimeout(E),n.state&&0!==n.state?s(new L(d.CROSS_CHANNEL_WAIT_STATUS_ERROR,"wait status error, status: ".concat(e))):t(void 0)})),this.once("dispose",(()=>{window.clearTimeout(E),s(new L(d.WS_ABORT))}))}))}async request(e){if("closed"===this.ws.state)throw new L(d.WS_DISCONNECT);const t=()=>new Promise(((e,t)=>{this.ws.once(k.CLOSED,(()=>t(new L(d.WS_ABORT)))),this.ws.once(k.CONNECTED,e)}));"connected"!==this.ws.state&&await t();const s=this.sendMessage(e),E=new Promise(((e,t)=>{const E=()=>{t(new L(d.WS_ABORT))};this.ws.once(k.RECONNECTING,E),this.ws.once(k.CLOSED,E),this.once("req_".concat(s),e),h(3e3).then((()=>{this.removeAllListeners("req_".concat(s)),this.ws.off(k.RECONNECTING,E),this.ws.off(k.CLOSED,E),t(new L(d.TIMEOUT,"cross channel ws request timeout"))}))})),n=await E;if(!n||200!==n.code)throw new L(d.CROSS_CHANNEL_SERVER_ERROR_RESPONSE,"response: ".concat(JSON.stringify(n)));return n}async connect(e){this.ws.removeAllListeners(k.REQUEST_NEW_URLS),this.ws.on(k.REQUEST_NEW_URLS,(t=>{t(e)})),await this.ws.init(e)}dispose(){this.clearHeartBeatCheck(),this.emit("dispose"),this.removeAllListeners(),this.ws.close()}sendPing(e){const t=this.requestId++;return e.requestId=t,this.ws.sendMessage(e),t}startHeartBeatCheck(){this.heartBeatTimer&&window.clearInterval(this.heartBeatTimer),this.heartBeatTimer=window.setInterval((()=>{this.sendPing({command:"ping",appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sid:this.joinInfo.sid,ts:+new Date,requestId:0})}),3e3)}clearHeartBeatCheck(){window.clearInterval(this.heartBeatTimer),this.heartBeatTimer=void 0}}class x extends i{set state(e){e!==this._state&&(e!==W.RELAY_STATE_FAILURE&&(this.errorCode=G.RELAY_OK),this.emit("state",e,this.errorCode),this._state=e)}get state(){return this._state}constructor(e,t,s,E,n){super(),this.joinInfo=void 0,this.sid=void 0,this.clientId=void 0,this.cancelToken=u.CancelToken.source(),this.workerToken=void 0,this.requestId=0,this.signal=void 0,this.prevChannelMediaConfig=void 0,this.httpRetryConfig=void 0,this._resolution=void 0,this._state=W.RELAY_STATE_IDLE,this.errorCode=G.RELAY_OK,this.onStatus=e=>{l.debug("[".concat(this.clientId,"] ChannelMediaStatus: ").concat(JSON.stringify(e))),e&&e.command&&("onAudioPacketReceived"===e.command&&this.emit("event",Y.PACKET_RECEIVED_AUDIO_FROM_SRC),"onVideoPacketReceived"===e.command&&this.emit("event",Y.PACKET_RECEIVED_VIDEO_FROM_SRC),"onSrcTokenPrivilegeDidExpire"===e.command&&(this.errorCode=G.SRC_TOKEN_EXPIRED,this.state=W.RELAY_STATE_FAILURE),"onDestTokenPrivilegeDidExpire"===e.command&&(this.errorCode=G.DEST_TOKEN_EXPIRED,this.state=W.RELAY_STATE_FAILURE))},this.onReconnect=async()=>{l.debug("[".concat(this.clientId,"] ChannelMediaSocket disconnect, reconnecting")),this.emit("event",Y.NETWORK_DISCONNECTED),this.state=W.RELAY_STATE_IDLE,this.prevChannelMediaConfig&&this.sendStartRelayMessage(this.prevChannelMediaConfig).catch((e=>{this.state!==W.RELAY_STATE_IDLE&&(l.error("auto restart channel media relay failed",e.toString()),this.errorCode=G.SERVER_CONNECTION_LOST,this.state=W.RELAY_STATE_FAILURE)}))},this.joinInfo=e,this.clientId=t,this.sid=C(),this.signal=new q(this.joinInfo,this.clientId,s),this.httpRetryConfig=E,this._resolution=n}async startChannelMediaRelay(e){if(this.state!==W.RELAY_STATE_IDLE)throw new L(d.INVALID_OPERATION);this.state=W.RELAY_STATE_CONNECTING,await this.connect(),l.debug("[".concat(this.clientId,"] startChannelMediaRelay: connect success"));try{await this.sendStartRelayMessage(e)}catch(e){if(e.data&&e.data.serverResponse&&"SetSourceChannel"===e.data.serverResponse.command)throw new L(d.CROSS_CHANNEL_FAILED_JOIN_SRC);if(e.data&&e.data.serverResponse&&"SetDestChannelStatus"===e.serverResponse.command)throw new L(d.CROSS_CHANNEL_FAILED_JOIN_DEST);if(e.data&&e.data.serverResponse&&"StartPacketTransfer"===e.serverResponse.command)throw new L(d.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST);throw e}this.prevChannelMediaConfig=e}async updateChannelMediaRelay(e){if(this.state!==W.RELAY_STATE_RUNNING)throw new L(d.INVALID_OPERATION);await this.sendUpdateMessage(e),this.prevChannelMediaConfig=e}async setVideoProfile(e){if(this._resolution=e,this.state!==W.RELAY_STATE_RUNNING)throw new L(d.INVALID_OPERATION);const t=this.genMessage(H.SetVideoProfile);await this.signal.request(t),l.debug("[".concat(this.clientId,"] startChannelMediaRelay: setVideoProfile success"))}async stopChannelMediaRelay(){await this.sendStopRelayMessage(),l.debug("[".concat(this.clientId,"] stopChannelMediaRelay: send stop message success")),this.state=W.RELAY_STATE_IDLE,this.dispose()}dispose(){l.debug("[".concat(this.clientId,"] disposeChannelMediaRelay")),this.cancelToken.cancel(),this.cancelToken=u.CancelToken.source(),this.state=W.RELAY_STATE_IDLE,this.emit("dispose"),this.signal.dispose(),this.prevChannelMediaConfig=void 0}async connect(){const e=await K(this.joinInfo,this.cancelToken.token,this.httpRetryConfig);this.workerToken=e.workerToken,await this.signal.connect(e.addressList),this.emit("event",Y.NETWORK_CONNECTED),this.signal.on("status",this.onStatus),this.signal.on("reconnecting",this.onReconnect)}async sendStartRelayMessage(e){const t=this.genMessage(H.StopPacketTransfer);await this.signal.request(t),await this.signal.waitStatus("Normal Quit"),l.debug("[".concat(this.clientId,"] startChannelMediaRelay: StopPacketTransfer success"));const s=this.genMessage(H.SetSdkProfile,e);await this.signal.request(s),l.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSdkProfile success"));const E=this.genMessage(H.SetSourceChannel,e);await this.signal.request(E),await this.signal.waitStatus("SetSourceChannelStatus"),this.emit("event",Y.PACKET_JOINED_SRC_CHANNEL),l.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceChannel success"));const n=this.genMessage(H.SetSourceUserId,e);await this.signal.request(n),l.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceUserId success"));const _=this.genMessage(H.SetDestChannel,e);await this.signal.request(_),await this.signal.waitStatus("SetDestChannelStatus"),this.emit("event",Y.PACKET_JOINED_DEST_CHANNEL),l.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetDestChannel success"));const o=this.genMessage(H.StartPacketTransfer,e);await this.signal.request(o),this.emit("event",Y.PACKET_SENT_TO_DEST_CHANNEL),this.state=W.RELAY_STATE_RUNNING,l.debug("[".concat(this.clientId,"] startChannelMediaRelay: StartPacketTransfer success")),this.setVideoProfile(this._resolution)}async sendUpdateMessage(e){const t=this.genMessage(H.UpdateDestChannel,e);await this.signal.request(t),this.emit("event",Y.PACKET_UPDATE_DEST_CHANNEL),l.debug("[".concat(this.clientId,"] sendUpdateMessage: UpdateDestChannel success"))}async sendStopRelayMessage(){const e=this.genMessage(H.StopPacketTransfer);await this.signal.request(e),l.debug("[".concat(this.clientId,"] sendStopRelayMessage: StopPacketTransfer success"))}genMessage(e,t){const s=[],E=[],n=[];this.requestId+=1;const o={appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sdkVersion:_,sid:this.sid,ts:Date.now(),requestId:this.requestId,seq:this.requestId,allocate:!0,clientRequest:{}};"4.23.0"===o.sdkVersion&&(o.sdkVersion="0.0.1");let i=null,r=null;switch(e){case H.SetSdkProfile:return o.clientRequest={command:"SetSdkProfile",type:"multi_channel"},o;case H.SetSourceChannel:if(r=t&&t.getSrcChannelMediaInfo(),!r)throw new L(d.UNEXPECTED_ERROR,"can not find source config");return o.clientRequest={command:"SetSourceChannel",uid:"0",channelName:r.channelName,token:r.token||this.joinInfo.appId},o;case H.SetSourceUserId:if(r=t&&t.getSrcChannelMediaInfo(),!r)throw new L(d.UNEXPECTED_ERROR,"can not find source config");return o.clientRequest={command:"SetSourceUserId",uid:r.uid+""},o;case H.SetDestChannel:if(i=t&&t.getDestChannelMediaInfo(),!i)throw new L(d.UNEXPECTED_ERROR,"can not find dest config");return i.forEach((e=>{s.push(e.channelName),E.push(e.uid+""),n.push(e.token||this.joinInfo.appId)})),o.clientRequest={command:"SetDestChannel",channelName:s,uid:E,token:n},o;case H.StartPacketTransfer:return o.clientRequest={command:"StartPacketTransfer"},o;case H.Reconnect:return o.clientRequest={command:"Reconnect"},o;case H.StopPacketTransfer:return o.clientRequest={command:"StopPacketTransfer"},o;case H.UpdateDestChannel:if(i=t&&t.getDestChannelMediaInfo(),!i)throw new L(d.UNEXPECTED_ERROR,"can not find dest config");return i.forEach((e=>{s.push(e.channelName),E.push(e.uid+""),n.push(e.token||this.joinInfo.appId)})),o.clientRequest={command:"UpdateDestChannel",channelName:s,uid:E,token:n},o;case H.SetVideoProfile:o.clientRequest={command:"SetVideoProfile",width:this._resolution.width,height:this._resolution.height}}return o}}const X={name:"ChannelMediaRelay",create:function(e){return new x(e.joinInfo,e.clientId,e.websocketRetryConfig||O,e.httpRetryConfig||O,e.resolution)}};export{X as ChannelMediaRelayService}; | ||
import{getParameter as e,getUTF8StringByteLength as t,getMultiUnilbsFormDataByteLength as s,AgoraRTCErrorCode as E,IS_GLOBAL_VERSION as n,VERSION as _,retryable as o,EventEmitter as i,PromiseMutex as r,NETWORK_STATE as c,networkIndicator as a,NETWORK_INDICATOR_EVENTS as R,createDefer as A,AgoraRTCError as I,getRetryWaitTime as N,wait as h,emitAsPromise as S,emitAsInvokerNoResponse as T,generateSessionID as C,DEFAULT_RETRY_CONFIG as O}from"@agora-js/shared";import{AgoraRTCError as L,AgoraRTCErrorCode as d,logger as l}from"@agora-js/report";import u from"axios";import"formdata-polyfill";function D(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 E=s.call(e,t||"default");if("object"!=typeof E)return E;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 w(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var E=Object.getOwnPropertySymbols(e);t&&(E=E.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,E)}return s}let V=0,g=0;let P=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}({}),U=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}({}),f=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}({}),M=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}({}),m=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.DATASTREAM2_NOT_AVAILABLE=27]="DATASTREAM2_NOT_AVAILABLE",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}({});P.ACCESS_POINT,M.NO_FLAG_SET,M.FLAG_SET_BUT_EMPTY,M.INVALID_FALG_SET,M.FLAG_SET_BUT_NO_RE,M.INVALID_SERVICE_ID,M.NO_SERVICE_AVAILABLE,M.NO_SERVICE_AVAILABLE_P2P,M.NO_SERVICE_AVAILABLE_VOICE,M.NO_SERVICE_AVAILABLE_WEBRTC,M.NO_SERVICE_AVAILABLE_CDS,M.NO_SERVICE_AVAILABLE_CDN,M.NO_SERVICE_AVAILABLE_TDS,M.NO_SERVICE_AVAILABLE_REPORT,M.NO_SERVICE_AVAILABLE_APP_CENTER,M.NO_SERVICE_AVAILABLE_ENV0,M.NO_SERVICE_AVAILABLE_VOET,M.NO_SERVICE_AVAILABLE_STRING_UID,M.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS,P.UNILBS,f.INVALID_VENDOR_KEY,f.INVALID_CHANNEL_NAME,f.INTERNAL_ERROR,f.NO_AUTHORIZED,f.DYNAMIC_KEY_TIMEOUT,f.NO_ACTIVE_STATUS,f.DYNAMIC_KEY_EXPIRED,f.STATIC_USE_DYNAMIC_KEY,f.DYNAMIC_USE_STATIC_KEY,f.USER_OVERLOAD,f.FORBIDDEN_REGION,f.CANNOT_MEET_AREA_DEMAND,P.STRING_UID_ALLOCATOR,U.IIIEGAL_APPID,U.IIIEGAL_UID,U.INTERNAL_ERROR,m.K_TIMESTAMP_EXPIRED,m.K_CHANNEL_PERMISSION_INVALID,m.K_CERTIFICATE_INVALID,m.K_CHANNEL_NAME_EMPTY,m.K_CHANNEL_NOT_FOUND,m.K_TICKET_INVALID,m.K_CHANNEL_CONFLICTED,m.K_SERVICE_NOT_READY,m.K_SERVICE_TOO_HEAVY,m.K_UID_BANNED,m.K_IP_BANNED,m.DATASTREAM2_NOT_AVAILABLE,m.K_AUTO_REBALANCE,m.ERR_INVALID_VENDOR_KEY,m.ERR_INVALID_CHANNEL_NAME,m.WARN_NO_AVAILABLE_CHANNEL,m.WARN_LOOKUP_CHANNEL_TIMEOUT,m.WARN_LOOKUP_CHANNEL_REJECTED,m.WARN_OPEN_CHANNEL_TIMEOUT,m.WARN_OPEN_CHANNEL_REJECTED,m.WARN_REQUEST_DEFERRED,m.ERR_DYNAMIC_KEY_TIMEOUT,m.ERR_NO_AUTHORIZED,m.ERR_VOM_SERVICE_UNAVAILABLE,m.ERR_NO_CHANNEL_AVAILABLE_CODE,m.ERR_MASTER_VOCS_UNAVAILABLE,m.ERR_INTERNAL_ERROR,m.ERR_NO_ACTIVE_STATUS,m.ERR_INVALID_UID,m.ERR_DYNAMIC_KEY_EXPIRED,m.ERR_STATIC_USE_DYANMIC_KE,m.ERR_DYNAMIC_USE_STATIC_KE,m.ERR_NO_VOCS_AVAILABLE,m.ERR_NO_VOS_AVAILABLE,m.ERR_JOIN_CHANNEL_TIMEOUT,m.ERR_JOIN_BY_MULTI_IP,m.ERR_NOT_JOINED,m.ERR_REPEAT_JOIN_REQUEST,m.ERR_REPEAT_JOIN_CHANNEL,m.ERR_INVALID_STRINGUID,m.ERR_TOO_MANY_USERS,m.ERR_SET_CLIENT_ROLE_TIMEOUT,m.ERR_SET_CLIENT_ROLE_NO_PERMISSION,m.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE,m.ERR_PUBLISH_REQUEST_INVALID,m.ERR_SUBSCRIBE_REQUEST_INVALID,m.ERR_NOT_SUPPORTED_MESSAGE,m.ERR_ILLEAGAL_PLUGIN,m.ILLEGAL_CLIENT_ROLE_LEVEL,m.ERR_REJOIN_TOKEN_INVALID,m.ERR_REJOIN_USER_NOT_JOINED,m.ERR_INVALID_OPTIONAL_INFO,m.ERR_TEST_RECOVER,m.ERR_TEST_TRYNEXT,m.ERR_TEST_RETRY,m.ILLEGAL_AES_PASSWORD,m.ERR_TOO_MANY_BROADCASTERS,m.ERR_TOO_MANY_SUBSCRIBERS,m.ERR_LICENSE_ILLEGAL,m.ERR_LICENSE_MISSING,m.ERR_LICENSE_EXPIRED,m.ERR_LICENSE_MINUTES_EXCEEDED,m.ERR_LICENSE_PERIOD_INVALID,m.ERR_LICENSE_MULTIPLE_SDK_SERVICE;let p=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}({});p.AFRICA,p.ASIA,p.CHINA,p.EUROPE,p.GLOBAL,p.INDIA,p.JAPAN,p.NORTH_AMERICA,p.OCEANIA,p.OVERSEA,p.SOUTH_AMERICA;let b=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}({});b.ASIA,b.NORTH_AMERICA,b.EUROPE,b.JAPAN,b.INDIA,b.KOREA,b.HKMC,b.US,b.OVERSEA,b.GLOBAL,b.OCEANIA,b.SOUTH_AMERICA,b.AFRICA,n&&b.CHINA;const v={GLOBAL:{ASIA:[p.CHINA,p.JAPAN,p.INDIA,p.KOREA,p.HKMC],EUROPE:[],NORTH_AMERICA:[p.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}};Object.keys(v[p.GLOBAL]),p.CHINA,p.NORTH_AMERICA,p.EUROPE,p.ASIA,p.JAPAN,p.INDIA,p.OCEANIA,p.SOUTH_AMERICA,p.AFRICA,p.KOREA,p.HKMC,p.US;let B=1;function y(n,i,r,c){const a={command:"convergeAllocateEdge",sid:i.sid,appId:i.appId,token:i.token,ts:Date.now(),version:_,cname:i.cname,uid:i.uid.toString(),requestId:B,seq:B};B+=1;const R={service_name:"tele_channel",json_body:JSON.stringify(a)};return o((async()=>{const _=await function(n,_,o,i){return new Promise(((r,c)=>{_.timeout=_.timeout||e("HTTP_CONNECT_TIMEOUT"),_.responseType=_.responseType||"json",_.data&&!o?(_.data=JSON.stringify(_.data),V+=t(_.data)):o&&(_.data.size?V+=_.data.size:_.data instanceof FormData?V+=s(_.data):V+=t(JSON.stringify(_.data))),_.headers=_.headers||{},_.headers["Content-Type"]=_.headers["Content-Type"]||"application/json",_.method="POST",_.url=n,u.request(_).then((e=>{"string"==typeof e.data?g+=t(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?g+=e.data.byteLength:g+=t(JSON.stringify(e.data)),i&&r({data:e.data,headers:e.headers}),r(e.data)})).catch((e=>{u.isCancel(e)?c(new L(E.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?c(new L(E.NETWORK_TIMEOUT,e.message)):e.response?c(new L(E.NETWORK_RESPONSE_ERROR,e.response.status)):c(new L(E.NETWORK_ERROR,e.message))}))}))}(n,{data:R,cancelToken:r,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":61}});if(0!==_.code){const e=new L(d.UNEXPECTED_RESPONSE,"cross channel ap error, code"+_.code,{retry:!0});throw l.error(e.toString()),e}const o=JSON.parse(_.json_body);if(200!==o.code){const e=new L(d.UNEXPECTED_RESPONSE,"cross channel app center error, code: ".concat(o.code,", reason: ").concat(o.reason));throw l.error(e.toString()),e}if(!o.servers||0===o.servers.length){const e=new L(d.UNEXPECTED_RESPONSE,"cross channel app center empty server");throw l.error(e.toString()),e}return{vid:o.vid,workerToken:o.workerToken,addressList:(e("CHANNEL_MEDIA_RELAY_SERVERS")||o.servers).map((t=>"wss://".concat(t.address.replace(/\./g,"-"),".").concat(e("WORKER_DOMAIN"),":").concat(t.wss)))}}),void 0,(e=>!!(e.code!==d.OPERATION_ABORTED&&e.code!==d.UNEXPECTED_RESPONSE||e.data&&e.data.retry)),c)}async function K(t,s,E){const n=e("UAP_AP").slice(0,e("AJAX_REQUEST_CONCURRENT")).map((e=>t.proxyServer?"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1?action=uap"):"https://".concat(e,"/api/v1?action=uap"))).map((e=>y(e,t,s,E)));try{const e=await(_=n,Promise.all(_.map((e=>e.then((e=>{throw e}),(e=>e))))).then((e=>{throw e}),(e=>e)));return n.forEach((e=>e.cancel())),e}catch(e){throw e[0]}var _}let k=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_CREATE_CONNECTION="websocket:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="websocket:on_token_privilege_did_expire",e}({}),H=function(e){return e[e.SetSdkProfile=0]="SetSdkProfile",e[e.SetSourceChannel=1]="SetSourceChannel",e[e.SetSourceUserId=2]="SetSourceUserId",e[e.SetDestChannel=3]="SetDestChannel",e[e.StartPacketTransfer=4]="StartPacketTransfer",e[e.StopPacketTransfer=5]="StopPacketTransfer",e[e.UpdateDestChannel=6]="UpdateDestChannel",e[e.Reconnect=7]="Reconnect",e[e.SetVideoProfile=8]="SetVideoProfile",e}({}),Y=function(e){return e.NETWORK_DISCONNECTED="NETWORK_DISCONNECTED",e.NETWORK_CONNECTED="NETWORK_CONNECTED",e.PACKET_JOINED_SRC_CHANNEL="PACKET_JOINED_SRC_CHANNEL",e.PACKET_JOINED_DEST_CHANNEL="PACKET_JOINED_DEST_CHANNEL",e.PACKET_SENT_TO_DEST_CHANNEL="PACKET_SENT_TO_DEST_CHANNEL",e.PACKET_RECEIVED_VIDEO_FROM_SRC="PACKET_RECEIVED_VIDEO_FROM_SRC",e.PACKET_RECEIVED_AUDIO_FROM_SRC="PACKET_RECEIVED_AUDIO_FROM_SRC",e.PACKET_UPDATE_DEST_CHANNEL="PACKET_UPDATE_DEST_CHANNEL",e.PACKET_UPDATE_DEST_CHANNEL_REFUSED="PACKET_UPDATE_DEST_CHANNEL_REFUSED",e.PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE="PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE",e}({}),W=function(e){return e.RELAY_STATE_IDLE="RELAY_STATE_IDLE",e.RELAY_STATE_CONNECTING="RELAY_STATE_CONNECTING",e.RELAY_STATE_RUNNING="RELAY_STATE_RUNNING",e.RELAY_STATE_FAILURE="RELAY_STATE_FAILURE",e}({}),G=function(e){return e.RELAY_OK="RELAY_OK",e.SERVER_CONNECTION_LOST="SERVER_CONNECTION_LOST",e.SRC_TOKEN_EXPIRED="SRC_TOKEN_EXPIRED",e.DEST_TOKEN_EXPIRED="DEST_TOKEN_EXPIRED",e}({}),F=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_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 J extends i{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(k.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(k.CONNECTED):"closed"===this._state?this.emit(k.CLOSED):"failed"===this._state&&this.emit(k.FAILED))}resetReconnectCount(e){l.debug("websocket reset reconnect count, reason: "+e),this.reconnectCount=0}constructor(e,t){let s=arguments.length>2&&void 0!==arguments[2]&&arguments[2],E=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=arguments.length>4&&void 0!==arguments[4]&&arguments[4],_=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=void 0,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=_,this.name=e,this.retryConfig=function(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?w(Object(s),!0).forEach((function(t){D(e,t,s[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):w(Object(s)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))}))}return e}({},t),this.useCompress=s,this.tryDoubleDomain=E,this.use443PortOnly=n,this._initMutex=new r("websocket",_?_.clientId:void 0);const{timeout:o,timeoutFactor:i}=t,A=Math.max(300,Math.floor(3*o/5)),I=Math.max(1.2,Math.floor(8*i)/10);c.ONLINE&&(this.retryConfig.timeout=A,this.retryConfig.timeoutFactor=I),a.on(R.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===c.ONLINE?(this.retryConfig.timeout=A,this.retryConfig.timeoutFactor=I):(this.retryConfig.timeout=o,this.retryConfig.timeoutFactor=i))}))}getConnection(){return this.websocket||void 0}async init(t){let s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const n=await this._initMutex.lock();this._reconnectMode="tryNext",this.forceCloseTimeout=s,this.urls=t,this.state="connecting";try{const t=A(),s=this.urls[this.currentURLIndex];e("ENABLE_PREALLOC_PC")&&this.emit(F.PRE_CONNECT_PC),this.createWebSocketConnection(s).then(t.resolve).catch(t.reject),this.once(k.CLOSED,(()=>{t.reject(new I(E.WS_DISCONNECT))})),this.once(k.CONNECTED,t.resolve),await t.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 l.warning("[".concat(this.name,"] can not reconnect, no websocket"));void 0!==e&&(this.reconnectMode=e),l.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 t=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new I(E.WS_ABORT,"websocket is not ready");try{t||(e=JSON.stringify(e)),this.websocket.send(e)}catch(e){throw new I(E.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(t){var s;const n=A();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const _=e=>{var t;null===(t=this.store)||void 0===t||t.signalChannelOpen(),l.debug("[".concat(this.name,"] websocket opened:"),e),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),n.resolve()},o=async e=>{var t;if(l.debug("[".concat(this.name,"] websocket close ").concat(null===(t=this.websocket)||void 0===t?void 0:t.url,", code: ").concat(e.code,", reason: ").concat(e.reason,", current mode: ").concat(this.reconnectMode)),this.reconnectCount>=this.retryConfig.maxRetryCount)n.reject(new I(E.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close();else{"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");const t=T(this,k.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,s=await this.reconnectWithAction(t);if("closed"===this.state)return void l.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!s)return n.reject(new I(E.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);n.resolve()}},i=e=>{this.emit(k.ON_MESSAGE,e)},r=e=>{l.warn("[".concat(this.connectionID,"] ws open error ").concat(e))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),e("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(t=e("GATEWAY_WSS_ADDRESS")),l.debug("[".concat(this.name,"] start connect, url:"),t);const c=null===(s=this.store)||void 0===s?void 0:s.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});try{var a;const e=await this.chooseBestWebsocketConnection(t);this.websocket=e,_&&_(this.websocket.url),this.websocket.onclose=o,this.websocket.onmessage=i,this.websocket.onerror=r,null===(a=this.store)||void 0===a||a.recordJoinChannelService({endTs:Date.now(),status:"success"},c),this.joinGatewayRecordIndex=c}catch(e){const t="closed"===this.state,s=e instanceof I,_=s&&e.code===E.WS_ABORT,i=s&&e.code===E.WS_ERR,r=s?e.message:e&&(e.reason||e.toString());l.warning("[choose-best-ws] chooseBestWebsocket error: ".concat(r)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:_?"aborted":"error",errors:[e]},c),t||i?(n.reject(t?new I(E.WS_DISCONNECT,"websocket is closed: ".concat(r)):new I(E.WS_ERR,"init websocket failed: ".concat(r))),i&&l.error("[".concat(this.name,"] init websocket failed: ").concat(r))):o&&o(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;l.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=N(this.reconnectCount,this.retryConfig);l.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 E=async(e,t)=>{this.emit(k.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e)};try{if("retry"===e)await E(this.urls[this.currentURLIndex],e);else if("tryNext"===e){if(this.currentURLIndex+=1,this.currentURLIndex>=this.urls.length)return this.reconnectWithAction("recover",!1);l.debug("[".concat(this.name,"] websocket url length: ").concat(this.urls.length," current index: ").concat(this.currentURLIndex)),await E(this.urls[this.currentURLIndex],e)}else"recover"===e&&(l.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.urls=await S(this,k.REQUEST_NEW_URLS),this.currentURLIndex=0,await E(this.urls[this.currentURLIndex],e))}catch(s){var n;l.error("[".concat(this.name,"] reconnect failed ").concat(s&&s.toString()));const E=null==s||null===(n=s.data)||void 0===n?void 0:n.desc;return Array.isArray(E)&&E.includes("dynamic key expired")?(this.emit(k.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):this.reconnectWithAction(e,t)}return!0}}class j extends J{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(t,s){return new Promise(((n,_)=>{let o=!1;const i=[];this.closeEstablishingWs=()=>{l.debug("[choose-best-ws] close establishing websockets"),i.forEach((e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close()})),_(new I(E.WS_ABORT,"choose best websocket aborted"))};const r=e("GATEWAY_DOMAINS");let c;const a=t.indexOf("?h="),R=r.find((e=>-1!==a?t.includes(e,a):t.includes(e)));l.debug("[choose-best-ws] currentDomain: ",R,", domains: ",r);let A=!this.tryDoubleDomain||!R;if(!A&&R){var N;const e=Date.now();try{r.forEach((e=>{const s=-1===a?t.replace(R,e):t.substr(0,a)+t.substr(a).replace(R,e),E=new WebSocket(s);E.binaryType="arraybuffer",i.push(E),l.debug("[choose-best-ws] ws is connecting:",E.url)}))}catch(e){for(l.debug("[choose-best-ws] ws create failed, fallback to single url"),i.forEach((e=>e.close()));i.length;)i.pop();A=!0}null===(N=this.store)||void 0===N||N.recordJoinChannelService({urls:i.map((e=>e.url)),service:"gateway"},s),i.forEach((t=>{t.onopen=()=>{if(o)return;const s=Date.now()-e;l.debug("[choose-best-ws] ws open cost ".concat(s,"ms")),i.filter((e=>e!==t)).forEach((e=>{l.debug("[choose-best-ws]close backup websocket: ".concat(e.url)),e.close()})),o=!0,n(t)},t.onclose=e=>{if(c=e,o)return;i.find((e=>!(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)))||(l.debug("[choose-best-ws] all websocket is closed"),o=!0,_(c))},t.onmessage=e=>{l.debug("[choose-best-ws]".concat(t.url," onmessage: ").concat(e.data))}})),h(this.forceCloseTimeout).then((()=>{i.forEach((e=>{e.readyState!==WebSocket.OPEN&&e.close()}))}))}if(A){var S;let e;l.debug("[choose-best-ws] use single url: ",t),null===(S=this.store)||void 0===S||S.recordJoinChannelService({urls:[t],service:"gateway"},s);try{e=new WebSocket(t),i.push(e),e.binaryType="arraybuffer"}catch(e){const t=new I(E.WS_ERR,"init websocket failed! Error: ".concat(e.toString()));return l.error("[".concat(this.name,"]").concat(t)),void _(t)}e.onopen=()=>{n(e)},e.onclose=e=>{_(e)},e.onmessage=t=>{l.debug("[choose-best-ws]".concat(e.url," onmessage: ").concat(t.data))},h(this.forceCloseTimeout).then((()=>{e&&e.readyState!==WebSocket.OPEN&&e.close()}))}})).then((e=>(this.closeEstablishingWs=void 0,e))).catch((e=>{throw this.closeEstablishingWs=void 0,e}))}}class q extends i{constructor(e,t,s){super(),this.ws=void 0,this.requestId=1,this.heartBeatTimer=void 0,this.joinInfo=void 0,this.clientId=void 0,this.onOpen=()=>{this.emit("open"),this.startHeartBeatCheck()},this.onClose=e=>{this.emit("close"),this.dispose()},this.onMessage=e=>{const t=JSON.parse(e.data);if(!t||"serverResponse"!==t.command||!t.requestId)return t&&"serverStatus"===t.command&&t.serverStatus&&t.serverStatus.command?(this.emit("status",t.serverStatus),void this.emit(t.serverStatus.command,t.serverStatus)):void 0;this.emit("req_".concat(t.requestId),t)},this.joinInfo=e,this.clientId=t,this.ws=new j("cross-channel-".concat(this.clientId),s),this.ws.on(k.RECONNECTING,(()=>{this.ws.reconnectMode="retry",this.emit("reconnecting")})),this.ws.on(k.CONNECTED,this.onOpen),this.ws.on(k.ON_MESSAGE,this.onMessage),this.ws.on(k.CLOSED,this.onClose)}isConnect(){return"connected"===this.ws.state}sendMessage(e){const t=this.requestId++;return e.requestId=t,e.seq=t,this.ws.sendMessage(e),t}waitStatus(e){return new Promise(((t,s)=>{const E=window.setTimeout((()=>{s(new L(d.TIMEOUT,"wait status timeout, status: ".concat(e)))}),5e3);this.once(e,(n=>{window.clearTimeout(E),n.state&&0!==n.state?s(new L(d.CROSS_CHANNEL_WAIT_STATUS_ERROR,"wait status error, status: ".concat(e))):t(void 0)})),this.once("dispose",(()=>{window.clearTimeout(E),s(new L(d.WS_ABORT))}))}))}async request(e){if("closed"===this.ws.state)throw new L(d.WS_DISCONNECT);const t=()=>new Promise(((e,t)=>{this.ws.once(k.CLOSED,(()=>t(new L(d.WS_ABORT)))),this.ws.once(k.CONNECTED,e)}));"connected"!==this.ws.state&&await t();const s=this.sendMessage(e),E=new Promise(((e,t)=>{const E=()=>{t(new L(d.WS_ABORT))};this.ws.once(k.RECONNECTING,E),this.ws.once(k.CLOSED,E),this.once("req_".concat(s),e),h(3e3).then((()=>{this.removeAllListeners("req_".concat(s)),this.ws.off(k.RECONNECTING,E),this.ws.off(k.CLOSED,E),t(new L(d.TIMEOUT,"cross channel ws request timeout"))}))})),n=await E;if(!n||200!==n.code)throw new L(d.CROSS_CHANNEL_SERVER_ERROR_RESPONSE,"response: ".concat(JSON.stringify(n)));return n}async connect(e){this.ws.removeAllListeners(k.REQUEST_NEW_URLS),this.ws.on(k.REQUEST_NEW_URLS,(t=>{t(e)})),await this.ws.init(e)}dispose(){this.clearHeartBeatCheck(),this.emit("dispose"),this.removeAllListeners(),this.ws.close()}sendPing(e){const t=this.requestId++;return e.requestId=t,this.ws.sendMessage(e),t}startHeartBeatCheck(){this.heartBeatTimer&&window.clearInterval(this.heartBeatTimer),this.heartBeatTimer=window.setInterval((()=>{this.sendPing({command:"ping",appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sid:this.joinInfo.sid,ts:+new Date,requestId:0})}),3e3)}clearHeartBeatCheck(){window.clearInterval(this.heartBeatTimer),this.heartBeatTimer=void 0}}class x extends i{set state(e){e!==this._state&&(e!==W.RELAY_STATE_FAILURE&&(this.errorCode=G.RELAY_OK),this.emit("state",e,this.errorCode),this._state=e)}get state(){return this._state}constructor(e,t,s,E,n){super(),this.joinInfo=void 0,this.sid=void 0,this.clientId=void 0,this.cancelToken=u.CancelToken.source(),this.workerToken=void 0,this.requestId=0,this.signal=void 0,this.prevChannelMediaConfig=void 0,this.httpRetryConfig=void 0,this._resolution=void 0,this._state=W.RELAY_STATE_IDLE,this.errorCode=G.RELAY_OK,this.onStatus=e=>{l.debug("[".concat(this.clientId,"] ChannelMediaStatus: ").concat(JSON.stringify(e))),e&&e.command&&("onAudioPacketReceived"===e.command&&this.emit("event",Y.PACKET_RECEIVED_AUDIO_FROM_SRC),"onVideoPacketReceived"===e.command&&this.emit("event",Y.PACKET_RECEIVED_VIDEO_FROM_SRC),"onSrcTokenPrivilegeDidExpire"===e.command&&(this.errorCode=G.SRC_TOKEN_EXPIRED,this.state=W.RELAY_STATE_FAILURE),"onDestTokenPrivilegeDidExpire"===e.command&&(this.errorCode=G.DEST_TOKEN_EXPIRED,this.state=W.RELAY_STATE_FAILURE))},this.onReconnect=async()=>{l.debug("[".concat(this.clientId,"] ChannelMediaSocket disconnect, reconnecting")),this.emit("event",Y.NETWORK_DISCONNECTED),this.state=W.RELAY_STATE_IDLE,this.prevChannelMediaConfig&&this.sendStartRelayMessage(this.prevChannelMediaConfig).catch((e=>{this.state!==W.RELAY_STATE_IDLE&&(l.error("auto restart channel media relay failed",e.toString()),this.errorCode=G.SERVER_CONNECTION_LOST,this.state=W.RELAY_STATE_FAILURE)}))},this.joinInfo=e,this.clientId=t,this.sid=C(),this.signal=new q(this.joinInfo,this.clientId,s),this.httpRetryConfig=E,this._resolution=n}async startChannelMediaRelay(e){if(this.state!==W.RELAY_STATE_IDLE)throw new L(d.INVALID_OPERATION);this.state=W.RELAY_STATE_CONNECTING,await this.connect(),l.debug("[".concat(this.clientId,"] startChannelMediaRelay: connect success"));try{await this.sendStartRelayMessage(e)}catch(e){if(e.data&&e.data.serverResponse&&"SetSourceChannel"===e.data.serverResponse.command)throw new L(d.CROSS_CHANNEL_FAILED_JOIN_SRC);if(e.data&&e.data.serverResponse&&"SetDestChannelStatus"===e.serverResponse.command)throw new L(d.CROSS_CHANNEL_FAILED_JOIN_DEST);if(e.data&&e.data.serverResponse&&"StartPacketTransfer"===e.serverResponse.command)throw new L(d.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST);throw e}this.prevChannelMediaConfig=e}async updateChannelMediaRelay(e){if(this.state!==W.RELAY_STATE_RUNNING)throw new L(d.INVALID_OPERATION);await this.sendUpdateMessage(e),this.prevChannelMediaConfig=e}async setVideoProfile(e){if(this._resolution=e,this.state!==W.RELAY_STATE_RUNNING)throw new L(d.INVALID_OPERATION);const t=this.genMessage(H.SetVideoProfile);await this.signal.request(t),l.debug("[".concat(this.clientId,"] startChannelMediaRelay: setVideoProfile success"))}async stopChannelMediaRelay(){await this.sendStopRelayMessage(),l.debug("[".concat(this.clientId,"] stopChannelMediaRelay: send stop message success")),this.state=W.RELAY_STATE_IDLE,this.dispose()}dispose(){l.debug("[".concat(this.clientId,"] disposeChannelMediaRelay")),this.cancelToken.cancel(),this.cancelToken=u.CancelToken.source(),this.state=W.RELAY_STATE_IDLE,this.emit("dispose"),this.signal.dispose(),this.prevChannelMediaConfig=void 0}async connect(){const e=await K(this.joinInfo,this.cancelToken.token,this.httpRetryConfig);this.workerToken=e.workerToken,await this.signal.connect(e.addressList),this.emit("event",Y.NETWORK_CONNECTED),this.signal.on("status",this.onStatus),this.signal.on("reconnecting",this.onReconnect)}async sendStartRelayMessage(e){const t=this.genMessage(H.StopPacketTransfer);await this.signal.request(t),await this.signal.waitStatus("Normal Quit"),l.debug("[".concat(this.clientId,"] startChannelMediaRelay: StopPacketTransfer success"));const s=this.genMessage(H.SetSdkProfile,e);await this.signal.request(s),l.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSdkProfile success"));const E=this.genMessage(H.SetSourceChannel,e);await this.signal.request(E),await this.signal.waitStatus("SetSourceChannelStatus"),this.emit("event",Y.PACKET_JOINED_SRC_CHANNEL),l.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceChannel success"));const n=this.genMessage(H.SetSourceUserId,e);await this.signal.request(n),l.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceUserId success"));const _=this.genMessage(H.SetDestChannel,e);await this.signal.request(_),await this.signal.waitStatus("SetDestChannelStatus"),this.emit("event",Y.PACKET_JOINED_DEST_CHANNEL),l.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetDestChannel success"));const o=this.genMessage(H.StartPacketTransfer,e);await this.signal.request(o),this.emit("event",Y.PACKET_SENT_TO_DEST_CHANNEL),this.state=W.RELAY_STATE_RUNNING,l.debug("[".concat(this.clientId,"] startChannelMediaRelay: StartPacketTransfer success")),this.setVideoProfile(this._resolution)}async sendUpdateMessage(e){const t=this.genMessage(H.UpdateDestChannel,e);await this.signal.request(t),this.emit("event",Y.PACKET_UPDATE_DEST_CHANNEL),l.debug("[".concat(this.clientId,"] sendUpdateMessage: UpdateDestChannel success"))}async sendStopRelayMessage(){const e=this.genMessage(H.StopPacketTransfer);await this.signal.request(e),l.debug("[".concat(this.clientId,"] sendStopRelayMessage: StopPacketTransfer success"))}genMessage(e,t){const s=[],E=[],n=[];this.requestId+=1;const o={appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sdkVersion:_,sid:this.sid,ts:Date.now(),requestId:this.requestId,seq:this.requestId,allocate:!0,clientRequest:{}};"4.23.1"===o.sdkVersion&&(o.sdkVersion="0.0.1");let i=null,r=null;switch(e){case H.SetSdkProfile:return o.clientRequest={command:"SetSdkProfile",type:"multi_channel"},o;case H.SetSourceChannel:if(r=t&&t.getSrcChannelMediaInfo(),!r)throw new L(d.UNEXPECTED_ERROR,"can not find source config");return o.clientRequest={command:"SetSourceChannel",uid:"0",channelName:r.channelName,token:r.token||this.joinInfo.appId},o;case H.SetSourceUserId:if(r=t&&t.getSrcChannelMediaInfo(),!r)throw new L(d.UNEXPECTED_ERROR,"can not find source config");return o.clientRequest={command:"SetSourceUserId",uid:r.uid+""},o;case H.SetDestChannel:if(i=t&&t.getDestChannelMediaInfo(),!i)throw new L(d.UNEXPECTED_ERROR,"can not find dest config");return i.forEach((e=>{s.push(e.channelName),E.push(e.uid+""),n.push(e.token||this.joinInfo.appId)})),o.clientRequest={command:"SetDestChannel",channelName:s,uid:E,token:n},o;case H.StartPacketTransfer:return o.clientRequest={command:"StartPacketTransfer"},o;case H.Reconnect:return o.clientRequest={command:"Reconnect"},o;case H.StopPacketTransfer:return o.clientRequest={command:"StopPacketTransfer"},o;case H.UpdateDestChannel:if(i=t&&t.getDestChannelMediaInfo(),!i)throw new L(d.UNEXPECTED_ERROR,"can not find dest config");return i.forEach((e=>{s.push(e.channelName),E.push(e.uid+""),n.push(e.token||this.joinInfo.appId)})),o.clientRequest={command:"UpdateDestChannel",channelName:s,uid:E,token:n},o;case H.SetVideoProfile:o.clientRequest={command:"SetVideoProfile",width:this._resolution.width,height:this._resolution.height}}return o}}const X={name:"ChannelMediaRelay",create:function(e){return new x(e.joinInfo,e.clientId,e.websocketRetryConfig||O,e.httpRetryConfig||O,e.resolution)}};export{X as ChannelMediaRelayService}; |
/** | ||
* AgoraWebSDK_N-v4.23.0-0-g98fcf352-dirty Copyright AgoraInc. | ||
* AgoraWebSDK_N-v4.23.1-0-gea45199f-dirty Copyright AgoraInc. | ||
*/ | ||
import{IS_GLOBAL_VERSION as e,EventEmitter as t,PromiseMutex as n,NETWORK_STATE as E,networkIndicator as o,NETWORK_INDICATOR_EVENTS as i,createDefer as s,getParameter as r,AgoraRTCError as _,AgoraRTCErrorCode as c,getRetryWaitTime as a,wait as R,emitAsPromise as N,emitAsInvokerNoResponse as A,getUTF8StringByteLength as I,getMultiUnilbsFormDataByteLength as C,retryable as T,getRandomString as O,DEFAULT_RETRY_CONFIG as h}from"@agora-js/shared";import{logger as S,AgoraRTCError as L,AgoraRTCErrorCode as l,report as d}from"@agora-js/report";import{frameData2CryptoBuffer as u}from"@agora-js/media";import D from"axios";import"formdata-polyfill";function f(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var E=n.call(e,t||"default");if("object"!=typeof E)return E;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:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function w(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var E=Object.getOwnPropertySymbols(e);t&&(E=E.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,E)}return n}function p(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?w(Object(n),!0).forEach((function(t){f(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):w(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let g=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}({}),m=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}({}),V=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}({}),P=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}({}),U=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.DATASTREAM2_NOT_AVAILABLE=27]="DATASTREAM2_NOT_AVAILABLE",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}({}),y=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_CREATE_CONNECTION="websocket:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="websocket:on_token_privilege_did_expire",e}({}),M=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}({});M.AFRICA,M.ASIA,M.CHINA,M.EUROPE,M.GLOBAL,M.INDIA,M.JAPAN,M.NORTH_AMERICA,M.OCEANIA,M.OVERSEA,M.SOUTH_AMERICA;let b=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}({});b.ASIA,b.NORTH_AMERICA,b.EUROPE,b.JAPAN,b.INDIA,b.KOREA,b.HKMC,b.US,b.OVERSEA,b.GLOBAL,b.OCEANIA,b.SOUTH_AMERICA,b.AFRICA,e&&b.CHINA;let v=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED",e}({}),k=function(e){return e[e.CONNECT_AP=0]="CONNECT_AP",e[e.AP_CONNECTED=1]="AP_CONNECTED",e[e.CONNECT_WORKER_MANAGER=2]="CONNECT_WORKER_MANAGER",e[e.WORKER_MANAGER_CONNECTED=3]="WORKER_MANAGER_CONNECTED",e[e.GET_WORKER_MANAGER_RESPONSE=4]="GET_WORKER_MANAGER_RESPONSE",e[e.CONNECT_WORKER=5]="CONNECT_WORKER",e[e.WORKER_CONNECTED=6]="WORKER_CONNECTED",e[e.CLOSED=7]="CLOSED",e}({}),B=function(e){return e.CONNECTION_STATE_CHANGE="connection-state-change",e.STATE_CHANGE="state-change",e.INSPECT_RESULT="inspect-result",e.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",e.REQUEST_NEW_WORKER_URL="request-new-worker-url",e}({}),K=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_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 W extends t{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(y.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(y.CONNECTED):"closed"===this._state?this.emit(y.CLOSED):"failed"===this._state&&this.emit(y.FAILED))}resetReconnectCount(e){S.debug("websocket reset reconnect count, reason: "+e),this.reconnectCount=0}constructor(e,t){let s=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3&&void 0!==arguments[3]&&arguments[3],_=arguments.length>4&&void 0!==arguments[4]&&arguments[4],c=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=void 0,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=c,this.name=e,this.retryConfig=p({},t),this.useCompress=s,this.tryDoubleDomain=r,this.use443PortOnly=_,this._initMutex=new n("websocket",c?c.clientId:void 0);const{timeout:a,timeoutFactor:R}=t,N=Math.max(300,Math.floor(3*a/5)),A=Math.max(1.2,Math.floor(8*R)/10);E.ONLINE&&(this.retryConfig.timeout=N,this.retryConfig.timeoutFactor=A),o.on(i.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===E.ONLINE?(this.retryConfig.timeout=N,this.retryConfig.timeoutFactor=A):(this.retryConfig.timeout=a,this.retryConfig.timeoutFactor=R))}))}getConnection(){return this.websocket||void 0}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const n=await this._initMutex.lock();this._reconnectMode="tryNext",this.forceCloseTimeout=t,this.urls=e,this.state="connecting";try{const e=s(),t=this.urls[this.currentURLIndex];r("ENABLE_PREALLOC_PC")&&this.emit(K.PRE_CONNECT_PC),this.createWebSocketConnection(t).then(e.resolve).catch(e.reject),this.once(y.CLOSED,(()=>{e.reject(new _(c.WS_DISCONNECT))})),this.once(y.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 S.warning("[".concat(this.name,"] can not reconnect, no websocket"));void 0!==e&&(this.reconnectMode=e),S.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 n=this.websocket.onclose;this.websocket.onclose=null,this.websocket.close(),n&&n.bind(this.websocket)({code:9999,reason:t})}sendMessage(e){let t=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new _(c.WS_ABORT,"websocket is not ready");try{t||(e=JSON.stringify(e)),this.websocket.send(e)}catch(e){throw new _(c.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 t;const n=s();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const E=e=>{var t;null===(t=this.store)||void 0===t||t.signalChannelOpen(),S.debug("[".concat(this.name,"] websocket opened:"),e),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),n.resolve()},o=async e=>{var t;if(S.debug("[".concat(this.name,"] websocket close ").concat(null===(t=this.websocket)||void 0===t?void 0:t.url,", code: ").concat(e.code,", reason: ").concat(e.reason,", current mode: ").concat(this.reconnectMode)),this.reconnectCount>=this.retryConfig.maxRetryCount)n.reject(new _(c.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close();else{"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");const t=A(this,y.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,E=await this.reconnectWithAction(t);if("closed"===this.state)return void S.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!E)return n.reject(new _(c.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);n.resolve()}},i=e=>{this.emit(y.ON_MESSAGE,e)},a=e=>{S.warn("[".concat(this.connectionID,"] ws open error ").concat(e))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),r("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(e=r("GATEWAY_WSS_ADDRESS")),S.debug("[".concat(this.name,"] start connect, url:"),e);const R=null===(t=this.store)||void 0===t?void 0:t.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});try{var N;const t=await this.chooseBestWebsocketConnection(e);this.websocket=t,E&&E(this.websocket.url),this.websocket.onclose=o,this.websocket.onmessage=i,this.websocket.onerror=a,null===(N=this.store)||void 0===N||N.recordJoinChannelService({endTs:Date.now(),status:"success"},R),this.joinGatewayRecordIndex=R}catch(e){const t="closed"===this.state,E=e instanceof _,i=E&&e.code===c.WS_ABORT,s=E&&e.code===c.WS_ERR,r=E?e.message:e&&(e.reason||e.toString());S.warning("[choose-best-ws] chooseBestWebsocket error: ".concat(r)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:i?"aborted":"error",errors:[e]},R),t||s?(n.reject(t?new _(c.WS_DISCONNECT,"websocket is closed: ".concat(r)):new _(c.WS_ERR,"init websocket failed: ".concat(r))),s&&S.error("[".concat(this.name,"] init websocket failed: ").concat(r))):o&&o(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;S.warning("[choose-best-ws] action: =>",e),this.onlineReconnectListener||o.isOnline||!o.onlineWaiter||(this.onlineReconnectListener=o.onlineWaiter.then((()=>{this.onlineReconnectListener=void 0})));let n=!0;if(this.reconnectInterrupter=()=>n=!1,t){const t=a(this.reconnectCount,this.retryConfig);S.debug("[".concat(this.name,"] wait ").concat(t,"ms to reconnect websocket, mode: ").concat(e)),await Promise.race([R(t),this.onlineReconnectListener||new Promise((()=>{}))])}if("closed"===this._state||!n)return!1;this.reconnectCount+=1;const E=async(e,t)=>{this.emit(y.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e)};try{if("retry"===e)await E(this.urls[this.currentURLIndex],e);else if("tryNext"===e){if(this.currentURLIndex+=1,this.currentURLIndex>=this.urls.length)return this.reconnectWithAction("recover",!1);S.debug("[".concat(this.name,"] websocket url length: ").concat(this.urls.length," current index: ").concat(this.currentURLIndex)),await E(this.urls[this.currentURLIndex],e)}else"recover"===e&&(S.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.urls=await N(this,y.REQUEST_NEW_URLS),this.currentURLIndex=0,await E(this.urls[this.currentURLIndex],e))}catch(n){var i;S.error("[".concat(this.name,"] reconnect failed ").concat(n&&n.toString()));const E=null==n||null===(i=n.data)||void 0===i?void 0:i.desc;return Array.isArray(E)&&E.includes("dynamic key expired")?(this.emit(y.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):this.reconnectWithAction(e,t)}return!0}}class G extends W{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,t){return new Promise(((n,E)=>{let o=!1;const i=[];this.closeEstablishingWs=()=>{S.debug("[choose-best-ws] close establishing websockets"),i.forEach((e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close()})),E(new _(c.WS_ABORT,"choose best websocket aborted"))};const s=r("GATEWAY_DOMAINS");let a;const N=e.indexOf("?h="),A=s.find((t=>-1!==N?e.includes(t,N):e.includes(t)));S.debug("[choose-best-ws] currentDomain: ",A,", domains: ",s);let I=!this.tryDoubleDomain||!A;if(!I&&A){var C;const r=Date.now();try{s.forEach((t=>{const n=-1===N?e.replace(A,t):e.substr(0,N)+e.substr(N).replace(A,t),E=new WebSocket(n);E.binaryType="arraybuffer",i.push(E),S.debug("[choose-best-ws] ws is connecting:",E.url)}))}catch(e){for(S.debug("[choose-best-ws] ws create failed, fallback to single url"),i.forEach((e=>e.close()));i.length;)i.pop();I=!0}null===(C=this.store)||void 0===C||C.recordJoinChannelService({urls:i.map((e=>e.url)),service:"gateway"},t),i.forEach((e=>{e.onopen=()=>{if(o)return;const t=Date.now()-r;S.debug("[choose-best-ws] ws open cost ".concat(t,"ms")),i.filter((t=>t!==e)).forEach((e=>{S.debug("[choose-best-ws]close backup websocket: ".concat(e.url)),e.close()})),o=!0,n(e)},e.onclose=e=>{if(a=e,o)return;i.find((e=>!(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)))||(S.debug("[choose-best-ws] all websocket is closed"),o=!0,E(a))},e.onmessage=t=>{S.debug("[choose-best-ws]".concat(e.url," onmessage: ").concat(t.data))}})),R(this.forceCloseTimeout).then((()=>{i.forEach((e=>{e.readyState!==WebSocket.OPEN&&e.close()}))}))}if(I){var T;let o;S.debug("[choose-best-ws] use single url: ",e),null===(T=this.store)||void 0===T||T.recordJoinChannelService({urls:[e],service:"gateway"},t);try{o=new WebSocket(e),i.push(o),o.binaryType="arraybuffer"}catch(e){const t=new _(c.WS_ERR,"init websocket failed! Error: ".concat(e.toString()));return S.error("[".concat(this.name,"]").concat(t)),void E(t)}o.onopen=()=>{n(o)},o.onclose=e=>{E(e)},o.onmessage=e=>{S.debug("[choose-best-ws]".concat(o.url," onmessage: ").concat(e.data))},R(this.forceCloseTimeout).then((()=>{o&&o.readyState!==WebSocket.OPEN&&o.close()}))}})).then((e=>(this.closeEstablishingWs=void 0,e))).catch((e=>{throw this.closeEstablishingWs=void 0,e}))}}function H(e){let t=$();return function(e,t){let n=e.appId;void 0!==n&&(Ae(t,10),se(t,n));let E=e.cid;void 0!==E&&(Ae(t,16),Ae(t,E));let o=e.cname;void 0!==o&&(Ae(t,26),se(t,o));let i=e.deviceId;void 0!==i&&(Ae(t,34),se(t,i));let s=e.elapse;void 0!==s&&(Ae(t,40),Ie(t,s));let r=e.fileSize;void 0!==r&&(Ae(t,48),Ie(t,Z(r)));let _=e.height;void 0!==_&&(Ae(t,56),Ie(t,Z(_)));let c=e.jpg;void 0!==c&&(Ae(t,66),Ae(t,c.length),function(e,t){let n=Ee(e,t.length);e.bytes.set(t,n)}(t,c));let a=e.networkType;void 0!==a&&(Ae(t,72),Ie(t,Z(a)));let R=e.osType;void 0!==R&&(Ae(t,80),Ie(t,Z(R)));let N=e.requestId;void 0!==N&&(Ae(t,90),se(t,N));let A=e.sdkVersion;void 0!==A&&(Ae(t,98),se(t,A));let I=e.sequence;void 0!==I&&(Ae(t,104),Ie(t,Z(I)));let C=e.sid;void 0!==C&&(Ae(t,114),se(t,C));let T=e.timestamp;void 0!==T&&(Ae(t,120),Ie(t,T));let O=e.uid;void 0!==O&&(Ae(t,128),Ae(t,O));let h=e.vid;void 0!==h&&(Ae(t,136),Ae(t,h));let S=e.width;void 0!==S&&(Ae(t,144),Ie(t,Z(S)));let L=e.service;void 0!==L&&(Ae(t,152),Ae(t,L));let l=e.callbackData;void 0!==l&&(Ae(t,162),se(t,l));let d=e.jpgEncryption;void 0!==d&&(Ae(t,168),Ae(t,d));let u=e.requestType;void 0!==u&&(Ae(t,176),Ae(t,u));let D=e.scorePorn;void 0!==D&&(Ae(t,185),Re(t,D));let f=e.scoreSexy;void 0!==f&&(Ae(t,193),Re(t,f));let w=e.scoreNeutral;void 0!==w&&(Ae(t,201),Re(t,w));let p=e.scene;void 0!==p&&(Ae(t,208),Ae(t,p));let g=e.ossFilePrefix;void 0!==g&&(Ae(t,218),se(t,g));let m=e.serviceVendor;if(void 0!==m)for(let e of m){Ae(t,226);let n=$();F(e,n),Ae(t,n.limit),re(t,n),ee(n)}}(e,t),function(e){let t=e.bytes,n=e.limit;return t.length===n?t:t.subarray(0,n)}(t)}function Y(e){return function(e){let t={};e:for(;!ne(e);){let n=Ne(e);switch(n>>>3){case 0:break e;case 1:t.code=Ne(e);break;case 2:t.msg=ie(e,Ne(e));break;case 3:{let n=q(e);t.data=x(e),e.limit=n;break}default:J(e,7&n)}}return t}({bytes:t=e,offset:0,limit:t.length});var t}function x(e){let t={};e:for(;!ne(e);){let n=Ne(e);switch(n>>>3){case 0:break e;case 1:t.requestId=ie(e,Ne(e));break;case 2:t.requestType=Ne(e)>>>0;break;case 3:t.scorePorn=ae(e);break;case 4:t.scoreSexy=ae(e);break;case 5:t.scoreNeutral=ae(e);break;case 6:t.requestScene=Ne(e)>>>0;break;case 7:t.scene=Ne(e)>>>0;break;default:J(e,7&n)}}return t}function F(e,t){let n=e.service;void 0!==n&&(Ae(t,8),Ae(t,n));let E=e.vendor;void 0!==E&&(Ae(t,16),Ae(t,E));let o=e.token;void 0!==o&&(Ae(t,26),se(t,o));let i=e.callbackUrl;void 0!==i&&(Ae(t,34),se(t,i))}function q(e){let t=Ne(e),n=e.limit;return e.limit=e.offset+t,n}function J(e,t){switch(t){case 0:for(;128&_e(e););break;case 2:te(e,Ne(e));break;case 5:te(e,4);break;case 1:te(e,8);break;default:throw new Error("Unimplemented type: "+t)}}let j=new Float32Array(1);new Uint8Array(j.buffer);let X=new Float64Array(1),Q=new Uint8Array(X.buffer);function Z(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let z=[];function $(){const e=z.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}function ee(e){z.push(e)}function te(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function ne(e){return e.offset>=e.limit}function Ee(e,t){let n=e.bytes,E=e.offset,o=e.limit,i=E+t;if(i>n.length){let t=new Uint8Array(2*i);t.set(n),e.bytes=t}return e.offset=i,i>o&&(e.limit=i),E}function oe(e,t){let n=e.offset;if(n+t>e.limit)throw new Error("Read past limit");return e.offset+=t,n}function ie(e,t){let n=oe(e,t),E=String.fromCharCode,o=e.bytes,i="�",s="";for(let e=0;e<t;e++){let r,_,c,a,R=o[e+n];0==(128&R)?s+=E(R):192==(224&R)?e+1>=t?s+=i:(r=o[e+n+1],128!=(192&r)?s+=i:(a=(31&R)<<6|63&r,a<128?s+=i:(s+=E(a),e++))):224==(240&R)?e+2>=t?s+=i:(r=o[e+n+1],_=o[e+n+2],32896!=(49344&(r|_<<8))?s+=i:(a=(15&R)<<12|(63&r)<<6|63&_,a<2048||a>=55296&&a<=57343?s+=i:(s+=E(a),e+=2))):240==(248&R)?e+3>=t?s+=i:(r=o[e+n+1],_=o[e+n+2],c=o[e+n+3],8421504!=(12632256&(r|_<<8|c<<16))?s+=i:(a=(7&R)<<18|(63&r)<<12|(63&_)<<6|63&c,a<65536||a>1114111?s+=i:(a-=65536,s+=E(55296+(a>>10),56320+(1023&a)),e+=3))):s+=i}return s}function se(e,t){let n=t.length,E=0;for(let e=0;e<n;e++){let o=t.charCodeAt(e);o>=55296&&o<=56319&&e+1<n&&(o=(o<<10)+t.charCodeAt(++e)-56613888),E+=o<128?1:o<2048?2:o<65536?3:4}Ae(e,E);let o=Ee(e,E),i=e.bytes;for(let e=0;e<n;e++){let E=t.charCodeAt(e);E>=55296&&E<=56319&&e+1<n&&(E=(E<<10)+t.charCodeAt(++e)-56613888),E<128?i[o++]=E:(E<2048?i[o++]=E>>6&31|192:(E<65536?i[o++]=E>>12&15|224:(i[o++]=E>>18&7|240,i[o++]=E>>12&63|128),i[o++]=E>>6&63|128),i[o++]=63&E|128)}}function re(e,t){let n=Ee(e,t.limit),E=e.bytes,o=t.bytes;for(let e=0,i=t.limit;e<i;e++)E[e+n]=o[e]}function _e(e){return e.bytes[oe(e,1)]}function ce(e,t){let n=Ee(e,1);e.bytes[n]=t}function ae(e){let t=oe(e,8),n=e.bytes;return Q[0]=n[t++],Q[1]=n[t++],Q[2]=n[t++],Q[3]=n[t++],Q[4]=n[t++],Q[5]=n[t++],Q[6]=n[t++],Q[7]=n[t++],X[0]}function Re(e,t){let n=Ee(e,8),E=e.bytes;X[0]=t,E[n++]=Q[0],E[n++]=Q[1],E[n++]=Q[2],E[n++]=Q[3],E[n++]=Q[4],E[n++]=Q[5],E[n++]=Q[6],E[n++]=Q[7]}function Ne(e){let t,n=0,E=0;do{t=_e(e),n<32&&(E|=(127&t)<<n),n+=7}while(128&t);return E}function Ae(e,t){for(t>>>=0;t>=128;)ce(e,127&t|128),t>>>=7;ce(e,t)}function Ie(e,t){let n=t.low>>>0,E=(t.low>>>28|t.high<<4)>>>0,o=t.high>>>24,i=0===o?0===E?n<16384?n<128?1:2:n<1<<21?3:4:E<16384?E<128?5:6:E<1<<21?7:8:o<128?9:10,s=Ee(e,i),r=e.bytes;switch(i){case 10:r[s+9]=o>>>7&1;case 9:r[s+8]=9!==i?128|o:127&o;case 8:r[s+7]=8!==i?E>>>21|128:E>>>21&127;case 7:r[s+6]=7!==i?E>>>14|128:E>>>14&127;case 6:r[s+5]=6!==i?E>>>7|128:E>>>7&127;case 5:r[s+4]=5!==i?128|E:127&E;case 4:r[s+3]=4!==i?n>>>21|128:n>>>21&127;case 3:r[s+2]=3!==i?n>>>14|128:n>>>14&127;case 2:r[s+1]=2!==i?n>>>7|128:n>>>7&127;case 1:r[s]=1!==i?128|n:127&n}}let Ce=0,Te=0;g.ACCESS_POINT,P.NO_FLAG_SET,P.FLAG_SET_BUT_EMPTY,P.INVALID_FALG_SET,P.FLAG_SET_BUT_NO_RE,P.INVALID_SERVICE_ID,P.NO_SERVICE_AVAILABLE,P.NO_SERVICE_AVAILABLE_P2P,P.NO_SERVICE_AVAILABLE_VOICE,P.NO_SERVICE_AVAILABLE_WEBRTC,P.NO_SERVICE_AVAILABLE_CDS,P.NO_SERVICE_AVAILABLE_CDN,P.NO_SERVICE_AVAILABLE_TDS,P.NO_SERVICE_AVAILABLE_REPORT,P.NO_SERVICE_AVAILABLE_APP_CENTER,P.NO_SERVICE_AVAILABLE_ENV0,P.NO_SERVICE_AVAILABLE_VOET,P.NO_SERVICE_AVAILABLE_STRING_UID,P.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS,g.UNILBS,V.INVALID_VENDOR_KEY,V.INVALID_CHANNEL_NAME,V.INTERNAL_ERROR,V.NO_AUTHORIZED,V.DYNAMIC_KEY_TIMEOUT,V.NO_ACTIVE_STATUS,V.DYNAMIC_KEY_EXPIRED,V.STATIC_USE_DYNAMIC_KEY,V.DYNAMIC_USE_STATIC_KEY,V.USER_OVERLOAD,V.FORBIDDEN_REGION,V.CANNOT_MEET_AREA_DEMAND,g.STRING_UID_ALLOCATOR,m.IIIEGAL_APPID,m.IIIEGAL_UID,m.INTERNAL_ERROR,U.K_TIMESTAMP_EXPIRED,U.K_CHANNEL_PERMISSION_INVALID,U.K_CERTIFICATE_INVALID,U.K_CHANNEL_NAME_EMPTY,U.K_CHANNEL_NOT_FOUND,U.K_TICKET_INVALID,U.K_CHANNEL_CONFLICTED,U.K_SERVICE_NOT_READY,U.K_SERVICE_TOO_HEAVY,U.K_UID_BANNED,U.K_IP_BANNED,U.DATASTREAM2_NOT_AVAILABLE,U.K_AUTO_REBALANCE,U.ERR_INVALID_VENDOR_KEY,U.ERR_INVALID_CHANNEL_NAME,U.WARN_NO_AVAILABLE_CHANNEL,U.WARN_LOOKUP_CHANNEL_TIMEOUT,U.WARN_LOOKUP_CHANNEL_REJECTED,U.WARN_OPEN_CHANNEL_TIMEOUT,U.WARN_OPEN_CHANNEL_REJECTED,U.WARN_REQUEST_DEFERRED,U.ERR_DYNAMIC_KEY_TIMEOUT,U.ERR_NO_AUTHORIZED,U.ERR_VOM_SERVICE_UNAVAILABLE,U.ERR_NO_CHANNEL_AVAILABLE_CODE,U.ERR_MASTER_VOCS_UNAVAILABLE,U.ERR_INTERNAL_ERROR,U.ERR_NO_ACTIVE_STATUS,U.ERR_INVALID_UID,U.ERR_DYNAMIC_KEY_EXPIRED,U.ERR_STATIC_USE_DYANMIC_KE,U.ERR_DYNAMIC_USE_STATIC_KE,U.ERR_NO_VOCS_AVAILABLE,U.ERR_NO_VOS_AVAILABLE,U.ERR_JOIN_CHANNEL_TIMEOUT,U.ERR_JOIN_BY_MULTI_IP,U.ERR_NOT_JOINED,U.ERR_REPEAT_JOIN_REQUEST,U.ERR_REPEAT_JOIN_CHANNEL,U.ERR_INVALID_STRINGUID,U.ERR_TOO_MANY_USERS,U.ERR_SET_CLIENT_ROLE_TIMEOUT,U.ERR_SET_CLIENT_ROLE_NO_PERMISSION,U.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE,U.ERR_PUBLISH_REQUEST_INVALID,U.ERR_SUBSCRIBE_REQUEST_INVALID,U.ERR_NOT_SUPPORTED_MESSAGE,U.ERR_ILLEAGAL_PLUGIN,U.ILLEGAL_CLIENT_ROLE_LEVEL,U.ERR_REJOIN_TOKEN_INVALID,U.ERR_REJOIN_USER_NOT_JOINED,U.ERR_INVALID_OPTIONAL_INFO,U.ERR_TEST_RECOVER,U.ERR_TEST_TRYNEXT,U.ERR_TEST_RETRY,U.ILLEGAL_AES_PASSWORD,U.ERR_TOO_MANY_BROADCASTERS,U.ERR_TOO_MANY_SUBSCRIBERS,U.ERR_LICENSE_ILLEGAL,U.ERR_LICENSE_MISSING,U.ERR_LICENSE_EXPIRED,U.ERR_LICENSE_MINUTES_EXCEEDED,U.ERR_LICENSE_PERIOD_INVALID,U.ERR_LICENSE_MULTIPLE_SDK_SERVICE;const Oe={GLOBAL:{ASIA:[M.CHINA,M.JAPAN,M.INDIA,M.KOREA,M.HKMC],EUROPE:[],NORTH_AMERICA:[M.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}};Object.keys(Oe[M.GLOBAL]),M.CHINA,M.NORTH_AMERICA,M.EUROPE,M.ASIA,M.JAPAN,M.INDIA,M.OCEANIA,M.SOUTH_AMERICA,M.AFRICA,M.KOREA,M.HKMC,M.US;let he=0;function Se(e,t,n,E){let{appId:o,areaCode:i,cname:s,sid:_,token:a,uid:R}=t;he++;const N="image_moderation_api",A={service_name:N,json_body:JSON.stringify({appId:o,areaCode:i,cname:s,command:"allocateEdge",requestId:he,seq:he,sid:_,token:a,ts:Date.now(),uid:R+""})};let O,h,u=e[0];return T((async()=>{O=Date.now();const e=await function(e,t,n,E){return new Promise(((o,i)=>{t.timeout=t.timeout||r("HTTP_CONNECT_TIMEOUT"),t.responseType=t.responseType||"json",t.data&&!n?(t.data=JSON.stringify(t.data),Ce+=I(t.data)):n&&(t.data.size?Ce+=t.data.size:t.data instanceof FormData?Ce+=C(t.data):Ce+=I(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,D.request(t).then((e=>{"string"==typeof e.data?Te+=I(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?Te+=e.data.byteLength:Te+=I(JSON.stringify(e.data)),E&&o({data:e.data,headers:e.headers}),o(e.data)})).catch((e=>{D.isCancel(e)?i(new L(c.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?i(new L(c.NETWORK_TIMEOUT,e.message)):e.response?i(new L(c.NETWORK_RESPONSE_ERROR,e.response.status)):i(new L(c.NETWORK_ERROR,e.message))}))}))}(u,{data:A,cancelToken:n,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(h=Date.now()-O,0!==e.code){const t=new L(l.UNEXPECTED_RESPONSE,"image inspect ap error, code"+e.code,{retry:!0,responseTime:h});throw S.error(t.toString()),t}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new L(l.UNEXPECTED_RESPONSE,"image inspect ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:h});throw S.error(e.toString()),e}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new L(l.UNEXPECTED_RESPONSE,"image inspect ap empty server",{code:t.code,responseTime:h});throw S.error(e.toString()),e}const E=r("VIDEO_INSPECT_WORKER_MANAGER_HOST"),o=r("VIDEO_INSPECT_WORKER_MANAGER_PORT");return{addressList:t.servers.map((e=>{let{address:t,wss:n}=e;if(t&&n)return"wss://".concat(t.replace(/\./g,"-"),".").concat(E,":").concat(o||n)})).filter((e=>!!e)),workerToken:t.workerToken,vid:t.vid,responseTime:h}}),((t,n)=>(d.apworkerEvent(_,{success:!0,sc:200,serviceName:N,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===n,responseTime:h,serverIp:e[n%e.length]}),!1)),((t,n)=>(d.apworkerEvent(_,{success:!1,sc:t.data&&t.data.code||200,serviceName:N,responseTime:h,serverIp:e[n%e.length]}),!!(t.code!==l.OPERATION_ABORTED&&t.code!==l.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(u=e[(n+1)%e.length],!0))),E)}const Le={},le={},de=4294967296,ue=de*de,De=ue/2,fe=Ve(0,!0),we=Ve(0),pe=Pe(0,-2147483648,!1),ge=Pe(-1,2147483647,!1),me=Pe(-1,-1,!0);function Ve(e,t){let n,E,o;return t?(o=0<=(e>>>=0)&&e<256)&&(E=le[e],E)?E:(n=Pe(e,0,!0),o&&(le[e]=n),n):(o=-128<=(e|=0)&&e<128)&&(E=Le[e],E)?E:(n=Pe(e,e<0?-1:0,!1),o&&(Le[e]=n),n)}function Pe(e,t,n){return{low:0|e,high:0|t,unsigned:!!n}}function Ue(e,t){if(isNaN(e))return t?fe:we;if(t){if(e<0)return fe;if(e>=ue)return me}else{if(e<=-De)return pe;if(e+1>=De)return ge}return e<0?t?fe:we:Pe(e%de|0,e/de|0,t)}const ye=new Map([["moderation",1],["supervise",2]]);class Me extends t{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(B.CONNECTION_STATE_CHANGE,t,e)}get inspectType(){return this._inspectType}set inspectType(e){this._inspectMode=e.map((e=>ye.get(e)||0)).reduce(((e,t)=>e+t)),this._inspectType=e}get quality(){return this._quality}set quality(e){this._quality=e>1?1:e<.1?.1:e,this.qualityTimer&&(window.clearTimeout(this.qualityTimer),this.qualityTimer=null),this._quality>=1||(this.qualityTimer=window.setTimeout((()=>{this.quality=this._quality/this.qualityRatio}),6e4))}constructor(e){super(),this.name="AgoraRTCVideoContentInspect",this._connectionState=v.CONNECTING,this._innerConnectionState=void 0,this.sequence=0,this.inspectStartTime=void 0,this.workerManagerConnection=void 0,this.workerConnection=void 0,this.workerMessageLengthLimit=void 0,this.inspectIntervalMinimum=void 0,this.qualityRatio=void 0,this._connectInfo=void 0,this._cancelTokenSource=D.CancelToken.source(),this._retryConfig=void 0,this.wmSequence=0,this.inspectInterval=void 0,this.inspectTimer=null,this.ossFilePrefix=void 0,this.extraInfo=void 0,this._inspectType=void 0,this._inspectMode=void 0,this._quality=1,this.qualityTimer=null,this._inspectId=void 0,this._needWorkUrlOnly=!1,this.inspectImage=()=>{if(this.connectionState!==v.CONNECTED)throw new L(l.OPERATION_ABORTED,"content inspect service connection status is ".concat(this.connectionState));this.inspectTimer&&(window.clearInterval(this.inspectTimer),this.inspectTimer=null),this.inspectTimer=window.setInterval((()=>{this.connectionState===v.CONNECTED?this.requestToInspectImage():S.debug("[".concat(this._inspectId,"] Inspect State is not connected , "),this.connectionState)}),this.inspectInterval<this.inspectIntervalMinimum?this.inspectIntervalMinimum:this.inspectInterval),this.requestToInspectImage()},this._inspectId=O(5,"inspect-"),this.workerMessageLengthLimit=r("VIDEO_INSPECT_WORKER_MESSAGE_LENGTH_LIMIT"),this.inspectIntervalMinimum=r("VIDEO_INSPECT_INTERVAL_MINIMUM"),this.qualityRatio=r("VIDEO_INSPECT_QUALITY_RATIO"),this.inspectInterval=e.interval,this.ossFilePrefix=e.ossFilePrefix,this.extraInfo=e.extraInfo,this.inspectType=e.inspectType,this.inspectStartTime=Number(Date.now()),this.workerManagerConnection=new G("worker-manager-"+this._inspectId,h),this.on(B.STATE_CHANGE,((e,t)=>{this._innerConnectionState=e,S.debug("[".concat(this._inspectId,"] Inspect operation :").concat(k[e]," ").concat(t||""))})),this.handleWorkerManagerEvents(),this.workerConnection=new G("worker-"+this._inspectId,h),this.handleWorkerEvents()}async init(e,t){this.emit(B.STATE_CHANGE,k.CONNECT_AP),this._connectInfo=e;const n=this._cancelTokenSource.token;return this._retryConfig=t,new Promise(((E,o)=>{this.on(B.CONNECTION_STATE_CHANGE,((e,t)=>{t===v.CONNECTED&&E()})),this.requestAP(e,n,t).then((e=>{this.connectWorkerManager(e)})).catch((e=>{o(e)}))}))}async requestAP(e,t,n){const E=r("WEBCS_DOMAIN").map((e=>"https://".concat(e,"/api/v1"))),o=await Se(E,e,t,n);this.emit(B.STATE_CHANGE,k.AP_CONNECTED);const{addressList:i}=o;return this.wmSequence++,i}async connectWorkerManager(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._needWorkUrlOnly=t,this.emit(B.STATE_CHANGE,k.CONNECT_WORKER_MANAGER),await this.workerManagerConnection.init(e,1e4)}async connectWorker(e){await this.workerConnection.init([e])}handleWorkerManagerEvents(){this.workerManagerConnection.on(y.CONNECTED,(async()=>{this.emit(B.STATE_CHANGE,k.WORKER_MANAGER_CONNECTED,this.workerManagerConnection.url),this.workerManagerConnection.sendMessage({appId:this._connectInfo.appId,cname:this._connectInfo.cname,uid:this._connectInfo.uid+"",sdkVersion:"4.23.0",sid:this._connectInfo.sid,seq:this.wmSequence,ts:Number(Date.now()),requestId:Math.floor(1e12*Math.random()),allocate:!0,clientRequest:{command:"join"}},!0)})),this.workerManagerConnection.on(y.CLOSED,(()=>{this._innerConnectionState<k.GET_WORKER_MANAGER_RESPONSE&&S.debug("[".concat(this._inspectId,"] Inspect worker manager is closed before connecting worker"))})),this.workerManagerConnection.on(y.FAILED,(()=>{this._innerConnectionState<k.GET_WORKER_MANAGER_RESPONSE&&S.debug("[".concat(this._inspectId,"] Connecting inspect worker manager is failed before connecting worker"))})),this.workerManagerConnection.on(y.RECONNECTING,(()=>{this._innerConnectionState<k.GET_WORKER_MANAGER_RESPONSE&&S.debug("[".concat(this._inspectId,"] Inspect worker manager is reconnecting before connecting worker"))})),this.workerManagerConnection.on(y.ON_MESSAGE,(async e=>{this.emit(B.STATE_CHANGE,k.GET_WORKER_MANAGER_RESPONSE);const t=this.workerManagerConnection.url;this.workerManagerConnection.close();const n=JSON.parse(e.data);if(200!==n.code)throw S.error("[".concat(this._inspectId,"] Unexpected code ").concat(n.code," from worker manager")),new L(l.UNEXPECTED_RESPONSE,"response code of worker is unexpected",n);if(!(n.serverResponse&&n.serverResponse.portWss&&t))throw S.error("[".concat(this._inspectId,"] Unexpected content from worker manager : ").concat(JSON.stringify(n))),new L(l.UNEXPECTED_RESPONSE,"response content of worker is unexpected",n);{const e=r("VIDEO_INSPECT_WORKER_PORT")||n.serverResponse.portWss,E=t.replace(/:\d+\/?$/,":".concat(e));this.emit(B.STATE_CHANGE,k.CONNECT_WORKER,E),this._needWorkUrlOnly?this.emit(B.REQUEST_NEW_WORKER_URL,E):await this.connectWorker(E)}})),this.workerManagerConnection.on(y.WILL_RECONNECT,((e,t,n)=>{n(e)})),this.workerManagerConnection.on(y.REQUEST_NEW_URLS,((e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t)}))}handleWorkerEvents(){this.workerConnection.on(y.CONNECTED,(async()=>{this.emit(B.STATE_CHANGE,k.WORKER_CONNECTED,this.workerConnection.url),this.connectionState=v.CONNECTED})),this.workerConnection.on(y.ON_MESSAGE,(async e=>{if(e.data instanceof ArrayBuffer){const t=Y(new Uint8Array(e.data));if(r("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")&&S.debug("[".concat(this._inspectId,"] Response message for worker of inspect content "),JSON.stringify(t)),200===t.code){if(Array.isArray(this.inspectType)&&1===this.inspectType.length&&"supervise"===this.inspectType[0])return void this.emit(B.INSPECT_RESULT,void 0,void 0);if(t.data&&t.data.scorePorn&&t.data.scoreSexy&&t.data.scoreNeutral){const e={porn:t.data.scorePorn,sexy:t.data.scoreSexy,neutral:t.data.scoreNeutral},n=Object.keys(e).reduce(((t,n)=>e[t]>e[n]?t:n),"porn"),E=Object.keys(e).find((e=>e===n));this.emit(B.INSPECT_RESULT,E)}else this.emit(B.INSPECT_RESULT,void 0,new L(l.UNEXPECTED_RESPONSE,t.code+"","There is an unexpected data on message"))}else this.emit(B.INSPECT_RESULT,void 0,new L(l.UNEXPECTED_RESPONSE,t.code+"",t.msg))}else S.error("[".concat(this._inspectId,"] Unexpected message type from worker")),this.emit(B.INSPECT_RESULT,void 0,new L(l.UNEXPECTED_RESPONSE,"invalid worker message type"))})),this.workerConnection.on(y.CLOSED,(()=>{this.connectionState=v.CLOSED})),this.workerConnection.on(y.FAILED,(()=>{this.connectionState=v.CLOSED})),this.workerConnection.on(y.RECONNECTING,(()=>{this.connectionState=this.connectionState===v.CONNECTED?v.RECONNECTING:v.CONNECTING})),this.workerConnection.on(y.WILL_RECONNECT,((e,t,n)=>{"recover"===e&&n(e),n("tryNext")})),this.workerConnection.on(y.REQUEST_NEW_URLS,((e,t)=>{this.workerManagerConnection.close(),this.once(B.REQUEST_NEW_WORKER_URL,(t=>{e([t])})),this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then((e=>{this.connectWorkerManager(e,!0)})).catch((e=>{t(e)}))}))}async requestToInspectImage(){this.sequence++;const e=A(this,B.CLIENT_LOCAL_VIDEO_TRACK),t={appId:this._connectInfo.appId,cname:this._connectInfo.cname,cid:this._connectInfo.cid,sid:this._connectInfo.sid,uid:this._connectInfo.uid,vid:this._connectInfo.vid};if(e){if(!e.isPlaying)return void this.emit(B.INSPECT_RESULT,void 0,new L(l.INVALID_OPERATION,"Only the track being played can be inspected"));const n=await this.generateRequestData(e,t);this.workerConnection.sendMessage(n,!0,!0)}else this.emit(B.INSPECT_RESULT,void 0,new L(l.INVALID_OPERATION,"Only the track being published can be inspected"))}async generateRequestData(e,t){let{appId:n,cname:E,cid:o,vid:i,sid:s,uid:_}=t;const c=Date.now(),a=await e.getCurrentFrameImage("image/jpeg",this.quality),R=await u(a,n,E),N=this.sequence+"-"+o+"-"+_+"-"+c+"-"+O(12,""),A={appId:n,cid:o,cname:E,deviceId:"",elapse:(I=Number(c-this.inspectStartTime),{low:I|=0,high:I>>31,unsigned:I>=0}),fileSize:R.byteLength,jpgEncryption:2,height:a.height,width:a.width,jpg:R,networkType:6,osType:7,requestId:N,sdkVersion:"4.23.0",sequence:this.sequence,sid:s,timestamp:Ue(c),uid:_,vid:i,service:this._inspectMode,callbackData:this.extraInfo,ossFilePrefix:this.ossFilePrefix};var I;void 0===this.extraInfo&&delete A.callbackData,void 0===this.ossFilePrefix&&delete A.ossFilePrefix;const C=H(A);if(C.byteLength<this.workerMessageLengthLimit){if(r("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")){const e=p({},A);delete e.jpg,S.debug("[".concat(this._inspectId,"] Request message for worker of inspect content "),JSON.stringify(e))}return C}{const t=this.quality*this.qualityRatio;return this.quality=t,await this.generateRequestData(e,{appId:n,cname:E,cid:o,vid:i,sid:s,uid:_})}}close(){this._cancelTokenSource.cancel(),this._cancelTokenSource=D.CancelToken.source(),this.workerManagerConnection&&this.workerManagerConnection.close(),this.workerConnection&&this.workerConnection.close(),this.inspectTimer&&window.clearInterval(this.inspectTimer),this.inspectTimer=null,this.connectionState=v.CLOSED,this.emit(B.STATE_CHANGE,k.CLOSED)}}function be(e){if(!e)throw new L(l.INVALID_PARAMS,"inspectConfig is necessary.");if(!e.inspectType||!Array.isArray(e.inspectType))throw new L(l.INVALID_PARAMS,"inspectConfig.inspectType is necessary and is an instance of Array.");{const t=[...new Set(e.inspectType)];t.forEach((e=>{if(!["supervise","moderation"].includes(e))throw new L(l.INVALID_PARAMS,"".concat(e," is not a valid inspect type."))})),e.inspectType=t}if(e&&e.extraInfo&&e.extraInfo.length>1024)throw new L(l.INVALID_PARAMS,"inspectConfig.extraInfo length cannot exceed 1024 bytes")}const ve={name:"ContentInspect",create:function(e){let{config:t}=e;return be(t),new Me(t)}};export{ve as ContentInspectService,be as checkContentInspectConfig}; | ||
import{IS_GLOBAL_VERSION as e,EventEmitter as t,PromiseMutex as n,NETWORK_STATE as E,networkIndicator as o,NETWORK_INDICATOR_EVENTS as i,createDefer as s,getParameter as r,AgoraRTCError as _,AgoraRTCErrorCode as c,getRetryWaitTime as a,wait as R,emitAsPromise as N,emitAsInvokerNoResponse as A,getUTF8StringByteLength as I,getMultiUnilbsFormDataByteLength as C,retryable as T,getRandomString as O,DEFAULT_RETRY_CONFIG as h}from"@agora-js/shared";import{logger as S,AgoraRTCError as L,AgoraRTCErrorCode as l,report as d}from"@agora-js/report";import{frameData2CryptoBuffer as u}from"@agora-js/media";import D from"axios";import"formdata-polyfill";function f(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var E=n.call(e,t||"default");if("object"!=typeof E)return E;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:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function w(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var E=Object.getOwnPropertySymbols(e);t&&(E=E.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,E)}return n}function p(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?w(Object(n),!0).forEach((function(t){f(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):w(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let g=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}({}),m=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}({}),V=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}({}),P=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}({}),U=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.DATASTREAM2_NOT_AVAILABLE=27]="DATASTREAM2_NOT_AVAILABLE",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}({}),y=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_CREATE_CONNECTION="websocket:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="websocket:on_token_privilege_did_expire",e}({}),M=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}({});M.AFRICA,M.ASIA,M.CHINA,M.EUROPE,M.GLOBAL,M.INDIA,M.JAPAN,M.NORTH_AMERICA,M.OCEANIA,M.OVERSEA,M.SOUTH_AMERICA;let b=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}({});b.ASIA,b.NORTH_AMERICA,b.EUROPE,b.JAPAN,b.INDIA,b.KOREA,b.HKMC,b.US,b.OVERSEA,b.GLOBAL,b.OCEANIA,b.SOUTH_AMERICA,b.AFRICA,e&&b.CHINA;let v=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED",e}({}),k=function(e){return e[e.CONNECT_AP=0]="CONNECT_AP",e[e.AP_CONNECTED=1]="AP_CONNECTED",e[e.CONNECT_WORKER_MANAGER=2]="CONNECT_WORKER_MANAGER",e[e.WORKER_MANAGER_CONNECTED=3]="WORKER_MANAGER_CONNECTED",e[e.GET_WORKER_MANAGER_RESPONSE=4]="GET_WORKER_MANAGER_RESPONSE",e[e.CONNECT_WORKER=5]="CONNECT_WORKER",e[e.WORKER_CONNECTED=6]="WORKER_CONNECTED",e[e.CLOSED=7]="CLOSED",e}({}),B=function(e){return e.CONNECTION_STATE_CHANGE="connection-state-change",e.STATE_CHANGE="state-change",e.INSPECT_RESULT="inspect-result",e.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",e.REQUEST_NEW_WORKER_URL="request-new-worker-url",e}({}),K=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_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 W extends t{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(y.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(y.CONNECTED):"closed"===this._state?this.emit(y.CLOSED):"failed"===this._state&&this.emit(y.FAILED))}resetReconnectCount(e){S.debug("websocket reset reconnect count, reason: "+e),this.reconnectCount=0}constructor(e,t){let s=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3&&void 0!==arguments[3]&&arguments[3],_=arguments.length>4&&void 0!==arguments[4]&&arguments[4],c=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=void 0,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=c,this.name=e,this.retryConfig=p({},t),this.useCompress=s,this.tryDoubleDomain=r,this.use443PortOnly=_,this._initMutex=new n("websocket",c?c.clientId:void 0);const{timeout:a,timeoutFactor:R}=t,N=Math.max(300,Math.floor(3*a/5)),A=Math.max(1.2,Math.floor(8*R)/10);E.ONLINE&&(this.retryConfig.timeout=N,this.retryConfig.timeoutFactor=A),o.on(i.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===E.ONLINE?(this.retryConfig.timeout=N,this.retryConfig.timeoutFactor=A):(this.retryConfig.timeout=a,this.retryConfig.timeoutFactor=R))}))}getConnection(){return this.websocket||void 0}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const n=await this._initMutex.lock();this._reconnectMode="tryNext",this.forceCloseTimeout=t,this.urls=e,this.state="connecting";try{const e=s(),t=this.urls[this.currentURLIndex];r("ENABLE_PREALLOC_PC")&&this.emit(K.PRE_CONNECT_PC),this.createWebSocketConnection(t).then(e.resolve).catch(e.reject),this.once(y.CLOSED,(()=>{e.reject(new _(c.WS_DISCONNECT))})),this.once(y.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 S.warning("[".concat(this.name,"] can not reconnect, no websocket"));void 0!==e&&(this.reconnectMode=e),S.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 n=this.websocket.onclose;this.websocket.onclose=null,this.websocket.close(),n&&n.bind(this.websocket)({code:9999,reason:t})}sendMessage(e){let t=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new _(c.WS_ABORT,"websocket is not ready");try{t||(e=JSON.stringify(e)),this.websocket.send(e)}catch(e){throw new _(c.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 t;const n=s();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const E=e=>{var t;null===(t=this.store)||void 0===t||t.signalChannelOpen(),S.debug("[".concat(this.name,"] websocket opened:"),e),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),n.resolve()},o=async e=>{var t;if(S.debug("[".concat(this.name,"] websocket close ").concat(null===(t=this.websocket)||void 0===t?void 0:t.url,", code: ").concat(e.code,", reason: ").concat(e.reason,", current mode: ").concat(this.reconnectMode)),this.reconnectCount>=this.retryConfig.maxRetryCount)n.reject(new _(c.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close();else{"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");const t=A(this,y.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,E=await this.reconnectWithAction(t);if("closed"===this.state)return void S.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!E)return n.reject(new _(c.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);n.resolve()}},i=e=>{this.emit(y.ON_MESSAGE,e)},a=e=>{S.warn("[".concat(this.connectionID,"] ws open error ").concat(e))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),r("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(e=r("GATEWAY_WSS_ADDRESS")),S.debug("[".concat(this.name,"] start connect, url:"),e);const R=null===(t=this.store)||void 0===t?void 0:t.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});try{var N;const t=await this.chooseBestWebsocketConnection(e);this.websocket=t,E&&E(this.websocket.url),this.websocket.onclose=o,this.websocket.onmessage=i,this.websocket.onerror=a,null===(N=this.store)||void 0===N||N.recordJoinChannelService({endTs:Date.now(),status:"success"},R),this.joinGatewayRecordIndex=R}catch(e){const t="closed"===this.state,E=e instanceof _,i=E&&e.code===c.WS_ABORT,s=E&&e.code===c.WS_ERR,r=E?e.message:e&&(e.reason||e.toString());S.warning("[choose-best-ws] chooseBestWebsocket error: ".concat(r)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:i?"aborted":"error",errors:[e]},R),t||s?(n.reject(t?new _(c.WS_DISCONNECT,"websocket is closed: ".concat(r)):new _(c.WS_ERR,"init websocket failed: ".concat(r))),s&&S.error("[".concat(this.name,"] init websocket failed: ").concat(r))):o&&o(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;S.warning("[choose-best-ws] action: =>",e),this.onlineReconnectListener||o.isOnline||!o.onlineWaiter||(this.onlineReconnectListener=o.onlineWaiter.then((()=>{this.onlineReconnectListener=void 0})));let n=!0;if(this.reconnectInterrupter=()=>n=!1,t){const t=a(this.reconnectCount,this.retryConfig);S.debug("[".concat(this.name,"] wait ").concat(t,"ms to reconnect websocket, mode: ").concat(e)),await Promise.race([R(t),this.onlineReconnectListener||new Promise((()=>{}))])}if("closed"===this._state||!n)return!1;this.reconnectCount+=1;const E=async(e,t)=>{this.emit(y.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e)};try{if("retry"===e)await E(this.urls[this.currentURLIndex],e);else if("tryNext"===e){if(this.currentURLIndex+=1,this.currentURLIndex>=this.urls.length)return this.reconnectWithAction("recover",!1);S.debug("[".concat(this.name,"] websocket url length: ").concat(this.urls.length," current index: ").concat(this.currentURLIndex)),await E(this.urls[this.currentURLIndex],e)}else"recover"===e&&(S.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.urls=await N(this,y.REQUEST_NEW_URLS),this.currentURLIndex=0,await E(this.urls[this.currentURLIndex],e))}catch(n){var i;S.error("[".concat(this.name,"] reconnect failed ").concat(n&&n.toString()));const E=null==n||null===(i=n.data)||void 0===i?void 0:i.desc;return Array.isArray(E)&&E.includes("dynamic key expired")?(this.emit(y.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):this.reconnectWithAction(e,t)}return!0}}class G extends W{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,t){return new Promise(((n,E)=>{let o=!1;const i=[];this.closeEstablishingWs=()=>{S.debug("[choose-best-ws] close establishing websockets"),i.forEach((e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close()})),E(new _(c.WS_ABORT,"choose best websocket aborted"))};const s=r("GATEWAY_DOMAINS");let a;const N=e.indexOf("?h="),A=s.find((t=>-1!==N?e.includes(t,N):e.includes(t)));S.debug("[choose-best-ws] currentDomain: ",A,", domains: ",s);let I=!this.tryDoubleDomain||!A;if(!I&&A){var C;const r=Date.now();try{s.forEach((t=>{const n=-1===N?e.replace(A,t):e.substr(0,N)+e.substr(N).replace(A,t),E=new WebSocket(n);E.binaryType="arraybuffer",i.push(E),S.debug("[choose-best-ws] ws is connecting:",E.url)}))}catch(e){for(S.debug("[choose-best-ws] ws create failed, fallback to single url"),i.forEach((e=>e.close()));i.length;)i.pop();I=!0}null===(C=this.store)||void 0===C||C.recordJoinChannelService({urls:i.map((e=>e.url)),service:"gateway"},t),i.forEach((e=>{e.onopen=()=>{if(o)return;const t=Date.now()-r;S.debug("[choose-best-ws] ws open cost ".concat(t,"ms")),i.filter((t=>t!==e)).forEach((e=>{S.debug("[choose-best-ws]close backup websocket: ".concat(e.url)),e.close()})),o=!0,n(e)},e.onclose=e=>{if(a=e,o)return;i.find((e=>!(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)))||(S.debug("[choose-best-ws] all websocket is closed"),o=!0,E(a))},e.onmessage=t=>{S.debug("[choose-best-ws]".concat(e.url," onmessage: ").concat(t.data))}})),R(this.forceCloseTimeout).then((()=>{i.forEach((e=>{e.readyState!==WebSocket.OPEN&&e.close()}))}))}if(I){var T;let o;S.debug("[choose-best-ws] use single url: ",e),null===(T=this.store)||void 0===T||T.recordJoinChannelService({urls:[e],service:"gateway"},t);try{o=new WebSocket(e),i.push(o),o.binaryType="arraybuffer"}catch(e){const t=new _(c.WS_ERR,"init websocket failed! Error: ".concat(e.toString()));return S.error("[".concat(this.name,"]").concat(t)),void E(t)}o.onopen=()=>{n(o)},o.onclose=e=>{E(e)},o.onmessage=e=>{S.debug("[choose-best-ws]".concat(o.url," onmessage: ").concat(e.data))},R(this.forceCloseTimeout).then((()=>{o&&o.readyState!==WebSocket.OPEN&&o.close()}))}})).then((e=>(this.closeEstablishingWs=void 0,e))).catch((e=>{throw this.closeEstablishingWs=void 0,e}))}}function H(e){let t=$();return function(e,t){let n=e.appId;void 0!==n&&(Ae(t,10),se(t,n));let E=e.cid;void 0!==E&&(Ae(t,16),Ae(t,E));let o=e.cname;void 0!==o&&(Ae(t,26),se(t,o));let i=e.deviceId;void 0!==i&&(Ae(t,34),se(t,i));let s=e.elapse;void 0!==s&&(Ae(t,40),Ie(t,s));let r=e.fileSize;void 0!==r&&(Ae(t,48),Ie(t,Z(r)));let _=e.height;void 0!==_&&(Ae(t,56),Ie(t,Z(_)));let c=e.jpg;void 0!==c&&(Ae(t,66),Ae(t,c.length),function(e,t){let n=Ee(e,t.length);e.bytes.set(t,n)}(t,c));let a=e.networkType;void 0!==a&&(Ae(t,72),Ie(t,Z(a)));let R=e.osType;void 0!==R&&(Ae(t,80),Ie(t,Z(R)));let N=e.requestId;void 0!==N&&(Ae(t,90),se(t,N));let A=e.sdkVersion;void 0!==A&&(Ae(t,98),se(t,A));let I=e.sequence;void 0!==I&&(Ae(t,104),Ie(t,Z(I)));let C=e.sid;void 0!==C&&(Ae(t,114),se(t,C));let T=e.timestamp;void 0!==T&&(Ae(t,120),Ie(t,T));let O=e.uid;void 0!==O&&(Ae(t,128),Ae(t,O));let h=e.vid;void 0!==h&&(Ae(t,136),Ae(t,h));let S=e.width;void 0!==S&&(Ae(t,144),Ie(t,Z(S)));let L=e.service;void 0!==L&&(Ae(t,152),Ae(t,L));let l=e.callbackData;void 0!==l&&(Ae(t,162),se(t,l));let d=e.jpgEncryption;void 0!==d&&(Ae(t,168),Ae(t,d));let u=e.requestType;void 0!==u&&(Ae(t,176),Ae(t,u));let D=e.scorePorn;void 0!==D&&(Ae(t,185),Re(t,D));let f=e.scoreSexy;void 0!==f&&(Ae(t,193),Re(t,f));let w=e.scoreNeutral;void 0!==w&&(Ae(t,201),Re(t,w));let p=e.scene;void 0!==p&&(Ae(t,208),Ae(t,p));let g=e.ossFilePrefix;void 0!==g&&(Ae(t,218),se(t,g));let m=e.serviceVendor;if(void 0!==m)for(let e of m){Ae(t,226);let n=$();F(e,n),Ae(t,n.limit),re(t,n),ee(n)}}(e,t),function(e){let t=e.bytes,n=e.limit;return t.length===n?t:t.subarray(0,n)}(t)}function Y(e){return function(e){let t={};e:for(;!ne(e);){let n=Ne(e);switch(n>>>3){case 0:break e;case 1:t.code=Ne(e);break;case 2:t.msg=ie(e,Ne(e));break;case 3:{let n=q(e);t.data=x(e),e.limit=n;break}default:J(e,7&n)}}return t}({bytes:t=e,offset:0,limit:t.length});var t}function x(e){let t={};e:for(;!ne(e);){let n=Ne(e);switch(n>>>3){case 0:break e;case 1:t.requestId=ie(e,Ne(e));break;case 2:t.requestType=Ne(e)>>>0;break;case 3:t.scorePorn=ae(e);break;case 4:t.scoreSexy=ae(e);break;case 5:t.scoreNeutral=ae(e);break;case 6:t.requestScene=Ne(e)>>>0;break;case 7:t.scene=Ne(e)>>>0;break;default:J(e,7&n)}}return t}function F(e,t){let n=e.service;void 0!==n&&(Ae(t,8),Ae(t,n));let E=e.vendor;void 0!==E&&(Ae(t,16),Ae(t,E));let o=e.token;void 0!==o&&(Ae(t,26),se(t,o));let i=e.callbackUrl;void 0!==i&&(Ae(t,34),se(t,i))}function q(e){let t=Ne(e),n=e.limit;return e.limit=e.offset+t,n}function J(e,t){switch(t){case 0:for(;128&_e(e););break;case 2:te(e,Ne(e));break;case 5:te(e,4);break;case 1:te(e,8);break;default:throw new Error("Unimplemented type: "+t)}}let j=new Float32Array(1);new Uint8Array(j.buffer);let X=new Float64Array(1),Q=new Uint8Array(X.buffer);function Z(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let z=[];function $(){const e=z.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}function ee(e){z.push(e)}function te(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function ne(e){return e.offset>=e.limit}function Ee(e,t){let n=e.bytes,E=e.offset,o=e.limit,i=E+t;if(i>n.length){let t=new Uint8Array(2*i);t.set(n),e.bytes=t}return e.offset=i,i>o&&(e.limit=i),E}function oe(e,t){let n=e.offset;if(n+t>e.limit)throw new Error("Read past limit");return e.offset+=t,n}function ie(e,t){let n=oe(e,t),E=String.fromCharCode,o=e.bytes,i="�",s="";for(let e=0;e<t;e++){let r,_,c,a,R=o[e+n];128&R?192==(224&R)?e+1>=t?s+=i:(r=o[e+n+1],128!=(192&r)?s+=i:(a=(31&R)<<6|63&r,a<128?s+=i:(s+=E(a),e++))):224==(240&R)?e+2>=t?s+=i:(r=o[e+n+1],_=o[e+n+2],32896!=(49344&(r|_<<8))?s+=i:(a=(15&R)<<12|(63&r)<<6|63&_,a<2048||a>=55296&&a<=57343?s+=i:(s+=E(a),e+=2))):240==(248&R)?e+3>=t?s+=i:(r=o[e+n+1],_=o[e+n+2],c=o[e+n+3],8421504!=(12632256&(r|_<<8|c<<16))?s+=i:(a=(7&R)<<18|(63&r)<<12|(63&_)<<6|63&c,a<65536||a>1114111?s+=i:(a-=65536,s+=E(55296+(a>>10),56320+(1023&a)),e+=3))):s+=i:s+=E(R)}return s}function se(e,t){let n=t.length,E=0;for(let e=0;e<n;e++){let o=t.charCodeAt(e);o>=55296&&o<=56319&&e+1<n&&(o=(o<<10)+t.charCodeAt(++e)-56613888),E+=o<128?1:o<2048?2:o<65536?3:4}Ae(e,E);let o=Ee(e,E),i=e.bytes;for(let e=0;e<n;e++){let E=t.charCodeAt(e);E>=55296&&E<=56319&&e+1<n&&(E=(E<<10)+t.charCodeAt(++e)-56613888),E<128?i[o++]=E:(E<2048?i[o++]=E>>6&31|192:(E<65536?i[o++]=E>>12&15|224:(i[o++]=E>>18&7|240,i[o++]=E>>12&63|128),i[o++]=E>>6&63|128),i[o++]=63&E|128)}}function re(e,t){let n=Ee(e,t.limit),E=e.bytes,o=t.bytes;for(let e=0,i=t.limit;e<i;e++)E[e+n]=o[e]}function _e(e){return e.bytes[oe(e,1)]}function ce(e,t){let n=Ee(e,1);e.bytes[n]=t}function ae(e){let t=oe(e,8),n=e.bytes;return Q[0]=n[t++],Q[1]=n[t++],Q[2]=n[t++],Q[3]=n[t++],Q[4]=n[t++],Q[5]=n[t++],Q[6]=n[t++],Q[7]=n[t++],X[0]}function Re(e,t){let n=Ee(e,8),E=e.bytes;X[0]=t,E[n++]=Q[0],E[n++]=Q[1],E[n++]=Q[2],E[n++]=Q[3],E[n++]=Q[4],E[n++]=Q[5],E[n++]=Q[6],E[n++]=Q[7]}function Ne(e){let t,n=0,E=0;do{t=_e(e),n<32&&(E|=(127&t)<<n),n+=7}while(128&t);return E}function Ae(e,t){for(t>>>=0;t>=128;)ce(e,127&t|128),t>>>=7;ce(e,t)}function Ie(e,t){let n=t.low>>>0,E=(t.low>>>28|t.high<<4)>>>0,o=t.high>>>24,i=0===o?0===E?n<16384?n<128?1:2:n<1<<21?3:4:E<16384?E<128?5:6:E<1<<21?7:8:o<128?9:10,s=Ee(e,i),r=e.bytes;switch(i){case 10:r[s+9]=o>>>7&1;case 9:r[s+8]=9!==i?128|o:127&o;case 8:r[s+7]=8!==i?E>>>21|128:E>>>21&127;case 7:r[s+6]=7!==i?E>>>14|128:E>>>14&127;case 6:r[s+5]=6!==i?E>>>7|128:E>>>7&127;case 5:r[s+4]=5!==i?128|E:127&E;case 4:r[s+3]=4!==i?n>>>21|128:n>>>21&127;case 3:r[s+2]=3!==i?n>>>14|128:n>>>14&127;case 2:r[s+1]=2!==i?n>>>7|128:n>>>7&127;case 1:r[s]=1!==i?128|n:127&n}}let Ce=0,Te=0;g.ACCESS_POINT,P.NO_FLAG_SET,P.FLAG_SET_BUT_EMPTY,P.INVALID_FALG_SET,P.FLAG_SET_BUT_NO_RE,P.INVALID_SERVICE_ID,P.NO_SERVICE_AVAILABLE,P.NO_SERVICE_AVAILABLE_P2P,P.NO_SERVICE_AVAILABLE_VOICE,P.NO_SERVICE_AVAILABLE_WEBRTC,P.NO_SERVICE_AVAILABLE_CDS,P.NO_SERVICE_AVAILABLE_CDN,P.NO_SERVICE_AVAILABLE_TDS,P.NO_SERVICE_AVAILABLE_REPORT,P.NO_SERVICE_AVAILABLE_APP_CENTER,P.NO_SERVICE_AVAILABLE_ENV0,P.NO_SERVICE_AVAILABLE_VOET,P.NO_SERVICE_AVAILABLE_STRING_UID,P.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS,g.UNILBS,V.INVALID_VENDOR_KEY,V.INVALID_CHANNEL_NAME,V.INTERNAL_ERROR,V.NO_AUTHORIZED,V.DYNAMIC_KEY_TIMEOUT,V.NO_ACTIVE_STATUS,V.DYNAMIC_KEY_EXPIRED,V.STATIC_USE_DYNAMIC_KEY,V.DYNAMIC_USE_STATIC_KEY,V.USER_OVERLOAD,V.FORBIDDEN_REGION,V.CANNOT_MEET_AREA_DEMAND,g.STRING_UID_ALLOCATOR,m.IIIEGAL_APPID,m.IIIEGAL_UID,m.INTERNAL_ERROR,U.K_TIMESTAMP_EXPIRED,U.K_CHANNEL_PERMISSION_INVALID,U.K_CERTIFICATE_INVALID,U.K_CHANNEL_NAME_EMPTY,U.K_CHANNEL_NOT_FOUND,U.K_TICKET_INVALID,U.K_CHANNEL_CONFLICTED,U.K_SERVICE_NOT_READY,U.K_SERVICE_TOO_HEAVY,U.K_UID_BANNED,U.K_IP_BANNED,U.DATASTREAM2_NOT_AVAILABLE,U.K_AUTO_REBALANCE,U.ERR_INVALID_VENDOR_KEY,U.ERR_INVALID_CHANNEL_NAME,U.WARN_NO_AVAILABLE_CHANNEL,U.WARN_LOOKUP_CHANNEL_TIMEOUT,U.WARN_LOOKUP_CHANNEL_REJECTED,U.WARN_OPEN_CHANNEL_TIMEOUT,U.WARN_OPEN_CHANNEL_REJECTED,U.WARN_REQUEST_DEFERRED,U.ERR_DYNAMIC_KEY_TIMEOUT,U.ERR_NO_AUTHORIZED,U.ERR_VOM_SERVICE_UNAVAILABLE,U.ERR_NO_CHANNEL_AVAILABLE_CODE,U.ERR_MASTER_VOCS_UNAVAILABLE,U.ERR_INTERNAL_ERROR,U.ERR_NO_ACTIVE_STATUS,U.ERR_INVALID_UID,U.ERR_DYNAMIC_KEY_EXPIRED,U.ERR_STATIC_USE_DYANMIC_KE,U.ERR_DYNAMIC_USE_STATIC_KE,U.ERR_NO_VOCS_AVAILABLE,U.ERR_NO_VOS_AVAILABLE,U.ERR_JOIN_CHANNEL_TIMEOUT,U.ERR_JOIN_BY_MULTI_IP,U.ERR_NOT_JOINED,U.ERR_REPEAT_JOIN_REQUEST,U.ERR_REPEAT_JOIN_CHANNEL,U.ERR_INVALID_STRINGUID,U.ERR_TOO_MANY_USERS,U.ERR_SET_CLIENT_ROLE_TIMEOUT,U.ERR_SET_CLIENT_ROLE_NO_PERMISSION,U.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE,U.ERR_PUBLISH_REQUEST_INVALID,U.ERR_SUBSCRIBE_REQUEST_INVALID,U.ERR_NOT_SUPPORTED_MESSAGE,U.ERR_ILLEAGAL_PLUGIN,U.ILLEGAL_CLIENT_ROLE_LEVEL,U.ERR_REJOIN_TOKEN_INVALID,U.ERR_REJOIN_USER_NOT_JOINED,U.ERR_INVALID_OPTIONAL_INFO,U.ERR_TEST_RECOVER,U.ERR_TEST_TRYNEXT,U.ERR_TEST_RETRY,U.ILLEGAL_AES_PASSWORD,U.ERR_TOO_MANY_BROADCASTERS,U.ERR_TOO_MANY_SUBSCRIBERS,U.ERR_LICENSE_ILLEGAL,U.ERR_LICENSE_MISSING,U.ERR_LICENSE_EXPIRED,U.ERR_LICENSE_MINUTES_EXCEEDED,U.ERR_LICENSE_PERIOD_INVALID,U.ERR_LICENSE_MULTIPLE_SDK_SERVICE;const Oe={GLOBAL:{ASIA:[M.CHINA,M.JAPAN,M.INDIA,M.KOREA,M.HKMC],EUROPE:[],NORTH_AMERICA:[M.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}};Object.keys(Oe[M.GLOBAL]),M.CHINA,M.NORTH_AMERICA,M.EUROPE,M.ASIA,M.JAPAN,M.INDIA,M.OCEANIA,M.SOUTH_AMERICA,M.AFRICA,M.KOREA,M.HKMC,M.US;let he=0;function Se(e,t,n,E){let{appId:o,areaCode:i,cname:s,sid:_,token:a,uid:R}=t;he++;const N="image_moderation_api",A={service_name:N,json_body:JSON.stringify({appId:o,areaCode:i,cname:s,command:"allocateEdge",requestId:he,seq:he,sid:_,token:a,ts:Date.now(),uid:R+""})};let O,h,u=e[0];return T((async()=>{O=Date.now();const e=await function(e,t,n,E){return new Promise(((o,i)=>{t.timeout=t.timeout||r("HTTP_CONNECT_TIMEOUT"),t.responseType=t.responseType||"json",t.data&&!n?(t.data=JSON.stringify(t.data),Ce+=I(t.data)):n&&(t.data.size?Ce+=t.data.size:t.data instanceof FormData?Ce+=C(t.data):Ce+=I(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,D.request(t).then((e=>{"string"==typeof e.data?Te+=I(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?Te+=e.data.byteLength:Te+=I(JSON.stringify(e.data)),E&&o({data:e.data,headers:e.headers}),o(e.data)})).catch((e=>{D.isCancel(e)?i(new L(c.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?i(new L(c.NETWORK_TIMEOUT,e.message)):e.response?i(new L(c.NETWORK_RESPONSE_ERROR,e.response.status)):i(new L(c.NETWORK_ERROR,e.message))}))}))}(u,{data:A,cancelToken:n,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(h=Date.now()-O,0!==e.code){const t=new L(l.UNEXPECTED_RESPONSE,"image inspect ap error, code"+e.code,{retry:!0,responseTime:h});throw S.error(t.toString()),t}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new L(l.UNEXPECTED_RESPONSE,"image inspect ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:h});throw S.error(e.toString()),e}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new L(l.UNEXPECTED_RESPONSE,"image inspect ap empty server",{code:t.code,responseTime:h});throw S.error(e.toString()),e}const E=r("VIDEO_INSPECT_WORKER_MANAGER_HOST"),o=r("VIDEO_INSPECT_WORKER_MANAGER_PORT");return{addressList:t.servers.map((e=>{let{address:t,wss:n}=e;if(t&&n)return"wss://".concat(t.replace(/\./g,"-"),".").concat(E,":").concat(o||n)})).filter((e=>!!e)),workerToken:t.workerToken,vid:t.vid,responseTime:h}}),((t,n)=>(d.apworkerEvent(_,{success:!0,sc:200,serviceName:N,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===n,responseTime:h,serverIp:e[n%e.length]}),!1)),((t,n)=>(d.apworkerEvent(_,{success:!1,sc:t.data&&t.data.code||200,serviceName:N,responseTime:h,serverIp:e[n%e.length]}),!!(t.code!==l.OPERATION_ABORTED&&t.code!==l.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(u=e[(n+1)%e.length],!0))),E)}const Le={},le={},de=4294967296,ue=0x10000000000000000,De=ue/2,fe=Ve(0,!0),we=Ve(0),pe=Pe(0,-2147483648,!1),ge=Pe(-1,2147483647,!1),me=Pe(-1,-1,!0);function Ve(e,t){let n,E,o;return t?(o=0<=(e>>>=0)&&e<256)&&(E=le[e],E)?E:(n=Pe(e,0,!0),o&&(le[e]=n),n):(o=-128<=(e|=0)&&e<128)&&(E=Le[e],E)?E:(n=Pe(e,e<0?-1:0,!1),o&&(Le[e]=n),n)}function Pe(e,t,n){return{low:0|e,high:0|t,unsigned:!!n}}function Ue(e,t){if(isNaN(e))return t?fe:we;if(t){if(e<0)return fe;if(e>=ue)return me}else{if(e<=-De)return pe;if(e+1>=De)return ge}return e<0?t?fe:we:Pe(e%de|0,e/de|0,t)}const ye=new Map([["moderation",1],["supervise",2]]);class Me extends t{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(B.CONNECTION_STATE_CHANGE,t,e)}get inspectType(){return this._inspectType}set inspectType(e){this._inspectMode=e.map((e=>ye.get(e)||0)).reduce(((e,t)=>e+t)),this._inspectType=e}get quality(){return this._quality}set quality(e){this._quality=e>1?1:e<.1?.1:e,this.qualityTimer&&(window.clearTimeout(this.qualityTimer),this.qualityTimer=null),this._quality>=1||(this.qualityTimer=window.setTimeout((()=>{this.quality=this._quality/this.qualityRatio}),6e4))}constructor(e){super(),this.name="AgoraRTCVideoContentInspect",this._connectionState=v.CONNECTING,this._innerConnectionState=void 0,this.sequence=0,this.inspectStartTime=void 0,this.workerManagerConnection=void 0,this.workerConnection=void 0,this.workerMessageLengthLimit=void 0,this.inspectIntervalMinimum=void 0,this.qualityRatio=void 0,this._connectInfo=void 0,this._cancelTokenSource=D.CancelToken.source(),this._retryConfig=void 0,this.wmSequence=0,this.inspectInterval=void 0,this.inspectTimer=null,this.ossFilePrefix=void 0,this.extraInfo=void 0,this._inspectType=void 0,this._inspectMode=void 0,this._quality=1,this.qualityTimer=null,this._inspectId=void 0,this._needWorkUrlOnly=!1,this.inspectImage=()=>{if(this.connectionState!==v.CONNECTED)throw new L(l.OPERATION_ABORTED,"content inspect service connection status is ".concat(this.connectionState));this.inspectTimer&&(window.clearInterval(this.inspectTimer),this.inspectTimer=null),this.inspectTimer=window.setInterval((()=>{this.connectionState===v.CONNECTED?this.requestToInspectImage():S.debug("[".concat(this._inspectId,"] Inspect State is not connected , "),this.connectionState)}),this.inspectInterval<this.inspectIntervalMinimum?this.inspectIntervalMinimum:this.inspectInterval),this.requestToInspectImage()},this._inspectId=O(5,"inspect-"),this.workerMessageLengthLimit=r("VIDEO_INSPECT_WORKER_MESSAGE_LENGTH_LIMIT"),this.inspectIntervalMinimum=r("VIDEO_INSPECT_INTERVAL_MINIMUM"),this.qualityRatio=r("VIDEO_INSPECT_QUALITY_RATIO"),this.inspectInterval=e.interval,this.ossFilePrefix=e.ossFilePrefix,this.extraInfo=e.extraInfo,this.inspectType=e.inspectType,this.inspectStartTime=Number(Date.now()),this.workerManagerConnection=new G("worker-manager-"+this._inspectId,h),this.on(B.STATE_CHANGE,((e,t)=>{this._innerConnectionState=e,S.debug("[".concat(this._inspectId,"] Inspect operation :").concat(k[e]," ").concat(t||""))})),this.handleWorkerManagerEvents(),this.workerConnection=new G("worker-"+this._inspectId,h),this.handleWorkerEvents()}async init(e,t){this.emit(B.STATE_CHANGE,k.CONNECT_AP),this._connectInfo=e;const n=this._cancelTokenSource.token;return this._retryConfig=t,new Promise(((E,o)=>{this.on(B.CONNECTION_STATE_CHANGE,((e,t)=>{t===v.CONNECTED&&E()})),this.requestAP(e,n,t).then((e=>{this.connectWorkerManager(e)})).catch((e=>{o(e)}))}))}async requestAP(e,t,n){const E=r("WEBCS_DOMAIN").map((e=>"https://".concat(e,"/api/v1"))),o=await Se(E,e,t,n);this.emit(B.STATE_CHANGE,k.AP_CONNECTED);const{addressList:i}=o;return this.wmSequence++,i}async connectWorkerManager(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._needWorkUrlOnly=t,this.emit(B.STATE_CHANGE,k.CONNECT_WORKER_MANAGER),await this.workerManagerConnection.init(e,1e4)}async connectWorker(e){await this.workerConnection.init([e])}handleWorkerManagerEvents(){this.workerManagerConnection.on(y.CONNECTED,(async()=>{this.emit(B.STATE_CHANGE,k.WORKER_MANAGER_CONNECTED,this.workerManagerConnection.url),this.workerManagerConnection.sendMessage({appId:this._connectInfo.appId,cname:this._connectInfo.cname,uid:this._connectInfo.uid+"",sdkVersion:"4.23.1",sid:this._connectInfo.sid,seq:this.wmSequence,ts:Number(Date.now()),requestId:Math.floor(1e12*Math.random()),allocate:!0,clientRequest:{command:"join"}},!0)})),this.workerManagerConnection.on(y.CLOSED,(()=>{this._innerConnectionState<k.GET_WORKER_MANAGER_RESPONSE&&S.debug("[".concat(this._inspectId,"] Inspect worker manager is closed before connecting worker"))})),this.workerManagerConnection.on(y.FAILED,(()=>{this._innerConnectionState<k.GET_WORKER_MANAGER_RESPONSE&&S.debug("[".concat(this._inspectId,"] Connecting inspect worker manager is failed before connecting worker"))})),this.workerManagerConnection.on(y.RECONNECTING,(()=>{this._innerConnectionState<k.GET_WORKER_MANAGER_RESPONSE&&S.debug("[".concat(this._inspectId,"] Inspect worker manager is reconnecting before connecting worker"))})),this.workerManagerConnection.on(y.ON_MESSAGE,(async e=>{this.emit(B.STATE_CHANGE,k.GET_WORKER_MANAGER_RESPONSE);const t=this.workerManagerConnection.url;this.workerManagerConnection.close();const n=JSON.parse(e.data);if(200!==n.code)throw S.error("[".concat(this._inspectId,"] Unexpected code ").concat(n.code," from worker manager")),new L(l.UNEXPECTED_RESPONSE,"response code of worker is unexpected",n);if(!(n.serverResponse&&n.serverResponse.portWss&&t))throw S.error("[".concat(this._inspectId,"] Unexpected content from worker manager : ").concat(JSON.stringify(n))),new L(l.UNEXPECTED_RESPONSE,"response content of worker is unexpected",n);{const e=r("VIDEO_INSPECT_WORKER_PORT")||n.serverResponse.portWss,E=t.replace(/:\d+\/?$/,":".concat(e));this.emit(B.STATE_CHANGE,k.CONNECT_WORKER,E),this._needWorkUrlOnly?this.emit(B.REQUEST_NEW_WORKER_URL,E):await this.connectWorker(E)}})),this.workerManagerConnection.on(y.WILL_RECONNECT,((e,t,n)=>{n(e)})),this.workerManagerConnection.on(y.REQUEST_NEW_URLS,((e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t)}))}handleWorkerEvents(){this.workerConnection.on(y.CONNECTED,(async()=>{this.emit(B.STATE_CHANGE,k.WORKER_CONNECTED,this.workerConnection.url),this.connectionState=v.CONNECTED})),this.workerConnection.on(y.ON_MESSAGE,(async e=>{if(e.data instanceof ArrayBuffer){const t=Y(new Uint8Array(e.data));if(r("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")&&S.debug("[".concat(this._inspectId,"] Response message for worker of inspect content "),JSON.stringify(t)),200===t.code){if(Array.isArray(this.inspectType)&&1===this.inspectType.length&&"supervise"===this.inspectType[0])return void this.emit(B.INSPECT_RESULT,void 0,void 0);if(t.data&&t.data.scorePorn&&t.data.scoreSexy&&t.data.scoreNeutral){const e={porn:t.data.scorePorn,sexy:t.data.scoreSexy,neutral:t.data.scoreNeutral},n=Object.keys(e).reduce(((t,n)=>e[t]>e[n]?t:n),"porn"),E=Object.keys(e).find((e=>e===n));this.emit(B.INSPECT_RESULT,E)}else this.emit(B.INSPECT_RESULT,void 0,new L(l.UNEXPECTED_RESPONSE,t.code+"","There is an unexpected data on message"))}else this.emit(B.INSPECT_RESULT,void 0,new L(l.UNEXPECTED_RESPONSE,t.code+"",t.msg))}else S.error("[".concat(this._inspectId,"] Unexpected message type from worker")),this.emit(B.INSPECT_RESULT,void 0,new L(l.UNEXPECTED_RESPONSE,"invalid worker message type"))})),this.workerConnection.on(y.CLOSED,(()=>{this.connectionState=v.CLOSED})),this.workerConnection.on(y.FAILED,(()=>{this.connectionState=v.CLOSED})),this.workerConnection.on(y.RECONNECTING,(()=>{this.connectionState=this.connectionState===v.CONNECTED?v.RECONNECTING:v.CONNECTING})),this.workerConnection.on(y.WILL_RECONNECT,((e,t,n)=>{"recover"===e&&n(e),n("tryNext")})),this.workerConnection.on(y.REQUEST_NEW_URLS,((e,t)=>{this.workerManagerConnection.close(),this.once(B.REQUEST_NEW_WORKER_URL,(t=>{e([t])})),this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then((e=>{this.connectWorkerManager(e,!0)})).catch((e=>{t(e)}))}))}async requestToInspectImage(){this.sequence++;const e=A(this,B.CLIENT_LOCAL_VIDEO_TRACK),t={appId:this._connectInfo.appId,cname:this._connectInfo.cname,cid:this._connectInfo.cid,sid:this._connectInfo.sid,uid:this._connectInfo.uid,vid:this._connectInfo.vid};if(e){if(!e.isPlaying)return void this.emit(B.INSPECT_RESULT,void 0,new L(l.INVALID_OPERATION,"Only the track being played can be inspected"));const n=await this.generateRequestData(e,t);this.workerConnection.sendMessage(n,!0,!0)}else this.emit(B.INSPECT_RESULT,void 0,new L(l.INVALID_OPERATION,"Only the track being published can be inspected"))}async generateRequestData(e,t){let{appId:n,cname:E,cid:o,vid:i,sid:s,uid:_}=t;const c=Date.now(),a=await e.getCurrentFrameImage("image/jpeg",this.quality),R=await u(a,n,E),N=this.sequence+"-"+o+"-"+_+"-"+c+"-"+O(12,""),A={appId:n,cid:o,cname:E,deviceId:"",elapse:(I=Number(c-this.inspectStartTime),{low:I|=0,high:I>>31,unsigned:I>=0}),fileSize:R.byteLength,jpgEncryption:2,height:a.height,width:a.width,jpg:R,networkType:6,osType:7,requestId:N,sdkVersion:"4.23.1",sequence:this.sequence,sid:s,timestamp:Ue(c),uid:_,vid:i,service:this._inspectMode,callbackData:this.extraInfo,ossFilePrefix:this.ossFilePrefix};var I;void 0===this.extraInfo&&delete A.callbackData,void 0===this.ossFilePrefix&&delete A.ossFilePrefix;const C=H(A);if(C.byteLength<this.workerMessageLengthLimit){if(r("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")){const e=p({},A);delete e.jpg,S.debug("[".concat(this._inspectId,"] Request message for worker of inspect content "),JSON.stringify(e))}return C}{const t=this.quality*this.qualityRatio;return this.quality=t,await this.generateRequestData(e,{appId:n,cname:E,cid:o,vid:i,sid:s,uid:_})}}close(){this._cancelTokenSource.cancel(),this._cancelTokenSource=D.CancelToken.source(),this.workerManagerConnection&&this.workerManagerConnection.close(),this.workerConnection&&this.workerConnection.close(),this.inspectTimer&&window.clearInterval(this.inspectTimer),this.inspectTimer=null,this.connectionState=v.CLOSED,this.emit(B.STATE_CHANGE,k.CLOSED)}}function be(e){if(!e)throw new L(l.INVALID_PARAMS,"inspectConfig is necessary.");if(!e.inspectType||!Array.isArray(e.inspectType))throw new L(l.INVALID_PARAMS,"inspectConfig.inspectType is necessary and is an instance of Array.");{const t=[...new Set(e.inspectType)];t.forEach((e=>{if(!["supervise","moderation"].includes(e))throw new L(l.INVALID_PARAMS,"".concat(e," is not a valid inspect type."))})),e.inspectType=t}if(e&&e.extraInfo&&e.extraInfo.length>1024)throw new L(l.INVALID_PARAMS,"inspectConfig.extraInfo length cannot exceed 1024 bytes")}const ve={name:"ContentInspect",create:function(e){let{config:t}=e;return be(t),new Me(t)}};export{ve as ContentInspectService,be as checkContentInspectConfig}; |
/** | ||
* AgoraWebSDK_N-v4.23.0-0-g98fcf352-dirty Copyright AgoraInc. | ||
* AgoraWebSDK_N-v4.23.1-0-gea45199f-dirty Copyright AgoraInc. | ||
*/ | ||
import{RemoteDataChannel as e,LocalDataChannel as t}from"@agora-js/media";import{logger as n}from"@agora-js/report";import{getParameter as r}from"@agora-js/shared";import{inflate as a,deflate as s}from"pako";var i=function(e){return e[e.ONE_BYTE=0]="ONE_BYTE",e[e.TWO_BYTE=1]="TWO_BYTE",e}(i||{});class o{constructor(){this._sequence=0,this._startTime=Date.now(),this.isUseOneByte=!0}get startTime(){const e=Date.now()-this._startTime;return e<Math.pow(2,16)?e:(this._startTime+=Math.pow(2,16),this.startTime)}get sequence(){return this._sequence<Math.pow(2,32)?this._sequence++:(this._sequence-=Math.pow(2,32),this.sequence)}serialize(e){const t={commonPacketHeader:{length:0,reserved:0,extension:0,sequence:this.sequence},commonStreamHeader:this.startTime,extension:void 0,payload:e};if(e.byteLength>128){const n=new Uint8Array(4);n.set([1,0,0,0]);const r={id:0,length:4,data:n.buffer},a={profile:this.isUseOneByte?0:1,length:this.isUseOneByte?5:6,datas:[r]};t.commonPacketHeader.extension=1,t.extension=a,t.payload=this.compress(e),t.commonPacketHeader.length=8+(t.extension.length+2)+t.payload.byteLength}else t.commonPacketHeader.length=8+t.payload.byteLength;r("SHOW_DATASTREAM2_LOG")&&n.debug("send data header: ".concat(JSON.stringify(t.commonPacketHeader)));const a=new ArrayBuffer(t.commonPacketHeader.length),s=new Uint8Array(a),i=new DataView(a);let o=0;if(i.setUint16(o,t.commonPacketHeader.extension<<15|t.commonPacketHeader.reserved<<14|t.commonPacketHeader.length,!0),o+=2,i.setUint32(o,t.commonPacketHeader.sequence,!0),o+=4,i.setUint16(o,t.commonStreamHeader,!0),o+=2,t.extension){const e=this.serializeExtension(t.extension);s.set(new Uint8Array(e),o),o+=e.byteLength}if(s.set(new Uint8Array(t.payload),o),o+=t.payload.byteLength,o!==t.commonPacketHeader.length)throw Error("serialize error!");return a}deserialize(e){if(e.byteLength<4)return new ArrayBuffer(0);const t=new DataView(e);let a=0;const s=t.getUint16(a,!0);a+=2;const i={length:16383&s,reserved:(16384&s)>>14,extension:(32768&s)>>15,sequence:t.getUint16(a+2,!0)<<16|t.getUint16(a,!0)};let o,c;if(a+=4,r("SHOW_DATASTREAM2_LOG")&&n.debug("receive data header: ".concat(JSON.stringify(i))),t.getUint16(a,!0),a+=2,i.extension){c=this.deserializeExtension(e.slice(a)),a+=2+c.length,o=e.slice(a);let t=!1;if(c.datas.length>0){const e=c.datas.find((e=>0===e.id));if(e){t=1==(1&new DataView(e.data).getUint32(0,!0))}}o=t?this.decompress(o):o}else o=e.slice(8);return o}serializeExtension(e){const{profile:t,length:n,datas:r}=e,a=new ArrayBuffer(n+2),s=new Uint8Array(a),i=new DataView(a);let o=0;if(i.setUint8(o++,t),i.setUint8(o++,n),r.forEach((e=>{t?(i.setUint8(o++,e.id),i.setUint8(o++,e.length),s.set(new Uint8Array(e.data),o),o+=e.data.byteLength):(i.setUint8(o++,e.id|e.length<<4),s.set(new Uint8Array(e.data),o),o+=e.data.byteLength)})),o!==n+2)throw Error("serialize extension error, is ".concat(o,"!==").concat(n+2));return a}deserializeExtension(e){const t=new DataView(e);let n=0;const r=t.getUint8(n);n++;const a=t.getUint8(n);n++;const s=r===i.TWO_BYTE,o=[],c=new DataView(e,2);let h=0;for(;h<a;){let e=0,t=0,n=new ArrayBuffer(0);s?(e=c.getUint8(h),h++,t=c.getUint8(h),h++):(e=15&c.getUint8(h),t=c.getUint8(h)>>4,h++),t>0&&(n=c.buffer.slice(h+2,h+2+t),h+=n.byteLength),o.push({id:e,length:t,data:n})}if(h!==a)throw Error("parse error");return{profile:r,length:a,datas:o}}decompress(e){return a(new Uint8Array(e))}compress(e){return s(new Uint8Array(e))}}const c={name:"DataStream",create:(n,r)=>{const a=r?new e(n):new t(n);return a.useDataStream(new o),a}};export{c as DataStreamService}; | ||
import{RemoteDataChannel as e,LocalDataChannel as t}from"@agora-js/media";import{logger as n}from"@agora-js/report";import{getParameter as r}from"@agora-js/shared";import{inflate as a,deflate as s}from"pako";var i=function(e){return e[e.ONE_BYTE=0]="ONE_BYTE",e[e.TWO_BYTE=1]="TWO_BYTE",e}(i||{});class o{constructor(){this._sequence=0,this._startTime=Date.now(),this.isUseOneByte=!0}get startTime(){const e=Date.now()-this._startTime;return e<Math.pow(2,16)?e:(this._startTime+=Math.pow(2,16),this.startTime)}get sequence(){return this._sequence<Math.pow(2,32)?this._sequence++:(this._sequence-=Math.pow(2,32),this.sequence)}serialize(e){const t={commonPacketHeader:{length:0,reserved:0,extension:0,sequence:this.sequence},commonStreamHeader:this.startTime,extension:void 0,payload:e};if(e.byteLength>128){const n=new Uint8Array(4);n.set([1,0,0,0]);const r={id:0,length:4,data:n.buffer},a={profile:this.isUseOneByte?0:1,length:this.isUseOneByte?5:6,datas:[r]};t.commonPacketHeader.extension=1,t.extension=a,t.payload=this.compress(e),t.commonPacketHeader.length=8+(t.extension.length+2)+t.payload.byteLength}else t.commonPacketHeader.length=8+t.payload.byteLength;r("SHOW_DATASTREAM2_LOG")&&n.debug("send data header: ".concat(JSON.stringify(t.commonPacketHeader)));const a=new ArrayBuffer(t.commonPacketHeader.length),s=new Uint8Array(a),i=new DataView(a);let o=0;if(i.setUint16(o,t.commonPacketHeader.extension<<15|t.commonPacketHeader.reserved<<14|t.commonPacketHeader.length,!0),o+=2,i.setUint32(o,t.commonPacketHeader.sequence,!0),o+=4,i.setUint16(o,t.commonStreamHeader,!0),o+=2,t.extension){const e=this.serializeExtension(t.extension);s.set(new Uint8Array(e),o),o+=e.byteLength}if(s.set(new Uint8Array(t.payload),o),o+=t.payload.byteLength,o!==t.commonPacketHeader.length)throw Error("serialize error!");return a}deserialize(e){if(e.byteLength<4)return new ArrayBuffer(0);const t=new DataView(e);let a=0;const s=t.getUint16(a,!0);a+=2;const i={length:16383&s,reserved:(16384&s)>>14,extension:(32768&s)>>15,sequence:t.getUint16(a+2,!0)<<16|t.getUint16(a,!0)};let o,c;if(a+=4,r("SHOW_DATASTREAM2_LOG")&&n.debug("receive data header: ".concat(JSON.stringify(i))),t.getUint16(a,!0),a+=2,i.extension){c=this.deserializeExtension(e.slice(a)),a+=2+c.length,o=e.slice(a);let t=!1;if(c.datas.length>0){const e=c.datas.find((e=>0===e.id));if(e){t=!(1&~new DataView(e.data).getUint32(0,!0))}}o=t?this.decompress(o):o}else o=e.slice(8);return o}serializeExtension(e){const{profile:t,length:n,datas:r}=e,a=new ArrayBuffer(n+2),s=new Uint8Array(a),i=new DataView(a);let o=0;if(i.setUint8(o++,t),i.setUint8(o++,n),r.forEach((e=>{t?(i.setUint8(o++,e.id),i.setUint8(o++,e.length),s.set(new Uint8Array(e.data),o),o+=e.data.byteLength):(i.setUint8(o++,e.id|e.length<<4),s.set(new Uint8Array(e.data),o),o+=e.data.byteLength)})),o!==n+2)throw Error("serialize extension error, is ".concat(o,"!==").concat(n+2));return a}deserializeExtension(e){const t=new DataView(e);let n=0;const r=t.getUint8(n);n++;const a=t.getUint8(n);n++;const s=r===i.TWO_BYTE,o=[],c=new DataView(e,2);let h=0;for(;h<a;){let e=0,t=0,n=new ArrayBuffer(0);s?(e=c.getUint8(h),h++,t=c.getUint8(h),h++):(e=15&c.getUint8(h),t=c.getUint8(h)>>4,h++),t>0&&(n=c.buffer.slice(h+2,h+2+t),h+=n.byteLength),o.push({id:e,length:t,data:n})}if(h!==a)throw Error("parse error");return{profile:r,length:a,datas:o}}decompress(e){return a(new Uint8Array(e))}compress(e){return s(new Uint8Array(e))}}const c={name:"DataStream",create:(n,r)=>{const a=r?new e(n):new t(n);return a.useDataStream(new o),a}};export{c as DataStreamService}; |
/** | ||
* AgoraWebSDK_N-v4.23.0-0-g98fcf352-dirty Copyright AgoraInc. | ||
* AgoraWebSDK_N-v4.23.1-0-gea45199f-dirty Copyright AgoraInc. | ||
*/ | ||
import{IS_GLOBAL_VERSION as e,EventEmitter as t,PromiseMutex as n,NETWORK_STATE as E,networkIndicator as o,NETWORK_INDICATOR_EVENTS as i,createDefer as _,getParameter as s,AgoraRTCError as r,AgoraRTCErrorCode as c,getRetryWaitTime as a,wait as R,emitAsPromise as A,emitAsInvokerNoResponse as N,getUTF8StringByteLength as I,getMultiUnilbsFormDataByteLength as O,retryable as T,checkValidNumber as C,getRandomString as h,DEFAULT_RETRY_CONFIG as L,AgoraAPIName as S,AgoraAPITag as d}from"@agora-js/shared";import{logger as l,AgoraRTCError as u,AgoraRTCErrorCode as D,report as m}from"@agora-js/report";import{frameData2CryptoBuffer as f}from"@agora-js/media";import w from"axios";import"formdata-polyfill";function g(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var E=n.call(e,t||"default");if("object"!=typeof E)return E;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:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function V(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var E=Object.getOwnPropertySymbols(e);t&&(E=E.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,E)}return n}function M(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?V(Object(n),!0).forEach((function(t){g(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):V(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let U=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}({}),b=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}({}),v=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}({}),p=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}({}),P=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.DATASTREAM2_NOT_AVAILABLE=27]="DATASTREAM2_NOT_AVAILABLE",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}({}),y=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_CREATE_CONNECTION="websocket:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="websocket:on_token_privilege_did_expire",e}({}),k=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}({});k.AFRICA,k.ASIA,k.CHINA,k.EUROPE,k.GLOBAL,k.INDIA,k.JAPAN,k.NORTH_AMERICA,k.OCEANIA,k.OVERSEA,k.SOUTH_AMERICA;let B=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}({});B.ASIA,B.NORTH_AMERICA,B.EUROPE,B.JAPAN,B.INDIA,B.KOREA,B.HKMC,B.US,B.OVERSEA,B.GLOBAL,B.OCEANIA,B.SOUTH_AMERICA,B.AFRICA,e&&B.CHINA;let K=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_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}({}),G=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED",e}({}),W=function(e){return e.CONNECTION_STATE_CHANGE="connection-state-change",e.STATE_CHANGE="state-change",e.INSPECT_RESULT="inspect-result",e.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",e.REQUEST_NEW_WORKER_URL="request-new-worker-url",e}({}),H=function(e){return e[e.CONNECT_AP=0]="CONNECT_AP",e[e.AP_CONNECTED=1]="AP_CONNECTED",e[e.CONNECT_WORKER_MANAGER=2]="CONNECT_WORKER_MANAGER",e[e.WORKER_MANAGER_CONNECTED=3]="WORKER_MANAGER_CONNECTED",e[e.GET_WORKER_MANAGER_RESPONSE=4]="GET_WORKER_MANAGER_RESPONSE",e[e.CONNECT_WORKER=5]="CONNECT_WORKER",e[e.WORKER_CONNECTED=6]="WORKER_CONNECTED",e[e.CLOSED=7]="CLOSED",e}({});class Y extends t{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(y.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(y.CONNECTED):"closed"===this._state?this.emit(y.CLOSED):"failed"===this._state&&this.emit(y.FAILED))}resetReconnectCount(e){l.debug("websocket reset reconnect count, reason: "+e),this.reconnectCount=0}constructor(e,t){let _=arguments.length>2&&void 0!==arguments[2]&&arguments[2],s=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=arguments.length>4&&void 0!==arguments[4]&&arguments[4],c=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=void 0,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=c,this.name=e,this.retryConfig=M({},t),this.useCompress=_,this.tryDoubleDomain=s,this.use443PortOnly=r,this._initMutex=new n("websocket",c?c.clientId:void 0);const{timeout:a,timeoutFactor:R}=t,A=Math.max(300,Math.floor(3*a/5)),N=Math.max(1.2,Math.floor(8*R)/10);E.ONLINE&&(this.retryConfig.timeout=A,this.retryConfig.timeoutFactor=N),o.on(i.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===E.ONLINE?(this.retryConfig.timeout=A,this.retryConfig.timeoutFactor=N):(this.retryConfig.timeout=a,this.retryConfig.timeoutFactor=R))}))}getConnection(){return this.websocket||void 0}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const n=await this._initMutex.lock();this._reconnectMode="tryNext",this.forceCloseTimeout=t,this.urls=e,this.state="connecting";try{const e=_(),t=this.urls[this.currentURLIndex];s("ENABLE_PREALLOC_PC")&&this.emit(K.PRE_CONNECT_PC),this.createWebSocketConnection(t).then(e.resolve).catch(e.reject),this.once(y.CLOSED,(()=>{e.reject(new r(c.WS_DISCONNECT))})),this.once(y.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 l.warning("[".concat(this.name,"] can not reconnect, no websocket"));void 0!==e&&(this.reconnectMode=e),l.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 n=this.websocket.onclose;this.websocket.onclose=null,this.websocket.close(),n&&n.bind(this.websocket)({code:9999,reason:t})}sendMessage(e){let t=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new r(c.WS_ABORT,"websocket is not ready");try{t||(e=JSON.stringify(e)),this.websocket.send(e)}catch(e){throw new r(c.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 t;const n=_();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const E=e=>{var t;null===(t=this.store)||void 0===t||t.signalChannelOpen(),l.debug("[".concat(this.name,"] websocket opened:"),e),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),n.resolve()},o=async e=>{var t;if(l.debug("[".concat(this.name,"] websocket close ").concat(null===(t=this.websocket)||void 0===t?void 0:t.url,", code: ").concat(e.code,", reason: ").concat(e.reason,", current mode: ").concat(this.reconnectMode)),this.reconnectCount>=this.retryConfig.maxRetryCount)n.reject(new r(c.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close();else{"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");const t=N(this,y.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,E=await this.reconnectWithAction(t);if("closed"===this.state)return void l.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!E)return n.reject(new r(c.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);n.resolve()}},i=e=>{this.emit(y.ON_MESSAGE,e)},a=e=>{l.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")),l.debug("[".concat(this.name,"] start connect, url:"),e);const R=null===(t=this.store)||void 0===t?void 0:t.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});try{var A;const t=await this.chooseBestWebsocketConnection(e);this.websocket=t,E&&E(this.websocket.url),this.websocket.onclose=o,this.websocket.onmessage=i,this.websocket.onerror=a,null===(A=this.store)||void 0===A||A.recordJoinChannelService({endTs:Date.now(),status:"success"},R),this.joinGatewayRecordIndex=R}catch(e){const t="closed"===this.state,E=e instanceof r,i=E&&e.code===c.WS_ABORT,_=E&&e.code===c.WS_ERR,s=E?e.message:e&&(e.reason||e.toString());l.warning("[choose-best-ws] chooseBestWebsocket error: ".concat(s)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:i?"aborted":"error",errors:[e]},R),t||_?(n.reject(t?new r(c.WS_DISCONNECT,"websocket is closed: ".concat(s)):new r(c.WS_ERR,"init websocket failed: ".concat(s))),_&&l.error("[".concat(this.name,"] init websocket failed: ").concat(s))):o&&o(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;l.warning("[choose-best-ws] action: =>",e),this.onlineReconnectListener||o.isOnline||!o.onlineWaiter||(this.onlineReconnectListener=o.onlineWaiter.then((()=>{this.onlineReconnectListener=void 0})));let n=!0;if(this.reconnectInterrupter=()=>n=!1,t){const t=a(this.reconnectCount,this.retryConfig);l.debug("[".concat(this.name,"] wait ").concat(t,"ms to reconnect websocket, mode: ").concat(e)),await Promise.race([R(t),this.onlineReconnectListener||new Promise((()=>{}))])}if("closed"===this._state||!n)return!1;this.reconnectCount+=1;const E=async(e,t)=>{this.emit(y.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e)};try{if("retry"===e)await E(this.urls[this.currentURLIndex],e);else if("tryNext"===e){if(this.currentURLIndex+=1,this.currentURLIndex>=this.urls.length)return this.reconnectWithAction("recover",!1);l.debug("[".concat(this.name,"] websocket url length: ").concat(this.urls.length," current index: ").concat(this.currentURLIndex)),await E(this.urls[this.currentURLIndex],e)}else"recover"===e&&(l.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.urls=await A(this,y.REQUEST_NEW_URLS),this.currentURLIndex=0,await E(this.urls[this.currentURLIndex],e))}catch(n){var i;l.error("[".concat(this.name,"] reconnect failed ").concat(n&&n.toString()));const E=null==n||null===(i=n.data)||void 0===i?void 0:i.desc;return Array.isArray(E)&&E.includes("dynamic key expired")?(this.emit(y.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):this.reconnectWithAction(e,t)}return!0}}class F extends Y{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,t){return new Promise(((n,E)=>{let o=!1;const i=[];this.closeEstablishingWs=()=>{l.debug("[choose-best-ws] close establishing websockets"),i.forEach((e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close()})),E(new r(c.WS_ABORT,"choose best websocket aborted"))};const _=s("GATEWAY_DOMAINS");let a;const A=e.indexOf("?h="),N=_.find((t=>-1!==A?e.includes(t,A):e.includes(t)));l.debug("[choose-best-ws] currentDomain: ",N,", domains: ",_);let I=!this.tryDoubleDomain||!N;if(!I&&N){var O;const s=Date.now();try{_.forEach((t=>{const n=-1===A?e.replace(N,t):e.substr(0,A)+e.substr(A).replace(N,t),E=new WebSocket(n);E.binaryType="arraybuffer",i.push(E),l.debug("[choose-best-ws] ws is connecting:",E.url)}))}catch(e){for(l.debug("[choose-best-ws] ws create failed, fallback to single url"),i.forEach((e=>e.close()));i.length;)i.pop();I=!0}null===(O=this.store)||void 0===O||O.recordJoinChannelService({urls:i.map((e=>e.url)),service:"gateway"},t),i.forEach((e=>{e.onopen=()=>{if(o)return;const t=Date.now()-s;l.debug("[choose-best-ws] ws open cost ".concat(t,"ms")),i.filter((t=>t!==e)).forEach((e=>{l.debug("[choose-best-ws]close backup websocket: ".concat(e.url)),e.close()})),o=!0,n(e)},e.onclose=e=>{if(a=e,o)return;i.find((e=>!(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)))||(l.debug("[choose-best-ws] all websocket is closed"),o=!0,E(a))},e.onmessage=t=>{l.debug("[choose-best-ws]".concat(e.url," onmessage: ").concat(t.data))}})),R(this.forceCloseTimeout).then((()=>{i.forEach((e=>{e.readyState!==WebSocket.OPEN&&e.close()}))}))}if(I){var T;let o;l.debug("[choose-best-ws] use single url: ",e),null===(T=this.store)||void 0===T||T.recordJoinChannelService({urls:[e],service:"gateway"},t);try{o=new WebSocket(e),i.push(o),o.binaryType="arraybuffer"}catch(e){const t=new r(c.WS_ERR,"init websocket failed! Error: ".concat(e.toString()));return l.error("[".concat(this.name,"]").concat(t)),void E(t)}o.onopen=()=>{n(o)},o.onclose=e=>{E(e)},o.onmessage=e=>{l.debug("[choose-best-ws]".concat(o.url," onmessage: ").concat(e.data))},R(this.forceCloseTimeout).then((()=>{o&&o.readyState!==WebSocket.OPEN&&o.close()}))}})).then((e=>(this.closeEstablishingWs=void 0,e))).catch((e=>{throw this.closeEstablishingWs=void 0,e}))}}function J(e){let t=function(){const e=X.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}();return function(e,t){let n=e.appId;void 0!==n&&(_e(t,10),ne(t,n));let E=e.cid;void 0!==E&&(_e(t,16),_e(t,E));let o=e.cname;void 0!==o&&(_e(t,26),ne(t,o));let i=e.deviceId;void 0!==i&&(_e(t,34),ne(t,i));let _=e.elapse;void 0!==_&&(_e(t,40),re(t,_));let s=e.fileSize;void 0!==s&&(_e(t,48),re(t,j(s)));let r=e.height;void 0!==r&&(_e(t,56),re(t,j(r)));let c=e.jpg;void 0!==c&&(_e(t,66),_e(t,c.length),ee(t,c));let a=e.networkType;void 0!==a&&(_e(t,72),re(t,j(a)));let R=e.osType;void 0!==R&&(_e(t,80),re(t,j(R)));let A=e.requestId;void 0!==A&&(_e(t,90),ne(t,A));let N=e.sdkVersion;void 0!==N&&(_e(t,98),ne(t,N));let I=e.sequence;void 0!==I&&(_e(t,104),re(t,j(I)));let O=e.sid;void 0!==O&&(_e(t,114),ne(t,O));let T=e.timestamp;void 0!==T&&(_e(t,120),re(t,T));let C=e.uid;void 0!==C&&(_e(t,128),_e(t,C));let h=e.vid;void 0!==h&&(_e(t,136),_e(t,h));let L=e.width;void 0!==L&&(_e(t,144),re(t,j(L)));let S=e.service;void 0!==S&&(_e(t,152),_e(t,S));let d=e.callbackData;void 0!==d&&(_e(t,162),_e(t,d.length),ee(t,d));let l=e.ticket;void 0!==l&&(_e(t,170),ne(t,l));let u=e.vendorConfigs;void 0!==u&&(_e(t,178),ne(t,u))}(e,t),function(e){let t=e.bytes,n=e.limit;return t.length===n?t:t.subarray(0,n)}(t)}function x(e){return function(e){let t={};e:for(;!Z(e);){let n=ie(e);switch(n>>>3){case 0:break e;case 1:t.code=ie(e);break;case 2:t.msg=te(e,ie(e));break;case 3:t.requestId=te(e,ie(e));break;case 4:t.timestamp=se(e,!1);break;default:q(e,7&n)}}return t}({bytes:t=e,offset:0,limit:t.length});var t}function q(e,t){switch(t){case 0:for(;128&Ee(e););break;case 2:Q(e,ie(e));break;case 5:Q(e,4);break;case 1:Q(e,8);break;default:throw new Error("Unimplemented type: "+t)}}function j(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let X=[];function Q(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function Z(e){return e.offset>=e.limit}function z(e,t){let n=e.bytes,E=e.offset,o=e.limit,i=E+t;if(i>n.length){let t=new Uint8Array(2*i);t.set(n),e.bytes=t}return e.offset=i,i>o&&(e.limit=i),E}function $(e,t){let n=e.offset;if(n+t>e.limit)throw new Error("Read past limit");return e.offset+=t,n}function ee(e,t){let n=z(e,t.length);e.bytes.set(t,n)}function te(e,t){let n=$(e,t),E=String.fromCharCode,o=e.bytes,i="�",_="";for(let e=0;e<t;e++){let s,r,c,a,R=o[e+n];0==(128&R)?_+=E(R):192==(224&R)?e+1>=t?_+=i:(s=o[e+n+1],128!=(192&s)?_+=i:(a=(31&R)<<6|63&s,a<128?_+=i:(_+=E(a),e++))):224==(240&R)?e+2>=t?_+=i:(s=o[e+n+1],r=o[e+n+2],32896!=(49344&(s|r<<8))?_+=i:(a=(15&R)<<12|(63&s)<<6|63&r,a<2048||a>=55296&&a<=57343?_+=i:(_+=E(a),e+=2))):240==(248&R)?e+3>=t?_+=i:(s=o[e+n+1],r=o[e+n+2],c=o[e+n+3],8421504!=(12632256&(s|r<<8|c<<16))?_+=i:(a=(7&R)<<18|(63&s)<<12|(63&r)<<6|63&c,a<65536||a>1114111?_+=i:(a-=65536,_+=E(55296+(a>>10),56320+(1023&a)),e+=3))):_+=i}return _}function ne(e,t){let n=t.length,E=0;for(let e=0;e<n;e++){let o=t.charCodeAt(e);o>=55296&&o<=56319&&e+1<n&&(o=(o<<10)+t.charCodeAt(++e)-56613888),E+=o<128?1:o<2048?2:o<65536?3:4}_e(e,E);let o=z(e,E),i=e.bytes;for(let e=0;e<n;e++){let E=t.charCodeAt(e);E>=55296&&E<=56319&&e+1<n&&(E=(E<<10)+t.charCodeAt(++e)-56613888),E<128?i[o++]=E:(E<2048?i[o++]=E>>6&31|192:(E<65536?i[o++]=E>>12&15|224:(i[o++]=E>>18&7|240,i[o++]=E>>12&63|128),i[o++]=E>>6&63|128),i[o++]=63&E|128)}}function Ee(e){return e.bytes[$(e,1)]}function oe(e,t){let n=z(e,1);e.bytes[n]=t}function ie(e){let t,n=0,E=0;do{t=Ee(e),n<32&&(E|=(127&t)<<n),n+=7}while(128&t);return E}function _e(e,t){for(t>>>=0;t>=128;)oe(e,127&t|128),t>>>=7;oe(e,t)}function se(e,t){let n,E=0,o=0,i=0;return n=Ee(e),E=127&n,128&n&&(n=Ee(e),E|=(127&n)<<7,128&n&&(n=Ee(e),E|=(127&n)<<14,128&n&&(n=Ee(e),E|=(127&n)<<21,128&n&&(n=Ee(e),o=127&n,128&n&&(n=Ee(e),o|=(127&n)<<7,128&n&&(n=Ee(e),o|=(127&n)<<14,128&n&&(n=Ee(e),o|=(127&n)<<21,128&n&&(n=Ee(e),i=127&n,128&n&&(n=Ee(e),i|=(127&n)<<7))))))))),{low:E|o<<28,high:o>>>4|i<<24,unsigned:t}}function re(e,t){let n=t.low>>>0,E=(t.low>>>28|t.high<<4)>>>0,o=t.high>>>24,i=0===o?0===E?n<16384?n<128?1:2:n<1<<21?3:4:E<16384?E<128?5:6:E<1<<21?7:8:o<128?9:10,_=z(e,i),s=e.bytes;switch(i){case 10:s[_+9]=o>>>7&1;case 9:s[_+8]=9!==i?128|o:127&o;case 8:s[_+7]=8!==i?E>>>21|128:E>>>21&127;case 7:s[_+6]=7!==i?E>>>14|128:E>>>14&127;case 6:s[_+5]=6!==i?E>>>7|128:E>>>7&127;case 5:s[_+4]=5!==i?128|E:127&E;case 4:s[_+3]=4!==i?n>>>21|128:n>>>21&127;case 3:s[_+2]=3!==i?n>>>14|128:n>>>14&127;case 2:s[_+1]=2!==i?n>>>7|128:n>>>7&127;case 1:s[_]=1!==i?128|n:127&n}}const ce={},ae={},Re=4294967296,Ae=Re*Re,Ne=Ae/2,Ie=Le(0,!0),Oe=Le(0),Te=Se(0,-2147483648,!1),Ce=Se(-1,2147483647,!1),he=Se(-1,-1,!0);function Le(e,t){let n,E,o;return t?(o=0<=(e>>>=0)&&e<256)&&(E=ae[e],E)?E:(n=Se(e,0,!0),o&&(ae[e]=n),n):(o=-128<=(e|=0)&&e<128)&&(E=ce[e],E)?E:(n=Se(e,e<0?-1:0,!1),o&&(ce[e]=n),n)}function Se(e,t,n){return{low:0|e,high:0|t,unsigned:!!n}}function de(e,t){if(isNaN(e))return t?Ie:Oe;if(t){if(e<0)return Ie;if(e>=Ae)return he}else{if(e<=-Ne)return Te;if(e+1>=Ne)return Ce}return e<0?t?Ie:Oe:Se(e%Re|0,e/Re|0,t)}let le=0,ue=0;U.ACCESS_POINT,p.NO_FLAG_SET,p.FLAG_SET_BUT_EMPTY,p.INVALID_FALG_SET,p.FLAG_SET_BUT_NO_RE,p.INVALID_SERVICE_ID,p.NO_SERVICE_AVAILABLE,p.NO_SERVICE_AVAILABLE_P2P,p.NO_SERVICE_AVAILABLE_VOICE,p.NO_SERVICE_AVAILABLE_WEBRTC,p.NO_SERVICE_AVAILABLE_CDS,p.NO_SERVICE_AVAILABLE_CDN,p.NO_SERVICE_AVAILABLE_TDS,p.NO_SERVICE_AVAILABLE_REPORT,p.NO_SERVICE_AVAILABLE_APP_CENTER,p.NO_SERVICE_AVAILABLE_ENV0,p.NO_SERVICE_AVAILABLE_VOET,p.NO_SERVICE_AVAILABLE_STRING_UID,p.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS,U.UNILBS,v.INVALID_VENDOR_KEY,v.INVALID_CHANNEL_NAME,v.INTERNAL_ERROR,v.NO_AUTHORIZED,v.DYNAMIC_KEY_TIMEOUT,v.NO_ACTIVE_STATUS,v.DYNAMIC_KEY_EXPIRED,v.STATIC_USE_DYNAMIC_KEY,v.DYNAMIC_USE_STATIC_KEY,v.USER_OVERLOAD,v.FORBIDDEN_REGION,v.CANNOT_MEET_AREA_DEMAND,U.STRING_UID_ALLOCATOR,b.IIIEGAL_APPID,b.IIIEGAL_UID,b.INTERNAL_ERROR,P.K_TIMESTAMP_EXPIRED,P.K_CHANNEL_PERMISSION_INVALID,P.K_CERTIFICATE_INVALID,P.K_CHANNEL_NAME_EMPTY,P.K_CHANNEL_NOT_FOUND,P.K_TICKET_INVALID,P.K_CHANNEL_CONFLICTED,P.K_SERVICE_NOT_READY,P.K_SERVICE_TOO_HEAVY,P.K_UID_BANNED,P.K_IP_BANNED,P.DATASTREAM2_NOT_AVAILABLE,P.K_AUTO_REBALANCE,P.ERR_INVALID_VENDOR_KEY,P.ERR_INVALID_CHANNEL_NAME,P.WARN_NO_AVAILABLE_CHANNEL,P.WARN_LOOKUP_CHANNEL_TIMEOUT,P.WARN_LOOKUP_CHANNEL_REJECTED,P.WARN_OPEN_CHANNEL_TIMEOUT,P.WARN_OPEN_CHANNEL_REJECTED,P.WARN_REQUEST_DEFERRED,P.ERR_DYNAMIC_KEY_TIMEOUT,P.ERR_NO_AUTHORIZED,P.ERR_VOM_SERVICE_UNAVAILABLE,P.ERR_NO_CHANNEL_AVAILABLE_CODE,P.ERR_MASTER_VOCS_UNAVAILABLE,P.ERR_INTERNAL_ERROR,P.ERR_NO_ACTIVE_STATUS,P.ERR_INVALID_UID,P.ERR_DYNAMIC_KEY_EXPIRED,P.ERR_STATIC_USE_DYANMIC_KE,P.ERR_DYNAMIC_USE_STATIC_KE,P.ERR_NO_VOCS_AVAILABLE,P.ERR_NO_VOS_AVAILABLE,P.ERR_JOIN_CHANNEL_TIMEOUT,P.ERR_JOIN_BY_MULTI_IP,P.ERR_NOT_JOINED,P.ERR_REPEAT_JOIN_REQUEST,P.ERR_REPEAT_JOIN_CHANNEL,P.ERR_INVALID_STRINGUID,P.ERR_TOO_MANY_USERS,P.ERR_SET_CLIENT_ROLE_TIMEOUT,P.ERR_SET_CLIENT_ROLE_NO_PERMISSION,P.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE,P.ERR_PUBLISH_REQUEST_INVALID,P.ERR_SUBSCRIBE_REQUEST_INVALID,P.ERR_NOT_SUPPORTED_MESSAGE,P.ERR_ILLEAGAL_PLUGIN,P.ILLEGAL_CLIENT_ROLE_LEVEL,P.ERR_REJOIN_TOKEN_INVALID,P.ERR_REJOIN_USER_NOT_JOINED,P.ERR_INVALID_OPTIONAL_INFO,P.ERR_TEST_RECOVER,P.ERR_TEST_TRYNEXT,P.ERR_TEST_RETRY,P.ILLEGAL_AES_PASSWORD,P.ERR_TOO_MANY_BROADCASTERS,P.ERR_TOO_MANY_SUBSCRIBERS,P.ERR_LICENSE_ILLEGAL,P.ERR_LICENSE_MISSING,P.ERR_LICENSE_EXPIRED,P.ERR_LICENSE_MINUTES_EXCEEDED,P.ERR_LICENSE_PERIOD_INVALID,P.ERR_LICENSE_MULTIPLE_SDK_SERVICE;const De={GLOBAL:{ASIA:[k.CHINA,k.JAPAN,k.INDIA,k.KOREA,k.HKMC],EUROPE:[],NORTH_AMERICA:[k.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}};Object.keys(De[k.GLOBAL]),k.CHINA,k.NORTH_AMERICA,k.EUROPE,k.ASIA,k.JAPAN,k.INDIA,k.OCEANIA,k.SOUTH_AMERICA,k.AFRICA,k.KOREA,k.HKMC,k.US;let me=0;function fe(e,t,n,E){let{appId:o,areaCode:i,cname:_,sid:r,token:a,uid:R}=t;me++;const A="moderation_plugin",N={service_name:A,json_body:JSON.stringify({appId:o,areaCode:i,cname:_,command:"allocateEdge",requestId:me,seq:me,sid:r,appToken:a,ts:Date.now(),uid:R+""})};let C,h,L=e[0];return T((async()=>{C=Date.now();const e=await function(e,t,n,E){return new Promise(((o,i)=>{t.timeout=t.timeout||s("HTTP_CONNECT_TIMEOUT"),t.responseType=t.responseType||"json",t.data&&!n?(t.data=JSON.stringify(t.data),le+=I(t.data)):n&&(t.data.size?le+=t.data.size:t.data instanceof FormData?le+=O(t.data):le+=I(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,w.request(t).then((e=>{"string"==typeof e.data?ue+=I(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?ue+=e.data.byteLength:ue+=I(JSON.stringify(e.data)),E&&o({data:e.data,headers:e.headers}),o(e.data)})).catch((e=>{w.isCancel(e)?i(new u(c.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?i(new u(c.NETWORK_TIMEOUT,e.message)):e.response?i(new u(c.NETWORK_RESPONSE_ERROR,e.response.status)):i(new u(c.NETWORK_ERROR,e.message))}))}))}(L,{data:N,cancelToken:n,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(h=Date.now()-C,0!==e.code){const t=new u(D.UNEXPECTED_RESPONSE,"moderation plugin ap error, code"+e.code,{retry:!0,responseTime:h});throw l.error(t.toString()),t}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new u(D.UNEXPECTED_RESPONSE,"moderation plugin ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:h});throw l.error(e.toString()),e}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new u(D.UNEXPECTED_RESPONSE,"moderation plugin ap empty server",{code:t.code,responseTime:h});throw l.error(e.toString()),e}if(!t.servers.some((e=>!!e.wss))){const e=new u(D.UNEXPECTED_RESPONSE,"moderation plugin ap empty port",{code:t.code,responseTime:h});throw l.error(e.toString()),e}const E=s("IMAGE_MODERATION_WORKER_HOST");return{addressList:t.servers.map((e=>{let{address:t,wss:n}=e;if(t&&n)return"wss://".concat(t.replace(/\./g,"-"),".").concat(E,":").concat(n,"/moderation")})).filter((e=>!!e)),workerToken:t.workerToken,vid:t.vid,ticket:t.appTicket,responseTime:h}}),((t,n)=>(m.apworkerEvent(r,{success:!0,sc:200,serviceName:A,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===n,responseTime:h,serverIp:e[n%e.length]}),!1)),((t,n)=>(m.apworkerEvent(r,{success:!1,sc:t.data&&t.data.code||200,serviceName:A,responseTime:h,serverIp:e[n%e.length]}),!!(t.code!==D.OPERATION_ABORTED&&t.code!==D.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(L=e[(n+1)%e.length],!0))),E)}class we extends t{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(W.CONNECTION_STATE_CHANGE,e,t)}get quality(){return this._quality}set quality(e){this._quality=e>1?1:e<.1?.1:e,this._qualityTimer&&(window.clearTimeout(this._qualityTimer),this._qualityTimer=null),this._quality>=1||(this._qualityTimer=window.setTimeout((()=>{this.quality=this._quality/this._qualityRatio}),6e4))}constructor(e){var t;super(),this.name="AgoraRTCImageModeration",this._connectionState=G.CONNECTING,this._sequence=0,this._moderationStartTime=void 0,this._workerConnection=void 0,this._workerMessageLengthLimit=void 0,this._qualityRatio=void 0,this._connectInfo=void 0,this._cancelTokenSource=w.CancelToken.source(),this._retryConfig=void 0,this._moderationInterval=void 0,this._moderationTimer=null,this._moderationMode=1,this._quality=1,this._qualityTimer=null,this._ticket=void 0,this._moderationIntervalMinimum=void 0,this._uploadFailedNum=0,this._uploadNum=0,this._uploadTimer=null,this._extraInfo=void 0,this._vendor="",this._encoder=new TextEncoder,this._moderationId=void 0,this.inspectImage=()=>{if(this.connectionState!==G.CONNECTED)throw new u(D.OPERATION_ABORTED,"image moderation service connection status is ".concat(this.connectionState));this._moderationTimer&&(window.clearInterval(this._moderationTimer),this._moderationTimer=null),this._moderationTimer=window.setInterval((()=>{this.connectionState===G.CONNECTED?this.requestToInspectImage():l.debug("[".concat(this._moderationId,"] Moderation State is not connected , "),this.connectionState)}),this._moderationInterval<this._moderationIntervalMinimum?this._moderationIntervalMinimum:this._moderationInterval),this.requestToInspectImage()},this._moderationId=h(5,"image-moderation-"),this._workerMessageLengthLimit=s("IMAGE_MODERATION_WORKER_MESSAGE_LENGTH_LIMIT"),this._moderationIntervalMinimum=s("IMAGE_MODERATION_INTERVAL_MINIMUM"),this._moderationInterval=null!==(t=e.interval)&&void 0!==t?t:1e3,e.extraInfo&&(this._extraInfo=this._encoder.encode(e.extraInfo)),e.vendor&&(this._vendor=e.vendor),this._qualityRatio=s("IMAGE_MODERATION_QUALITY_RATIO"),this._moderationStartTime=Number(Date.now()),this._workerConnection=new F("worker-"+this._moderationId,L),this.on(W.STATE_CHANGE,((e,t)=>{l.debug("[".concat(this._moderationId,"] Moderation operation :").concat(H[e]," ").concat(t||""))})),this.handleWorkerEvents()}async init(e,t){this.emit(W.STATE_CHANGE,H.CONNECT_AP),this._connectInfo=e;const n=this._cancelTokenSource.token;return this._retryConfig=t,new Promise(((E,o)=>{this.on(W.CONNECTION_STATE_CHANGE,((e,t)=>{e===G.CONNECTED&&E()})),this.requestAP(e,n,t).then((e=>{this.connectWorker(e)})).catch((e=>{o(e)}))}))}updateConfig(e){var t;this._moderationInterval=null!==(t=e.interval)&&void 0!==t?t:1e3,e.extraInfo&&(this._extraInfo=this._encoder.encode(e.extraInfo)),e.vendor&&(this._vendor=e.vendor),l.debug("[".concat(this._moderationId,"] updateConfig: ").concat(JSON.stringify(e))),this.connectionState===G.CONNECTED&&this.inspectImage()}async requestAP(e,t,n){const E=s("WEBCS_DOMAIN").map((e=>"https://".concat(e,"/api/v1"))),o=await fe(E,e,t,n);this.emit(W.STATE_CHANGE,H.AP_CONNECTED);const{addressList:i,ticket:_}=o;return this._ticket=_,i}async connectWorker(e){this.emit(W.STATE_CHANGE,H.CONNECT_WORKER),await this._workerConnection.init(e,1e4)}handleWorkerEvents(){this._workerConnection.on(y.CONNECTED,(async()=>{this.emit(W.STATE_CHANGE,H.WORKER_CONNECTED,this._workerConnection.url),this.connectionState=G.CONNECTED})),this._workerConnection.on(y.CLOSED,(()=>{this.connectionState=G.CLOSED})),this._workerConnection.on(y.FAILED,(()=>{this.connectionState=G.CLOSED})),this._workerConnection.on(y.RECONNECTING,(()=>{this.connectionState=this.connectionState===G.CONNECTED?G.RECONNECTING:G.CONNECTING})),this._workerConnection.on(y.ON_MESSAGE,(async e=>{if(e.data instanceof ArrayBuffer){const t=x(new Uint8Array(e.data));s("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&l.debug("[".concat(this._moderationId,"] Response message for worker of image moderation "),JSON.stringify(t)),this._uploadNum++,void 0===t.code||0===t.code||(this._uploadFailedNum++,l.error("[".concat(this._moderationId,"] Error response from worke, code is ").concat(t.code,", msg is ").concat(t.msg)),this._uploadTimer||(this._uploadTimer=window.setTimeout((()=>{m.reportApiInvoke(this._connectInfo.sid||null,{name:S.IMAGE_MODERATION_UPLOAD,options:[this._uploadFailedNum,this._uploadNum,t.code],tag:d.TRACER}).onError(new u(D.IMAGE_MODERATION_UPLOAD_FAILED,t.msg)),this._uploadTimer=null}),s("IMAGE_MODERATION_UPLOAD_REPORT_INTERVAL"))))}else l.error("[".concat(this._moderationId,"] Unexpected message type from worker"))})),this._workerConnection.on(y.WILL_RECONNECT,((e,t,n)=>{"recover"===e&&n(e),n("tryNext")})),this._workerConnection.on(y.REQUEST_NEW_URLS,((e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t)}))}static intToLong(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}async requestToInspectImage(){const e=N(this,W.CLIENT_LOCAL_VIDEO_TRACK),t={appId:this._connectInfo.appId,cname:this._connectInfo.cname,cid:this._connectInfo.cid,sid:this._connectInfo.sid,uid:this._connectInfo.uid,vid:this._connectInfo.vid};if(e){if(!e.isPlaying)return void(s("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&l.debug("Only the track being played can be inspected"));this._sequence++;const n=await this.generateRequestData(e,t);this._workerConnection.sendMessage(n,!0,!0)}else s("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&l.debug("Only the track being published can be inspected")}async generateRequestData(e,t){let{appId:n,cname:E,cid:o,vid:i,sid:_,uid:r}=t;const c=Date.now(),a=await e.getCurrentFrameImage("image/jpeg",this.quality),R=await f(a,n,E),A=this._sequence+"-"+o+"-"+r+"-"+c+"-"+h(12,""),N={appId:n,cid:o,cname:E,deviceId:"",elapse:we.intToLong(Number(c-this._moderationStartTime)),fileSize:a.buffer.byteLength,height:a.height,width:a.width,jpg:R,networkType:6,osType:7,requestId:A,sdkVersion:"4.23.0",sequence:this._sequence,sid:_,timestamp:de(c),uid:r,vid:i,service:this._moderationMode,ticket:this._ticket,callbackData:this._extraInfo,vendorConfigs:this._vendor};void 0===this._extraInfo&&delete N.callbackData;const I=J(N);if(I.byteLength<this._workerMessageLengthLimit){if(s("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")){const e=M({},N);delete e.jpg,l.debug("[".concat(this._moderationId,"] Request message for worker of image moderation service: "),JSON.stringify(e))}return I}{const t=this.quality*this._qualityRatio;return this.quality=t,await this.generateRequestData(e,{appId:n,cname:E,cid:o,vid:i,sid:_,uid:r})}}close(){this._cancelTokenSource.cancel(),this._cancelTokenSource=w.CancelToken.source(),this._workerConnection&&this._workerConnection.close(),this._moderationTimer&&window.clearInterval(this._moderationTimer),this._moderationTimer=null,this._uploadTimer&&window.clearTimeout(this._uploadTimer),this._uploadTimer=null,this.connectionState=G.CLOSED,this.emit(W.STATE_CHANGE,H.CLOSED)}}function ge(e){if(C(e.interval,"interval",1e3,1/0),e&&e.extraInfo&&e.extraInfo.length>1024)throw new u(D.INVALID_PARAMS,"config.extraInfo length cannot exceed 1024 bytes");if(e&&e.vendor&&e.vendor.length>1024)throw new u(D.INVALID_PARAMS,"config.vendor length cannot exceed 1024 bytes")}const Ve={name:"ImageModeration",create:function(e){let{config:t}=e;return ge(t),new we(t)}};export{Ve as ImageModerationService,ge as checkImageModerationConfig}; | ||
import{IS_GLOBAL_VERSION as e,EventEmitter as t,PromiseMutex as n,NETWORK_STATE as E,networkIndicator as o,NETWORK_INDICATOR_EVENTS as i,createDefer as _,getParameter as s,AgoraRTCError as r,AgoraRTCErrorCode as c,getRetryWaitTime as a,wait as R,emitAsPromise as A,emitAsInvokerNoResponse as N,getUTF8StringByteLength as I,getMultiUnilbsFormDataByteLength as O,retryable as T,checkValidNumber as C,getRandomString as h,DEFAULT_RETRY_CONFIG as L,AgoraAPIName as S,AgoraAPITag as d}from"@agora-js/shared";import{logger as l,AgoraRTCError as u,AgoraRTCErrorCode as D,report as m}from"@agora-js/report";import{frameData2CryptoBuffer as f}from"@agora-js/media";import w from"axios";import"formdata-polyfill";function g(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var E=n.call(e,t||"default");if("object"!=typeof E)return E;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:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function V(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var E=Object.getOwnPropertySymbols(e);t&&(E=E.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,E)}return n}function M(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?V(Object(n),!0).forEach((function(t){g(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):V(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let U=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}({}),b=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}({}),v=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}({}),p=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}({}),P=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.DATASTREAM2_NOT_AVAILABLE=27]="DATASTREAM2_NOT_AVAILABLE",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}({}),y=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_CREATE_CONNECTION="websocket:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="websocket:on_token_privilege_did_expire",e}({}),k=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}({});k.AFRICA,k.ASIA,k.CHINA,k.EUROPE,k.GLOBAL,k.INDIA,k.JAPAN,k.NORTH_AMERICA,k.OCEANIA,k.OVERSEA,k.SOUTH_AMERICA;let B=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}({});B.ASIA,B.NORTH_AMERICA,B.EUROPE,B.JAPAN,B.INDIA,B.KOREA,B.HKMC,B.US,B.OVERSEA,B.GLOBAL,B.OCEANIA,B.SOUTH_AMERICA,B.AFRICA,e&&B.CHINA;let K=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_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}({}),G=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED",e}({}),W=function(e){return e.CONNECTION_STATE_CHANGE="connection-state-change",e.STATE_CHANGE="state-change",e.INSPECT_RESULT="inspect-result",e.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",e.REQUEST_NEW_WORKER_URL="request-new-worker-url",e}({}),H=function(e){return e[e.CONNECT_AP=0]="CONNECT_AP",e[e.AP_CONNECTED=1]="AP_CONNECTED",e[e.CONNECT_WORKER_MANAGER=2]="CONNECT_WORKER_MANAGER",e[e.WORKER_MANAGER_CONNECTED=3]="WORKER_MANAGER_CONNECTED",e[e.GET_WORKER_MANAGER_RESPONSE=4]="GET_WORKER_MANAGER_RESPONSE",e[e.CONNECT_WORKER=5]="CONNECT_WORKER",e[e.WORKER_CONNECTED=6]="WORKER_CONNECTED",e[e.CLOSED=7]="CLOSED",e}({});class Y extends t{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(y.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(y.CONNECTED):"closed"===this._state?this.emit(y.CLOSED):"failed"===this._state&&this.emit(y.FAILED))}resetReconnectCount(e){l.debug("websocket reset reconnect count, reason: "+e),this.reconnectCount=0}constructor(e,t){let _=arguments.length>2&&void 0!==arguments[2]&&arguments[2],s=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=arguments.length>4&&void 0!==arguments[4]&&arguments[4],c=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=void 0,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=c,this.name=e,this.retryConfig=M({},t),this.useCompress=_,this.tryDoubleDomain=s,this.use443PortOnly=r,this._initMutex=new n("websocket",c?c.clientId:void 0);const{timeout:a,timeoutFactor:R}=t,A=Math.max(300,Math.floor(3*a/5)),N=Math.max(1.2,Math.floor(8*R)/10);E.ONLINE&&(this.retryConfig.timeout=A,this.retryConfig.timeoutFactor=N),o.on(i.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===E.ONLINE?(this.retryConfig.timeout=A,this.retryConfig.timeoutFactor=N):(this.retryConfig.timeout=a,this.retryConfig.timeoutFactor=R))}))}getConnection(){return this.websocket||void 0}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const n=await this._initMutex.lock();this._reconnectMode="tryNext",this.forceCloseTimeout=t,this.urls=e,this.state="connecting";try{const e=_(),t=this.urls[this.currentURLIndex];s("ENABLE_PREALLOC_PC")&&this.emit(K.PRE_CONNECT_PC),this.createWebSocketConnection(t).then(e.resolve).catch(e.reject),this.once(y.CLOSED,(()=>{e.reject(new r(c.WS_DISCONNECT))})),this.once(y.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 l.warning("[".concat(this.name,"] can not reconnect, no websocket"));void 0!==e&&(this.reconnectMode=e),l.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 n=this.websocket.onclose;this.websocket.onclose=null,this.websocket.close(),n&&n.bind(this.websocket)({code:9999,reason:t})}sendMessage(e){let t=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new r(c.WS_ABORT,"websocket is not ready");try{t||(e=JSON.stringify(e)),this.websocket.send(e)}catch(e){throw new r(c.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 t;const n=_();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const E=e=>{var t;null===(t=this.store)||void 0===t||t.signalChannelOpen(),l.debug("[".concat(this.name,"] websocket opened:"),e),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),n.resolve()},o=async e=>{var t;if(l.debug("[".concat(this.name,"] websocket close ").concat(null===(t=this.websocket)||void 0===t?void 0:t.url,", code: ").concat(e.code,", reason: ").concat(e.reason,", current mode: ").concat(this.reconnectMode)),this.reconnectCount>=this.retryConfig.maxRetryCount)n.reject(new r(c.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close();else{"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");const t=N(this,y.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,E=await this.reconnectWithAction(t);if("closed"===this.state)return void l.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!E)return n.reject(new r(c.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);n.resolve()}},i=e=>{this.emit(y.ON_MESSAGE,e)},a=e=>{l.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")),l.debug("[".concat(this.name,"] start connect, url:"),e);const R=null===(t=this.store)||void 0===t?void 0:t.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});try{var A;const t=await this.chooseBestWebsocketConnection(e);this.websocket=t,E&&E(this.websocket.url),this.websocket.onclose=o,this.websocket.onmessage=i,this.websocket.onerror=a,null===(A=this.store)||void 0===A||A.recordJoinChannelService({endTs:Date.now(),status:"success"},R),this.joinGatewayRecordIndex=R}catch(e){const t="closed"===this.state,E=e instanceof r,i=E&&e.code===c.WS_ABORT,_=E&&e.code===c.WS_ERR,s=E?e.message:e&&(e.reason||e.toString());l.warning("[choose-best-ws] chooseBestWebsocket error: ".concat(s)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:i?"aborted":"error",errors:[e]},R),t||_?(n.reject(t?new r(c.WS_DISCONNECT,"websocket is closed: ".concat(s)):new r(c.WS_ERR,"init websocket failed: ".concat(s))),_&&l.error("[".concat(this.name,"] init websocket failed: ").concat(s))):o&&o(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;l.warning("[choose-best-ws] action: =>",e),this.onlineReconnectListener||o.isOnline||!o.onlineWaiter||(this.onlineReconnectListener=o.onlineWaiter.then((()=>{this.onlineReconnectListener=void 0})));let n=!0;if(this.reconnectInterrupter=()=>n=!1,t){const t=a(this.reconnectCount,this.retryConfig);l.debug("[".concat(this.name,"] wait ").concat(t,"ms to reconnect websocket, mode: ").concat(e)),await Promise.race([R(t),this.onlineReconnectListener||new Promise((()=>{}))])}if("closed"===this._state||!n)return!1;this.reconnectCount+=1;const E=async(e,t)=>{this.emit(y.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e)};try{if("retry"===e)await E(this.urls[this.currentURLIndex],e);else if("tryNext"===e){if(this.currentURLIndex+=1,this.currentURLIndex>=this.urls.length)return this.reconnectWithAction("recover",!1);l.debug("[".concat(this.name,"] websocket url length: ").concat(this.urls.length," current index: ").concat(this.currentURLIndex)),await E(this.urls[this.currentURLIndex],e)}else"recover"===e&&(l.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.urls=await A(this,y.REQUEST_NEW_URLS),this.currentURLIndex=0,await E(this.urls[this.currentURLIndex],e))}catch(n){var i;l.error("[".concat(this.name,"] reconnect failed ").concat(n&&n.toString()));const E=null==n||null===(i=n.data)||void 0===i?void 0:i.desc;return Array.isArray(E)&&E.includes("dynamic key expired")?(this.emit(y.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):this.reconnectWithAction(e,t)}return!0}}class F extends Y{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,t){return new Promise(((n,E)=>{let o=!1;const i=[];this.closeEstablishingWs=()=>{l.debug("[choose-best-ws] close establishing websockets"),i.forEach((e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close()})),E(new r(c.WS_ABORT,"choose best websocket aborted"))};const _=s("GATEWAY_DOMAINS");let a;const A=e.indexOf("?h="),N=_.find((t=>-1!==A?e.includes(t,A):e.includes(t)));l.debug("[choose-best-ws] currentDomain: ",N,", domains: ",_);let I=!this.tryDoubleDomain||!N;if(!I&&N){var O;const s=Date.now();try{_.forEach((t=>{const n=-1===A?e.replace(N,t):e.substr(0,A)+e.substr(A).replace(N,t),E=new WebSocket(n);E.binaryType="arraybuffer",i.push(E),l.debug("[choose-best-ws] ws is connecting:",E.url)}))}catch(e){for(l.debug("[choose-best-ws] ws create failed, fallback to single url"),i.forEach((e=>e.close()));i.length;)i.pop();I=!0}null===(O=this.store)||void 0===O||O.recordJoinChannelService({urls:i.map((e=>e.url)),service:"gateway"},t),i.forEach((e=>{e.onopen=()=>{if(o)return;const t=Date.now()-s;l.debug("[choose-best-ws] ws open cost ".concat(t,"ms")),i.filter((t=>t!==e)).forEach((e=>{l.debug("[choose-best-ws]close backup websocket: ".concat(e.url)),e.close()})),o=!0,n(e)},e.onclose=e=>{if(a=e,o)return;i.find((e=>!(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)))||(l.debug("[choose-best-ws] all websocket is closed"),o=!0,E(a))},e.onmessage=t=>{l.debug("[choose-best-ws]".concat(e.url," onmessage: ").concat(t.data))}})),R(this.forceCloseTimeout).then((()=>{i.forEach((e=>{e.readyState!==WebSocket.OPEN&&e.close()}))}))}if(I){var T;let o;l.debug("[choose-best-ws] use single url: ",e),null===(T=this.store)||void 0===T||T.recordJoinChannelService({urls:[e],service:"gateway"},t);try{o=new WebSocket(e),i.push(o),o.binaryType="arraybuffer"}catch(e){const t=new r(c.WS_ERR,"init websocket failed! Error: ".concat(e.toString()));return l.error("[".concat(this.name,"]").concat(t)),void E(t)}o.onopen=()=>{n(o)},o.onclose=e=>{E(e)},o.onmessage=e=>{l.debug("[choose-best-ws]".concat(o.url," onmessage: ").concat(e.data))},R(this.forceCloseTimeout).then((()=>{o&&o.readyState!==WebSocket.OPEN&&o.close()}))}})).then((e=>(this.closeEstablishingWs=void 0,e))).catch((e=>{throw this.closeEstablishingWs=void 0,e}))}}function x(e){let t=function(){const e=X.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}();return function(e,t){let n=e.appId;void 0!==n&&(_e(t,10),ne(t,n));let E=e.cid;void 0!==E&&(_e(t,16),_e(t,E));let o=e.cname;void 0!==o&&(_e(t,26),ne(t,o));let i=e.deviceId;void 0!==i&&(_e(t,34),ne(t,i));let _=e.elapse;void 0!==_&&(_e(t,40),re(t,_));let s=e.fileSize;void 0!==s&&(_e(t,48),re(t,j(s)));let r=e.height;void 0!==r&&(_e(t,56),re(t,j(r)));let c=e.jpg;void 0!==c&&(_e(t,66),_e(t,c.length),ee(t,c));let a=e.networkType;void 0!==a&&(_e(t,72),re(t,j(a)));let R=e.osType;void 0!==R&&(_e(t,80),re(t,j(R)));let A=e.requestId;void 0!==A&&(_e(t,90),ne(t,A));let N=e.sdkVersion;void 0!==N&&(_e(t,98),ne(t,N));let I=e.sequence;void 0!==I&&(_e(t,104),re(t,j(I)));let O=e.sid;void 0!==O&&(_e(t,114),ne(t,O));let T=e.timestamp;void 0!==T&&(_e(t,120),re(t,T));let C=e.uid;void 0!==C&&(_e(t,128),_e(t,C));let h=e.vid;void 0!==h&&(_e(t,136),_e(t,h));let L=e.width;void 0!==L&&(_e(t,144),re(t,j(L)));let S=e.service;void 0!==S&&(_e(t,152),_e(t,S));let d=e.callbackData;void 0!==d&&(_e(t,162),_e(t,d.length),ee(t,d));let l=e.ticket;void 0!==l&&(_e(t,170),ne(t,l));let u=e.vendorConfigs;void 0!==u&&(_e(t,178),ne(t,u))}(e,t),function(e){let t=e.bytes,n=e.limit;return t.length===n?t:t.subarray(0,n)}(t)}function J(e){return function(e){let t={};e:for(;!Z(e);){let n=ie(e);switch(n>>>3){case 0:break e;case 1:t.code=ie(e);break;case 2:t.msg=te(e,ie(e));break;case 3:t.requestId=te(e,ie(e));break;case 4:t.timestamp=se(e,!1);break;default:q(e,7&n)}}return t}({bytes:t=e,offset:0,limit:t.length});var t}function q(e,t){switch(t){case 0:for(;128&Ee(e););break;case 2:Q(e,ie(e));break;case 5:Q(e,4);break;case 1:Q(e,8);break;default:throw new Error("Unimplemented type: "+t)}}function j(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let X=[];function Q(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function Z(e){return e.offset>=e.limit}function z(e,t){let n=e.bytes,E=e.offset,o=e.limit,i=E+t;if(i>n.length){let t=new Uint8Array(2*i);t.set(n),e.bytes=t}return e.offset=i,i>o&&(e.limit=i),E}function $(e,t){let n=e.offset;if(n+t>e.limit)throw new Error("Read past limit");return e.offset+=t,n}function ee(e,t){let n=z(e,t.length);e.bytes.set(t,n)}function te(e,t){let n=$(e,t),E=String.fromCharCode,o=e.bytes,i="�",_="";for(let e=0;e<t;e++){let s,r,c,a,R=o[e+n];128&R?192==(224&R)?e+1>=t?_+=i:(s=o[e+n+1],128!=(192&s)?_+=i:(a=(31&R)<<6|63&s,a<128?_+=i:(_+=E(a),e++))):224==(240&R)?e+2>=t?_+=i:(s=o[e+n+1],r=o[e+n+2],32896!=(49344&(s|r<<8))?_+=i:(a=(15&R)<<12|(63&s)<<6|63&r,a<2048||a>=55296&&a<=57343?_+=i:(_+=E(a),e+=2))):240==(248&R)?e+3>=t?_+=i:(s=o[e+n+1],r=o[e+n+2],c=o[e+n+3],8421504!=(12632256&(s|r<<8|c<<16))?_+=i:(a=(7&R)<<18|(63&s)<<12|(63&r)<<6|63&c,a<65536||a>1114111?_+=i:(a-=65536,_+=E(55296+(a>>10),56320+(1023&a)),e+=3))):_+=i:_+=E(R)}return _}function ne(e,t){let n=t.length,E=0;for(let e=0;e<n;e++){let o=t.charCodeAt(e);o>=55296&&o<=56319&&e+1<n&&(o=(o<<10)+t.charCodeAt(++e)-56613888),E+=o<128?1:o<2048?2:o<65536?3:4}_e(e,E);let o=z(e,E),i=e.bytes;for(let e=0;e<n;e++){let E=t.charCodeAt(e);E>=55296&&E<=56319&&e+1<n&&(E=(E<<10)+t.charCodeAt(++e)-56613888),E<128?i[o++]=E:(E<2048?i[o++]=E>>6&31|192:(E<65536?i[o++]=E>>12&15|224:(i[o++]=E>>18&7|240,i[o++]=E>>12&63|128),i[o++]=E>>6&63|128),i[o++]=63&E|128)}}function Ee(e){return e.bytes[$(e,1)]}function oe(e,t){let n=z(e,1);e.bytes[n]=t}function ie(e){let t,n=0,E=0;do{t=Ee(e),n<32&&(E|=(127&t)<<n),n+=7}while(128&t);return E}function _e(e,t){for(t>>>=0;t>=128;)oe(e,127&t|128),t>>>=7;oe(e,t)}function se(e,t){let n,E=0,o=0,i=0;return n=Ee(e),E=127&n,128&n&&(n=Ee(e),E|=(127&n)<<7,128&n&&(n=Ee(e),E|=(127&n)<<14,128&n&&(n=Ee(e),E|=(127&n)<<21,128&n&&(n=Ee(e),o=127&n,128&n&&(n=Ee(e),o|=(127&n)<<7,128&n&&(n=Ee(e),o|=(127&n)<<14,128&n&&(n=Ee(e),o|=(127&n)<<21,128&n&&(n=Ee(e),i=127&n,128&n&&(n=Ee(e),i|=(127&n)<<7))))))))),{low:E|o<<28,high:o>>>4|i<<24,unsigned:t}}function re(e,t){let n=t.low>>>0,E=(t.low>>>28|t.high<<4)>>>0,o=t.high>>>24,i=0===o?0===E?n<16384?n<128?1:2:n<1<<21?3:4:E<16384?E<128?5:6:E<1<<21?7:8:o<128?9:10,_=z(e,i),s=e.bytes;switch(i){case 10:s[_+9]=o>>>7&1;case 9:s[_+8]=9!==i?128|o:127&o;case 8:s[_+7]=8!==i?E>>>21|128:E>>>21&127;case 7:s[_+6]=7!==i?E>>>14|128:E>>>14&127;case 6:s[_+5]=6!==i?E>>>7|128:E>>>7&127;case 5:s[_+4]=5!==i?128|E:127&E;case 4:s[_+3]=4!==i?n>>>21|128:n>>>21&127;case 3:s[_+2]=3!==i?n>>>14|128:n>>>14&127;case 2:s[_+1]=2!==i?n>>>7|128:n>>>7&127;case 1:s[_]=1!==i?128|n:127&n}}const ce={},ae={},Re=4294967296,Ae=0x10000000000000000,Ne=Ae/2,Ie=Le(0,!0),Oe=Le(0),Te=Se(0,-2147483648,!1),Ce=Se(-1,2147483647,!1),he=Se(-1,-1,!0);function Le(e,t){let n,E,o;return t?(o=0<=(e>>>=0)&&e<256)&&(E=ae[e],E)?E:(n=Se(e,0,!0),o&&(ae[e]=n),n):(o=-128<=(e|=0)&&e<128)&&(E=ce[e],E)?E:(n=Se(e,e<0?-1:0,!1),o&&(ce[e]=n),n)}function Se(e,t,n){return{low:0|e,high:0|t,unsigned:!!n}}function de(e,t){if(isNaN(e))return t?Ie:Oe;if(t){if(e<0)return Ie;if(e>=Ae)return he}else{if(e<=-Ne)return Te;if(e+1>=Ne)return Ce}return e<0?t?Ie:Oe:Se(e%Re|0,e/Re|0,t)}let le=0,ue=0;U.ACCESS_POINT,p.NO_FLAG_SET,p.FLAG_SET_BUT_EMPTY,p.INVALID_FALG_SET,p.FLAG_SET_BUT_NO_RE,p.INVALID_SERVICE_ID,p.NO_SERVICE_AVAILABLE,p.NO_SERVICE_AVAILABLE_P2P,p.NO_SERVICE_AVAILABLE_VOICE,p.NO_SERVICE_AVAILABLE_WEBRTC,p.NO_SERVICE_AVAILABLE_CDS,p.NO_SERVICE_AVAILABLE_CDN,p.NO_SERVICE_AVAILABLE_TDS,p.NO_SERVICE_AVAILABLE_REPORT,p.NO_SERVICE_AVAILABLE_APP_CENTER,p.NO_SERVICE_AVAILABLE_ENV0,p.NO_SERVICE_AVAILABLE_VOET,p.NO_SERVICE_AVAILABLE_STRING_UID,p.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS,U.UNILBS,v.INVALID_VENDOR_KEY,v.INVALID_CHANNEL_NAME,v.INTERNAL_ERROR,v.NO_AUTHORIZED,v.DYNAMIC_KEY_TIMEOUT,v.NO_ACTIVE_STATUS,v.DYNAMIC_KEY_EXPIRED,v.STATIC_USE_DYNAMIC_KEY,v.DYNAMIC_USE_STATIC_KEY,v.USER_OVERLOAD,v.FORBIDDEN_REGION,v.CANNOT_MEET_AREA_DEMAND,U.STRING_UID_ALLOCATOR,b.IIIEGAL_APPID,b.IIIEGAL_UID,b.INTERNAL_ERROR,P.K_TIMESTAMP_EXPIRED,P.K_CHANNEL_PERMISSION_INVALID,P.K_CERTIFICATE_INVALID,P.K_CHANNEL_NAME_EMPTY,P.K_CHANNEL_NOT_FOUND,P.K_TICKET_INVALID,P.K_CHANNEL_CONFLICTED,P.K_SERVICE_NOT_READY,P.K_SERVICE_TOO_HEAVY,P.K_UID_BANNED,P.K_IP_BANNED,P.DATASTREAM2_NOT_AVAILABLE,P.K_AUTO_REBALANCE,P.ERR_INVALID_VENDOR_KEY,P.ERR_INVALID_CHANNEL_NAME,P.WARN_NO_AVAILABLE_CHANNEL,P.WARN_LOOKUP_CHANNEL_TIMEOUT,P.WARN_LOOKUP_CHANNEL_REJECTED,P.WARN_OPEN_CHANNEL_TIMEOUT,P.WARN_OPEN_CHANNEL_REJECTED,P.WARN_REQUEST_DEFERRED,P.ERR_DYNAMIC_KEY_TIMEOUT,P.ERR_NO_AUTHORIZED,P.ERR_VOM_SERVICE_UNAVAILABLE,P.ERR_NO_CHANNEL_AVAILABLE_CODE,P.ERR_MASTER_VOCS_UNAVAILABLE,P.ERR_INTERNAL_ERROR,P.ERR_NO_ACTIVE_STATUS,P.ERR_INVALID_UID,P.ERR_DYNAMIC_KEY_EXPIRED,P.ERR_STATIC_USE_DYANMIC_KE,P.ERR_DYNAMIC_USE_STATIC_KE,P.ERR_NO_VOCS_AVAILABLE,P.ERR_NO_VOS_AVAILABLE,P.ERR_JOIN_CHANNEL_TIMEOUT,P.ERR_JOIN_BY_MULTI_IP,P.ERR_NOT_JOINED,P.ERR_REPEAT_JOIN_REQUEST,P.ERR_REPEAT_JOIN_CHANNEL,P.ERR_INVALID_STRINGUID,P.ERR_TOO_MANY_USERS,P.ERR_SET_CLIENT_ROLE_TIMEOUT,P.ERR_SET_CLIENT_ROLE_NO_PERMISSION,P.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE,P.ERR_PUBLISH_REQUEST_INVALID,P.ERR_SUBSCRIBE_REQUEST_INVALID,P.ERR_NOT_SUPPORTED_MESSAGE,P.ERR_ILLEAGAL_PLUGIN,P.ILLEGAL_CLIENT_ROLE_LEVEL,P.ERR_REJOIN_TOKEN_INVALID,P.ERR_REJOIN_USER_NOT_JOINED,P.ERR_INVALID_OPTIONAL_INFO,P.ERR_TEST_RECOVER,P.ERR_TEST_TRYNEXT,P.ERR_TEST_RETRY,P.ILLEGAL_AES_PASSWORD,P.ERR_TOO_MANY_BROADCASTERS,P.ERR_TOO_MANY_SUBSCRIBERS,P.ERR_LICENSE_ILLEGAL,P.ERR_LICENSE_MISSING,P.ERR_LICENSE_EXPIRED,P.ERR_LICENSE_MINUTES_EXCEEDED,P.ERR_LICENSE_PERIOD_INVALID,P.ERR_LICENSE_MULTIPLE_SDK_SERVICE;const De={GLOBAL:{ASIA:[k.CHINA,k.JAPAN,k.INDIA,k.KOREA,k.HKMC],EUROPE:[],NORTH_AMERICA:[k.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}};Object.keys(De[k.GLOBAL]),k.CHINA,k.NORTH_AMERICA,k.EUROPE,k.ASIA,k.JAPAN,k.INDIA,k.OCEANIA,k.SOUTH_AMERICA,k.AFRICA,k.KOREA,k.HKMC,k.US;let me=0;function fe(e,t,n,E){let{appId:o,areaCode:i,cname:_,sid:r,token:a,uid:R}=t;me++;const A="moderation_plugin",N={service_name:A,json_body:JSON.stringify({appId:o,areaCode:i,cname:_,command:"allocateEdge",requestId:me,seq:me,sid:r,appToken:a,ts:Date.now(),uid:R+""})};let C,h,L=e[0];return T((async()=>{C=Date.now();const e=await function(e,t,n,E){return new Promise(((o,i)=>{t.timeout=t.timeout||s("HTTP_CONNECT_TIMEOUT"),t.responseType=t.responseType||"json",t.data&&!n?(t.data=JSON.stringify(t.data),le+=I(t.data)):n&&(t.data.size?le+=t.data.size:t.data instanceof FormData?le+=O(t.data):le+=I(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,w.request(t).then((e=>{"string"==typeof e.data?ue+=I(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?ue+=e.data.byteLength:ue+=I(JSON.stringify(e.data)),E&&o({data:e.data,headers:e.headers}),o(e.data)})).catch((e=>{w.isCancel(e)?i(new u(c.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?i(new u(c.NETWORK_TIMEOUT,e.message)):e.response?i(new u(c.NETWORK_RESPONSE_ERROR,e.response.status)):i(new u(c.NETWORK_ERROR,e.message))}))}))}(L,{data:N,cancelToken:n,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(h=Date.now()-C,0!==e.code){const t=new u(D.UNEXPECTED_RESPONSE,"moderation plugin ap error, code"+e.code,{retry:!0,responseTime:h});throw l.error(t.toString()),t}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new u(D.UNEXPECTED_RESPONSE,"moderation plugin ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:h});throw l.error(e.toString()),e}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new u(D.UNEXPECTED_RESPONSE,"moderation plugin ap empty server",{code:t.code,responseTime:h});throw l.error(e.toString()),e}if(!t.servers.some((e=>!!e.wss))){const e=new u(D.UNEXPECTED_RESPONSE,"moderation plugin ap empty port",{code:t.code,responseTime:h});throw l.error(e.toString()),e}const E=s("IMAGE_MODERATION_WORKER_HOST");return{addressList:t.servers.map((e=>{let{address:t,wss:n}=e;if(t&&n)return"wss://".concat(t.replace(/\./g,"-"),".").concat(E,":").concat(n,"/moderation")})).filter((e=>!!e)),workerToken:t.workerToken,vid:t.vid,ticket:t.appTicket,responseTime:h}}),((t,n)=>(m.apworkerEvent(r,{success:!0,sc:200,serviceName:A,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===n,responseTime:h,serverIp:e[n%e.length]}),!1)),((t,n)=>(m.apworkerEvent(r,{success:!1,sc:t.data&&t.data.code||200,serviceName:A,responseTime:h,serverIp:e[n%e.length]}),!!(t.code!==D.OPERATION_ABORTED&&t.code!==D.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(L=e[(n+1)%e.length],!0))),E)}class we extends t{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(W.CONNECTION_STATE_CHANGE,e,t)}get quality(){return this._quality}set quality(e){this._quality=e>1?1:e<.1?.1:e,this._qualityTimer&&(window.clearTimeout(this._qualityTimer),this._qualityTimer=null),this._quality>=1||(this._qualityTimer=window.setTimeout((()=>{this.quality=this._quality/this._qualityRatio}),6e4))}constructor(e){var t;super(),this.name="AgoraRTCImageModeration",this._connectionState=G.CONNECTING,this._sequence=0,this._moderationStartTime=void 0,this._workerConnection=void 0,this._workerMessageLengthLimit=void 0,this._qualityRatio=void 0,this._connectInfo=void 0,this._cancelTokenSource=w.CancelToken.source(),this._retryConfig=void 0,this._moderationInterval=void 0,this._moderationTimer=null,this._moderationMode=1,this._quality=1,this._qualityTimer=null,this._ticket=void 0,this._moderationIntervalMinimum=void 0,this._uploadFailedNum=0,this._uploadNum=0,this._uploadTimer=null,this._extraInfo=void 0,this._vendor="",this._encoder=new TextEncoder,this._moderationId=void 0,this.inspectImage=()=>{if(this.connectionState!==G.CONNECTED)throw new u(D.OPERATION_ABORTED,"image moderation service connection status is ".concat(this.connectionState));this._moderationTimer&&(window.clearInterval(this._moderationTimer),this._moderationTimer=null),this._moderationTimer=window.setInterval((()=>{this.connectionState===G.CONNECTED?this.requestToInspectImage():l.debug("[".concat(this._moderationId,"] Moderation State is not connected , "),this.connectionState)}),this._moderationInterval<this._moderationIntervalMinimum?this._moderationIntervalMinimum:this._moderationInterval),this.requestToInspectImage()},this._moderationId=h(5,"image-moderation-"),this._workerMessageLengthLimit=s("IMAGE_MODERATION_WORKER_MESSAGE_LENGTH_LIMIT"),this._moderationIntervalMinimum=s("IMAGE_MODERATION_INTERVAL_MINIMUM"),this._moderationInterval=null!==(t=e.interval)&&void 0!==t?t:1e3,e.extraInfo&&(this._extraInfo=this._encoder.encode(e.extraInfo)),e.vendor&&(this._vendor=e.vendor),this._qualityRatio=s("IMAGE_MODERATION_QUALITY_RATIO"),this._moderationStartTime=Number(Date.now()),this._workerConnection=new F("worker-"+this._moderationId,L),this.on(W.STATE_CHANGE,((e,t)=>{l.debug("[".concat(this._moderationId,"] Moderation operation :").concat(H[e]," ").concat(t||""))})),this.handleWorkerEvents()}async init(e,t){this.emit(W.STATE_CHANGE,H.CONNECT_AP),this._connectInfo=e;const n=this._cancelTokenSource.token;return this._retryConfig=t,new Promise(((E,o)=>{this.on(W.CONNECTION_STATE_CHANGE,((e,t)=>{e===G.CONNECTED&&E()})),this.requestAP(e,n,t).then((e=>{this.connectWorker(e)})).catch((e=>{o(e)}))}))}updateConfig(e){var t;this._moderationInterval=null!==(t=e.interval)&&void 0!==t?t:1e3,e.extraInfo&&(this._extraInfo=this._encoder.encode(e.extraInfo)),e.vendor&&(this._vendor=e.vendor),l.debug("[".concat(this._moderationId,"] updateConfig: ").concat(JSON.stringify(e))),this.connectionState===G.CONNECTED&&this.inspectImage()}async requestAP(e,t,n){const E=s("WEBCS_DOMAIN").map((e=>"https://".concat(e,"/api/v1"))),o=await fe(E,e,t,n);this.emit(W.STATE_CHANGE,H.AP_CONNECTED);const{addressList:i,ticket:_}=o;return this._ticket=_,i}async connectWorker(e){this.emit(W.STATE_CHANGE,H.CONNECT_WORKER),await this._workerConnection.init(e,1e4)}handleWorkerEvents(){this._workerConnection.on(y.CONNECTED,(async()=>{this.emit(W.STATE_CHANGE,H.WORKER_CONNECTED,this._workerConnection.url),this.connectionState=G.CONNECTED})),this._workerConnection.on(y.CLOSED,(()=>{this.connectionState=G.CLOSED})),this._workerConnection.on(y.FAILED,(()=>{this.connectionState=G.CLOSED})),this._workerConnection.on(y.RECONNECTING,(()=>{this.connectionState=this.connectionState===G.CONNECTED?G.RECONNECTING:G.CONNECTING})),this._workerConnection.on(y.ON_MESSAGE,(async e=>{if(e.data instanceof ArrayBuffer){const t=J(new Uint8Array(e.data));s("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&l.debug("[".concat(this._moderationId,"] Response message for worker of image moderation "),JSON.stringify(t)),this._uploadNum++,void 0===t.code||0===t.code||(this._uploadFailedNum++,l.error("[".concat(this._moderationId,"] Error response from worke, code is ").concat(t.code,", msg is ").concat(t.msg)),this._uploadTimer||(this._uploadTimer=window.setTimeout((()=>{m.reportApiInvoke(this._connectInfo.sid||null,{name:S.IMAGE_MODERATION_UPLOAD,options:[this._uploadFailedNum,this._uploadNum,t.code],tag:d.TRACER}).onError(new u(D.IMAGE_MODERATION_UPLOAD_FAILED,t.msg)),this._uploadTimer=null}),s("IMAGE_MODERATION_UPLOAD_REPORT_INTERVAL"))))}else l.error("[".concat(this._moderationId,"] Unexpected message type from worker"))})),this._workerConnection.on(y.WILL_RECONNECT,((e,t,n)=>{"recover"===e&&n(e),n("tryNext")})),this._workerConnection.on(y.REQUEST_NEW_URLS,((e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t)}))}static intToLong(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}async requestToInspectImage(){const e=N(this,W.CLIENT_LOCAL_VIDEO_TRACK),t={appId:this._connectInfo.appId,cname:this._connectInfo.cname,cid:this._connectInfo.cid,sid:this._connectInfo.sid,uid:this._connectInfo.uid,vid:this._connectInfo.vid};if(e){if(!e.isPlaying)return void(s("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&l.debug("Only the track being played can be inspected"));this._sequence++;const n=await this.generateRequestData(e,t);this._workerConnection.sendMessage(n,!0,!0)}else s("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&l.debug("Only the track being published can be inspected")}async generateRequestData(e,t){let{appId:n,cname:E,cid:o,vid:i,sid:_,uid:r}=t;const c=Date.now(),a=await e.getCurrentFrameImage("image/jpeg",this.quality),R=await f(a,n,E),A=this._sequence+"-"+o+"-"+r+"-"+c+"-"+h(12,""),N={appId:n,cid:o,cname:E,deviceId:"",elapse:we.intToLong(Number(c-this._moderationStartTime)),fileSize:a.buffer.byteLength,height:a.height,width:a.width,jpg:R,networkType:6,osType:7,requestId:A,sdkVersion:"4.23.1",sequence:this._sequence,sid:_,timestamp:de(c),uid:r,vid:i,service:this._moderationMode,ticket:this._ticket,callbackData:this._extraInfo,vendorConfigs:this._vendor};void 0===this._extraInfo&&delete N.callbackData;const I=x(N);if(I.byteLength<this._workerMessageLengthLimit){if(s("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")){const e=M({},N);delete e.jpg,l.debug("[".concat(this._moderationId,"] Request message for worker of image moderation service: "),JSON.stringify(e))}return I}{const t=this.quality*this._qualityRatio;return this.quality=t,await this.generateRequestData(e,{appId:n,cname:E,cid:o,vid:i,sid:_,uid:r})}}close(){this._cancelTokenSource.cancel(),this._cancelTokenSource=w.CancelToken.source(),this._workerConnection&&this._workerConnection.close(),this._moderationTimer&&window.clearInterval(this._moderationTimer),this._moderationTimer=null,this._uploadTimer&&window.clearTimeout(this._uploadTimer),this._uploadTimer=null,this.connectionState=G.CLOSED,this.emit(W.STATE_CHANGE,H.CLOSED)}}function ge(e){if(C(e.interval,"interval",1e3,1/0),e&&e.extraInfo&&e.extraInfo.length>1024)throw new u(D.INVALID_PARAMS,"config.extraInfo length cannot exceed 1024 bytes");if(e&&e.vendor&&e.vendor.length>1024)throw new u(D.INVALID_PARAMS,"config.vendor length cannot exceed 1024 bytes")}const Ve={name:"ImageModeration",create:function(e){let{config:t}=e;return ge(t),new we(t)}};export{Ve as ImageModerationService,ge as checkImageModerationConfig}; |
/** | ||
* AgoraWebSDK_N-v4.23.0-0-g98fcf352-dirty Copyright AgoraInc. | ||
* AgoraWebSDK_N-v4.23.1-0-gea45199f-dirty Copyright AgoraInc. | ||
*/ | ||
import{isValidString as e,AgoraRTCErrorCode as t,isEmpty as s,checkValidNumber as n,checkValidBoolean as E,checkValidEnum as r,checkValidString as o,checkValidArray as i,IS_GLOBAL_VERSION as _,EventEmitter as c,PromiseMutex as R,NETWORK_STATE as a,networkIndicator as A,NETWORK_INDICATOR_EVENTS as I,createDefer as S,getParameter as N,AgoraRTCError as T,getRetryWaitTime as d,wait as h,emitAsPromise as O,emitAsInvokerNoResponse as L,noop as l,VERSION as u,getUTF8StringByteLength as C,getMultiUnilbsFormDataByteLength as g,retryable as D,DEFAULT_RETRY_CONFIG as U}from"@agora-js/shared";import{AgoraRTCError as w,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.DATASTREAM2_NOT_AVAILABLE=27]="DATASTREAM2_NOT_AVAILABLE",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_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 w(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},x={x:0,y:0,width:160,height:160,zOrder:255,alpha:1};function F(e,t){o(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_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=void 0,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,this._initMutex=new R("websocket",r?r.clientId:void 0);const{timeout:o,timeoutFactor:i}=t,_=Math.max(300,Math.floor(3*o/5)),c=Math.max(1.2,Math.floor(8*i)/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=o,this.retryConfig.timeoutFactor=i))}))}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._reconnectMode="tryNext",this.forceCloseTimeout=s,this.urls=e,this.state="connecting";try{const e=S(),s=this.urls[this.currentURLIndex];N("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=S();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()}},o=e=>{this.emit(H.ON_MESSAGE,e)},i=e=>{M.warn("[".concat(this.connectionID,"] ws open error ").concat(e))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),N("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(e=N("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=o,this.websocket.onerror=i,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,o=E&&e.code===t.WS_ABORT,i=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:o?"aborted":"error",errors:[e]},_),s||i?(n.reject(s?new T(t.WS_DISCONNECT,"websocket is closed: ".concat(c)):new T(t.WS_ERR,"init websocket failed: ".concat(c))),i&&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)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)),await n(this.urls[this.currentURLIndex],e)}else"recover"===e&&(M.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),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 o=[];this.closeEstablishingWs=()=>{M.debug("[choose-best-ws] close establishing websockets"),o.forEach((e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close()})),E(new T(t.WS_ABORT,"choose best websocket aborted"))};const i=N("GATEWAY_DOMAINS");let _;const c=e.indexOf("?h="),R=i.find((t=>-1!==c?e.includes(t,c):e.includes(t)));M.debug("[choose-best-ws] currentDomain: ",R,", domains: ",i);let a=!this.tryDoubleDomain||!R;if(!a&&R){var A;const t=Date.now();try{i.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",o.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"),o.forEach((e=>e.close()));o.length;)o.pop();a=!0}null===(A=this.store)||void 0===A||A.recordJoinChannelService({urls:o.map((e=>e.url)),service:"gateway"},s),o.forEach((e=>{e.onopen=()=>{if(r)return;const s=Date.now()-t;M.debug("[choose-best-ws] ws open cost ".concat(s,"ms")),o.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;o.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((()=>{o.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),o.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 w(V.UNEXPECTED_ERROR);const o=v({command:e,sdkVersion:"4.23.0"===u?"0.0.1":u,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 w(V.WS_DISCONNECT);const i=()=>new Promise(((e,t)=>{this.websocket.once(H.CLOSED,(()=>t(new w(V.WS_ABORT)))),this.websocket.once(H.CONNECTED,e)}));"connected"!==this.websocket.state&&await i(),o.clientRequest&&(o.clientRequest.workerToken=this.token);const _=new Promise(((e,t)=>{const s=()=>{t(new w(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(o);let R=null;try{R=await _}catch(n){if("closed"===this.websocket.state)throw n;return await i(),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.23.0"===u?"0.0.1":u;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 w(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 w(V.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case Q.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED:return new w(V.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED,"",{code:e.code}).throw();case Q.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const t=new w(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 w(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 w(V.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case Q.LIVE_STREAM_RESPONSE_NOT_SUPPORTED:return new w(V.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED,"",{code:e.code}).throw();case Q.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM:{const t=new w(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 w(V.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code}).throw();case Q.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT:throw new w(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 w(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 w(V.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{code:e.code}).throw();throw new w(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 w(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(l)}),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.DATASTREAM2_NOT_AVAILABLE,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 oe={GLOBAL:{ASIA:[j.CHINA,j.JAPAN,j.INDIA,j.KOREA,j.HKMC],EUROPE:[],NORTH_AMERICA:[j.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}};async function ie(e,s,n,E,r){const o=Date.now(),i={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,o)=>{s.timeout=s.timeout||N("HTTP_CONNECT_TIMEOUT"),s.responseType=s.responseType||"json",s.data&&!n?(s.data=JSON.stringify(s.data),se+=C(s.data)):n&&(s.data.size?se+=s.data.size:s.data instanceof FormData?se+=g(s.data):se+=C(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+=C(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?ne+=e.data.byteLength:ne+=C(JSON.stringify(e.data)),E&&r({data:e.data,headers:e.headers}),r(e.data)})).catch((e=>{P.isCancel(e)?o(new w(t.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?o(new w(t.NETWORK_TIMEOUT,e.message)):e.response?o(new w(t.NETWORK_RESPONSE_ERROR,e.response.status)):o(new w(t.NETWORK_ERROR,e.message))}))}))}(_+"".concat(-1===_.indexOf("?")?"?":"&","action=stringuid"),{data:i,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(i.sid,{lts:o,success:!1,serverAddr:_,stringUid:i.string_uid,uid:t.uid,errorCode:V.INVALID_UINT_UID_FROM_STRING_UID,extend:i}),new w(V.INVALID_UINT_UID_FROM_STRING_UID);return m.reqUserAccount(i.sid,{lts:o,success:!0,serverAddr:_,stringUid:i.string_uid,uid:t.uid,errorCode:null,extend:i}),!1}const E=re(t.code);return E.retry&&(_=e[(n+1)%e.length]),m.reqUserAccount(i.sid,{lts:o,success:!1,serverAddr:_,stringUid:i.string_uid,uid:t.uid,errorCode:E.desc,extend:i}),E.retry}),((t,s)=>t.code!==V.OPERATION_ABORTED&&(m.reqUserAccount(i.sid,{lts:o,success:!1,serverAddr:_,stringUid:i.string_uid,uid:null,errorCode:t.code,extend:i}),_=e[(s+1)%e.length],!0)),r);if(0!==c.code){const e=re(c.code);throw new w(V.UNEXPECTED_RESPONSE,e.desc)}return c}Object.keys(oe[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]:U,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:U;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)||o(e.userConfigExtraInfo,"config.userConfigExtraInfo",0,4096,!1),e.transcodingUsers&&!s(e.transcodingUsers)&&(i(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)||F(e.watermark,"watermark"),s(e.backgroundImage)||F(e.backgroundImage,"backgroundImage"),e.images&&!s(e.images)&&(i(e.images,"config.images"),e.images.forEach(((e,t)=>{F(e,"images[".concat(t,"]"))})))}(t);const _=[];t.images&&_.push(...t.images.map((e=>v(v(v({},x),e),{},{zOrder:255})))),t.backgroundImage&&(_.push(v(v(v({},x),t.backgroundImage),{},{zOrder:0})),delete t.backgroundImage),t.watermark&&(_.push(v(v(v({},x),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=N("ACCOUNT_REGISTER").slice(0,N("AJAX_REQUEST_CONCURRENT"));let o=[];o=t.proxyServer?r.map((e=>"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1"))):r.map((e=>"https://".concat(e,"/api/v1")));const i=null==E?void 0:E.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"stringUID",urls:o});try{const r=await ie(o,e,t,s,n);return null==E||E.recordJoinChannelService({status:"success",endTs:Date.now()},i),r.uid}catch(e){throw null==E||E.recordJoinChannelService({status:"error",endTs:Date.now(),errors:[e]},i),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 w(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 w(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 o=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}))})),i=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()}),o]);this.isStartingStreamingTask=!1,M.debug("[".concat(this.spec.clientId,"] live streaming started, code: ").concat(i.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 w(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 w(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 w(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 w(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 w(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 w(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||U,e.httpRetryConfig||U)}};export{ce as LiveStreamingService}; | ||
import{isValidString as e,AgoraRTCErrorCode as t,isEmpty as s,checkValidNumber as n,checkValidBoolean as E,checkValidEnum as r,checkValidString as o,checkValidArray as i,IS_GLOBAL_VERSION as _,EventEmitter as c,PromiseMutex as R,NETWORK_STATE as a,networkIndicator as A,NETWORK_INDICATOR_EVENTS as I,createDefer as S,getParameter as N,AgoraRTCError as T,getRetryWaitTime as d,wait as h,emitAsPromise as O,emitAsInvokerNoResponse as L,noop as l,VERSION as u,getUTF8StringByteLength as C,getMultiUnilbsFormDataByteLength as g,retryable as D,DEFAULT_RETRY_CONFIG as U}from"@agora-js/shared";import{AgoraRTCError as w,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.DATASTREAM2_NOT_AVAILABLE=27]="DATASTREAM2_NOT_AVAILABLE",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_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 w(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},x={x:0,y:0,width:160,height:160,zOrder:255,alpha:1};function F(e,t){o(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_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=void 0,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,this._initMutex=new R("websocket",r?r.clientId:void 0);const{timeout:o,timeoutFactor:i}=t,_=Math.max(300,Math.floor(3*o/5)),c=Math.max(1.2,Math.floor(8*i)/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=o,this.retryConfig.timeoutFactor=i))}))}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._reconnectMode="tryNext",this.forceCloseTimeout=s,this.urls=e,this.state="connecting";try{const e=S(),s=this.urls[this.currentURLIndex];N("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=S();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()}},o=e=>{this.emit(H.ON_MESSAGE,e)},i=e=>{M.warn("[".concat(this.connectionID,"] ws open error ").concat(e))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),N("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(e=N("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=o,this.websocket.onerror=i,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,o=E&&e.code===t.WS_ABORT,i=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:o?"aborted":"error",errors:[e]},_),s||i?(n.reject(s?new T(t.WS_DISCONNECT,"websocket is closed: ".concat(c)):new T(t.WS_ERR,"init websocket failed: ".concat(c))),i&&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)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)),await n(this.urls[this.currentURLIndex],e)}else"recover"===e&&(M.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),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 o=[];this.closeEstablishingWs=()=>{M.debug("[choose-best-ws] close establishing websockets"),o.forEach((e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close()})),E(new T(t.WS_ABORT,"choose best websocket aborted"))};const i=N("GATEWAY_DOMAINS");let _;const c=e.indexOf("?h="),R=i.find((t=>-1!==c?e.includes(t,c):e.includes(t)));M.debug("[choose-best-ws] currentDomain: ",R,", domains: ",i);let a=!this.tryDoubleDomain||!R;if(!a&&R){var A;const t=Date.now();try{i.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",o.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"),o.forEach((e=>e.close()));o.length;)o.pop();a=!0}null===(A=this.store)||void 0===A||A.recordJoinChannelService({urls:o.map((e=>e.url)),service:"gateway"},s),o.forEach((e=>{e.onopen=()=>{if(r)return;const s=Date.now()-t;M.debug("[choose-best-ws] ws open cost ".concat(s,"ms")),o.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;o.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((()=>{o.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),o.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 w(V.UNEXPECTED_ERROR);const o=v({command:e,sdkVersion:"4.23.1"===u?"0.0.1":u,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 w(V.WS_DISCONNECT);const i=()=>new Promise(((e,t)=>{this.websocket.once(H.CLOSED,(()=>t(new w(V.WS_ABORT)))),this.websocket.once(H.CONNECTED,e)}));"connected"!==this.websocket.state&&await i(),o.clientRequest&&(o.clientRequest.workerToken=this.token);const _=new Promise(((e,t)=>{const s=()=>{t(new w(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(o);let R=null;try{R=await _}catch(n){if("closed"===this.websocket.state)throw n;return await i(),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.23.1"===u?"0.0.1":u;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 w(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 w(V.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case Q.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED:return new w(V.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED,"",{code:e.code}).throw();case Q.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const t=new w(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 w(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 w(V.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case Q.LIVE_STREAM_RESPONSE_NOT_SUPPORTED:return new w(V.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED,"",{code:e.code}).throw();case Q.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM:{const t=new w(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 w(V.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code}).throw();case Q.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT:throw new w(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 w(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 w(V.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{code:e.code}).throw();throw new w(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 w(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(l)}),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.DATASTREAM2_NOT_AVAILABLE,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 oe={GLOBAL:{ASIA:[j.CHINA,j.JAPAN,j.INDIA,j.KOREA,j.HKMC],EUROPE:[],NORTH_AMERICA:[j.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}};async function ie(e,s,n,E,r){const o=Date.now(),i={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,o)=>{s.timeout=s.timeout||N("HTTP_CONNECT_TIMEOUT"),s.responseType=s.responseType||"json",s.data&&!n?(s.data=JSON.stringify(s.data),se+=C(s.data)):n&&(s.data.size?se+=s.data.size:s.data instanceof FormData?se+=g(s.data):se+=C(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+=C(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?ne+=e.data.byteLength:ne+=C(JSON.stringify(e.data)),E&&r({data:e.data,headers:e.headers}),r(e.data)})).catch((e=>{P.isCancel(e)?o(new w(t.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?o(new w(t.NETWORK_TIMEOUT,e.message)):e.response?o(new w(t.NETWORK_RESPONSE_ERROR,e.response.status)):o(new w(t.NETWORK_ERROR,e.message))}))}))}(_+"".concat(-1===_.indexOf("?")?"?":"&","action=stringuid"),{data:i,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(i.sid,{lts:o,success:!1,serverAddr:_,stringUid:i.string_uid,uid:t.uid,errorCode:V.INVALID_UINT_UID_FROM_STRING_UID,extend:i}),new w(V.INVALID_UINT_UID_FROM_STRING_UID);return m.reqUserAccount(i.sid,{lts:o,success:!0,serverAddr:_,stringUid:i.string_uid,uid:t.uid,errorCode:null,extend:i}),!1}const E=re(t.code);return E.retry&&(_=e[(n+1)%e.length]),m.reqUserAccount(i.sid,{lts:o,success:!1,serverAddr:_,stringUid:i.string_uid,uid:t.uid,errorCode:E.desc,extend:i}),E.retry}),((t,s)=>t.code!==V.OPERATION_ABORTED&&(m.reqUserAccount(i.sid,{lts:o,success:!1,serverAddr:_,stringUid:i.string_uid,uid:null,errorCode:t.code,extend:i}),_=e[(s+1)%e.length],!0)),r);if(0!==c.code){const e=re(c.code);throw new w(V.UNEXPECTED_RESPONSE,e.desc)}return c}Object.keys(oe[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]:U,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:U;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)||o(e.userConfigExtraInfo,"config.userConfigExtraInfo",0,4096,!1),e.transcodingUsers&&!s(e.transcodingUsers)&&(i(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)||F(e.watermark,"watermark"),s(e.backgroundImage)||F(e.backgroundImage,"backgroundImage"),e.images&&!s(e.images)&&(i(e.images,"config.images"),e.images.forEach(((e,t)=>{F(e,"images[".concat(t,"]"))})))}(t);const _=[];t.images&&_.push(...t.images.map((e=>v(v(v({},x),e),{},{zOrder:255})))),t.backgroundImage&&(_.push(v(v(v({},x),t.backgroundImage),{},{zOrder:0})),delete t.backgroundImage),t.watermark&&(_.push(v(v(v({},x),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=N("ACCOUNT_REGISTER").slice(0,N("AJAX_REQUEST_CONCURRENT"));let o=[];o=t.proxyServer?r.map((e=>"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1"))):r.map((e=>"https://".concat(e,"/api/v1")));const i=null==E?void 0:E.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"stringUID",urls:o});try{const r=await ie(o,e,t,s,n);return null==E||E.recordJoinChannelService({status:"success",endTs:Date.now()},i),r.uid}catch(e){throw null==E||E.recordJoinChannelService({status:"error",endTs:Date.now(),errors:[e]},i),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 w(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 w(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 o=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}))})),i=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()}),o]);this.isStartingStreamingTask=!1,M.debug("[".concat(this.spec.clientId,"] live streaming started, code: ").concat(i.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 w(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 w(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 w(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 w(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 w(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 w(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||U,e.httpRetryConfig||U)}};export{ce as LiveStreamingService}; |
import { RetryConfiguration, TurnServerConfigWithMode, UID, Candidate, Setup, PayloadAttribute, Extmap, FingerPrint, EventEmitter, PromiseMutex, SDKStore, SDK_CODEC, AgoraPCStats, NetworkQuality as NetworkQuality$1, AgoraVideoReceiverStats, WebSocketQuitReason, ConnectionDisconnectedReason } from '@agora-js/shared'; | ||
import { IRemoteAudioTrack, IRemoteVideoTrack, IRemoteDataChannel, RemoteAudioTrack, RemoteVideoTrack, RemoteDataChannel, LocalTrack, LocalDataChannel, LowStreamParameter, VideoEncoderConfiguration, AudioEncoderConfiguration, MediaStats, LocalAudioTrackStats, LocalVideoTrackStats, RemoteAudioTrackStats, RemoteVideoTrackStats, AgoraRTCStats } from '@agora-js/media'; | ||
import { IRemoteAudioTrack, IRemoteVideoTrack, IRemoteDataChannel, RemoteAudioTrack, RemoteVideoTrack, RemoteDataChannel, LocalTrack, LocalDataChannel, LowStreamParameter, AudioMetadata, VideoEncoderConfiguration, AudioEncoderConfiguration, MediaStats, LocalAudioTrackStats, LocalVideoTrackStats, RemoteAudioTrackStats, RemoteVideoTrackStats, AgoraRTCStats } from '@agora-js/media'; | ||
@@ -102,13 +102,2 @@ interface SignalSpec { | ||
interface ConfigDistributeLimitBitrate { | ||
uplink: { | ||
max_bitrate: number; | ||
min_bitrate: number; | ||
}; | ||
low_stream_uplink?: { | ||
bitrate: number; | ||
}; | ||
id: number; | ||
} | ||
/** | ||
@@ -174,2 +163,13 @@ * Information about a remote user. You can get this through [AgoraRTCClient.remoteUsers]{@link IAgoraRTCClient.remoteUsers}. | ||
interface ConfigDistributeLimitBitrate { | ||
uplink: { | ||
max_bitrate: number; | ||
min_bitrate: number; | ||
}; | ||
low_stream_uplink?: { | ||
bitrate: number; | ||
}; | ||
id: number; | ||
} | ||
declare enum LocalTrackType { | ||
@@ -368,2 +368,3 @@ LocalVideoTrack = "videoTrack", | ||
unmuteRemoteNoLock(user: AgoraRTCRemoteUser, kind: Kind): Promise<void>; | ||
addAudioMetadata(metadata: AudioMetadata): void; | ||
getAllTracks(filterLowVideoTrack?: boolean): LocalTrack[]; | ||
@@ -370,0 +371,0 @@ getAllDataChannels(): LocalDataChannel[]; |
/** | ||
* AgoraWebSDK_N-v4.23.0-0-g98fcf352-dirty Copyright AgoraInc. | ||
* AgoraWebSDK_N-v4.23.1-0-gea45199f-dirty Copyright AgoraInc. | ||
*/ | ||
import{LocalAudioTrack as e,LocalVideoTrack as t,TrackHint as r,getCompatibility as n}from"@agora-js/media";import{logger as i}from"@agora-js/report";import{IS_GLOBAL_VERSION as o,EventEmitter as s,parseSdp as a,getParameter as c,isFirefox as d,getRandomString as p,jsonClone as l,printSdp as u,VideoCodec as h,PromiseMutex as m,createWebRTCStatsFilter as f,AgoraRTCError as v,AgoraRTCErrorCode as C,isSafari as g,getBrowserInfo as S,isIOS as P,isRTCIceServerList as b,isChromeKernel as E}from"@agora-js/shared";function y(e,t){this.v=e,this.k=t}function D(e,t,r,n,i){var o={};return Object.keys(n).forEach((function(e){o[e]=n[e]})),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=r.slice().reverse().reduce((function(r,n){return n(e,t,r)||r}),o),i&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(i):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}function w(e){return new y(e,0)}function R(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.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:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function A(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function I(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?A(Object(r),!0).forEach((function(t){R(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):A(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function O(e){return function(){return new T(e.apply(this,arguments))}}function T(e){var t,r;function n(t,r){try{var o=e[t](r),s=o.value,a=s instanceof y;Promise.resolve(a?s.v:s).then((function(r){if(a){var c="return"===t?"return":"next";if(!s.k||r.done)return n(c,r);r=e[c](r).value}i(o.done?"return":"normal",r)}),(function(e){n("throw",e)}))}catch(e){i("throw",e)}}function i(e,i){switch(e){case"return":t.resolve({value:i,done:!0});break;case"throw":t.reject(i);break;default:t.resolve({value:i,done:!1})}(t=t.next)?n(t.key,t.arg):r=null}this._invoke=function(e,i){return new Promise((function(o,s){var a={key:e,arg:i,resolve:o,reject:s,next:null};r?r=r.next=a:(t=r=a,n(e,i))}))},"function"!=typeof e.return&&(this.return=void 0)}T.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},T.prototype.next=function(e){return this._invoke("next",e)},T.prototype.throw=function(e){return this._invoke("throw",e)},T.prototype.return=function(e){return this._invoke("return",e)};let k=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}({});k.AFRICA,k.ASIA,k.CHINA,k.EUROPE,k.GLOBAL,k.INDIA,k.JAPAN,k.NORTH_AMERICA,k.OCEANIA,k.OVERSEA,k.SOUTH_AMERICA;let L=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}({});L.ASIA,L.NORTH_AMERICA,L.EUROPE,L.JAPAN,L.INDIA,L.KOREA,L.HKMC,L.US,L.OVERSEA,L.GLOBAL,L.OCEANIA,L.SOUTH_AMERICA,L.AFRICA,o&&L.CHINA;class _ extends s{constructor(e,t){super(),this.onICEConnectionStateChange=void 0,this.onConnectionStateChange=void 0,this.onDTLSTransportStateChange=void 0,this.onDTLSTransportError=void 0,this.onICETransportStateChange=void 0,this.onFirstAudioReceived=void 0,this.onFirstVideoReceived=void 0,this.onFirstAudioDecoded=void 0,this.onFirstVideoDecoded=void 0,this.onFirstVideoDecodedTimeout=void 0,this.onSelectedLocalCandidateChanged=void 0,this.onSelectedRemoteCandidateChanged=void 0,this.onICECandidateError=void 0,this.getLocalVideoStats=void 0}}class N extends _{constructor(e,t){super(e,t),this.establishPromise=void 0}}let F=function(e){return e.VIDEO="video",e.AUDIO="audio",e}({}),x=function(e){return e.UDP_RELAY="udp_relay",e.UDP_TCP_RELAY="udp_tcp_relay",e.TCP_RELAY="tcp_relay",e.RELAY="relay",e}({});function M(e){const t=a(e);let r,n;for(const e of t.mediaDescriptions){if(!r){const t=e.attributes.iceUfrag,n=e.attributes.icePwd;if(!t||!n)throw new Error("Cannot get iceUfrag or icePwd from SDP.");r={iceUfrag:t,icePwd:n}}if(!n){const t=e.attributes.fingerprints;t.length>0&&(n={fingerprints:t})}}if(!n&&t.attributes.fingerprints.length>0&&(n={fingerprints:t.attributes.fingerprints}),!n||!r)throw new Error("Cannot get iceParameters or dtlsParameters from SDP.");return{iceParameters:r,dtlsParameters:n}}function U(t,r){r instanceof e&&t.attributes.payloads.forEach((e=>{var t;const n=null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase();if(!n||-1===["opus","pcmu","pcma","g722"].indexOf(n))return;e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters.minptime="10",e.fmtp.parameters.useinbandfec="1";const i=r._encoderConfig;i&&"pcmu"!==n&&"pcma"!==n&&"g722"!==n&&(i.bitrate&&!d()&&(e.fmtp.parameters.maxaveragebitrate="".concat(Math.floor(1e3*i.bitrate))),i.sampleRate&&(e.fmtp.parameters.maxplaybackrate="".concat(i.sampleRate),e.fmtp.parameters["sprop-maxcapturerate"]="".concat(i.sampleRate)),i.stereo&&(e.fmtp.parameters.stereo="1",e.fmtp.parameters["sprop-stereo"]="1"))}))}F.VIDEO,F.AUDIO;class j{constructor(e){this.sessionDesc=void 0,this.localCapabilities=void 0,this.rtpCapabilities=void 0,this.candidates=void 0,this._originCandidates=void 0,this.iceParameters=void 0,this.dtlsParameters=void 0,this.setup=void 0,this.currentMidIndex=void 0,this.cname=void 0,e=l(e);const{iceParameters:t,dtlsParameters:r,candidates:n,rtpCapabilities:i,setup:o,localCapabilities:s,sdkCodec:c,cname:d}=e,p=a("v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE audio video\na=msid-semantic: WMS\na=ice-lite\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendrecv\na=rtcp-mux\na=rtcp-rsize\na=mid:audio\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendrecv\na=rtcp-mux\na=rtcp-rsize\na=mid:video\n");this.rtpCapabilities=i,this.candidates=n,this._originCandidates=l(n),this.iceParameters=t,this.dtlsParameters=r,this.setup=o,this.localCapabilities=s,this.cname=d;for(let e=0;e<p.mediaDescriptions.length;e++){const s=p.mediaDescriptions[e];if(s.attributes.iceUfrag=t.iceUfrag,s.attributes.icePwd=t.icePwd,s.attributes.fingerprints=r.fingerprints,s.attributes.candidates=n,s.attributes.setup=o,"video"===s.media.mediaType){s.media.fmts=i.videoCodecs.map((e=>e.payloadType.toString(10)));let e=i.videoCodecs.filter((e=>{var t;return null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase().includes(c)}));0===e.length&&(e=i.videoCodecs),s.attributes.payloads=e,s.attributes.extmaps=i.videoExtensions}"audio"===s.media.mediaType&&(s.media.fmts=i.audioCodecs.map((e=>e.payloadType.toString(10))),s.attributes.payloads=i.audioCodecs,s.attributes.extmaps=i.audioExtensions),p.mediaDescriptions[e]=this.mungMediaDesc(s)}this.sessionDesc=p,this.currentMidIndex=p.mediaDescriptions.length-1}toString(){return u(this.sessionDesc)}send(e,t,r){const{ssrcs:n,ssrcGroups:i}=function(e,t,r){const n=[],i=[];return e.forEach((e=>{let{ssrcId:o,rtx:s}=e;const a=p(8,"track-"),c={ssrcId:o,attributes:I({label:a,mslabel:r=r||p(10,""),msid:"".concat(r," ").concat(a)},t&&{cname:t})};if(n.push(c),void 0!==s){const e={ssrcId:s,attributes:I({label:a,mslabel:r,msid:"".concat(r," ").concat(a)},t&&{cname:t})};n.push(e),i.push({semantic:"FID",ssrcIds:[o,s]})}})),e.length>1&&i.push({semantic:"SIM",ssrcIds:e.map((e=>{let{ssrcId:t}=e;return t}))}),{ssrcs:n,ssrcGroups:i}}(t,this.cname),o=this.sessionDesc.mediaDescriptions.find((t=>e===F.VIDEO?"video"===t.media.mediaType:"audio"===t.media.mediaType)),s=n[0].attributes.label,a=n[0].attributes.mslabel;return o.attributes.ssrcs=o.attributes.ssrcs.concat(n),o.attributes.ssrcGroups=o.attributes.ssrcGroups.concat(i),{id:s,mslabel:a}}batchSend(e){return e.map((e=>{let{kind:t,ssrcMsg:r}=e;return this.send(t,r,void 0)}))}stopSending(e){this.sessionDesc.mediaDescriptions.forEach((t=>{const r=[],n=[],i=[];t.attributes.ssrcs.forEach((t=>{e.includes(t.attributes.label||"")?i.push(t):r.push(t)})),t.attributes.ssrcGroups.forEach((e=>{i.map((e=>e.ssrcId)).includes(e.ssrcIds[0])||n.push(e)})),t.attributes.ssrcs=r,t.attributes.ssrcGroups=n}))}mute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.mute."));t.attributes.direction="inactive"}unmute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.unmute."));t.attributes.direction="sendonly"}receive(e,t,r){e.forEach(((e,t)=>{const r=e._mediaStreamTrack,n=this.sessionDesc.mediaDescriptions.findIndex((e=>e.attributes.mid===r.kind)),i=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[n],e);this.sessionDesc.mediaDescriptions[n]=i}))}stopReceiving(e){}updateCandidates(e){const t=this._originCandidates.filter((e=>"udp"===e.transport)),r=[];if(t.forEach((e=>{r.push(I(I({},e),{},{foundation:"tcpcandidate",priority:Number(e.priority)-1+"",transport:"tcp",port:Number(e.port)+90+""}))})),0!==t.length){switch(e){case x.TCP_RELAY:this.candidates=r;break;case x.UDP_TCP_RELAY:case x.RELAY:this.candidates=[...t,...r];break;default:this.candidates=t}for(const e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates}}restartICE(e){e=l(e),this.iceParameters=e,this.sessionDesc.mediaDescriptions.forEach((t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd}))}predictReceivingMids(e){const t=[];for(let r=0;r<e;r++)t.push((this.currentMidIndex+r+1).toString(10));return t}mungRecvMediaDsec(e,i){const o=l(e);return U(o,i),function(e,i){if(!(i instanceof t&&i._encoderConfig&&-1===i._hints.indexOf(r.SCREEN_TRACK)))return;const o=i._encoderConfig;n().supportMinBitrate&&o.bitrateMin&&e.attributes.payloads.forEach((e=>{var t;["h264","h265","vp8","vp9","av1"].includes((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["x-google-min-bitrate"]="".concat(o.bitrateMin))})),n().supportMinBitrate&&!i._hints.includes(r.LOW_STREAM)&&o.bitrateMax&&e.attributes.payloads.forEach((e=>{var t;["h264","h265","vp8","vp9","av1"].includes((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["x-google-start-bitrate"]="".concat(c("X_GOOGLE_START_BITRATE")||Math.floor(o.bitrateMax)))}))}(o,i),o}updateRecvMedia(e,t){const r=this.sessionDesc.mediaDescriptions.findIndex((t=>t.attributes.mid===e));if(-1!==r){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[r],t);this.sessionDesc.mediaDescriptions[r]=e}}bumpMid(e){this.currentMidIndex+=e}updateTrackLabel(e,t,r){const n=this.sessionDesc.mediaDescriptions.find((t=>e===F.VIDEO?"video"===t.attributes.mid:"audio"===t.attributes.mid));if(n){const e=n.attributes.ssrcs.find((e=>e.attributes.label===t));var i;if(e)e.attributes.label=r,null===(i=e.attributes.msid)||void 0===i||i.replace(t,r)}}mungMediaDesc(e){const t=l(e);return function(e){const t=e.attributes.unrecognized.findIndex((e=>"x-google-flag"===e.attField&&"conference"===e.attValue));-1!==t&&e.attributes.unrecognized.splice(t,1)}(t),function(e){const t=e.attributes.extmaps.find((e=>{return"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===(t=e.extensionName)||t.includes("draft-holmer-rmcat-transport-wide-cc-extensions-01");var t}));t&&e.attributes.extmaps.splice(e.attributes.extmaps.indexOf(t),1),e.attributes.payloads.forEach((e=>{const t=e.rtcpFeedbacks.findIndex((e=>"transport-cc"===e.type));-1!==t&&e.rtcpFeedbacks.splice(t,1)}))}(t),t}getSSRC(e){for(const t of this.sessionDesc.mediaDescriptions)for(const r of t.attributes.ssrcs)if(r.attributes.label===e)return[r]}}var V;let G=(V=class e extends N{get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get localCodecs(){return[...new Set(this.localCapabilities&&this.localCapabilities.videoCodecs.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")).filter((e=>Object.keys(h).includes(e))))]}constructor(t,r){super(t,r),this.store=void 0,this.peerConnection=void 0,this.remoteSDP=void 0,this.initialOffer=void 0,this.statsFilter=void 0,this.useRTX=!1,this.localCapabilities=void 0,this.localCandidateCount=0,this.allCandidatesReceived=!1,this.establishPromise=void 0,this.mutex=void 0,this.store=r,this.mutex=new m("P2PConnection-mutex",r.clientId),this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.statsFilter=f(this.peerConnection,c("STATS_UPDATE_INTERVAL"),void 0,d()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,this.establishPromise=this.establish()}async establish(){try{const e=await this.peerConnection.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});if(!e.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const t=M(e.sdp),r=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=arguments.length>3?arguments[3]:void 0;const{filterRTX:i,filterVideoFec:o,filterAudioFec:s,filterAudioCodec:d,filterVideoCodec:p}=t,{useXR:l}=r;let u=[],h=[],m=[],f=[],v=!1,C=!1;if(a(e).mediaDescriptions.forEach((e=>{n&&n!==e.attributes.direction||("video"!==e.media.mediaType||v||(h=e.attributes.payloads,f=e.attributes.extmaps,v=!0),"audio"!==e.media.mediaType||C||(u=e.attributes.payloads,m=e.attributes.extmaps,C=!0))})),!f||0===h.length)throw new Error("Cannot get video capabilities from SDP.");if(!m||0===u.length)throw new Error("Cannot get audio capabilities from SDP.");if(h.forEach((e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),l&&e.rtcpFeedbacks.push({type:"rrtr"})})),u.forEach((e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),l&&e.rtcpFeedbacks.push({type:"rrtr"})})),i&&(u=u.filter((e=>{var t;return"rtx"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())})),h=h.filter((e=>{var t;return"rtx"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())}))),o&&(h=h.filter((e=>{var t;return!/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||"")}))),s&&(u=u.filter((e=>{var t;return!/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||"")}))),d&&(null==d?void 0:d.length)>0&&(u=u.filter((e=>{var t;return d.includes((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")}))),p&&(null==p?void 0:p.length)>0){const e=h.filter((e=>{var t;return p.includes((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")}));h=e.concat(i?[]:function(e,t){const r=e.map((e=>e.payloadType.toString()));return t.filter((e=>e.rtpMap&&"rtx"===e.rtpMap.encodingName&&e.fmtp&&e.fmtp.parameters.apt&&r.includes(e.fmtp&&e.fmtp.parameters.apt)))}(e,h))}const g=c("UNSUPPORTED_VIDEO_CODEC");return g&&g.length>0&&(h=h.filter((e=>!(e.rtpMap&&g.includes(e.rtpMap.encodingName.toLowerCase()))))),{audioCodecs:u,videoCodecs:h,audioExtensions:m,videoExtensions:f}}(e.sdp,{filterRTX:!this.useRTX,filterVideoFec:c("FILTER_VIDEO_FEC"),filterAudioFec:c("FILTER_AUDIO_FEC"),filterAudioCodec:["opus"]});return this.localCapabilities=r,this.initialOffer=e,I(I({},t),{},{rtpCapabilities:{send:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},recv:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},sendrecv:r},offerSDP:e.sdp})}catch(e){throw new v(C.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async updateRemoteConnect(){}async connect(e){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");this.remoteSDP=new j(I(I({},e),{},{rtpCapabilities:e.rtpCapabilities.send,localCapabilities:this.localCapabilities,sdkCodec:this.store.codec}));const t=this.remoteSDP.toString();await this.peerConnection.setLocalDescription(this.initialOffer),await this.peerConnection.setRemoteDescription({type:"answer",sdp:t})}catch(e){throw new v(C.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}}async updateRemoteRTPCapabilities(e,t){throw new v(C.NOT_SUPPORTED,"Planb mode does not support createDataChannels.")}getPreMedia(e){}send(e,t){var r=this;return O((function*(){const n=yield w(r.mutex.lock());try{if(!r.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const i=e.map((e=>r.peerConnection.addTrack(e._mediaStreamTrack))),o=yield w(r.peerConnection.createOffer()),s=a(o.sdp),c=e.map((e=>{const t=e._mediaStreamTrack,n=s.mediaDescriptions.find((e=>e.attributes.mid===t.kind));if(!n)throw new Error("Cannot extract ssrc from mediaDescription.");return function(e,t,r){const n=e.attributes.ssrcs.filter((e=>e.attributes.label===t)),i=e.attributes.ssrcGroups;if(0===n.length)throw new Error("Cannot extract ssrc from plan-b SDP.");if(i&&n.length>1){const e=i.find((e=>-1!==e.ssrcIds.indexOf(n[0].ssrcId)));return e?[{ssrcId:e.ssrcIds[0],rtx:r?e.ssrcIds[1]:void 0}]:[{ssrcId:n[0].ssrcId}]}return[{ssrcId:n[0].ssrcId}]}(n,t.id,r.useRTX)}));let d;try{d=yield c}catch(e){throw i.forEach((e=>{g()&&e.replaceTrack(null),r.peerConnection.removeTrack(e)})),e}const p=r.mungSendOfferSDP(o.sdp,e);r.remoteSDP.receive(e,t,d);const l=r.remoteSDP.toString();return yield w(r.peerConnection.setLocalDescription({type:"offer",sdp:p})),yield w(r.applySendEncodings(i,e)),yield w(r.peerConnection.setRemoteDescription({type:"answer",sdp:l})),e.map(((e,t)=>{const r=e._mediaStreamTrack.id;return{localSSRC:c[t],id:r}}))}catch(e){throw new v(C.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()))}finally{n()}}))()}async stopSending(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const t=this.peerConnection.getSenders().filter((t=>{var r;return-1!==e.indexOf((null===(r=t.track)||void 0===r?void 0:r.id)||"")}));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.");t.map((e=>{g()&&e.replaceTrack(null),this.peerConnection.removeTrack(e)}));const r=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(r),this.remoteSDP.stopReceiving(e);const n=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}catch(e){throw new v(C.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()))}}async receive(e,t,r,n){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const{id:r,mslabel:i}=this.remoteSDP.send(e,t,n),o=new Promise(((t,n)=>{const o=setTimeout((()=>{n(new Error("Cannot receive track, id: ".concat(r)))}),1e4),s=n=>{const a=S();if(("Safari"===a.name&&11===Number(a.version)||P())&&n.track.id!==r&&n.streams[0].id===i){var c;const i=n.streams[0].getTracks()[0];return null===(c=this.remoteSDP)||void 0===c||c.updateTrackLabel(e,r,n.track.id),this.peerConnection.removeEventListener("track",s),clearTimeout(o),void t(i)}if(n.track.id===r)return this.peerConnection.removeEventListener("track",s),clearTimeout(o),void t(n.track)};this.peerConnection.addEventListener("track",s)})),s=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:s});const a=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(a);return{track:await o,id:r}}catch(e){throw new v(C.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const r=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(r)}catch(e){throw new v(C.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}async muteRemote(e){}async unmuteRemote(e){}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const t=this.peerConnection.getSenders().filter((t=>{var r;return-1!==e.indexOf((null===(r=t.track)||void 0===r?void 0:r.id)||"")}));if(t.length!==e.length)throw new Error("sender' length doesn't match mids' length.");t.map((e=>{if(g()&&e.track)e.track.enabled=!1;else{const t=e.getParameters();t.encodings.forEach((e=>e.active=!1)),e.setParameters(t)}}))}catch(e){throw new v(C.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const t=this.peerConnection.getSenders().filter((t=>{var r;return-1!==e.indexOf((null===(r=t.track)||void 0===r?void 0:r.id)||"")}));if(t.length!==e.length)throw new Error("Senders' length doesn't match mids' length.");t.map((async e=>{if(g()&&e.track)e.track.enabled=!0;else{const t=e.getParameters();t.encodings.forEach((e=>e.active=!0)),await e.setParameters(t)}}));const r=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(r);const n=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}catch(e){throw new v(C.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(e){var t=this;return O((function*(){const r=yield w(t.mutex.lock("From P2PConnection.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");const o=n().supportPCSetConfiguration;if(e===x.RELAY&&!o)return;if(o){const r=t.peerConnection.getConfiguration(),n=e===x.RELAY?"relay":"all";r.iceTransportPolicy!==n&&(i.debug("[".concat(t.store.clientId,"] restartICE change iceTransportPolicy from [").concat(r.iceTransportPolicy,"] to [").concat(n,"]")),r.iceTransportPolicy=n,t.peerConnection.setConfiguration(r))}e!==x.RELAY&&t.remoteSDP.updateCandidates(e);const s=yield w(t.peerConnection.createOffer({iceRestart:!0}));if(!s.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const a=M(s.sdp),{remoteIceParameters:c}=yield a.iceParameters;t.remoteSDP.restartICE(c);const d=t.remoteSDP.toString();yield w(t.peerConnection.setLocalDescription(s)),yield w(t.peerConnection.setRemoteDescription({type:"answer",sdp:d}))}catch(e){i.warning("[".concat(t.store.clientId,"] restart ICE failed, abort operation"),e)}finally{r()}}))()}close(){var e;this.peerConnection.close(),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,"closed"),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.statsFilter.destroy()}getStats(){return this.statsFilter.getStats()}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const e=await this.peerConnection.createOffer(),r=this.mungSendOfferSDP(e.sdp,[t]);this.remoteSDP.updateRecvMedia(t._mediaStreamTrack.kind,t);const n=this.remoteSDP.toString();await this.peerConnection.setLocalDescription({type:"offer",sdp:r}),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}catch(e){throw new v(C.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const r=this.peerConnection.getSenders().filter((t=>{var r;return(null===(r=t.track)||void 0===r?void 0:r.id)===e}));1===r.length&&await this.applySendEncodings(r,[t])}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const r=this.peerConnection.getSenders().find((e=>{var r;return(null===(r=e.track)||void 0===r?void 0:r.id)===t}));r&&await r.replaceTrack(e._mediaStreamTrack)}createDataChannels(e,t){throw new v(C.NOT_SUPPORTED,"Planb mode does not support createDataChannels.")}stopDataChannels(e){throw new v(C.NOT_SUPPORTED,"Planb mode does not support stopDataChannels.")}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null===(e=this.onICEConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,i.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,i.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))}),c("CANDIDATE_TIMEOUT"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t){const r={iceServers:[],sdpSemantics:"plan-b"};return t.iceServers?r.iceServers=t.iceServers:t.turnServer&&"off"!==t.turnServer.mode&&(b(t.turnServer.servers)?r.iceServers=t.turnServer.servers:(r.iceServers&&r.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),c("USE_TURN_SERVER_OF_GATEWAY")&&r.iceServers&&t.turnServer.serversFromGateway&&r.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(r.iceTransportPolicy="relay")})))),r}static turnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}))})),t}async updateRtpSenderEncodings(e,r){var o;if(!r){r=this.peerConnection.getSenders().find((t=>{var r;return(null===(r=t.track)||void 0===r?void 0:r.id)===e._mediaStreamTrack.id}))}if(!r)return i.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(!n().supportSetRtpSenderParameters)return i.warn("Browser not support set rtp-sender parameters");const s={},a={};if(e instanceof t)switch(e._optimizationMode){case"motion":s.degradationPreference="maintain-framerate";break;case"detail":s.degradationPreference="maintain-resolution";break;default:s.degradationPreference="balanced"}if(c("DSCP_TYPE")&&E()){const e=c("DSCP_TYPE");["very-low","low","medium","high"].includes(e)&&(a.networkPriority=e)}const d=r.getParameters(),p=null===(o=d.encodings)||void 0===o?void 0:o[0];p&&Object.assign(p,a),Object.assign(d,s),i.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(d.encodings))),await r.setParameters(d)}async applySendEncodings(e,t){try{if(!n().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let r=0;r<e.length;r++){const n=e[r],i=t[r];n&&i&&await this.updateRtpSenderEncodings(i,n)}}catch(e){i.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t){const r=a(e);return t.forEach(((e,t)=>{const n=e._mediaStreamTrack,i=r.mediaDescriptions.find((e=>e.attributes.mid===n.kind));i&&U(i,e)})),u(r)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,r)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,r)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var r;null===(r=this.onSelectedLocalCandidateChanged)||void 0===r||r.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var r;null===(r=this.onSelectedRemoteCandidateChanged)||void 0===r||r.call(this,e,t)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0}async batchReceive(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.batchReceive before remoteSDP created.");const t=this.remoteSDP.batchSend(e).map(((t,r)=>{let{id:n,mslabel:i}=t;const{kind:o}=e[r];return new Promise(((e,t)=>{const r=setTimeout((()=>{t(new Error("Cannot receive track, id: ".concat(n)))}),1e4),s=t=>{const a=S();if("Safari"===a.name&&11===Number(a.version)&&t.track.id!==n&&t.streams[0].id===i){var c;const i=t.streams[0].getTracks()[0];return null===(c=this.remoteSDP)||void 0===c||c.updateTrackLabel(o,n,t.track.id),this.peerConnection.removeEventListener("track",s),clearTimeout(r),void e({track:i,id:n})}if(t.track.id===n)return this.peerConnection.removeEventListener("track",s),clearTimeout(r),void e({track:t.track,id:n})};this.peerConnection.addEventListener("track",s)}))})),r=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:r});const n=await this.peerConnection.createAnswer();return await this.peerConnection.setLocalDescription(n),await Promise.all(t)}catch(e){throw new v(C.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async getRemoteSSRC(e){if(!this.remoteSDP)return;const t=this.remoteSDP.getSSRC(e);return null==t?void 0:t[0].ssrcId}setConfiguration(t){if(n().supportPCSetConfiguration){const r=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(r)}}},D(V.prototype,"connect",[H],Object.getOwnPropertyDescriptor(V.prototype,"connect"),V.prototype),D(V.prototype,"stopSending",[H],Object.getOwnPropertyDescriptor(V.prototype,"stopSending"),V.prototype),D(V.prototype,"receive",[H],Object.getOwnPropertyDescriptor(V.prototype,"receive"),V.prototype),D(V.prototype,"stopReceiving",[H],Object.getOwnPropertyDescriptor(V.prototype,"stopReceiving"),V.prototype),D(V.prototype,"muteRemote",[H],Object.getOwnPropertyDescriptor(V.prototype,"muteRemote"),V.prototype),D(V.prototype,"unmuteRemote",[H],Object.getOwnPropertyDescriptor(V.prototype,"unmuteRemote"),V.prototype),D(V.prototype,"muteLocal",[H],Object.getOwnPropertyDescriptor(V.prototype,"muteLocal"),V.prototype),D(V.prototype,"unmuteLocal",[H],Object.getOwnPropertyDescriptor(V.prototype,"unmuteLocal"),V.prototype),D(V.prototype,"close",[H],Object.getOwnPropertyDescriptor(V.prototype,"close"),V.prototype),D(V.prototype,"updateEncoderConfig",[H],Object.getOwnPropertyDescriptor(V.prototype,"updateEncoderConfig"),V.prototype),D(V.prototype,"updateSendParameters",[H],Object.getOwnPropertyDescriptor(V.prototype,"updateSendParameters"),V.prototype),D(V.prototype,"replaceTrack",[H],Object.getOwnPropertyDescriptor(V.prototype,"replaceTrack"),V.prototype),D(V.prototype,"getRemoteSSRC",[H],Object.getOwnPropertyDescriptor(V.prototype,"getRemoteSSRC"),V.prototype),V);function H(e,t,r){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return r.value=async function(){const e=this.mutex,r=await e.lock("Locking from P2PConnection.".concat(t));try{for(var i=arguments.length,o=new Array(i),s=0;s<i;s++)o[s]=arguments[s];return await n.apply(this,o)}finally{r()}},r}const X={name:"PlanBConnection",create:function(e){let{store:t,spec:r}=e;return new G(r,t)}};export{X as PlanBConnectionService}; | ||
import{LocalAudioTrack as e,LocalVideoTrack as t,TrackHint as r,getCompatibility as n}from"@agora-js/media";import{logger as i}from"@agora-js/report";import{IS_GLOBAL_VERSION as o,EventEmitter as s,parseSdp as a,getParameter as c,isFirefox as d,getRandomString as p,jsonClone as l,printSdp as u,VideoCodec as h,PromiseMutex as m,createWebRTCStatsFilter as f,AgoraRTCError as v,AgoraRTCErrorCode as C,isSafari as g,getBrowserInfo as S,isIOS as P,isRTCIceServerList as b,isChromeKernel as E}from"@agora-js/shared";function y(e,t){this.v=e,this.k=t}function D(e,t,r,n,i){var o={};return Object.keys(n).forEach((function(e){o[e]=n[e]})),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=r.slice().reverse().reduce((function(r,n){return n(e,t,r)||r}),o),i&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(i):void 0,o.initializer=void 0),void 0===o.initializer?(Object.defineProperty(e,t,o),null):o}function w(e){return new y(e,0)}function R(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.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:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function A(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function I(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?A(Object(r),!0).forEach((function(t){R(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):A(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function O(e){return function(){return new T(e.apply(this,arguments))}}function T(e){var t,r;function n(t,r){try{var o=e[t](r),s=o.value,a=s instanceof y;Promise.resolve(a?s.v:s).then((function(r){if(a){var c="return"===t?"return":"next";if(!s.k||r.done)return n(c,r);r=e[c](r).value}i(o.done?"return":"normal",r)}),(function(e){n("throw",e)}))}catch(e){i("throw",e)}}function i(e,i){switch(e){case"return":t.resolve({value:i,done:!0});break;case"throw":t.reject(i);break;default:t.resolve({value:i,done:!1})}(t=t.next)?n(t.key,t.arg):r=null}this._invoke=function(e,i){return new Promise((function(o,s){var a={key:e,arg:i,resolve:o,reject:s,next:null};r?r=r.next=a:(t=r=a,n(e,i))}))},"function"!=typeof e.return&&(this.return=void 0)}T.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},T.prototype.next=function(e){return this._invoke("next",e)},T.prototype.throw=function(e){return this._invoke("throw",e)},T.prototype.return=function(e){return this._invoke("return",e)};let k=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}({});k.AFRICA,k.ASIA,k.CHINA,k.EUROPE,k.GLOBAL,k.INDIA,k.JAPAN,k.NORTH_AMERICA,k.OCEANIA,k.OVERSEA,k.SOUTH_AMERICA;let L=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}({});L.ASIA,L.NORTH_AMERICA,L.EUROPE,L.JAPAN,L.INDIA,L.KOREA,L.HKMC,L.US,L.OVERSEA,L.GLOBAL,L.OCEANIA,L.SOUTH_AMERICA,L.AFRICA,o&&L.CHINA;class _ extends s{constructor(e,t){super(),this.onICEConnectionStateChange=void 0,this.onConnectionStateChange=void 0,this.onDTLSTransportStateChange=void 0,this.onDTLSTransportError=void 0,this.onICETransportStateChange=void 0,this.onFirstAudioReceived=void 0,this.onFirstVideoReceived=void 0,this.onFirstAudioDecoded=void 0,this.onFirstVideoDecoded=void 0,this.onFirstVideoDecodedTimeout=void 0,this.onSelectedLocalCandidateChanged=void 0,this.onSelectedRemoteCandidateChanged=void 0,this.onICECandidateError=void 0,this.getLocalVideoStats=void 0}}class N extends _{constructor(e,t){super(e,t),this.establishPromise=void 0}}let F=function(e){return e.VIDEO="video",e.AUDIO="audio",e}({}),x=function(e){return e.UDP_RELAY="udp_relay",e.UDP_TCP_RELAY="udp_tcp_relay",e.TCP_RELAY="tcp_relay",e.RELAY="relay",e}({});function M(e){const t=a(e);let r,n;for(const e of t.mediaDescriptions){if(!r){const t=e.attributes.iceUfrag,n=e.attributes.icePwd;if(!t||!n)throw new Error("Cannot get iceUfrag or icePwd from SDP.");r={iceUfrag:t,icePwd:n}}if(!n){const t=e.attributes.fingerprints;t.length>0&&(n={fingerprints:t})}}if(!n&&t.attributes.fingerprints.length>0&&(n={fingerprints:t.attributes.fingerprints}),!n||!r)throw new Error("Cannot get iceParameters or dtlsParameters from SDP.");return{iceParameters:r,dtlsParameters:n}}function U(t,r){r instanceof e&&t.attributes.payloads.forEach((e=>{var t;const n=null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase();if(!n||-1===["opus","pcmu","pcma","g722"].indexOf(n))return;e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters.minptime="10",e.fmtp.parameters.useinbandfec="1";const i=r._encoderConfig;i&&"pcmu"!==n&&"pcma"!==n&&"g722"!==n&&(i.bitrate&&!d()&&(e.fmtp.parameters.maxaveragebitrate="".concat(Math.floor(1e3*i.bitrate))),i.sampleRate&&(e.fmtp.parameters.maxplaybackrate="".concat(i.sampleRate),e.fmtp.parameters["sprop-maxcapturerate"]="".concat(i.sampleRate)),i.stereo&&(e.fmtp.parameters.stereo="1",e.fmtp.parameters["sprop-stereo"]="1"))}))}F.VIDEO,F.AUDIO;class j{constructor(e){this.sessionDesc=void 0,this.localCapabilities=void 0,this.rtpCapabilities=void 0,this.candidates=void 0,this._originCandidates=void 0,this.iceParameters=void 0,this.dtlsParameters=void 0,this.setup=void 0,this.currentMidIndex=void 0,this.cname=void 0,e=l(e);const{iceParameters:t,dtlsParameters:r,candidates:n,rtpCapabilities:i,setup:o,localCapabilities:s,sdkCodec:c,cname:d}=e,p=a("v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE audio video\na=msid-semantic: WMS\na=ice-lite\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendrecv\na=rtcp-mux\na=rtcp-rsize\na=mid:audio\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendrecv\na=rtcp-mux\na=rtcp-rsize\na=mid:video\n");this.rtpCapabilities=i,this.candidates=n,this._originCandidates=l(n),this.iceParameters=t,this.dtlsParameters=r,this.setup=o,this.localCapabilities=s,this.cname=d;for(let e=0;e<p.mediaDescriptions.length;e++){const s=p.mediaDescriptions[e];if(s.attributes.iceUfrag=t.iceUfrag,s.attributes.icePwd=t.icePwd,s.attributes.fingerprints=r.fingerprints,s.attributes.candidates=n,s.attributes.setup=o,"video"===s.media.mediaType){s.media.fmts=i.videoCodecs.map((e=>e.payloadType.toString(10)));let e=i.videoCodecs.filter((e=>{var t;return null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase().includes(c)}));0===e.length&&(e=i.videoCodecs),s.attributes.payloads=e,s.attributes.extmaps=i.videoExtensions}"audio"===s.media.mediaType&&(s.media.fmts=i.audioCodecs.map((e=>e.payloadType.toString(10))),s.attributes.payloads=i.audioCodecs,s.attributes.extmaps=i.audioExtensions),p.mediaDescriptions[e]=this.mungMediaDesc(s)}this.sessionDesc=p,this.currentMidIndex=p.mediaDescriptions.length-1}toString(){return u(this.sessionDesc)}send(e,t,r){const{ssrcs:n,ssrcGroups:i}=function(e,t,r){const n=[],i=[];return e.forEach((e=>{let{ssrcId:o,rtx:s}=e;const a=p(8,"track-"),c={ssrcId:o,attributes:I({label:a,mslabel:r=r||p(10,""),msid:"".concat(r," ").concat(a)},t&&{cname:t})};if(n.push(c),void 0!==s){const e={ssrcId:s,attributes:I({label:a,mslabel:r,msid:"".concat(r," ").concat(a)},t&&{cname:t})};n.push(e),i.push({semantic:"FID",ssrcIds:[o,s]})}})),e.length>1&&i.push({semantic:"SIM",ssrcIds:e.map((e=>{let{ssrcId:t}=e;return t}))}),{ssrcs:n,ssrcGroups:i}}(t,this.cname),o=this.sessionDesc.mediaDescriptions.find((t=>e===F.VIDEO?"video"===t.media.mediaType:"audio"===t.media.mediaType)),s=n[0].attributes.label,a=n[0].attributes.mslabel;return o.attributes.ssrcs=o.attributes.ssrcs.concat(n),o.attributes.ssrcGroups=o.attributes.ssrcGroups.concat(i),{id:s,mslabel:a}}batchSend(e){return e.map((e=>{let{kind:t,ssrcMsg:r}=e;return this.send(t,r,void 0)}))}stopSending(e){this.sessionDesc.mediaDescriptions.forEach((t=>{const r=[],n=[],i=[];t.attributes.ssrcs.forEach((t=>{e.includes(t.attributes.label||"")?i.push(t):r.push(t)})),t.attributes.ssrcGroups.forEach((e=>{i.map((e=>e.ssrcId)).includes(e.ssrcIds[0])||n.push(e)})),t.attributes.ssrcs=r,t.attributes.ssrcGroups=n}))}mute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.mute."));t.attributes.direction="inactive"}unmute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.unmute."));t.attributes.direction="sendonly"}receive(e,t,r){e.forEach(((e,t)=>{const r=e._mediaStreamTrack,n=this.sessionDesc.mediaDescriptions.findIndex((e=>e.attributes.mid===r.kind)),i=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[n],e);this.sessionDesc.mediaDescriptions[n]=i}))}stopReceiving(e){}updateCandidates(e){const t=this._originCandidates.filter((e=>"udp"===e.transport)),r=[];if(t.forEach((e=>{r.push(I(I({},e),{},{foundation:"tcpcandidate",priority:Number(e.priority)-1+"",transport:"tcp",port:Number(e.port)+90+""}))})),0!==t.length){switch(e){case x.TCP_RELAY:this.candidates=r;break;case x.UDP_TCP_RELAY:case x.RELAY:this.candidates=[...t,...r];break;default:this.candidates=t}for(const e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates}}restartICE(e){e=l(e),this.iceParameters=e,this.sessionDesc.mediaDescriptions.forEach((t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd}))}predictReceivingMids(e){const t=[];for(let r=0;r<e;r++)t.push((this.currentMidIndex+r+1).toString(10));return t}mungRecvMediaDsec(e,i){const o=l(e);return U(o,i),function(e,i){if(!(i instanceof t&&i._encoderConfig&&-1===i._hints.indexOf(r.SCREEN_TRACK)))return;const o=i._encoderConfig;n().supportMinBitrate&&o.bitrateMin&&e.attributes.payloads.forEach((e=>{var t;["h264","h265","vp8","vp9","av1"].includes((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["x-google-min-bitrate"]="".concat(o.bitrateMin))})),n().supportMinBitrate&&!i._hints.includes(r.LOW_STREAM)&&o.bitrateMax&&e.attributes.payloads.forEach((e=>{var t;["h264","h265","vp8","vp9","av1"].includes((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["x-google-start-bitrate"]="".concat(c("X_GOOGLE_START_BITRATE")||Math.floor(o.bitrateMax)))}))}(o,i),o}updateRecvMedia(e,t){const r=this.sessionDesc.mediaDescriptions.findIndex((t=>t.attributes.mid===e));if(-1!==r){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[r],t);this.sessionDesc.mediaDescriptions[r]=e}}bumpMid(e){this.currentMidIndex+=e}updateTrackLabel(e,t,r){const n=this.sessionDesc.mediaDescriptions.find((t=>e===F.VIDEO?"video"===t.attributes.mid:"audio"===t.attributes.mid));if(n){const e=n.attributes.ssrcs.find((e=>e.attributes.label===t));var i;if(e)e.attributes.label=r,null===(i=e.attributes.msid)||void 0===i||i.replace(t,r)}}mungMediaDesc(e){const t=l(e);return function(e){const t=e.attributes.unrecognized.findIndex((e=>"x-google-flag"===e.attField&&"conference"===e.attValue));-1!==t&&e.attributes.unrecognized.splice(t,1)}(t),function(e){const t=e.attributes.extmaps.find((e=>{return"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===(t=e.extensionName)||t.includes("draft-holmer-rmcat-transport-wide-cc-extensions-01");var t}));t&&e.attributes.extmaps.splice(e.attributes.extmaps.indexOf(t),1),e.attributes.payloads.forEach((e=>{const t=e.rtcpFeedbacks.findIndex((e=>"transport-cc"===e.type));-1!==t&&e.rtcpFeedbacks.splice(t,1)}))}(t),t}getSSRC(e){for(const t of this.sessionDesc.mediaDescriptions)for(const r of t.attributes.ssrcs)if(r.attributes.label===e)return[r]}}var V;let G=(V=class e extends N{get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get localCodecs(){return[...new Set(this.localCapabilities&&this.localCapabilities.videoCodecs.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")).filter((e=>Object.keys(h).includes(e))))]}constructor(t,r){super(t,r),this.store=void 0,this.peerConnection=void 0,this.remoteSDP=void 0,this.initialOffer=void 0,this.statsFilter=void 0,this.useRTX=!1,this.localCapabilities=void 0,this.localCandidateCount=0,this.allCandidatesReceived=!1,this.establishPromise=void 0,this.mutex=void 0,this.store=r,this.mutex=new m("P2PConnection-mutex",r.clientId),this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.statsFilter=f(this.peerConnection,c("STATS_UPDATE_INTERVAL"),void 0,d()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,this.establishPromise=this.establish()}async establish(){try{const e=await this.peerConnection.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});if(!e.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const t=M(e.sdp),r=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=arguments.length>3?arguments[3]:void 0;const{filterRTX:i,filterVideoFec:o,filterAudioFec:s,filterAudioCodec:d,filterVideoCodec:p}=t,{useXR:l}=r;let u=[],h=[],m=[],f=[],v=!1,C=!1;if(a(e).mediaDescriptions.forEach((e=>{n&&n!==e.attributes.direction||("video"!==e.media.mediaType||v||(h=e.attributes.payloads,f=e.attributes.extmaps,v=!0),"audio"!==e.media.mediaType||C||(u=e.attributes.payloads,m=e.attributes.extmaps,C=!0))})),!f||0===h.length)throw new Error("Cannot get video capabilities from SDP.");if(!m||0===u.length)throw new Error("Cannot get audio capabilities from SDP.");if(h.forEach((e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),l&&e.rtcpFeedbacks.push({type:"rrtr"})})),u.forEach((e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),l&&e.rtcpFeedbacks.push({type:"rrtr"})})),i&&(u=u.filter((e=>{var t;return"rtx"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())})),h=h.filter((e=>{var t;return"rtx"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())}))),o&&(h=h.filter((e=>{var t;return!/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||"")}))),s&&(u=u.filter((e=>{var t;return!/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||"")}))),d&&(null==d?void 0:d.length)>0&&(u=u.filter((e=>{var t;return d.includes((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")}))),p&&(null==p?void 0:p.length)>0){const e=h.filter((e=>{var t;return p.includes((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")}));h=e.concat(i?[]:function(e,t){const r=e.map((e=>e.payloadType.toString()));return t.filter((e=>e.rtpMap&&"rtx"===e.rtpMap.encodingName&&e.fmtp&&e.fmtp.parameters.apt&&r.includes(e.fmtp&&e.fmtp.parameters.apt)))}(e,h))}const g=c("UNSUPPORTED_VIDEO_CODEC");return g&&g.length>0&&(h=h.filter((e=>!(e.rtpMap&&g.includes(e.rtpMap.encodingName.toLowerCase()))))),{audioCodecs:u,videoCodecs:h,audioExtensions:m,videoExtensions:f}}(e.sdp,{filterRTX:!this.useRTX,filterVideoFec:c("FILTER_VIDEO_FEC"),filterAudioFec:c("FILTER_AUDIO_FEC"),filterAudioCodec:["opus"]});return this.localCapabilities=r,this.initialOffer=e,I(I({},t),{},{rtpCapabilities:{send:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},recv:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},sendrecv:r},offerSDP:e.sdp})}catch(e){throw new v(C.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async updateRemoteConnect(){}async connect(e){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");this.remoteSDP=new j(I(I({},e),{},{rtpCapabilities:e.rtpCapabilities.send,localCapabilities:this.localCapabilities,sdkCodec:this.store.codec}));const t=this.remoteSDP.toString();await this.peerConnection.setLocalDescription(this.initialOffer),await this.peerConnection.setRemoteDescription({type:"answer",sdp:t})}catch(e){throw new v(C.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}}async updateRemoteRTPCapabilities(e,t){throw new v(C.NOT_SUPPORTED,"Planb mode does not support createDataChannels.")}getPreMedia(e){}send(e,t){var r=this;return O((function*(){const n=yield w(r.mutex.lock());try{if(!r.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const n=e.map((e=>r.peerConnection.addTrack(e._mediaStreamTrack))),i=yield w(r.peerConnection.createOffer()),o=a(i.sdp),s=e.map((e=>{const t=e._mediaStreamTrack,n=o.mediaDescriptions.find((e=>e.attributes.mid===t.kind));if(!n)throw new Error("Cannot extract ssrc from mediaDescription.");return function(e,t,r){const n=e.attributes.ssrcs.filter((e=>e.attributes.label===t)),i=e.attributes.ssrcGroups;if(0===n.length)throw new Error("Cannot extract ssrc from plan-b SDP.");if(i&&n.length>1){const e=i.find((e=>-1!==e.ssrcIds.indexOf(n[0].ssrcId)));return e?[{ssrcId:e.ssrcIds[0],rtx:r?e.ssrcIds[1]:void 0}]:[{ssrcId:n[0].ssrcId}]}return[{ssrcId:n[0].ssrcId}]}(n,t.id,r.useRTX)}));let c;try{c=yield s}catch(e){throw n.forEach((e=>{g()&&e.replaceTrack(null),r.peerConnection.removeTrack(e)})),e}const d=r.mungSendOfferSDP(i.sdp,e);r.remoteSDP.receive(e,t,c);const p=r.remoteSDP.toString();return yield w(r.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield w(r.applySendEncodings(n,e)),yield w(r.peerConnection.setRemoteDescription({type:"answer",sdp:p})),e.map(((e,t)=>{const r=e._mediaStreamTrack.id;return{localSSRC:s[t],id:r}}))}catch(e){throw new v(C.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()))}finally{n()}}))()}async stopSending(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const t=this.peerConnection.getSenders().filter((t=>{var r;return-1!==e.indexOf((null===(r=t.track)||void 0===r?void 0:r.id)||"")}));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.");t.map((e=>{g()&&e.replaceTrack(null),this.peerConnection.removeTrack(e)}));const r=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(r),this.remoteSDP.stopReceiving(e);const n=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}catch(e){throw new v(C.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()))}}async receive(e,t,r,n){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const{id:r,mslabel:i}=this.remoteSDP.send(e,t,n),o=new Promise(((t,n)=>{const o=setTimeout((()=>{n(new Error("Cannot receive track, id: ".concat(r)))}),1e4),s=n=>{const a=S();if(("Safari"===a.name&&11===Number(a.version)||P())&&n.track.id!==r&&n.streams[0].id===i){var c;const i=n.streams[0].getTracks()[0];return null===(c=this.remoteSDP)||void 0===c||c.updateTrackLabel(e,r,n.track.id),this.peerConnection.removeEventListener("track",s),clearTimeout(o),void t(i)}if(n.track.id===r)return this.peerConnection.removeEventListener("track",s),clearTimeout(o),void t(n.track)};this.peerConnection.addEventListener("track",s)})),s=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:s});const a=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(a);return{track:await o,id:r}}catch(e){throw new v(C.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const r=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(r)}catch(e){throw new v(C.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}async muteRemote(e){}async unmuteRemote(e){}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const t=this.peerConnection.getSenders().filter((t=>{var r;return-1!==e.indexOf((null===(r=t.track)||void 0===r?void 0:r.id)||"")}));if(t.length!==e.length)throw new Error("sender' length doesn't match mids' length.");t.map((e=>{if(g()&&e.track)e.track.enabled=!1;else{const t=e.getParameters();t.encodings.forEach((e=>e.active=!1)),e.setParameters(t)}}))}catch(e){throw new v(C.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const t=this.peerConnection.getSenders().filter((t=>{var r;return-1!==e.indexOf((null===(r=t.track)||void 0===r?void 0:r.id)||"")}));if(t.length!==e.length)throw new Error("Senders' length doesn't match mids' length.");t.map((async e=>{if(g()&&e.track)e.track.enabled=!0;else{const t=e.getParameters();t.encodings.forEach((e=>e.active=!0)),await e.setParameters(t)}}));const r=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(r);const n=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}catch(e){throw new v(C.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(e){var t=this;return O((function*(){const r=yield w(t.mutex.lock("From P2PConnection.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");const r=n().supportPCSetConfiguration;if(e===x.RELAY&&!r)return;if(r){const r=t.peerConnection.getConfiguration(),n=e===x.RELAY?"relay":"all";r.iceTransportPolicy!==n&&(i.debug("[".concat(t.store.clientId,"] restartICE change iceTransportPolicy from [").concat(r.iceTransportPolicy,"] to [").concat(n,"]")),r.iceTransportPolicy=n,t.peerConnection.setConfiguration(r))}e!==x.RELAY&&t.remoteSDP.updateCandidates(e);const o=yield w(t.peerConnection.createOffer({iceRestart:!0}));if(!o.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const s=M(o.sdp),{remoteIceParameters:a}=yield s.iceParameters;t.remoteSDP.restartICE(a);const c=t.remoteSDP.toString();yield w(t.peerConnection.setLocalDescription(o)),yield w(t.peerConnection.setRemoteDescription({type:"answer",sdp:c}))}catch(e){i.warning("[".concat(t.store.clientId,"] restart ICE failed, abort operation"),e)}finally{r()}}))()}close(){var e;this.peerConnection.close(),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,"closed"),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.statsFilter.destroy()}getStats(){return this.statsFilter.getStats()}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const e=await this.peerConnection.createOffer(),r=this.mungSendOfferSDP(e.sdp,[t]);this.remoteSDP.updateRecvMedia(t._mediaStreamTrack.kind,t);const n=this.remoteSDP.toString();await this.peerConnection.setLocalDescription({type:"offer",sdp:r}),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}catch(e){throw new v(C.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const r=this.peerConnection.getSenders().filter((t=>{var r;return(null===(r=t.track)||void 0===r?void 0:r.id)===e}));1===r.length&&await this.applySendEncodings(r,[t])}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const r=this.peerConnection.getSenders().find((e=>{var r;return(null===(r=e.track)||void 0===r?void 0:r.id)===t}));r&&await r.replaceTrack(e._mediaStreamTrack)}createDataChannels(e,t){throw new v(C.NOT_SUPPORTED,"Planb mode does not support createDataChannels.")}stopDataChannels(e){throw new v(C.NOT_SUPPORTED,"Planb mode does not support stopDataChannels.")}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null===(e=this.onICEConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,i.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,i.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))}),c("CANDIDATE_TIMEOUT"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t){const r={iceServers:[],sdpSemantics:"plan-b"};return t.iceServers?r.iceServers=t.iceServers:t.turnServer&&"off"!==t.turnServer.mode&&(b(t.turnServer.servers)?r.iceServers=t.turnServer.servers:(r.iceServers&&r.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),c("USE_TURN_SERVER_OF_GATEWAY")&&r.iceServers&&t.turnServer.serversFromGateway&&r.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(r.iceTransportPolicy="relay")})))),r}static turnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}))})),t}async updateRtpSenderEncodings(e,r){var o;if(!r){r=this.peerConnection.getSenders().find((t=>{var r;return(null===(r=t.track)||void 0===r?void 0:r.id)===e._mediaStreamTrack.id}))}if(!r)return i.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(!n().supportSetRtpSenderParameters)return i.warn("Browser not support set rtp-sender parameters");const s={},a={};if(e instanceof t)switch(e._optimizationMode){case"motion":s.degradationPreference="maintain-framerate";break;case"detail":s.degradationPreference="maintain-resolution";break;default:s.degradationPreference="balanced"}if(c("DSCP_TYPE")&&E()){const e=c("DSCP_TYPE");["very-low","low","medium","high"].includes(e)&&(a.networkPriority=e)}const d=r.getParameters(),p=null===(o=d.encodings)||void 0===o?void 0:o[0];p&&Object.assign(p,a),Object.assign(d,s),i.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(d.encodings))),await r.setParameters(d)}async applySendEncodings(e,t){try{if(!n().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let r=0;r<e.length;r++){const n=e[r],i=t[r];n&&i&&await this.updateRtpSenderEncodings(i,n)}}catch(e){i.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t){const r=a(e);return t.forEach(((e,t)=>{const n=e._mediaStreamTrack,i=r.mediaDescriptions.find((e=>e.attributes.mid===n.kind));i&&U(i,e)})),u(r)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,r)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,r)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var r;null===(r=this.onSelectedLocalCandidateChanged)||void 0===r||r.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var r;null===(r=this.onSelectedRemoteCandidateChanged)||void 0===r||r.call(this,e,t)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0}async batchReceive(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.batchReceive before remoteSDP created.");const t=this.remoteSDP.batchSend(e).map(((t,r)=>{let{id:n,mslabel:i}=t;const{kind:o}=e[r];return new Promise(((e,t)=>{const r=setTimeout((()=>{t(new Error("Cannot receive track, id: ".concat(n)))}),1e4),s=t=>{const a=S();if("Safari"===a.name&&11===Number(a.version)&&t.track.id!==n&&t.streams[0].id===i){var c;const i=t.streams[0].getTracks()[0];return null===(c=this.remoteSDP)||void 0===c||c.updateTrackLabel(o,n,t.track.id),this.peerConnection.removeEventListener("track",s),clearTimeout(r),void e({track:i,id:n})}if(t.track.id===n)return this.peerConnection.removeEventListener("track",s),clearTimeout(r),void e({track:t.track,id:n})};this.peerConnection.addEventListener("track",s)}))})),r=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:r});const n=await this.peerConnection.createAnswer();return await this.peerConnection.setLocalDescription(n),await Promise.all(t)}catch(e){throw new v(C.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async getRemoteSSRC(e){if(!this.remoteSDP)return;const t=this.remoteSDP.getSSRC(e);return null==t?void 0:t[0].ssrcId}setConfiguration(t){if(n().supportPCSetConfiguration){const r=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(r)}}},D(V.prototype,"connect",[H],Object.getOwnPropertyDescriptor(V.prototype,"connect"),V.prototype),D(V.prototype,"stopSending",[H],Object.getOwnPropertyDescriptor(V.prototype,"stopSending"),V.prototype),D(V.prototype,"receive",[H],Object.getOwnPropertyDescriptor(V.prototype,"receive"),V.prototype),D(V.prototype,"stopReceiving",[H],Object.getOwnPropertyDescriptor(V.prototype,"stopReceiving"),V.prototype),D(V.prototype,"muteRemote",[H],Object.getOwnPropertyDescriptor(V.prototype,"muteRemote"),V.prototype),D(V.prototype,"unmuteRemote",[H],Object.getOwnPropertyDescriptor(V.prototype,"unmuteRemote"),V.prototype),D(V.prototype,"muteLocal",[H],Object.getOwnPropertyDescriptor(V.prototype,"muteLocal"),V.prototype),D(V.prototype,"unmuteLocal",[H],Object.getOwnPropertyDescriptor(V.prototype,"unmuteLocal"),V.prototype),D(V.prototype,"close",[H],Object.getOwnPropertyDescriptor(V.prototype,"close"),V.prototype),D(V.prototype,"updateEncoderConfig",[H],Object.getOwnPropertyDescriptor(V.prototype,"updateEncoderConfig"),V.prototype),D(V.prototype,"updateSendParameters",[H],Object.getOwnPropertyDescriptor(V.prototype,"updateSendParameters"),V.prototype),D(V.prototype,"replaceTrack",[H],Object.getOwnPropertyDescriptor(V.prototype,"replaceTrack"),V.prototype),D(V.prototype,"getRemoteSSRC",[H],Object.getOwnPropertyDescriptor(V.prototype,"getRemoteSSRC"),V.prototype),V);function H(e,t,r){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return r.value=async function(){const e=this.mutex,r=await e.lock("Locking from P2PConnection.".concat(t));try{for(var i=arguments.length,o=new Array(i),s=0;s<i;s++)o[s]=arguments[s];return await n.apply(this,o)}finally{r()}},r}const X={name:"PlanBConnection",create:function(e){let{store:t,spec:r}=e;return new G(r,t)}};export{X as PlanBConnectionService}; |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
4013074
28782
+ Added@agora-js/media@4.23.1(transitive)
+ Added@agora-js/report@4.23.1(transitive)
+ Added@agora-js/shared@4.23.1(transitive)
- Removed@agora-js/media@4.23.0(transitive)
- Removed@agora-js/report@4.23.0(transitive)
- Removed@agora-js/shared@4.23.0(transitive)
Updated@agora-js/media@4.23.1
Updated@agora-js/report@4.23.1
Updated@agora-js/shared@4.23.1