@realsee/live 0.5.2-dev.7 → 0.5.2-dev.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("trtc-js-sdk"),t=require("amazon-chime-sdk-js"),i=require("react");function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=o(e),s=o(i);const r=Symbol("$$REALSEE_LIVE_EVENT$$");function c(e){return e[r]||(e[r]={}),e[r]}class a{hasListener(e){const t=c(this);return t&&t[e]&&t[e].length>0}on(e,t,i){const o=c(this);return o[e]||(o[e]=[]),o[e].push([t,i||!1]),()=>this.off(e,t)}once(e,t){return this.on(e,t,!0)}off(e,t){if(void 0===e)return void((i=this)[r]||delete i[r]);var i;const o=c(this);if(o[e]||(o[e]=[]),void 0===t)return void(o[e].length=0);let n=0;for(;n<o[e].length&&o[e][n][0]!==t;n++);n<o[e].length&&o[e].splice(n,1)}emit(e,...t){let i=!1;const o=c(this)[e]||[];for(let n of o.slice()){const[o,s=!1]=n,r=o(...t);s&&this.off(e,o),!1===r&&(i=!0)}return i}}class l extends a{}function d(e,t,i,o){return new(i||(i=Promise))((function(n,s){function r(e){try{a(o.next(e))}catch(e){s(e)}}function c(e){try{a(o.throw(e))}catch(e){s(e)}}function a(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,c)}a((o=o.apply(e,t||[])).next())}))}var h,u;exports.RTCType=void 0,(h=exports.RTCType||(exports.RTCType={})).RealseeBrowserRTC="RealseeBrowserRTC",h.RealseeVRWebViewRTC="RealseeVRWebViewRTC",h.RealseeBrowserChimeRTC="RealseeBrowserChimeRTC",exports.BuiltInRTCType=void 0,(u=exports.BuiltInRTCType||(exports.BuiltInRTCType={})).RealseeXTRTC="trtc",u.RealseeXChimeRTC="chime";var v;!function(e){e.info="INFO",e.log="LOG",e.error="ERROR",e.warn="WARN"}(v||(v={}));const m=(e,t=[])=>{switch(t.unshift(`Realsee Live ${(()=>{const e=new Date;return`[${e.getFullYear()}-${(e.getMonth()+1).toString().padStart(2,"0")}-${e.getDate().toString().padStart(2,"0")} ${e.getHours().toString().padStart(2,"0")}:${e.getMinutes().toString().padStart(2,"0")}:${e.getSeconds().toString().padStart(2,"0")}.${e.getMilliseconds()}]`})()} <${e}> `),e){case v.info:return console.info(...t);case v.error:return console.error(...t);case v.warn:return console.warn(...t);default:return console.log(...t)}};var g,f,p,_,y,b,S,w,k,E,C,T={log:(...e)=>m(v.log,e),info:(...e)=>m(v.info,e),error:(...e)=>m(v.error,e),warn:(...e)=>m(v.warn,e)};function I(){return(65536*(1+Math.random())|0).toString(16).substring(1)}function R(){return(I()+I()+"-"+I()+"-4"+I().substr(0,3)+"-"+I()+"-"+I()+I()+I()).toLowerCase()}class B extends l{constructor(e){super(),this.type=exports.RTCType.RealseeBrowserRTC,this.joined=!1,this.micro=!1,this.voiceId="",this._getVoiceSign=()=>{throw new Error("方法 getVoiceSign 未实现")},this.checkRequirement=()=>n.default.checkSystemRequirements(),this.$dom=document.createElement("div"),this._trtc={client:null,stream:null},this.join=e=>d(this,void 0,void 0,(function*(){var t;this.emit("joinWillStart");const i=yield this._getVoiceSign({voiceId:e.voiceId,roomId:e.roomId,userId:e.userId});this._trtc.client=n.default.createClient(Object.assign(Object.assign({mode:"rtc"},i),{enableAutoPlayDialog:"function"!=typeof this._autoPlayConfirm})),null===(t=this._trtc.client)||void 0===t||t.enableAudioVolumeEvaluation(),this._registerRtcEvent();let o=yield new Promise((t=>{var i;null===(i=this._trtc.client)||void 0===i||i.join({roomId:Number(e.voiceId)}).then((()=>t(!0))).catch((()=>t(!1)))}));return this.joined=o,!!o&&(this._trtc.stream=n.default.createStream({userId:i.userId,audio:!0,video:!1}),o=yield new Promise((e=>{var t;null===(t=this._trtc.stream)||void 0===t||t.initialize().then((()=>e(!0))).catch((()=>e(!1)))})),o=yield new Promise((e=>{var t;null===(t=this._trtc.client)||void 0===t||t.publish(this._trtc.stream).then((()=>e(!0))).catch((()=>e(!1)))})),this.joined=o,this.joined&&this.emit("joined"),o)})),this._handleStreamAdded=e=>{var t;const i=e.stream;console.log("远端流增加: "+i.getId()),null===(t=this._trtc.client)||void 0===t||t.subscribe(i)},this._handleStreamSubscribed=e=>{const t=e.stream;console.log("远端流订阅成功:"+t.getId());const i=`rs-rtc-remote_stream-${t.getId()}`,o=document.createElement("div");o.id=i,this.$dom.appendChild(o),"function"==typeof this._autoPlayConfirm?(t.play(i).catch((e=>{})),t.on("error",(e=>{if(16451===e.getCode()){const e=()=>t.resume();this._autoPlayConfirm({onConfirm:e})}}))):t.play(i)},this._getVoiceSign=e.getVoiceSign,this._autoPlayConfirm=e.autoPlayConfirm,this._initParentDom()}_initParentDom(){this.$dom.id=`rs-rtc-${R()}`,this.$dom.style.display="none",document.body.appendChild(this.$dom)}quit(){return new Promise((e=>d(this,void 0,void 0,(function*(){var t,i;this.joined=!1,this._trtc.stream&&(yield null===(t=this._trtc.client)||void 0===t?void 0:t.unpublish(this._trtc.stream),this._trtc.stream.stop(),this._trtc.stream.close(),this._trtc.stream=null),null===(i=this._trtc.client)||void 0===i||i.leave().then((()=>this._trtc.client=null)).then((()=>e(!0))).catch((()=>e(!1))),e(!0)}))))}detectMicro(){return new Promise((e=>{const t={audio:!0,video:!1};try{navigator.mediaDevices.getUserMedia(t).then((()=>e(!0))).catch((t=>{T.error(t.message),e(!1)}))}catch(t){console.error(t),e(!1)}}))}toggleMicro(e){var t,i,o,n;return Promise.resolve((e?null===(i=null===(t=this._trtc)||void 0===t?void 0:t.stream)||void 0===i?void 0:i.unmuteAudio():null===(n=null===(o=this._trtc)||void 0===o?void 0:o.stream)||void 0===n?void 0:n.muteAudio())||!1)}shock(){throw new Error("Method not implemented.")}_registerRtcEvent(){var e,t,i,o;null===(e=this._trtc.client)||void 0===e||e.on("stream-added",this._handleStreamAdded),null===(t=this._trtc.client)||void 0===t||t.on("stream-subscribed",this._handleStreamSubscribed),null===(i=this._trtc.client)||void 0===i||i.on("audio-volume",(e=>this.emit("userVolumes",e.result.map((({userId:e,audioVolume:t})=>({userId:e,audioVolume:t})))))),null===(o=this._trtc.client)||void 0===o||o.on("error",(e=>this.emit("error",e)))}}class O extends l{constructor(e){super(),this.type=exports.RTCType.RealseeBrowserChimeRTC,this.joined=!1,this.micro=!1,this.voiceId="",this.userId="",this.deviceChangeObserver={},this.audioVideoObserver={},this._getVoiceSign=()=>{throw new Error("方法 getVoiceSign 未实现")},this.$dom=document.createElement("div"),this.$audio=document.createElement("audio"),this._initDom=()=>{this.$audio.id=`rs-rtc-${R()}`,this.$dom.id=`rs-rtc-${R()}`,this.$dom.appendChild(this.$audio),document.body.appendChild(this.$dom)},this.initObservers=()=>{this.deviceChangeObserver={audioInputsChanged:e=>{null==e||e.forEach((e=>{this.logger.info(`Device ID: ${e.deviceId} Microphone: ${e.label}`)}))},audioOutputsChanged:e=>{this.logger.info(`Audio outputs updated: ${e}`)},videoInputsChanged:e=>{this.logger.info(`Video inputs updated: ${e}`)},audioInputMuteStateChanged:(e,t)=>{this.logger.info(`Device ${e.toString()} ${t?"is muted in hardware":"is not muted"}`)}},this.audioVideoObserver={audioVideoDidStart:()=>{this.logger.info("Started")},audioVideoDidStop:e=>{this.logger.info(`Stopped with a session status code: ${e.statusCode()}`)},audioVideoDidStartConnecting:e=>{e&&this.logger.info("Attempting to reconnect")}}},this._registerRtcEvent=()=>{var e,i,o,n,s,r;const c=(null===(o=null===(i=null===(e=this.meetingSession)||void 0===e?void 0:e.configuration)||void 0===i?void 0:i.credentials)||void 0===o?void 0:o.attendeeId)||"";if(c){const e=new Map,i=()=>{const t=[];return e.forEach(((e,i)=>{t.push({userId:e.userId,volume:e.muted||0===e.signalStrength||!Boolean(e.volume)?0:e.volume})})),t};null===(n=this.meetingSession)||void 0===n||n.audioVideo.realtimeSubscribeToAttendeeIdPresence(((o,n,s)=>{var r;if(!n)return e.delete(o),void this.emit("userVolumes",i());null===(r=this.meetingSession)||void 0===r||r.audioVideo.realtimeSubscribeToVolumeIndicator(o,((o,n,r,c)=>{new t.DefaultModality(o).base()===o&&(e.set(o,{userId:s||o,volume:n,muted:r,signalStrength:c}),this.emit("userVolumes",i()))}))})),null===(s=this.meetingSession)||void 0===s||s.audioVideo.realtimeSubscribeToVolumeIndicator(c,((e,i,o,n)=>{new t.DefaultModality(e).base()===e&&null!==n&&1!==n&&this.emit("weakNetwork")})),null===(r=this.meetingSession)||void 0===r||r.audioVideo.realtimeSubscribeToFatalError((e=>this.emit("error",e)))}},this._getVoiceSign=e.getVoiceSign,this._initDom(),this.logger=new t.ConsoleLogger("WebRTCLogger",e.logLevel||t.LogLevel.OFF),this.deviceController=new t.DefaultDeviceController(this.logger),this.initObservers()}join(e){return d(this,void 0,void 0,(function*(){return new Promise(((i,o)=>d(this,void 0,void 0,(function*(){var o;this.emit("joinWillStart");try{const{sdkAppId:n,userId:s,roomId:r,userSig:c}=yield this._getVoiceSign(Object.assign(Object.assign({},e),{roomId:e.roomId||0}));this.userId=s;const{attendence:a,vendor_wrapper:l}=JSON.parse(decodeURIComponent(c)),d=new t.MeetingSessionConfiguration({Meeting:l},{Attendee:{ExternalUserId:a.external_user_id,AttendeeId:a.attendee_id,JoinToken:a.join_token}});this.meetingSession=new t.DefaultMeetingSession(d,this.logger,this.deviceController),this._registerRtcEvent(),this.meetingSession.audioVideo.addDeviceChangeObserver(this.deviceChangeObserver),this.meetingSession.audioVideo.addObserver(this.audioVideoObserver),this.meetingSession.audioVideo.bindAudioElement(this.$audio);const h={audioVideoDidStart:()=>{var e;null===(e=this.meetingSession)||void 0===e||e.audioVideo.realtimeMuteLocalAudio(),this.joined=!0,this.emit("joined"),i(!0)},audioVideoDidStop:()=>{this.joined=!1,i(!1)}};this.meetingSession.audioVideo.addObserver(h);const u=yield this.deviceController.listAudioInputDevices(!0),v=u.find((e=>"default"===e.deviceId)),m=u.find((e=>""!==e.deviceId));this.audioInput=v||m,yield this.meetingSession.audioVideo.chooseVideoInputDevice(null),yield this.meetingSession.audioVideo.chooseAudioInputDevice((null===(o=this.audioInput)||void 0===o?void 0:o.deviceId)||"default"),this.meetingSession.audioVideo.start()}catch(e){this.emit("error",e),this.logger.error(e.message),i(!1)}}))))}))}quit(){return this.joined?new Promise(((e,i)=>{var o,n;this.joined=!1;const s={audioVideoDidStop:i=>{const o=i.statusCode();o===t.MeetingSessionStatusCode.Left?(this.logger.info("You left the session"),e(!0)):(this.logger.info(`Stopped with a session status code: ${o}`),e(!0))}};null===(o=this.meetingSession)||void 0===o||o.audioVideo.addObserver(s),null===(n=this.meetingSession)||void 0===n||n.audioVideo.stop()})):Promise.resolve(!0)}detectMicro(){return d(this,void 0,void 0,(function*(){return new Promise((e=>{const t={audio:!0,video:!1};try{navigator.mediaDevices.getUserMedia(t).then((()=>e(!0))).catch((()=>e(!1)))}catch(t){this.logger.error(t.message),e(!1)}}))}))}toggleMicro(e){var t,i,o;return d(this,void 0,void 0,(function*(){e?null===(t=this.meetingSession)||void 0===t||t.audioVideo.realtimeUnmuteLocalAudio():null===(i=this.meetingSession)||void 0===i||i.audioVideo.realtimeMuteLocalAudio();const n=null===(o=this.meetingSession)||void 0===o?void 0:o.audioVideo.realtimeIsLocalAudioMuted();return void 0!==n&&e!==n}))}shock(){throw new Error("Method not implemented.")}}exports.RTCJoinedInfoCodeEnum=void 0,(g=exports.RTCJoinedInfoCodeEnum||(exports.RTCJoinedInfoCodeEnum={}))[g.Success=0]="Success",g[g.Failure=1]="Failure",g[g.ReJoin=2]="ReJoin",g[g.NoMicroPermission=3]="NoMicroPermission";class A extends l{get jsBridge(){return this.options.jsBridge}constructor({jsBridge:e,getVoiceSign:t}){super(),this.type=exports.RTCType.RealseeVRWebViewRTC,this.joined=!1,this.micro=!1,this.voiceId="",this.options={jsBridge:e,getVoiceSign:t},"WxMiniProgramWebView"!==this.jsBridge.webViewType&&this.jsBridge.callAndListen("live/userVolumes",(e=>{this.emit("userVolumes",e)})),this.jsBridge.callAndListen("live/weakNetwork",(e=>{e&&this.emit("weakNetwork")}))}join(e){return d(this,void 0,void 0,(function*(){try{this.emit("joinWillStart");const{sdkAppId:t,userId:i,userSig:o}=yield this.options.getVoiceSign(e);if(!(Boolean(t)&&Boolean(i)&&Boolean(o)))return this.emit("error",new Error("加入房间失败:rtc 签名请求异常")),this.joined=!1,this.joined;this.type=e.type;const[n,s]=yield this.jsBridge.callAndBackfeed(`live/join?sdkAppID=${t}&userID=${i}&roomID=${Number(e.voiceId)}&userSig=${o}`);return n?n.code===exports.RTCJoinedInfoCodeEnum.Success?(this.emit("joined"),this.joined=!0):(this.emit("error",n),this.joined=!1):(this.emit("error",s||new Error("加入房间失败:未知异常。")),this.joined=!1),this.joined}catch(e){return this.emit("error",new Error("加入房间失败:"+e.message)),this.joined=!1,this.joined}}))}quit(){return d(this,void 0,void 0,(function*(){const[e,t]=yield this.jsBridge.callAndBackfeed("live/quit");return null===e&&this.emit("error",t||new Error("退出房间失败:未知异常。")),this.joined=!1,!!e}))}detectMicro(){return d(this,void 0,void 0,(function*(){const[e,t]=yield this.jsBridge.detectMicro();return null===e?(this.emit("error",t||new Error("麦克风监测异常!")),!1):e}))}toggleMicro(e){return d(this,void 0,void 0,(function*(){const[t,i]=yield this.jsBridge.callAndBackfeed("live/toggleMicro?flag="+(e?1:0));return null===t?(this.emit("error",i||new Error("麦克风监测异常!")),!1):(this.micro=t,t)}))}shock(){this.jsBridge.shock(1)}}function L(e){switch(e){case 1001:return exports.WebSocketCloseError.Err_1001;case 1002:return exports.WebSocketCloseError.Err_1002;case 1003:return exports.WebSocketCloseError.Err_1003;case 1006:return exports.WebSocketCloseError.Err_1006;case 1007:return exports.WebSocketCloseError.Err_1007;case 1008:return exports.WebSocketCloseError.Err_1008;case 1009:return exports.WebSocketCloseError.Err_1009}return exports.WebSocketCloseError.Err_unknown}function x(e,t,i,o){return new(i||(i=Promise))((function(n,s){function r(e){try{a(o.next(e))}catch(e){s(e)}}function c(e){try{a(o.throw(e))}catch(e){s(e)}}function a(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,c)}a((o=o.apply(e,t||[])).next())}))}exports.Command=void 0,(f=exports.Command||(exports.Command={})).SelfUserInfo="SELF_USER_INFO",f.RoomInfo="ROOM_INFO",f.RTCInfo="RTC_INFO",f.UserList="USER_LIST",f.BuiltinMsg="BUILTIN_MSG",f.CustomEvent="CUSTOM_EVENT",f.KeyframeSync="KEYFRAME_SYNC",f.UserKickOut="USER_KICK_OUT",exports.BuiltinEventType=void 0,(p=exports.BuiltinEventType||(exports.BuiltinEventType={})).UserChange="user_change",p.RoomChange="room_change",exports.BuiltinActionType=void 0,(_=exports.BuiltinActionType||(exports.BuiltinActionType={})).UserMicroStatus="change_micro_status",_.UserMicroStatusSync="sync_micro_status",_.UserPermission="change_permission",_.UserStatus="change_status",_.UserInfo="change_info",_.RoomClose="close",exports.MicroStatus=void 0,(y=exports.MicroStatus||(exports.MicroStatus={})).OPEN="OPEN",y.CLOSE="CLOSE",exports.LiveState=void 0,(b=exports.LiveState||(exports.LiveState={}))[b.NOTINITIALIZED=-1]="NOTINITIALIZED",b[b.CONNECTING=0]="CONNECTING",b[b.OPEN=1]="OPEN",b[b.CLOSED=3]="CLOSED",exports.UserStatus=void 0,(S=exports.UserStatus||(exports.UserStatus={}))[S.Normal=0]="Normal",S[S.Removed=1]="Removed",S[S.Replaced=2]="Replaced",exports.MemUserStatus=void 0,(w=exports.MemUserStatus||(exports.MemUserStatus={})).WAIT_ENTER="WAIT_ENTER",w.ONLINE="ONLINE",w.LEAVE="LEAVE",w.KICK_OUT="KICK_OUT",w.BE_REPLACE="BE_REPLACE",w.EXCEPTION="EXCEPTION",exports.WebSocketState=void 0,(k=exports.WebSocketState||(exports.WebSocketState={}))[k.NOTINITIALIZED=-1]="NOTINITIALIZED",k[k.CONNECTING=0]="CONNECTING",k[k.OPEN=1]="OPEN",k[k.CLOSING=2]="CLOSING",k[k.CLOSED=3]="CLOSED",exports.WebSocketErrorType=void 0,(E=exports.WebSocketErrorType||(exports.WebSocketErrorType={})).Error="Error",E.Close="Close",E.MicroAuth="MicroAuth",E.DuplicateConnect="DuplicateConnect",E.IllegalURL="IllegalURL",E.Unknown="Unknown",E.IllegalArgs="IllegalArgs",exports.WebSocketCloseError=void 0,(C=exports.WebSocketCloseError||(exports.WebSocketCloseError={})).Err_1001="CLOSE_GOING_AWAY",C.Err_1002="CLOSE_PROTOCOL_ERROR",C.Err_1003="CLOSE_UNSUPPORTED",C.Err_1006="CLOSE_ABNORMAL",C.Err_1007="Unsupported Data",C.Err_1008="Policy Violation",C.Err_1009="CLOSE_TOO_LARGE",C.Err_unknown="unknown";const N={};function W(e,t,i=!0){if(N[e])N[e].queue.push({once:i,callback:t});else{const o="$jsBridgeFn_"+Date.now().toString(16).toUpperCase()+"_"+Math.ceil(1e4*Math.random()).toString(16).toUpperCase();N[e]={uuid:o,queue:[{once:i,callback:t}]}}return Object.assign(window,{[N[e].uuid]:t=>{N[e].queue=N[e].queue.reduce(((e,i)=>{const{once:o,callback:n}=i;return o||e.push(i),n(t),e}),[])}}),N[e].uuid}class M{checkReady(e){return Promise.resolve([!1,null])}callAndBackfeed(e){return Promise.resolve([!1,null])}callAndListen(e,t){return Promise.resolve([!1,null])}}const P=window;class V extends M{constructor(){super(),Promise.resolve().then((()=>x(this,void 0,void 0,(function*(){try{yield this.checkBridgeReady()}catch(e){console.warn(e)}}))))}checkBridgeReady(e=6e3){if(this.hybridBridge)return!0;const t=performance.now();return new Promise(((i,o)=>{const n=()=>{if(this.hybridBridge)return i(!0);if(P.HybridBridgeLJ){const e=P.HybridBridgeLJ;null==e||e.getStaticData(W("HYBRID_BRIDGE_NAME",(t=>(this.deviceInfo=JSON.parse(t),this.hybridBridge=e,i(!0)))))}if(performance.now()-t>(e||6e3))return o(new Error("HybridBridge 初始化超时~"));requestAnimationFrame(n)};n()}))}checkReady(e=6e3){return x(this,void 0,void 0,(function*(){const t=[null,null];if(this.hybridBridge)return t[0]=!0,t;try{t[0]=yield this.checkBridgeReady(e)}catch(e){t[0]=!1,t[1]=e}return t}))}get ready(){return!!this.hybridBridge}get scheme(){var e;return(null===(e=this.deviceInfo)||void 0===e?void 0:e.scheme)||""}createSchemeLink(e){return e.startsWith(this.scheme)?e:this.scheme+"://"+e}callAndBackfeed(e){return x(this,void 0,void 0,(function*(){const t=[!1,null],[i,o]=yield this.checkReady();return i?yield new Promise((i=>x(this,void 0,void 0,(function*(){const o=this.createSchemeLink(e),n=JSON.stringify({actionUrl:o,functionName:W(this.createSchemeLink(e),(e=>{const o=(()=>{try{return JSON.parse(e)}catch(t){return e}})();t[0]=1===o||0!==o&&o,i(t)}))});this.hybridBridge.callAndBackfeed(n)})))):(t[0]=!1,t[1]=o,t)}))}callAndListen(e,t){return x(this,void 0,void 0,(function*(){const i=[!1,null],[o,n]=yield this.checkReady();return o?yield new Promise((o=>x(this,void 0,void 0,(function*(){const n=this.createSchemeLink(e),s=e=>{const r=(()=>{try{return JSON.parse(e)}catch(t){return e}})();t(1===r||0!==r&&r),i[0]=()=>{const e=N[n];if(!e)return;const t=e.queue.findIndex((e=>e.callback===s));-1!==t&&e.queue.splice(t,1)},o(i)},r=JSON.stringify({actionUrl:n,functionName:W(n,s,!1)});this.hybridBridge.callAndListen(r)})))):(i[0]=!1,i[1]=n,i)}))}}var j;!function(e){e.callAndBackfeed="callAndBack",e.callAndListen="callAndListen"}(j||(j={}));const U=window;class D{constructor(){this.checkBridgeReady()}checkBridgeReady(e=6e3){if(this.worker)return!0;const t=performance.now();return new Promise(((i,o)=>{const n=()=>{if(this.worker)return i(!0);if(U.webkit&&U.webkit.messageHandlers&&U.webkit.messageHandlers.realsee){const e=U.webkit.messageHandlers.realsee;e.postMessage(JSON.stringify({type:"getStaticData",param:JSON.stringify({functionName:W("HYBRID_BRIDGE_NAME",(t=>(this.deviceInfo=JSON.parse(t),this.worker=e,i(!0))))})}))}else{if(performance.now()-t>(e||6e3))return o(new Error("HybridBridge 初始化超时~"));requestAnimationFrame(n)}};n()}))}checkReady(e=6e3){return x(this,void 0,void 0,(function*(){const t=[null,null];if(this.worker)return t[0]=!0,t;try{t[0]=yield this.checkBridgeReady(e)}catch(e){t[0]=!1,t[1]=e}return t}))}get ready(){return!!this.worker}get scheme(){var e;return(null===(e=this.deviceInfo)||void 0===e?void 0:e.scheme)||""}createSchemeLink(e){return e.startsWith(this.scheme)?e:this.scheme+"://"+e}callAndBackfeed(e){return x(this,void 0,void 0,(function*(){const t=[!1,null],[i,o]=yield this.checkReady();return i?yield new Promise((i=>x(this,void 0,void 0,(function*(){const o=this.createSchemeLink(e),n=JSON.stringify({actionUrl:o,functionName:W(this.createSchemeLink(e),(e=>{const o=(()=>{try{return JSON.parse(e)}catch(t){return e}})();t[0]=1===o||0!==o&&o,i(t)}))});this.worker.postMessage(JSON.stringify({type:"callAndBackfeed",param:n}))})))):(t[0]=!1,t[1]=o,t)}))}callAndListen(e,t){return x(this,void 0,void 0,(function*(){const i=[!1,null],[o,n]=yield this.checkReady();return o?yield new Promise((o=>x(this,void 0,void 0,(function*(){const n=this.createSchemeLink(e),s=e=>{const r=(()=>{try{return JSON.parse(e)}catch(t){return e}})();t(1===r||0!==r&&r),i[0]=()=>{const e=N[n];if(!e)return;const t=e.queue.findIndex((e=>e.callback===s));-1!==t&&e.queue.splice(t,1)},o(i)},r=JSON.stringify({actionUrl:n,functionName:W(n,s,!1)});this.worker.postMessage(JSON.stringify({type:"callAndListen",param:r}))})))):(i[0]=!1,i[1]=n,i)}))}}function $(){return(65536*(1+Math.random())|0).toString(16).substring(1)}function H(){return($()+$()+"-"+$()+"-4"+$().substr(0,3)+"-"+$()+"-"+$()+$()+$()).toLowerCase()}var J;!function(e){e.isReady="Are You OK?",e.ready="I`m OK!",e.ping="ping",e.pong="pong",e.alive="I`m alive!"}(J||(J={}));var q="wss://ws.realsee.com";var F=(e,t)=>{const i=Object.keys(t).reduce(((e,i)=>e.replace(`{{${i}}}`,`${t[i]}`)),e);return encodeURI(i)};var K=(e,t)=>e in t;var G=(e="")=>e.replace("?","").split("&").map((e=>{const[t,i]=e.split("=");return{[t]:decodeURIComponent(i)}})).reduce(((e,t)=>Object.assign(Object.assign({},e),t)),{});const z="$$REALSEE_JSBRIDGE_EVENT$$";function Y(e){return e[z]||(e[z]={}),e[z]}class Z{hasListener(e){const t=Y(this);return t&&t[e]&&t[e].length>0}on(e,t,i){const o=Y(this);return o[e]||(o[e]=[]),o[e].push([t,i||!1]),()=>this.off(e,t)}once(e,t){return this.on(e,t,!0)}off(e,t){if(void 0===e)return void((i=this)[z]||delete i[z]);var i;const o=Y(this);if(o[e]||(o[e]=[]),void 0===t)return void(o[e].length=0);let n=0;for(;n<o[e].length&&o[e][n][0]!==t;n++);n<o[e].length&&o[e].splice(n,1)}emit(e,...t){let i=!1;const o=Y(this)[e]||[];for(const n of o.slice()){const[o,s=!1]=n,r=o(...t);s&&this.off(e,o),!1===r&&(i=!0)}return i}}class X extends Z{get attempts(){return this._attempts}constructor(e){super(),this._options={timeout:1e4,shouldReconnect:(e,t)=>{if(1008!==e.code&&1011!==e.code)return[0,3e3,1e4][t.attempts]},should1000Reconnect:!1,ignoreConnectivityEvents:!1,automaticOpen:!1},this._attempts=0,this._reconnects=-1,this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!1,this._connectivityEventsAttached=!1,this._clearPendingReconnectIfNeeded=()=>{this._pendingReconnect&&(clearTimeout(this._pendingReconnect),this._pendingReconnect=void 0)},this._online=e=>{this._reconnectWhenOnlineAgain&&(this._clearPendingReconnectIfNeeded(),this._reconnect(e))},this._offline=()=>{var e;this._reconnectWhenOnlineAgain=!0,null===(e=this._realWebSocket)||void 0===e||e.close(1e3)},this._detachConnectivityEvents=()=>{this._connectivityEventsAttached&&(null===globalThis||void 0===globalThis||globalThis.removeEventListener("online",this._online),null===globalThis||void 0===globalThis||globalThis.removeEventListener("offline",this._offline),this._connectivityEventsAttached=!1)},this._attachConnectivityEvents=()=>{this._connectivityEventsAttached||(null===globalThis||void 0===globalThis||globalThis.addEventListener("online",this._online),null===globalThis||void 0===globalThis||globalThis.addEventListener("offline",this._offline),this._connectivityEventsAttached=!0)},this.send=e=>{var t,i,o;(null===(t=this._realWebSocket)||void 0===t?void 0:t.readyState)===(null===(i=this._realWebSocket)||void 0===i?void 0:i.OPEN)&&(null===(o=this._realWebSocket)||void 0===o||o.send(e))},this.close=(e,t)=>{var i;return"number"!=typeof e&&(t=e,e=1e3),this._clearPendingReconnectIfNeeded(),this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!0,this._detachConnectivityEvents(),null===(i=this._realWebSocket)||void 0===i?void 0:i.close(e,t)},this.open=e=>{var t,i;e&&(this._url=e),(null===(t=this._realWebSocket)||void 0===t?void 0:t.readyState)!==WebSocket.OPEN&&(null===(i=this._realWebSocket)||void 0===i?void 0:i.readyState)!==WebSocket.CONNECTING&&(this._clearPendingReconnectIfNeeded(),this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!1,this._createWebSocket())},this._createWebSocket=()=>{var e,t,i;const o="string"==typeof this._url?this._url:null===(e=this._url)||void 0===e?void 0:e.call(this,this);if(!o)return;this._pendingReconnect=void 0,this._removeWebSocketEvent(),this._realWebSocket=new WebSocket(o,this._protocols||void 0),this._attempts=this._attempts+1,this.emit("connecting",new CustomEvent("connecting",{detail:{attempts:this._attempts,reconnects:this._reconnects}}));this._connectTimeout=setTimeout((()=>{this._connectTimeout=void 0,this._detachConnectivityEvents(),this.emit("timeout",new CustomEvent("connecting",{detail:{attempts:this._attempts,reconnects:this._reconnects}}))}),null===(t=this._options)||void 0===t?void 0:t.timeout),this._dispatchWebSocketEvent(),(null===(i=this._options)||void 0===i?void 0:i.ignoreConnectivityEvents)||this._attachConnectivityEvents()},this._removeWebSocketEvent=()=>{var e,t,i,o;null===(e=this._realWebSocket)||void 0===e||e.removeEventListener("open",this._webSocketOpenHandler),null===(t=this._realWebSocket)||void 0===t||t.removeEventListener("close",this._webSocketCloseHandler),null===(i=this._realWebSocket)||void 0===i||i.removeEventListener("error",this._webSocketErrorHandler),null===(o=this._realWebSocket)||void 0===o||o.removeEventListener("message",this._webSocketMessageHandler)},this._dispatchWebSocketEvent=()=>{var e,t,i,o;null===(e=this._realWebSocket)||void 0===e||e.addEventListener("open",this._webSocketOpenHandler),null===(t=this._realWebSocket)||void 0===t||t.addEventListener("close",this._webSocketCloseHandler),null===(i=this._realWebSocket)||void 0===i||i.addEventListener("error",this._webSocketErrorHandler),null===(o=this._realWebSocket)||void 0===o||o.addEventListener("message",this._webSocketMessageHandler)},this._webSocketOpenHandler=e=>{this._connectTimeout&&(clearTimeout(this._connectTimeout),this._connectTimeout=void 0);const t=++this._reconnects,i=this._attempts;return this._attempts=0,this._reconnectWhenOnlineAgain=!1,this.emit("open",Object.assign(e,{detail:{reconnects:t,attempts:i}}))},this._webSocketCloseHandler=e=>(this._reconnect(e),this.emit("close",e)),this._webSocketErrorHandler=e=>this.emit("error",new CustomEvent("error",{detail:{error:e}})),this._webSocketMessageHandler=e=>this.emit("message",e),e&&this.setOptions(e)}setOptions(e){if(!e)return;this._url=e.url,this._protocols=e.protocols;const t=Object.assign(this._options,e.robustOptions||{});if("number"!=typeof(null==t?void 0:t.timeout))throw new Error("timeout must be the number of milliseconds to timeout a connection attempt");if("function"!=typeof(null==t?void 0:t.shouldReconnect))throw new Error("shouldReconnect must be a function that returns the number of milliseconds to wait for a reconnect attempt, or null or undefined to not reconnect.");this._options=t,this._options.automaticOpen&&this._createWebSocket()}_reconnect(e){var t,i,o,n;if(!(null===(t=this._options)||void 0===t?void 0:t.should1000Reconnect)&&1e3===e.code||this._explicitlyClosed)return void(this._attempts=0);if(!1===(null===(i=null===globalThis||void 0===globalThis?void 0:globalThis.navigator)||void 0===i?void 0:i.onLine))return void(this._reconnectWhenOnlineAgain=!0);const s=null===(n=null===(o=this._options)||void 0===o?void 0:o.shouldReconnect)||void 0===n?void 0:n.call(o,e,this);"number"==typeof s&&(this._pendingReconnect=setTimeout(this._createWebSocket,s))}}class Q{get isReady(){return"open"===this._readyState}constructor(){var e,t;if(this._rsWeappBridgeMethodAdapter={},this._ws=new X,this._readyState="close",this.initialize=(e=6e3)=>x(this,void 0,void 0,(function*(){const t=[!1,null],{wssid:i,wstsp:o,wssig:n,wsmnt:s=q}=G(globalThis.location.search);if(!(i&&o&&n&&s))return t[1]=new Error("HybridBridge 参数缺失,初始化失败~"),t;const r=F("{{origin}}/{{endpoint}}/{{uuid}}/{{member}}/{{ak}}/{{ts}}/{{sign}}",{origin:s,endpoint:"proxy",uuid:i,member:"webview",ak:"vr_live_miniapp",ts:o,sign:n});try{(yield this._open(r))?(this.initBuiltInHandlers(),t[0]=yield this.waitReady(e)):t[1]=new Error("HybridBridge ws未连接,初始化失败~")}catch(e){t[1]=e}return t})),this.initBuiltInHandlers=()=>{this._registerLifecycleHandler(),this._registerHeartbeatHandler(),this._registerMessageHandler(),this._registerBridgeRequestHandler(),this._registerReadyHandler()},this._open=e=>new Promise((t=>{this._ws.once("open",(()=>{this._receivedMessage(J.ready,(()=>t(!0)),!0),this._ws.once("timeout",(()=>t(!1))),this.send(J.isReady)})),this._ws.open(e)})),this._registerLifecycleHandler=()=>{this._ws.on("connecting",(()=>{console.log("RsWeappBridge connecting"),this._readyState="connecting"})),this._ws.on("open",(()=>{console.log("RsWeappBridge open"),this._readyState="open"})),this._ws.on("close",(()=>{this._readyState="close"})),this._ws.on("error",(()=>{console.log("RsWeappBridge error"),this._readyState="close"})),this._ws.on("timeout",(()=>{console.log("RsWeappBridge timeout"),this._readyState="close"}))},this._registerHeartbeatHandler=()=>{this._receivedMessage(J.ping,(()=>setTimeout((()=>this._ws.send(J.pong)),500))),this._receivedMessage(J.pong,(()=>setTimeout((()=>this._ws.send(J.ping)),1e3)))},this._receivedMessage=(e,t,i)=>{const o=n=>{n.data===e&&(t(),i&&this._ws.off("message",o))};this._ws.on("message",o)},this._registerReadyHandler=()=>{this._receivedMessage(J.isReady,(()=>this._ws.send(J.ready)))},this.send=e=>{this._ws.send(e)},this.waitReady=(e=6e3)=>new Promise(((t,i)=>{this._receivedMessage(J.ready,(()=>t(!0))),this.send(J.isReady),setTimeout((()=>i("HybridBridge 初始化超时~")),e)})),this._parseMessage=e=>{try{return JSON.parse(e.data)}catch(t){return e.data}},this._registerMessageHandler=()=>{this._ws.on("message",(e=>{const t=this._parseMessage(e);if("object"==typeof t){const{id:e,command:i,data:o}=t;"message"===i&&"function"==typeof this._rsWeappBridgeMethodAdapter.bindMessage&&this._rsWeappBridgeMethodAdapter.bindMessage({id:e,data:o})}}))},this.getStaticData=e=>{this.callAndBackfeed(JSON.stringify({actionUrl:"common/staticData",functionName:e}))},this.callAndBackfeed=e=>{const{actionUrl:t="",functionName:i=""}=JSON.parse(e);if(!t)throw new Error("callAndBackfeed actionUrl is empty!");if(!i)throw new Error("callAndBackfeed functionName is empty!");this._callAndBackfeed(t,(e=>{"function"==typeof globalThis[i]&&globalThis[i](e)}))},this.callAndListen=e=>{const{actionUrl:t,functionName:i}=JSON.parse(e);if(!t)throw new Error("callAndListen actionUrl is empty!");if(!i)throw new Error("callAndListen functionName is empty!");const o=e=>{"function"==typeof globalThis[i]&&globalThis[i](e)};try{this._callAndListen(t,o)}catch(e){console.warn(e),o(!1)}},this.execute=(e,t)=>x(this,void 0,void 0,(function*(){return yield this._invokeBridgeMethod(e,t)})),this._invokeBridgeMethod=(e,t)=>new Promise(((i,o)=>{const n=H(),s=t=>{const r=this._parseMessage(t);"object"==typeof r&&r.method===e&&r.id===n&&(this._ws.off("message",s),r.error?o(r.error):i(r.data))};this._ws.on("message",s),this.send(JSON.stringify({method:e,args:t,id:n}))})),(null===(e=null===globalThis||void 0===globalThis?void 0:globalThis.window)||void 0===e?void 0:e.__Realsee_WxMini_HybridBridge__)instanceof Q)return null===(t=null===globalThis||void 0===globalThis?void 0:globalThis.window)||void 0===t?void 0:t.__Realsee_WxMini_HybridBridge__;(null===globalThis||void 0===globalThis?void 0:globalThis.window)&&(globalThis.window.__Realsee_WxMini_HybridBridge__=this,this.initBuiltInHandlers())}_registerBridgeRequestHandler(){this._ws.on("message",(e=>x(this,void 0,void 0,(function*(){const t=this._parseMessage(e);if("object"==typeof t){const{id:e,method:i,args:o,command:n}=t;if("request"===n&&i){let t=null,n=null,s=null;if("function"==typeof this._rsWeappBridgeMethodAdapter[i]?s=this._rsWeappBridgeMethodAdapter[i]:globalThis&&K(i,globalThis)&&(s=globalThis[i]),"function"==typeof s)try{t=yield s(o)}catch(e){n=e.message||e}else n="Method not implemented.";this.send(JSON.stringify({id:e,method:i,result:t,error:n,command:"response"}))}}}))))}_callAndBackfeed(e,t){const i=H(),o=JSON.stringify({id:i,actionUrl:e,command:"rsSchemeRequest",type:"callAndBackfeed"});let n=null;const s=e=>{const o=this._parseMessage(e);if("object"==typeof o){const{id:e,result:r,errmsg:c,command:a}=o;"rsSchemeResponse"===a&&e===i&&(this._ws.off("message",s),n&&clearTimeout(n),c?(console.warn(c),t(0)):t(r))}};this._ws.on("message",s),this.send(o),n=globalThis.setTimeout((()=>{console.warn("callAndBackfeed timeout"),t(0)}),3e4)}_callAndListen(e,t){const i=H(),o=JSON.stringify({id:i,actionUrl:e,command:"rsSchemeRequest",type:"callAndListen"});this._ws.on("message",(e=>{const o=this._parseMessage(e);if("object"==typeof o){const{id:e,result:n,errmsg:s,command:r}=o;"rsSchemeResponse"===r&&e===i&&(s?(console.warn(s),t(!1)):t(n))}})),this.send(o)}invoke(e,t){return x(this,void 0,void 0,(function*(){return new Promise(((i,o)=>{const n=H(),s=JSON.stringify({id:n,method:e,args:t,command:"request"});let r=null;const c=t=>{const s=this._parseMessage(t);if("object"==typeof s){const{id:t,result:a,error:l,command:d}=s;"response"===d&&t===n&&s.method===e&&(this._ws.off("message",c),r&&clearTimeout(r),l?o(l):i(a))}};this._ws.on("message",c),this.send(s),r=setTimeout((()=>o("method invoke timeout")),3e4)}))}))}}class ee extends M{constructor(){super(...arguments),this._hybridBridge=new Q,this.initializing=!1}get hybridBridge(){return this._hybridBridge}checkBridgeReady(e=6e4){return!!this.ready||new Promise(((t,i)=>x(this,void 0,void 0,(function*(){if(this.ready)return t(!0);if(!this.initializing){this.initializing=!0;const[i,o]=yield this._hybridBridge.initialize(e);if(!i||o)throw o||new Error("HybridBridge 初始化失败~");return this._hybridBridge.getStaticData(W("HYBRID_BRIDGE_NAME",(e=>{this.deviceInfo=(()=>{try{return JSON.parse(e)}catch(t){return e}})()}))),this.initializing=!1,t(!0)}{const e=()=>{if(this.ready)return t(!0);requestAnimationFrame(e)};e()}}))))}checkReady(e=6e4){return x(this,void 0,void 0,(function*(){const t=[null,null];if(this.ready)return t[0]=!0,t;try{t[0]=yield this.checkBridgeReady(e)}catch(e){t[0]=!1,t[1]=e}return t}))}get ready(){return!!this._hybridBridge.isReady}get scheme(){var e;return(null===(e=this.deviceInfo)||void 0===e?void 0:e.scheme)||""}createSchemeLink(e){return e.startsWith(this.scheme)?e:this.scheme+"://"+e}callAndBackfeed(e){return x(this,void 0,void 0,(function*(){const t=[!1,null],[i,o]=yield this.checkReady();return i?yield new Promise((i=>x(this,void 0,void 0,(function*(){const o=this.createSchemeLink(e),n=JSON.stringify({actionUrl:o,functionName:W(this.createSchemeLink(e),(e=>{let o=e;try{o=JSON.parse(e)}catch(e){}t[0]=1===o||0!==o&&o,i(t)}))});this._hybridBridge.callAndBackfeed(n)})))):(t[0]=!1,t[1]=o,t)}))}callAndListen(e,t){return x(this,void 0,void 0,(function*(){const i=[!1,null],[o,n]=yield this.checkReady();return o?yield new Promise((o=>x(this,void 0,void 0,(function*(){const n=this.createSchemeLink(e),s=e=>{let r=e;try{r=JSON.parse(e)}catch(e){}t(1===r||0!==r&&r),i[0]=()=>{const e=N[n];if(!e)return;const t=e.queue.findIndex((e=>e.callback===s));-1!==t&&e.queue.splice(t,1)},o(i)},r=JSON.stringify({actionUrl:n,functionName:W(n,s,!1)});this._hybridBridge.callAndListen(r)})))):(i[0]=!1,i[1]=n,i)}))}invoke(e,t){var i,o;return x(this,void 0,void 0,(function*(){const[n,s]=yield this.checkReady();if(n)return yield null===(o=(i=this._hybridBridge).invoke)||void 0===o?void 0:o.call(i,e,t);throw s}))}}var te;!function(e){e.WebView="WebKit",e.WKWebview="WKWebview",e.UIWebview="UIWebview",e.Browser="Browser",e.WeChatMPWebView="WxMiniProgramWebView",e.Unsupported="Unsupported"}(te||(te={}));class ie extends Z{constructor(){super(...arguments),this.webViewType=te.Unsupported}}const oe=globalThis.navigator.userAgent,ne=/android/gi.test(oe),se=/iPhone|iPad\s+OS/gi.test(oe),re=/MicroMessenger/gi.test(oe)&&/miniProgram/gi.test(oe),ce=/realsee/gi.test(oe),ae={timeout:6e3};class le extends ie{constructor(e={}){super(),this.options=Object.assign(ae,e),ce||console.warn("未知容器:此版本 `jsBridge` 不支持当前 WebView 容器 ... "),this.webViewType=ne?te.WebView:se?te.WKWebview:te.Browser,this._controller=ne?new V:se?new D:new M,this.callAndListen("common/webViewState",(e=>{this.emit("webViewStateChange",e)})),this.callAndListen("common/webViewError",(e=>{this.emit("error",e)}))}ready(){return x(this,void 0,void 0,(function*(){return yield this._controller.checkReady(this.options.timeout)}))}callAndBackfeed(e){return x(this,void 0,void 0,(function*(){return yield this._controller.callAndBackfeed(e)}))}callAndListen(e,t){var i;return x(this,void 0,void 0,(function*(){return yield null===(i=this._controller)||void 0===i?void 0:i.callAndListen(e,t)}))}setLeftTopBackButton(e){return x(this,void 0,void 0,(function*(){return this.webViewType===te.WebView?[!0,null]:yield this.callAndBackfeed("common/setLeftTopBackButton?enable="+(e?1:0))}))}getBangsHeight(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/getBangsHeight")}))}shock(e=4){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed(`common/shock?duration=${e}`)}))}minimize(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/minimize")}))}loadProgress(e){return x(this,void 0,void 0,(function*(){return e=e<0?0:e>100?100:e,yield this.callAndBackfeed(`common/loadProgress?progress=${e}`)}))}closeLoading(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/closeLoading")}))}setOrientation(e){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed(`common/setOrientation?orientation=${e}`)}))}keepScreenLight(e){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/keepScreenLight?enable="+(e?1:0))}))}closeWebView(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/closeWebView")}))}openWebView(e,t){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed(`common/openWebView?way=${t}&url=${encodeURIComponent(e)}`)}))}saveImage2Album(e){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed(`common/saveImage2Album?base64=${e}`)}))}actionShare(e){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed(`common/actionShare?json=${JSON.stringify(e)}`)}))}getDeviceInfo(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/getDeviceInfo")}))}getUserInfo(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/getUserInfo")}))}getWebViewState(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/getWebViewState")}))}login(){return x(this,void 0,void 0,(function*(){const e=yield this.callAndBackfeed("common/login");return e[0]?yield this.getUserInfo():e}))}logout(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/logout")}))}detectMicro(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/detectMicro")}))}preload(e){return x(this,void 0,void 0,(function*(){return e=e.map((e=>e.startsWith("//")?"https:"+e:e)),yield this.callAndBackfeed(`common/preload?urls=${JSON.stringify(e)}`)}))}createCacheProxyUrl(e){e=Array.isArray(e)?e:[e];const t=window.navigator.userAgent;if(!/supportCache/i.test(t))return e;return e.map((e=>this.webViewType===te.WKWebview?e.replace(/https*:/,"").replace(/\/\//,"realseeproxycache://"):this.webViewType===te.WebView?e+(-1!==e.indexOf("?")?"&":"?")+"realseeproxycache=1":e))}}var de;!function(e){e.Append="Append",e.Replace="Replace",e.Single="Single"}(de||(de={}));class he extends ie{constructor(){super(...arguments),this.webViewType=te.Browser}ready(){return Promise.resolve([!0,null])}callAndBackfeed(e){return Promise.resolve([!1,null])}callAndListen(e,t){return Promise.resolve([()=>{},null])}loadProgress(e){return Promise.resolve([!0,null])}closeLoading(){return Promise.resolve([!0,null])}getDeviceInfo(){return Promise.resolve([!1,null])}getWebViewState(){return Promise.resolve([!1,null])}setLeftTopBackButton(e){return Promise.resolve([!1,null])}login(){return Promise.resolve([!1,null])}logout(){return Promise.resolve([!1,null])}getUserInfo(){return Promise.resolve([!1,null])}openWebView(e,t){switch(t){case de.Replace:case de.Single:setTimeout((()=>globalThis.location.replace(e)),200);break;case de.Append:default:setTimeout((()=>globalThis.location.href=e),200)}return Promise.resolve([!0,null])}closeWebView(){return globalThis.close(),Promise.resolve([!0,null])}getBangsHeight(){return Promise.resolve([0,null])}setOrientation(e){return Promise.resolve([!1,null])}keepScreenLight(e){return Promise.resolve([!1,null])}shock(e){return Promise.resolve([!1,null])}minimize(){return Promise.resolve([!1,null])}saveImage2Album(e){return Promise.resolve([!1,null])}detectMicro(){return new Promise((e=>{const t={audio:!0,video:!1};try{globalThis.navigator.mediaDevices.getUserMedia(t).then((()=>e([!0,null]))).catch((t=>e([!1,t])))}catch(t){console.error(t),e([!1,t])}}))}actionShare(e){return Promise.resolve([!1,null])}preload(e){return Promise.resolve([!1,null])}createCacheProxyUrl(e){return[]}}const ue={timeout:6e4};class ve extends ie{constructor(e={}){super(),this._controller=new ee,this.options=Object.assign(ue,e),re||console.warn("未知容器:此版本 `jsBridge` 不支持当前 WebView 容器 ... "),this.webViewType=te.WeChatMPWebView,this.callAndListen("common/webViewState",(e=>{this.emit("webViewStateChange",e)})),this.callAndListen("common/webViewError",(e=>{this.emit("error",e)}))}ready(){return x(this,void 0,void 0,(function*(){return yield this._controller.checkReady(this.options.timeout)}))}callAndBackfeed(e){return x(this,void 0,void 0,(function*(){return yield this._controller.callAndBackfeed(e)}))}callAndListen(e,t){return x(this,void 0,void 0,(function*(){return yield this._controller.callAndListen(e,t)}))}setLeftTopBackButton(e){return x(this,void 0,void 0,(function*(){return this.webViewType===te.WebView?[!0,null]:yield this.callAndBackfeed("common/setLeftTopBackButton?enable="+(e?1:0))}))}getBangsHeight(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/getBangsHeight")}))}shock(e=4){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed(`common/shock?duration=${e}`)}))}minimize(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/minimize")}))}loadProgress(e){return x(this,void 0,void 0,(function*(){return e=e<0?0:e>100?100:e,yield this.callAndBackfeed(`common/loadProgress?progress=${e}`)}))}closeLoading(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/closeLoading")}))}setOrientation(e){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed(`common/setOrientation?orientation=${e}`)}))}keepScreenLight(e){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/keepScreenLight?enable="+(e?1:0))}))}closeWebView(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/closeWebView")}))}openWebView(e,t){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed(`common/openWebView?way=${t}&url=${encodeURIComponent(e)}`)}))}saveImage2Album(e){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed(`common/saveImage2Album?base64=${e}`)}))}actionShare(e){var t,i,o;return x(this,void 0,void 0,(function*(){const n={path:null===(t=e.miniprogram)||void 0===t?void 0:t[0].path,title:null===(i=e.miniprogram)||void 0===i?void 0:i[0].title,imageUrl:null===(o=e.miniprogram)||void 0===o?void 0:o[0].hdImageData};return yield this.callAndBackfeed(`common/actionShare?json=${JSON.stringify(n)}`)}))}getDeviceInfo(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/getDeviceInfo")}))}getUserInfo(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/getUserInfo")}))}getWebViewState(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/getWebViewState")}))}login(){return x(this,void 0,void 0,(function*(){const e=yield this.callAndBackfeed("common/login");return e[0]?yield this.getUserInfo():e}))}logout(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/logout")}))}detectMicro(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/detectMicro")}))}preload(e){return x(this,void 0,void 0,(function*(){return e=e.map((e=>e.startsWith("//")?"https:"+e:e)),yield this.callAndBackfeed(`common/preload?urls=${JSON.stringify(e)}`)}))}createCacheProxyUrl(e){e=Array.isArray(e)?e:[e];const t=window.navigator.userAgent;if(!/supportCache/i.test(t))return e;return e.map((e=>this.webViewType===te.WKWebview?e.replace(/https*:/,"").replace(/\/\//,"realseeproxycache://"):this.webViewType===te.WebView?e+(-1!==e.indexOf("?")?"&":"?")+"realseeproxycache=1":e))}invokeNativeApi(e,t){return x(this,void 0,void 0,(function*(){return yield this._controller.invoke(e,t)}))}execute(e,t){var i,o,n;return x(this,void 0,void 0,(function*(){return yield null===(n=null===(o=null===(i=this._controller)||void 0===i?void 0:i.hybridBridge)||void 0===o?void 0:o.execute)||void 0===n?void 0:n.call(o,e,t)}))}}class me extends ie{constructor(e={}){return super(),ce&&(ne||se)?new le(e):re?new ve(e):new he}}function ge(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var fe,pe,_e=(fe=function(e,t){var i;Object.defineProperty(t,"__esModule",{value:!0}),t.LogLevel=void 0,function(e){e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e[e.OFF=4]="OFF"}(i=t.LogLevel||(t.LogLevel={})),t.default=i},fe(pe={exports:{}},pe.exports),pe.exports),ye=ge(_e);const be=globalThis.navigator.userAgent,Se=/android/gi.test(be),we=/iPhone|iPad\s+OS/gi.test(be),ke=/MicroMessenger/gi.test(be)&&/miniProgram/gi.test(be),Ee=/realsee/gi.test(be);function Ce(e){return"[object Object]"===Object.prototype.toString.call(e)}function Te(e,t){return e===t||typeof e==typeof t&&!(!Number.isNaN(e)||!Number.isNaN(t))}function Ie(e,t){return!!Te(e,t)||(Ce(e)&&Ce(t)?function(e,t){const i=Object.getOwnPropertyNames(e),o=Object.getOwnPropertyNames(t);if(i.length!==o.length)return!1;for(let o=0,n=i.length;o<n;o++){const n=i[o];if(!Te(e[n],t[n]))return!1}return!0}(e,t):!(!Array.isArray(e)||!Array.isArray(t))&&function(e,t){if(e.length!==t.length)return!1;for(let i=0,o=e.length;i<o;i++)if(!Te(e[i],t[i]))return!1;return!0}(e,t))}function Re(e,t){return!!Te(e,t)||(Ce(e)&&Ce(t)?function(e,t){const i=Object.getOwnPropertyNames(e),o=Object.getOwnPropertyNames(t);if(i.length!==o.length)return!1;for(let o=0,n=i.length;o<n;o++){const n=i[o];if(!Re(e[n],t[n]))return!1}return!0}(e,t):!(!Array.isArray(e)||!Array.isArray(t))&&function(e,t){if(e.length!==t.length)return!1;for(let i=0,o=e.length;i<o;i++)if(!Re(e[i],t[i]))return!1;return!0}(e,t))}function Be(e,t,i={deep:!1}){return i.deep?Re(e,t):Ie(e,t)}class Oe extends a{get attempts(){return this._attempts}constructor(e){super(),this._readyState=exports.WebSocketState.NOTINITIALIZED,this._options={timeout:1e4,shouldReconnect:(e,t)=>{if(1008!==e.code&&1011!==e.code)return[0,3e3,1e4][t.attempts]},should1000Reconnect:!1,ignoreConnectivityEvents:!1,automaticOpen:!1},this._attempts=0,this._reconnects=-1,this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!1,this._connectivityEventsAttached=!1,this._healthCheck=()=>d(this,void 0,void 0,(function*(){this._realWebSocket&&this._realWebSocket.readyState!==this._readyState&&(this._readyState=this._realWebSocket.readyState,this._readyState===exports.WebSocketState.CLOSING&&this.emit("closing")),yield new Promise((e=>setTimeout(e,2e3))),this._heathCheckTimer=requestAnimationFrame(this._healthCheck)})),this._clearHeathCheckIfNeed=()=>{this._heathCheckTimer&&(cancelAnimationFrame(this._heathCheckTimer),this._heathCheckTimer=void 0)},this._startHealthCheck=()=>{this._clearHeathCheckIfNeed(),this._heathCheckTimer=requestAnimationFrame(this._healthCheck)},this._stopHealthCheck=()=>{this._clearHeathCheckIfNeed()},this._clearPendingReconnectIfNeeded=()=>{this._pendingReconnect&&(clearTimeout(this._pendingReconnect),this._pendingReconnect=void 0)},this._online=e=>{this._reconnectWhenOnlineAgain&&(this._clearPendingReconnectIfNeeded(),this._reconnect(e))},this._offline=()=>{var e;this._reconnectWhenOnlineAgain=!0,null===(e=this._realWebSocket)||void 0===e||e.close(1e3,"offline")},this._detachConnectivityEvents=()=>{this._connectivityEventsAttached&&(null===globalThis||void 0===globalThis||globalThis.removeEventListener("online",this._online),null===globalThis||void 0===globalThis||globalThis.removeEventListener("offline",this._offline),this._connectivityEventsAttached=!1)},this._attachConnectivityEvents=()=>{this._connectivityEventsAttached||(null===globalThis||void 0===globalThis||globalThis.addEventListener("online",this._online),null===globalThis||void 0===globalThis||globalThis.addEventListener("offline",this._offline),this._connectivityEventsAttached=!0)},this.send=e=>{var t,i,o;(null===(t=this._realWebSocket)||void 0===t?void 0:t.readyState)===(null===(i=this._realWebSocket)||void 0===i?void 0:i.OPEN)&&(null===(o=this._realWebSocket)||void 0===o||o.send(e))},this.close=(e,t)=>{var i;return"number"!=typeof e&&(t=e,e=1e3),this._clearPendingReconnectIfNeeded(),this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!0,this._detachConnectivityEvents(),null===(i=this._realWebSocket)||void 0===i?void 0:i.close(e,t)},this.open=e=>{var t,i;e&&(this._url=e),(null===(t=this._realWebSocket)||void 0===t?void 0:t.readyState)!==WebSocket.OPEN&&(null===(i=this._realWebSocket)||void 0===i?void 0:i.readyState)!==WebSocket.CONNECTING&&(this._clearPendingReconnectIfNeeded(),this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!1,this._createWebSocket())},this._createWebSocket=()=>{var e,t,i;const o="string"==typeof this._url?this._url:null===(e=this._url)||void 0===e?void 0:e.call(this,this);if(!o)return;this._pendingReconnect=void 0,this._removeWebSocketEvent(),this._realWebSocket=new WebSocket(o,this._protocols||void 0),this._attempts=this._attempts+1,this.emit("connecting",new CustomEvent("connecting",{detail:{attempts:this._attempts,reconnects:this._reconnects}}));this._connectTimeout=setTimeout((()=>{this._connectTimeout=void 0,this._detachConnectivityEvents(),this.emit("timeout",new CustomEvent("connecting",{detail:{attempts:this._attempts,reconnects:this._reconnects}}))}),null===(t=this._options)||void 0===t?void 0:t.timeout),this._dispatchWebSocketEvent(),(null===(i=this._options)||void 0===i?void 0:i.ignoreConnectivityEvents)||this._attachConnectivityEvents()},this._removeWebSocketEvent=()=>{var e,t,i,o;null===(e=this._realWebSocket)||void 0===e||e.removeEventListener("open",this._webSocketOpenHandler),null===(t=this._realWebSocket)||void 0===t||t.removeEventListener("close",this._webSocketCloseHandler),null===(i=this._realWebSocket)||void 0===i||i.removeEventListener("error",this._webSocketErrorHandler),null===(o=this._realWebSocket)||void 0===o||o.removeEventListener("message",this._webSocketMessageHandler)},this._dispatchWebSocketEvent=()=>{var e,t,i,o;null===(e=this._realWebSocket)||void 0===e||e.addEventListener("open",this._webSocketOpenHandler),null===(t=this._realWebSocket)||void 0===t||t.addEventListener("close",this._webSocketCloseHandler),null===(i=this._realWebSocket)||void 0===i||i.addEventListener("error",this._webSocketErrorHandler),null===(o=this._realWebSocket)||void 0===o||o.addEventListener("message",this._webSocketMessageHandler)},this._webSocketOpenHandler=e=>{this._connectTimeout&&(clearTimeout(this._connectTimeout),this._connectTimeout=void 0);const t=++this._reconnects,i=this._attempts;return this._attempts=0,this._reconnectWhenOnlineAgain=!1,this._startHealthCheck(),this.emit("open",Object.assign(e,{detail:{reconnects:t,attempts:i}}))},this._webSocketCloseHandler=e=>(this._reconnect(e),this._stopHealthCheck(),this.emit("close",e)),this._webSocketErrorHandler=e=>this.emit("error",new CustomEvent("error",{detail:{error:e}})),this._webSocketMessageHandler=e=>this.emit("message",e),e&&this.setOptions(e),this._startHealthCheck()}setOptions(e){if(!e)return;this._url=e.url,this._protocols=e.protocols;const t=Object.assign(this._options,e.robustOptions||{});if("number"!=typeof(null==t?void 0:t.timeout))throw new Error("timeout must be the number of milliseconds to timeout a connection attempt");if("function"!=typeof(null==t?void 0:t.shouldReconnect))throw new Error("shouldReconnect must be a function that returns the number of milliseconds to wait for a reconnect attempt, or null or undefined to not reconnect.");this._options=t,this._options.automaticOpen&&this._createWebSocket()}_reconnect(e){var t,i,o,n;if(!(null===(t=this._options)||void 0===t?void 0:t.should1000Reconnect)&&1e3===e.code||this._explicitlyClosed)return void(this._attempts=0);if(!1===(null===(i=null===globalThis||void 0===globalThis?void 0:globalThis.navigator)||void 0===i?void 0:i.onLine))return void(this._reconnectWhenOnlineAgain=!0);const s=null===(n=null===(o=this._options)||void 0===o?void 0:o.shouldReconnect)||void 0===n?void 0:n.call(o,e,this);"number"==typeof s&&(this._pendingReconnect=setTimeout(this._createWebSocket,s))}}class Ae extends a{set state(e){const t=JSON.parse(JSON.stringify(this._state));this._state=e,this.emit("stateChange",this.state,t)}get state(){return this._state}constructor(){super(),this._ws=new Oe({url:"",robustOptions:{timeout:18e4}}),this._state=exports.LiveState.NOTINITIALIZED,this._addWebSocketEventListeners=()=>{this._ws.on("close",this._handleCloseEvent),this._ws.on("closing",this._handleClosingEvent),this._ws.on("connecting",this._handleConnectingEvent),this._ws.on("error",this._handleErrorEvent),this._ws.on("message",this._handleMessageEvent),this._ws.on("open",this._handleOpenEvent),this._ws.on("timeout",this._handleTimeoutEvent)},this._removeWebSocketEventListeners=()=>{this._ws.off("close",this._handleCloseEvent),this._ws.off("closing",this._handleClosingEvent),this._ws.off("connecting",this._handleConnectingEvent),this._ws.off("error",this._handleErrorEvent),this._ws.off("message",this._handleMessageEvent),this._ws.off("open",this._handleOpenEvent),this._ws.off("timeout",this._handleTimeoutEvent)},this._handleCloseEvent=e=>{T.info(`live room closed bacause of ${e.code}-${e.reason||L(e.code)}`),this.state=exports.LiveState.CLOSED},this._handleClosingEvent=()=>{var e;T.info("live room is closing, onLine:",null===(e=null===globalThis||void 0===globalThis?void 0:globalThis.navigator)||void 0===e?void 0:e.onLine),this.state=exports.LiveState.CLOSED},this._handleConnectingEvent=()=>{T.info("live room is connecting"),this.state=exports.LiveState.CONNECTING},this._handleErrorEvent=e=>{T.error("live room error",e),this.state=exports.LiveState.CLOSED},this._handleMessageEvent=e=>{let t=(()=>{try{return JSON.parse(e.data)}catch(t){return e.data}})();this.emit("message",t)},this._handleOpenEvent=e=>{T.info("live room open",e.detail),this.state=exports.LiveState.OPEN,e.detail.reconnects>0&&this.emit("reconnected",e.detail)},this._handleTimeoutEvent=e=>{T.error("live room connect timeout!",e.detail),this.state=exports.LiveState.CLOSED},this.dispose=()=>d(this,void 0,void 0,(function*(){return this._removeWebSocketEventListeners(),yield this.close("live room close by controller disposed!")})),this.open=e=>this._ws.open(e),this.close=(e,t)=>new Promise((i=>{this._ws.once("close",(()=>i(!0))),this._ws.close(e,t)})),this._addWebSocketEventListeners()}sendMessage(e=""){if(null==e||""===e)throw new Error("live message is empty!");if(this.state===exports.LiveState.OPEN)return this._ws.send(JSON.stringify(e));throw new Error("live has not yet been initialized!")}}const Le=e=>Promise.reject("unimplemented method GetVoiceSign"),xe=(e,t={},i=[])=>({command:e,front_request_id:R(),data:Object.assign(Object.assign({},t),{to_user_ids:Array.isArray(i)?i:[i]})});class Ne extends a{get options(){return Object.freeze(this._options||{})}get state(){return this._controller.state}get readyState(){return this._controller.state}get url(){return this.options.url}get $RTC(){return this._options.rtc}get jsBridge(){return this._options.jsBridge}get snapshot(){return this._buildInData.keyframes}get selfInfo(){return this._buildInData.selfInfo}get userList(){return this._buildInData.userList||[]}get roomInfo(){return this._buildInData.roomInfo}constructor(e){var t;super(),this._options={},this.keyframes=new a,this._buildInData={keyframes:{}},this.getFramesByKey=e=>this.snapshot[e],this.sendKeyframe=(e,t)=>{if(this.state!==exports.LiveState.OPEN)return!1;this._buildInData.keyframes=Object.assign(Object.assign({},this._buildInData.keyframes),{[e]:t});const i=xe(exports.Command.KeyframeSync,this.snapshot);try{return this._controller.sendMessage(i),!0}catch(e){return T.error(e),!1}},this._controller=new Ae,this._addLiveControllerEventListeners=()=>{this._controller.on("stateChange",this._handleStateChange),this._controller.on("message",this._handleMessage)},this._removeLiveControllerEventListeners=()=>{this._controller.off("stateChange",this._handleStateChange),this._controller.off("message",this._handleMessage)},this._handleStateChange=(e,t)=>this.emit("stateChange",e,t),this._handleMessage=e=>d(this,void 0,void 0,(function*(){var t,i,o,n,s;if("object"==typeof e){const{command:r,data:c={},frontRequestId:a,code:l,message:d}=e;if("SUCCESS"===l)switch(r){case exports.Command.SelfUserInfo:{const e=c;Be(this.selfInfo,e,{deep:!0})||(this._buildInData.selfInfo=e,this.emit("selfInfoUpdate",this._buildInData.selfInfo,a));break}case exports.Command.RoomInfo:{const e=c;this._buildInData.roomInfo=Object.assign({},e),this.emit("readyKeyframeSync",e.last_frame||{});break}case exports.Command.RTCInfo:{const{voice_id:e,type:r}=c;if(this._buildInData.rtcInfo={voiceId:e,type:r},null===(t=this.$RTC)||void 0===t?void 0:t.joined)T.warn("已加入语音房间,无需重复加入!");else{if(yield null===(i=this.$RTC)||void 0===i?void 0:i.join({voiceId:e,userId:(null===(o=this.selfInfo)||void 0===o?void 0:o.id)||"",roomId:null===(n=this.roomInfo)||void 0===n?void 0:n.info.room_code,type:r})){const e=null!==(s=this._options.initialMicroStatus)&&void 0!==s?s:exports.MicroStatus.OPEN;yield this.toggleMicro(e===exports.MicroStatus.OPEN)}else T.error("加入语音房间失败")}break}case exports.Command.UserList:{const e=c;this._buildInData.userList=e,this.emit("userListUpdate",this.userList,a);break}case exports.Command.CustomEvent:{const e=c;this.emit("broadcast",e,a);break}case exports.Command.KeyframeSync:{const e=c,t=Object.keys(e).reduce(((t,i)=>{if(Be(e[i],this._buildInData.keyframes[i],{deep:!0}))return t;const o=[e[i],this._buildInData.keyframes[i],a],n=i;return this.keyframes.emit(n,...o),this._buildInData.keyframes[i]=e[i],t[i]=e[i],t}),{});this.emit("keyframes",t,a);break}case exports.Command.BuiltinMsg:{const e=c;this.emit("builtinEvent",e),e.event_type===exports.BuiltinEventType.UserChange&&this.emit("userChange",e),e.event_type===exports.BuiltinEventType.RoomChange&&this.emit("roomChange",e),e.event_type===exports.BuiltinEventType.UserChange&&e.action===exports.BuiltinActionType.UserMicroStatus&&(yield this.toggleMicro(e.data.status===exports.MicroStatus.OPEN)),e.event_type===exports.BuiltinEventType.RoomChange&&e.action===exports.BuiltinActionType.RoomClose&&(yield this.exit());break}case exports.Command.UserKickOut:this.emit("kickOut");break;default:console.warn("unknown command: ",r)}else this.emit("error",e)}})),this._clearLiveData=()=>{this._buildInData={keyframes:{}}},this.connect=(e={})=>d(this,void 0,void 0,(function*(){var t,i,o,n;if(this._options.url=null!==(i=null!==(t=e.url)&&void 0!==t?t:this._options.url)&&void 0!==i?i:"",this._options.getTicket=null!==(o=e.getTicket)&&void 0!==o?o:this._options.getTicket,this._options.initialMicroStatus=null!==(n=e.rtcMicStatus)&&void 0!==n?n:this._options.initialMicroStatus,!/^ws(s):\/\//.test(this._options.url)||"function"!=typeof this._options.getTicket)return/^ws(s):\/\//.test(this._options.url)?"function"!=typeof this._options.getTicket&&new Error("getTicket muse be function"):new Error("Illegal realsee live room link");const{force:s=!1}=e;if(this._options.rtc){if(!(yield this._options.rtc.detectMicro()))return new Error("Failed to obtain microphone authorization")}const r=this.state;if(r===exports.LiveState.CONNECTING||r===exports.LiveState.OPEN){if(!s)return new Error("已有Live实例正在连接中,请勿重复连接!");try{yield this._controller.close("force close by connect")}catch(e){console.warn(e)}}this._clearLiveData();const c=function(e,t={}){const i=-1!==e.indexOf("?");return e+Object.keys(t).reduce(((e,o,n)=>`${e}${0!==n||i?"&":"?"}${o}=${t[o]}`),"")}(this._options.url,{ticket:yield this._options.getTicket(),force:Number(!!s)});return this._controller.open(c),!0})),this.exit=()=>d(this,void 0,void 0,(function*(){var e;if(this._clearLiveData(),this.state!==exports.LiveState.OPEN)return!0;try{null===(e=this.$RTC)||void 0===e||e.quit(),yield this.updateStatus(exports.BuiltinEventType.RoomChange,exports.BuiltinActionType.RoomClose,{})}catch(e){T.warn(e)}return yield this._controller.close("user exit")})),this.dispose=()=>d(this,void 0,void 0,(function*(){return this._removeLiveControllerEventListeners(),this._clearLiveData(),yield this._controller.dispose()})),this.setSelfInfo=e=>d(this,void 0,void 0,(function*(){return yield this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserInfo,e)})),this.toggleMicro=e=>d(this,void 0,void 0,(function*(){var t,i,o;if(!(null===(i=null===(t=this.selfInfo)||void 0===t?void 0:t.permission)||void 0===i?void 0:i.control_own_micro))return!1;const n=yield null===(o=this.$RTC)||void 0===o?void 0:o.toggleMicro(e);return n&&(yield this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserMicroStatus,{status:e?exports.MicroStatus.OPEN:exports.MicroStatus.CLOSE},[])),n})),this.forbidMicro=(e,t)=>d(this,void 0,void 0,(function*(){var i,o;return!("function"==typeof this._options.canForbidUserMicro&&!this._options.canForbidUserMicro(t))&&(!!(null===(o=null===(i=this.selfInfo)||void 0===i?void 0:i.permission)||void 0===o?void 0:o.control_other_micro)&&(yield this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserMicroStatus,{status:e},t)))})),this.forbidSync=(e,t)=>d(this,void 0,void 0,(function*(){var i,o;return!("function"==typeof this._options.canForbidUserSync&&!this._options.canForbidUserSync(t))&&(!!(null===(o=null===(i=this.selfInfo)||void 0===i?void 0:i.permission)||void 0===o?void 0:o.control_other_sync)&&(yield this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserPermission,{sync_frame:e},t)))})),this.kick=e=>d(this,void 0,void 0,(function*(){var t,i;return!("function"==typeof this._options.canForbidUserKick&&!this._options.canForbidUserKick(e))&&(!!(null===(i=null===(t=this.selfInfo)||void 0===t?void 0:t.permission)||void 0===i?void 0:i.change_other_status)&&(yield this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserStatus,{status:"KICK_OUT"},e)))})),this._addLiveControllerEventListeners(),this._options=Object.assign({initialMicroStatus:exports.MicroStatus.OPEN},e),this._options.jsBridge=e.jsBridge?e.jsBridge:e.useBuiltInJsBridge?new me:void 0,this._options.getVoiceSign=null!==(t=e.getVoiceSign)&&void 0!==t?t:Le,this._options.autoPlayConfirm=e.autoPlayConfirm,this._options.rtc=(()=>{if(e.rtc)return e.rtc;if(e.rtcType)switch(e.getVoiceSign||T.error("GetVoiceSign method must be passed when using built-in RTC instances"),e.rtcType){case exports.RTCType.RealseeVRWebViewRTC:return this._options.jsBridge?new A({jsBridge:this._options.jsBridge,getVoiceSign:this._options.getVoiceSign}):void T.error("JsBridge instance must be passed when using built-in VRWebViewRTC instances");case exports.RTCType.RealseeBrowserChimeRTC:return new O({getVoiceSign:this._options.getVoiceSign,logLevel:e.__debug__?ye.DEBUG:ye.ERROR});case exports.RTCType.RealseeBrowserRTC:return this._options.autoPlayConfirm||T.error("autoPlayConfirm method must be passed when using built-in RealseeBrowserRTC instances"),new B({getVoiceSign:this._options.getVoiceSign,autoPlayConfirm:this._options.autoPlayConfirm});default:return void T.error("unknown built-in RTC type")}return e.useBuiltInRTC?(e.getVoiceSign||T.error("GetVoiceSign method must be passed when using built-in RTC instances"),this._options.jsBridge?Ee&&(Se||we)||ke?new A({jsBridge:this._options.jsBridge,getVoiceSign:this._options.getVoiceSign}):e.builtInRTCType===exports.BuiltInRTCType.RealseeXChimeRTC?new O({getVoiceSign:this._options.getVoiceSign}):new B({getVoiceSign:this._options.getVoiceSign,autoPlayConfirm:this._options.autoPlayConfirm}):void T.error("jsBridge instance must be passed when using built-in RTC instances")):void 0})(),this._options.rtc||T.warn("unused rtc"),this._options.url&&this._options.getTicket&&this.connect(),this._options.__debug__&&Object.assign(window,{$liveController:this._controller,$live:this})}updateStatus(e,t,i,o){return d(this,void 0,void 0,(function*(){if(this.state!==exports.LiveState.OPEN)return!1;const n=Object.assign({event_type:e,action:t},{data:i}),s=xe(exports.Command.BuiltinMsg,n,o);try{return this._controller.sendMessage(s),!0}catch(e){return T.error(e),!1}}))}broadcast(e,t,i){return this.state===exports.LiveState.OPEN&&new Promise(((o,n)=>{const s=xe(exports.Command.CustomEvent,e,t),r=s.front_request_id,c=i?setTimeout((()=>{n(new Error("RESPONSE TIMEOUT")),this.off("broadcast",a)}),i):void 0,a=(e,t)=>{t===r&&(c&&clearTimeout(c),this.off("broadcast",a),o(e))};this.on("broadcast",a);try{this._controller.sendMessage(s)}catch(e){n(e)}}))}}const We=e=>{var t,i;return(null===window||void 0===window?void 0:window.__Realsee_Live__)&&(null===(i=null===(t=null===window||void 0===window?void 0:window.__Realsee_Live__)||void 0===t?void 0:t.dispose)||void 0===i||i.call(t),window.__Realsee_Live__=null),new Ne(e)};exports.BrowserRTC=B,exports.BrowserRTC4Chime=O,exports.CoreRTC=l,exports.VRWebViewRTC=A,exports.createLive=We,exports.createLiveReact=function(e){const t=i.createContext(null),o=We(e),n=o.jsBridge,r=()=>{const e=s.default.useContext(t);if(!e)throw new Error("LiveProvider never found.");return e};return{live:o,jsBridge:n,LiveProvider:e=>s.default.createElement(t.Provider,{value:o},e.children),unsafe__useLiveInstance:()=>o,unsafe__useRTCInstance:()=>o.$RTC,useConnect:()=>e=>d(this,void 0,void 0,(function*(){return yield o.connect(e)})),useKeyframe:function(e){const t=r(),[i,o]=s.default.useState(t.getFramesByKey(e));return s.default.useEffect((()=>{const i=e,n=e=>o(e);return t.keyframes.on(i,n),()=>t.keyframes.off(i,n)}),[t]),[i,s.default.useCallback((i=>t.sendKeyframe(e,i)),[t])]},useKeyframeUpdateCallback:function(e,t,i=[]){const o=r(),n=[o,name,...i],c=()=>o.keyframes.off(e,t);return s.default.useEffect((()=>(o.keyframes.on(e,t),c)),n),c},useLiveAction:function(){const e=r();return{connect:t=>d(this,void 0,void 0,(function*(){return yield e.connect(t)})),broadcast:(t,i,o=0)=>d(this,void 0,void 0,(function*(){return yield e.broadcast(t,i,o)})),exit:()=>d(this,void 0,void 0,(function*(){return yield e.exit()})),kick:t=>d(this,void 0,void 0,(function*(){return yield e.kick(t)})),toggleMicro:t=>e.toggleMicro(t),forbidMicro:(t,i=[])=>d(this,void 0,void 0,(function*(){return yield e.forbidMicro(t,i)})),forbidSync:(t,i=[])=>e.forbidSync(t,i),sendKeyframe:(t,i)=>e.sendKeyframe(t,i),getFramesByKey:t=>e.getFramesByKey(t),setSelfInfo:t=>e.setSelfInfo(t),updateStatus:(t,i,o,n)=>e.updateStatus(t,i,o,n)}},useLiveEventCallback:function(e,t,i=[]){const o=r(),n=()=>o.off(e,t),c=[o,e,...i];return s.default.useEffect((()=>(o.on(e,t),n)),c),n},useLiveState:function(){const e=r(),[t,i]=s.default.useState(e.state);return s.default.useEffect((()=>{const t=e=>i(e);return e.on("stateChange",t),()=>e.off("stateChange",t)}),[e]),t},useRTCAction:function(){const e=r();return{join:t=>e.$RTC.join(t),quit:()=>e.$RTC.quit(),shock:()=>{var t,i;return null===(i=(t=e.$RTC).shock)||void 0===i?void 0:i.call(t)},toggleMicro:t=>e.$RTC.toggleMicro(t),detectMicro:()=>e.$RTC.detectMicro()}},useRTCEventCallback:function(e,t,i=[]){const o=r(),n=()=>o.$RTC.off(e,t),c=[o,e,...i];return s.default.useEffect((()=>(o.$RTC.on(e,t),n)),c),n},useSelfInfo:function(){const e=r(),[t,i]=s.default.useState(e.selfInfo||{}),o=e=>i(e);return s.default.useEffect((()=>(e.on("selfInfoUpdate",o),()=>e.off("selfInfoUpdate",o))),[e]),[t,s.default.useCallback((t=>d(this,void 0,void 0,(function*(){return yield e.setSelfInfo(t)}))),[e])]},useKeyframesSnapshot:function(){const e=r(),[t,i]=s.default.useState(e.snapshot);return s.default.useEffect((()=>{const t=e=>i(e);return e.on("keyframes",t),()=>e.off("keyframes",t)})),t},useUserList:function(){const e=r(),[t,i]=s.default.useState(e.userList),o=e=>i(e);return s.default.useEffect((()=>(e.on("userListUpdate",o),()=>e.off("userListUpdate",o))),[e]),t}}},exports.parseLiveMsg=function(e){try{const t=JSON.parse(e),i={code:t.code,message:t.message,command:t.command,roomCode:t.room_code,appID:t.app_id,requestId:t.request_id,frontRequestId:t.front_request_id,triggerUserID:t.trigger_user_id,data:t.data||{}},o=Object.keys(i).filter((e=>void 0===i[e]));return o.length>0&&console.warn(`推送数据格式异常:${o.join(" ")} 值不存在!`),i}catch(e){return!1}},exports.parseWSClsErr=L;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("trtc-js-sdk"),t=require("amazon-chime-sdk-js"),i=require("react");function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=o(e),s=o(i);const r=Symbol("$$REALSEE_LIVE_EVENT$$");function c(e){return e[r]||(e[r]={}),e[r]}class a{hasListener(e){const t=c(this);return t&&t[e]&&t[e].length>0}on(e,t,i){const o=c(this);return o[e]||(o[e]=[]),o[e].push([t,i||!1]),()=>this.off(e,t)}once(e,t){return this.on(e,t,!0)}off(e,t){if(void 0===e)return void((i=this)[r]||delete i[r]);var i;const o=c(this);if(o[e]||(o[e]=[]),void 0===t)return void(o[e].length=0);let n=0;for(;n<o[e].length&&o[e][n][0]!==t;n++);n<o[e].length&&o[e].splice(n,1)}emit(e,...t){let i=!1;const o=c(this)[e]||[];for(let n of o.slice()){const[o,s=!1]=n,r=o(...t);s&&this.off(e,o),!1===r&&(i=!0)}return i}}class l extends a{}function d(e,t,i,o){return new(i||(i=Promise))((function(n,s){function r(e){try{a(o.next(e))}catch(e){s(e)}}function c(e){try{a(o.throw(e))}catch(e){s(e)}}function a(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,c)}a((o=o.apply(e,t||[])).next())}))}var h,u;exports.RTCType=void 0,(h=exports.RTCType||(exports.RTCType={})).RealseeBrowserRTC="RealseeBrowserRTC",h.RealseeVRWebViewRTC="RealseeVRWebViewRTC",h.RealseeBrowserChimeRTC="RealseeBrowserChimeRTC",exports.BuiltInRTCType=void 0,(u=exports.BuiltInRTCType||(exports.BuiltInRTCType={})).RealseeXTRTC="trtc",u.RealseeXChimeRTC="chime";var v;!function(e){e.info="INFO",e.log="LOG",e.error="ERROR",e.warn="WARN"}(v||(v={}));const m=(e,t=[])=>{switch(t.unshift(`Realsee Live ${(()=>{const e=new Date;return`[${e.getFullYear()}-${(e.getMonth()+1).toString().padStart(2,"0")}-${e.getDate().toString().padStart(2,"0")} ${e.getHours().toString().padStart(2,"0")}:${e.getMinutes().toString().padStart(2,"0")}:${e.getSeconds().toString().padStart(2,"0")}.${e.getMilliseconds()}]`})()} <${e}> `),e){case v.info:return console.info(...t);case v.error:return console.error(...t);case v.warn:return console.warn(...t);default:return console.log(...t)}};var g,f,p,_,y,b,S,w,k,E,C,T={log:(...e)=>m(v.log,e),info:(...e)=>m(v.info,e),error:(...e)=>m(v.error,e),warn:(...e)=>m(v.warn,e)};function I(){return(65536*(1+Math.random())|0).toString(16).substring(1)}function R(){return(I()+I()+"-"+I()+"-4"+I().substr(0,3)+"-"+I()+"-"+I()+I()+I()).toLowerCase()}class O extends l{constructor(e){super(),this.type=exports.RTCType.RealseeBrowserRTC,this.joined=!1,this.micro=!1,this.voiceId="",this._getVoiceSign=()=>{throw new Error("方法 getVoiceSign 未实现")},this.checkRequirement=()=>n.default.checkSystemRequirements(),this.$dom=document.createElement("div"),this._trtc={client:null,stream:null},this.join=e=>d(this,void 0,void 0,(function*(){var t;this.emit("joinWillStart");const i=yield this._getVoiceSign({voiceId:e.voiceId,roomId:e.roomId,userId:e.userId});this._trtc.client=n.default.createClient(Object.assign(Object.assign({mode:"rtc"},i),{enableAutoPlayDialog:"function"!=typeof this._autoPlayConfirm})),null===(t=this._trtc.client)||void 0===t||t.enableAudioVolumeEvaluation(),this._registerRtcEvent();let o=yield new Promise((t=>{var i;null===(i=this._trtc.client)||void 0===i||i.join({roomId:Number(e.voiceId)}).then((()=>t(!0))).catch((()=>t(!1)))}));return this.joined=o,!!o&&(this._trtc.stream=n.default.createStream({userId:i.userId,audio:!0,video:!1}),o=yield new Promise((e=>{var t;null===(t=this._trtc.stream)||void 0===t||t.initialize().then((()=>e(!0))).catch((()=>e(!1)))})),o=yield new Promise((e=>{var t;null===(t=this._trtc.client)||void 0===t||t.publish(this._trtc.stream).then((()=>e(!0))).catch((()=>e(!1)))})),this.joined=o,this.joined&&this.emit("joined"),o)})),this._handleStreamAdded=e=>{var t;const i=e.stream;console.log("远端流增加: "+i.getId()),null===(t=this._trtc.client)||void 0===t||t.subscribe(i)},this._handleStreamSubscribed=e=>{const t=e.stream;console.log("远端流订阅成功:"+t.getId());const i=`rs-rtc-remote_stream-${t.getId()}`,o=document.createElement("div");o.id=i,this.$dom.appendChild(o),"function"==typeof this._autoPlayConfirm?(t.play(i).catch((e=>{})),t.on("error",(e=>{if(16451===e.getCode()){const e=()=>t.resume();this._autoPlayConfirm({onConfirm:e})}}))):t.play(i)},this._getVoiceSign=e.getVoiceSign,this._autoPlayConfirm=e.autoPlayConfirm,this._initParentDom()}_initParentDom(){this.$dom.id=`rs-rtc-${R()}`,this.$dom.style.display="none",document.body.appendChild(this.$dom)}quit(){return new Promise((e=>d(this,void 0,void 0,(function*(){var t,i;this.joined=!1,this._trtc.stream&&(yield null===(t=this._trtc.client)||void 0===t?void 0:t.unpublish(this._trtc.stream),this._trtc.stream.stop(),this._trtc.stream.close(),this._trtc.stream=null),null===(i=this._trtc.client)||void 0===i||i.leave().then((()=>this._trtc.client=null)).then((()=>e(!0))).catch((()=>e(!1))),e(!0)}))))}detectMicro(){return new Promise((e=>{const t={audio:!0,video:!1};try{navigator.mediaDevices.getUserMedia(t).then((()=>e(!0))).catch((t=>{T.error(t.message),e(!1)}))}catch(t){console.error(t),e(!1)}}))}toggleMicro(e){var t,i,o,n;return Promise.resolve((e?null===(i=null===(t=this._trtc)||void 0===t?void 0:t.stream)||void 0===i?void 0:i.unmuteAudio():null===(n=null===(o=this._trtc)||void 0===o?void 0:o.stream)||void 0===n?void 0:n.muteAudio())||!1)}shock(){throw new Error("Method not implemented.")}_registerRtcEvent(){var e,t,i,o;null===(e=this._trtc.client)||void 0===e||e.on("stream-added",this._handleStreamAdded),null===(t=this._trtc.client)||void 0===t||t.on("stream-subscribed",this._handleStreamSubscribed),null===(i=this._trtc.client)||void 0===i||i.on("audio-volume",(e=>this.emit("userVolumes",e.result.map((({userId:e,audioVolume:t})=>({userId:e,audioVolume:t})))))),null===(o=this._trtc.client)||void 0===o||o.on("error",(e=>this.emit("error",e)))}}class B extends l{constructor(e){super(),this.type=exports.RTCType.RealseeBrowserChimeRTC,this.joined=!1,this.micro=!1,this.voiceId="",this.userId="",this.deviceChangeObserver={},this.audioVideoObserver={},this._getVoiceSign=()=>{throw new Error("方法 getVoiceSign 未实现")},this.$dom=document.createElement("div"),this.$audio=document.createElement("audio"),this._initDom=()=>{this.$audio.id=`rs-rtc-${R()}`,this.$dom.id=`rs-rtc-${R()}`,this.$dom.appendChild(this.$audio),document.body.appendChild(this.$dom)},this.initObservers=()=>{this.deviceChangeObserver={audioInputsChanged:e=>{null==e||e.forEach((e=>{this.logger.info(`Device ID: ${e.deviceId} Microphone: ${e.label}`)}))},audioOutputsChanged:e=>{this.logger.info(`Audio outputs updated: ${e}`)},videoInputsChanged:e=>{this.logger.info(`Video inputs updated: ${e}`)},audioInputMuteStateChanged:(e,t)=>{this.logger.info(`Device ${e.toString()} ${t?"is muted in hardware":"is not muted"}`)}},this.audioVideoObserver={audioVideoDidStart:()=>{this.logger.info("Started")},audioVideoDidStop:e=>{this.logger.info(`Stopped with a session status code: ${e.statusCode()}`)},audioVideoDidStartConnecting:e=>{e&&this.logger.info("Attempting to reconnect")}}},this._registerRtcEvent=()=>{var e,i,o,n,s,r;const c=(null===(o=null===(i=null===(e=this.meetingSession)||void 0===e?void 0:e.configuration)||void 0===i?void 0:i.credentials)||void 0===o?void 0:o.attendeeId)||"";if(c){const e=new Map,i=()=>{const t=[];return e.forEach(((e,i)=>{t.push({userId:e.userId,volume:e.muted||0===e.signalStrength||!Boolean(e.volume)?0:e.volume})})),t};null===(n=this.meetingSession)||void 0===n||n.audioVideo.realtimeSubscribeToAttendeeIdPresence(((o,n,s)=>{var r;if(!n)return e.delete(o),void this.emit("userVolumes",i());null===(r=this.meetingSession)||void 0===r||r.audioVideo.realtimeSubscribeToVolumeIndicator(o,((o,n,r,c)=>{new t.DefaultModality(o).base()===o&&(e.set(o,{userId:s||o,volume:n,muted:r,signalStrength:c}),this.emit("userVolumes",i()))}))})),null===(s=this.meetingSession)||void 0===s||s.audioVideo.realtimeSubscribeToVolumeIndicator(c,((e,i,o,n)=>{new t.DefaultModality(e).base()===e&&null!==n&&1!==n&&this.emit("weakNetwork")})),null===(r=this.meetingSession)||void 0===r||r.audioVideo.realtimeSubscribeToFatalError((e=>this.emit("error",e)))}},this._getVoiceSign=e.getVoiceSign,this._initDom(),this.logger=new t.ConsoleLogger("WebRTCLogger",e.logLevel||t.LogLevel.OFF),this.deviceController=new t.DefaultDeviceController(this.logger),this.initObservers()}join(e){return d(this,void 0,void 0,(function*(){return new Promise(((i,o)=>d(this,void 0,void 0,(function*(){var o;this.emit("joinWillStart");try{const{sdkAppId:n,userId:s,roomId:r,userSig:c}=yield this._getVoiceSign(Object.assign(Object.assign({},e),{roomId:e.roomId||0}));this.userId=s;const{attendence:a,vendor_wrapper:l}=JSON.parse(decodeURIComponent(c)),d=new t.MeetingSessionConfiguration({Meeting:l},{Attendee:{ExternalUserId:a.external_user_id,AttendeeId:a.attendee_id,JoinToken:a.join_token}});this.meetingSession=new t.DefaultMeetingSession(d,this.logger,this.deviceController),this._registerRtcEvent(),this.meetingSession.audioVideo.addDeviceChangeObserver(this.deviceChangeObserver),this.meetingSession.audioVideo.addObserver(this.audioVideoObserver),this.meetingSession.audioVideo.bindAudioElement(this.$audio);const h={audioVideoDidStart:()=>{var e;null===(e=this.meetingSession)||void 0===e||e.audioVideo.realtimeMuteLocalAudio(),this.joined=!0,this.emit("joined"),i(!0)},audioVideoDidStop:()=>{this.joined=!1,i(!1)}};this.meetingSession.audioVideo.addObserver(h);const u=yield this.deviceController.listAudioInputDevices(!0),v=u.find((e=>"default"===e.deviceId)),m=u.find((e=>""!==e.deviceId));this.audioInput=v||m,yield this.meetingSession.audioVideo.chooseVideoInputDevice(null),yield this.meetingSession.audioVideo.chooseAudioInputDevice((null===(o=this.audioInput)||void 0===o?void 0:o.deviceId)||"default"),this.meetingSession.audioVideo.start()}catch(e){this.emit("error",e),this.logger.error(e.message),i(!1)}}))))}))}quit(){return this.joined?new Promise(((e,i)=>{var o,n;this.joined=!1;const s={audioVideoDidStop:i=>{const o=i.statusCode();o===t.MeetingSessionStatusCode.Left?(this.logger.info("You left the session"),e(!0)):(this.logger.info(`Stopped with a session status code: ${o}`),e(!0))}};null===(o=this.meetingSession)||void 0===o||o.audioVideo.addObserver(s),null===(n=this.meetingSession)||void 0===n||n.audioVideo.stop()})):Promise.resolve(!0)}detectMicro(){return d(this,void 0,void 0,(function*(){return new Promise((e=>{const t={audio:!0,video:!1};try{navigator.mediaDevices.getUserMedia(t).then((()=>e(!0))).catch((()=>e(!1)))}catch(t){this.logger.error(t.message),e(!1)}}))}))}toggleMicro(e){var t,i,o;return d(this,void 0,void 0,(function*(){e?null===(t=this.meetingSession)||void 0===t||t.audioVideo.realtimeUnmuteLocalAudio():null===(i=this.meetingSession)||void 0===i||i.audioVideo.realtimeMuteLocalAudio();const n=null===(o=this.meetingSession)||void 0===o?void 0:o.audioVideo.realtimeIsLocalAudioMuted();return void 0!==n&&e!==n}))}shock(){throw new Error("Method not implemented.")}}exports.RTCJoinedInfoCodeEnum=void 0,(g=exports.RTCJoinedInfoCodeEnum||(exports.RTCJoinedInfoCodeEnum={}))[g.Success=0]="Success",g[g.Failure=1]="Failure",g[g.ReJoin=2]="ReJoin",g[g.NoMicroPermission=3]="NoMicroPermission";class A extends l{get jsBridge(){return this.options.jsBridge}constructor({jsBridge:e,getVoiceSign:t}){super(),this.type=exports.RTCType.RealseeVRWebViewRTC,this.joined=!1,this.micro=!1,this.voiceId="",this.options={jsBridge:e,getVoiceSign:t},"WxMiniProgramWebView"!==this.jsBridge.webViewType&&this.jsBridge.callAndListen("live/userVolumes",(e=>{this.emit("userVolumes",e)})),this.jsBridge.callAndListen("live/weakNetwork",(e=>{e&&this.emit("weakNetwork")}))}join(e){return d(this,void 0,void 0,(function*(){try{this.emit("joinWillStart");const{sdkAppId:t,userId:i,userSig:o}=yield this.options.getVoiceSign(e);if(!(Boolean(t)&&Boolean(i)&&Boolean(o)))return this.emit("error",new Error("加入房间失败:rtc 签名请求异常")),this.joined=!1,this.joined;this.type=e.type;const[n,s]=yield this.jsBridge.callAndBackfeed(`live/join?sdkAppID=${t}&userID=${i}&roomID=${Number(e.voiceId)}&userSig=${o}`);return n?n.code===exports.RTCJoinedInfoCodeEnum.Success?(this.emit("joined"),this.joined=!0):(this.emit("error",n),this.joined=!1):(this.emit("error",s||new Error("加入房间失败:未知异常。")),this.joined=!1),this.joined}catch(e){return this.emit("error",new Error("加入房间失败:"+e.message)),this.joined=!1,this.joined}}))}quit(){return d(this,void 0,void 0,(function*(){const[e,t]=yield this.jsBridge.callAndBackfeed("live/quit");return null===e&&this.emit("error",t||new Error("退出房间失败:未知异常。")),this.joined=!1,!!e}))}detectMicro(){return d(this,void 0,void 0,(function*(){const[e,t]=yield this.jsBridge.detectMicro();return null===e?(this.emit("error",t||new Error("麦克风监测异常!")),!1):e}))}toggleMicro(e){return d(this,void 0,void 0,(function*(){const[t,i]=yield this.jsBridge.callAndBackfeed("live/toggleMicro?flag="+(e?1:0));return null===t?(this.emit("error",i||new Error("麦克风监测异常!")),!1):(this.micro=t,t)}))}shock(){this.jsBridge.shock(1)}}function L(e){switch(e){case 1e3:return exports.WebSocketCloseError.Err_1000;case 1001:return exports.WebSocketCloseError.Err_1001;case 1002:return exports.WebSocketCloseError.Err_1002;case 1003:return exports.WebSocketCloseError.Err_1003;case 1006:return exports.WebSocketCloseError.Err_1006;case 1007:return exports.WebSocketCloseError.Err_1007;case 1008:return exports.WebSocketCloseError.Err_1008;case 1009:return exports.WebSocketCloseError.Err_1009}return exports.WebSocketCloseError.Err_unknown}function x(e,t,i,o){return new(i||(i=Promise))((function(n,s){function r(e){try{a(o.next(e))}catch(e){s(e)}}function c(e){try{a(o.throw(e))}catch(e){s(e)}}function a(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,c)}a((o=o.apply(e,t||[])).next())}))}exports.Command=void 0,(f=exports.Command||(exports.Command={})).SelfUserInfo="SELF_USER_INFO",f.RoomInfo="ROOM_INFO",f.RTCInfo="RTC_INFO",f.UserList="USER_LIST",f.BuiltinMsg="BUILTIN_MSG",f.CustomEvent="CUSTOM_EVENT",f.KeyframeSync="KEYFRAME_SYNC",f.UserKickOut="USER_KICK_OUT",exports.BuiltinEventType=void 0,(p=exports.BuiltinEventType||(exports.BuiltinEventType={})).UserChange="user_change",p.RoomChange="room_change",exports.BuiltinActionType=void 0,(_=exports.BuiltinActionType||(exports.BuiltinActionType={})).UserMicroStatus="change_micro_status",_.UserMicroStatusSync="sync_micro_status",_.UserPermission="change_permission",_.UserStatus="change_status",_.UserInfo="change_info",_.RoomClose="close",exports.MicroStatus=void 0,(y=exports.MicroStatus||(exports.MicroStatus={})).OPEN="OPEN",y.CLOSE="CLOSE",exports.LiveState=void 0,(b=exports.LiveState||(exports.LiveState={}))[b.NOTINITIALIZED=-1]="NOTINITIALIZED",b[b.CONNECTING=0]="CONNECTING",b[b.OPEN=1]="OPEN",b[b.CLOSED=3]="CLOSED",exports.UserStatus=void 0,(S=exports.UserStatus||(exports.UserStatus={}))[S.Normal=0]="Normal",S[S.Removed=1]="Removed",S[S.Replaced=2]="Replaced",exports.MemUserStatus=void 0,(w=exports.MemUserStatus||(exports.MemUserStatus={})).WAIT_ENTER="WAIT_ENTER",w.ONLINE="ONLINE",w.LEAVE="LEAVE",w.KICK_OUT="KICK_OUT",w.BE_REPLACE="BE_REPLACE",w.EXCEPTION="EXCEPTION",exports.WebSocketState=void 0,(k=exports.WebSocketState||(exports.WebSocketState={}))[k.NOTINITIALIZED=-1]="NOTINITIALIZED",k[k.CONNECTING=0]="CONNECTING",k[k.OPEN=1]="OPEN",k[k.CLOSING=2]="CLOSING",k[k.CLOSED=3]="CLOSED",exports.WebSocketErrorType=void 0,(E=exports.WebSocketErrorType||(exports.WebSocketErrorType={})).Error="Error",E.Close="Close",E.MicroAuth="MicroAuth",E.DuplicateConnect="DuplicateConnect",E.IllegalURL="IllegalURL",E.Unknown="Unknown",E.IllegalArgs="IllegalArgs",exports.WebSocketCloseError=void 0,(C=exports.WebSocketCloseError||(exports.WebSocketCloseError={})).Err_1000="CLOSE_NORMAL",C.Err_1001="CLOSE_GOING_AWAY",C.Err_1002="CLOSE_PROTOCOL_ERROR",C.Err_1003="CLOSE_UNSUPPORTED",C.Err_1006="CLOSE_ABNORMAL",C.Err_1007="Unsupported Data",C.Err_1008="Policy Violation",C.Err_1009="CLOSE_TOO_LARGE",C.Err_unknown="unknown";const N={};function W(e,t,i=!0){if(N[e])N[e].queue.push({once:i,callback:t});else{const o="$jsBridgeFn_"+Date.now().toString(16).toUpperCase()+"_"+Math.ceil(1e4*Math.random()).toString(16).toUpperCase();N[e]={uuid:o,queue:[{once:i,callback:t}]}}return Object.assign(window,{[N[e].uuid]:t=>{N[e].queue=N[e].queue.reduce(((e,i)=>{const{once:o,callback:n}=i;return o||e.push(i),n(t),e}),[])}}),N[e].uuid}class M{checkReady(e){return Promise.resolve([!1,null])}callAndBackfeed(e){return Promise.resolve([!1,null])}callAndListen(e,t){return Promise.resolve([!1,null])}}const P=window;class V extends M{constructor(){super(),Promise.resolve().then((()=>x(this,void 0,void 0,(function*(){try{yield this.checkBridgeReady()}catch(e){console.warn(e)}}))))}checkBridgeReady(e=6e3){if(this.hybridBridge)return!0;const t=performance.now();return new Promise(((i,o)=>{const n=()=>{if(this.hybridBridge)return i(!0);if(P.HybridBridgeLJ){const e=P.HybridBridgeLJ;null==e||e.getStaticData(W("HYBRID_BRIDGE_NAME",(t=>(this.deviceInfo=JSON.parse(t),this.hybridBridge=e,i(!0)))))}if(performance.now()-t>(e||6e3))return o(new Error("HybridBridge 初始化超时~"));requestAnimationFrame(n)};n()}))}checkReady(e=6e3){return x(this,void 0,void 0,(function*(){const t=[null,null];if(this.hybridBridge)return t[0]=!0,t;try{t[0]=yield this.checkBridgeReady(e)}catch(e){t[0]=!1,t[1]=e}return t}))}get ready(){return!!this.hybridBridge}get scheme(){var e;return(null===(e=this.deviceInfo)||void 0===e?void 0:e.scheme)||""}createSchemeLink(e){return e.startsWith(this.scheme)?e:this.scheme+"://"+e}callAndBackfeed(e){return x(this,void 0,void 0,(function*(){const t=[!1,null],[i,o]=yield this.checkReady();return i?yield new Promise((i=>x(this,void 0,void 0,(function*(){const o=this.createSchemeLink(e),n=JSON.stringify({actionUrl:o,functionName:W(this.createSchemeLink(e),(e=>{const o=(()=>{try{return JSON.parse(e)}catch(t){return e}})();t[0]=1===o||0!==o&&o,i(t)}))});this.hybridBridge.callAndBackfeed(n)})))):(t[0]=!1,t[1]=o,t)}))}callAndListen(e,t){return x(this,void 0,void 0,(function*(){const i=[!1,null],[o,n]=yield this.checkReady();return o?yield new Promise((o=>x(this,void 0,void 0,(function*(){const n=this.createSchemeLink(e),s=e=>{const r=(()=>{try{return JSON.parse(e)}catch(t){return e}})();t(1===r||0!==r&&r),i[0]=()=>{const e=N[n];if(!e)return;const t=e.queue.findIndex((e=>e.callback===s));-1!==t&&e.queue.splice(t,1)},o(i)},r=JSON.stringify({actionUrl:n,functionName:W(n,s,!1)});this.hybridBridge.callAndListen(r)})))):(i[0]=!1,i[1]=n,i)}))}}var j;!function(e){e.callAndBackfeed="callAndBack",e.callAndListen="callAndListen"}(j||(j={}));const U=window;class D{constructor(){this.checkBridgeReady()}checkBridgeReady(e=6e3){if(this.worker)return!0;const t=performance.now();return new Promise(((i,o)=>{const n=()=>{if(this.worker)return i(!0);if(U.webkit&&U.webkit.messageHandlers&&U.webkit.messageHandlers.realsee){const e=U.webkit.messageHandlers.realsee;e.postMessage(JSON.stringify({type:"getStaticData",param:JSON.stringify({functionName:W("HYBRID_BRIDGE_NAME",(t=>(this.deviceInfo=JSON.parse(t),this.worker=e,i(!0))))})}))}else{if(performance.now()-t>(e||6e3))return o(new Error("HybridBridge 初始化超时~"));requestAnimationFrame(n)}};n()}))}checkReady(e=6e3){return x(this,void 0,void 0,(function*(){const t=[null,null];if(this.worker)return t[0]=!0,t;try{t[0]=yield this.checkBridgeReady(e)}catch(e){t[0]=!1,t[1]=e}return t}))}get ready(){return!!this.worker}get scheme(){var e;return(null===(e=this.deviceInfo)||void 0===e?void 0:e.scheme)||""}createSchemeLink(e){return e.startsWith(this.scheme)?e:this.scheme+"://"+e}callAndBackfeed(e){return x(this,void 0,void 0,(function*(){const t=[!1,null],[i,o]=yield this.checkReady();return i?yield new Promise((i=>x(this,void 0,void 0,(function*(){const o=this.createSchemeLink(e),n=JSON.stringify({actionUrl:o,functionName:W(this.createSchemeLink(e),(e=>{const o=(()=>{try{return JSON.parse(e)}catch(t){return e}})();t[0]=1===o||0!==o&&o,i(t)}))});this.worker.postMessage(JSON.stringify({type:"callAndBackfeed",param:n}))})))):(t[0]=!1,t[1]=o,t)}))}callAndListen(e,t){return x(this,void 0,void 0,(function*(){const i=[!1,null],[o,n]=yield this.checkReady();return o?yield new Promise((o=>x(this,void 0,void 0,(function*(){const n=this.createSchemeLink(e),s=e=>{const r=(()=>{try{return JSON.parse(e)}catch(t){return e}})();t(1===r||0!==r&&r),i[0]=()=>{const e=N[n];if(!e)return;const t=e.queue.findIndex((e=>e.callback===s));-1!==t&&e.queue.splice(t,1)},o(i)},r=JSON.stringify({actionUrl:n,functionName:W(n,s,!1)});this.worker.postMessage(JSON.stringify({type:"callAndListen",param:r}))})))):(i[0]=!1,i[1]=n,i)}))}}function $(){return(65536*(1+Math.random())|0).toString(16).substring(1)}function H(){return($()+$()+"-"+$()+"-4"+$().substr(0,3)+"-"+$()+"-"+$()+$()+$()).toLowerCase()}var J;!function(e){e.isReady="Are You OK?",e.ready="I`m OK!",e.ping="ping",e.pong="pong",e.alive="I`m alive!"}(J||(J={}));var q="wss://ws.realsee.com";var F=(e,t)=>{const i=Object.keys(t).reduce(((e,i)=>e.replace(`{{${i}}}`,`${t[i]}`)),e);return encodeURI(i)};var K=(e,t)=>e in t;var G=(e="")=>e.replace("?","").split("&").map((e=>{const[t,i]=e.split("=");return{[t]:decodeURIComponent(i)}})).reduce(((e,t)=>Object.assign(Object.assign({},e),t)),{});const z="$$REALSEE_JSBRIDGE_EVENT$$";function Y(e){return e[z]||(e[z]={}),e[z]}class Z{hasListener(e){const t=Y(this);return t&&t[e]&&t[e].length>0}on(e,t,i){const o=Y(this);return o[e]||(o[e]=[]),o[e].push([t,i||!1]),()=>this.off(e,t)}once(e,t){return this.on(e,t,!0)}off(e,t){if(void 0===e)return void((i=this)[z]||delete i[z]);var i;const o=Y(this);if(o[e]||(o[e]=[]),void 0===t)return void(o[e].length=0);let n=0;for(;n<o[e].length&&o[e][n][0]!==t;n++);n<o[e].length&&o[e].splice(n,1)}emit(e,...t){let i=!1;const o=Y(this)[e]||[];for(const n of o.slice()){const[o,s=!1]=n,r=o(...t);s&&this.off(e,o),!1===r&&(i=!0)}return i}}class X extends Z{get attempts(){return this._attempts}constructor(e){super(),this._options={timeout:1e4,shouldReconnect:(e,t)=>{if(1008!==e.code&&1011!==e.code)return[0,3e3,1e4][t.attempts]},should1000Reconnect:!1,ignoreConnectivityEvents:!1,automaticOpen:!1},this._attempts=0,this._reconnects=-1,this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!1,this._connectivityEventsAttached=!1,this._clearPendingReconnectIfNeeded=()=>{this._pendingReconnect&&(clearTimeout(this._pendingReconnect),this._pendingReconnect=void 0)},this._online=e=>{this._reconnectWhenOnlineAgain&&(this._clearPendingReconnectIfNeeded(),this._reconnect(e))},this._offline=()=>{var e;this._reconnectWhenOnlineAgain=!0,null===(e=this._realWebSocket)||void 0===e||e.close(1e3)},this._detachConnectivityEvents=()=>{this._connectivityEventsAttached&&(null===globalThis||void 0===globalThis||globalThis.removeEventListener("online",this._online),null===globalThis||void 0===globalThis||globalThis.removeEventListener("offline",this._offline),this._connectivityEventsAttached=!1)},this._attachConnectivityEvents=()=>{this._connectivityEventsAttached||(null===globalThis||void 0===globalThis||globalThis.addEventListener("online",this._online),null===globalThis||void 0===globalThis||globalThis.addEventListener("offline",this._offline),this._connectivityEventsAttached=!0)},this.send=e=>{var t,i,o;(null===(t=this._realWebSocket)||void 0===t?void 0:t.readyState)===(null===(i=this._realWebSocket)||void 0===i?void 0:i.OPEN)&&(null===(o=this._realWebSocket)||void 0===o||o.send(e))},this.close=(e,t)=>{var i;return"number"!=typeof e&&(t=e,e=1e3),this._clearPendingReconnectIfNeeded(),this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!0,this._detachConnectivityEvents(),null===(i=this._realWebSocket)||void 0===i?void 0:i.close(e,t)},this.open=e=>{var t,i;e&&(this._url=e),(null===(t=this._realWebSocket)||void 0===t?void 0:t.readyState)!==WebSocket.OPEN&&(null===(i=this._realWebSocket)||void 0===i?void 0:i.readyState)!==WebSocket.CONNECTING&&(this._clearPendingReconnectIfNeeded(),this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!1,this._createWebSocket())},this._createWebSocket=()=>{var e,t,i;const o="string"==typeof this._url?this._url:null===(e=this._url)||void 0===e?void 0:e.call(this,this);if(!o)return;this._pendingReconnect=void 0,this._removeWebSocketEvent(),this._realWebSocket=new WebSocket(o,this._protocols||void 0),this._attempts=this._attempts+1,this.emit("connecting",new CustomEvent("connecting",{detail:{attempts:this._attempts,reconnects:this._reconnects}}));this._connectTimeout=setTimeout((()=>{this._connectTimeout=void 0,this._detachConnectivityEvents(),this.emit("timeout",new CustomEvent("connecting",{detail:{attempts:this._attempts,reconnects:this._reconnects}}))}),null===(t=this._options)||void 0===t?void 0:t.timeout),this._dispatchWebSocketEvent(),(null===(i=this._options)||void 0===i?void 0:i.ignoreConnectivityEvents)||this._attachConnectivityEvents()},this._removeWebSocketEvent=()=>{var e,t,i,o;null===(e=this._realWebSocket)||void 0===e||e.removeEventListener("open",this._webSocketOpenHandler),null===(t=this._realWebSocket)||void 0===t||t.removeEventListener("close",this._webSocketCloseHandler),null===(i=this._realWebSocket)||void 0===i||i.removeEventListener("error",this._webSocketErrorHandler),null===(o=this._realWebSocket)||void 0===o||o.removeEventListener("message",this._webSocketMessageHandler)},this._dispatchWebSocketEvent=()=>{var e,t,i,o;null===(e=this._realWebSocket)||void 0===e||e.addEventListener("open",this._webSocketOpenHandler),null===(t=this._realWebSocket)||void 0===t||t.addEventListener("close",this._webSocketCloseHandler),null===(i=this._realWebSocket)||void 0===i||i.addEventListener("error",this._webSocketErrorHandler),null===(o=this._realWebSocket)||void 0===o||o.addEventListener("message",this._webSocketMessageHandler)},this._webSocketOpenHandler=e=>{this._connectTimeout&&(clearTimeout(this._connectTimeout),this._connectTimeout=void 0);const t=++this._reconnects,i=this._attempts;return this._attempts=0,this._reconnectWhenOnlineAgain=!1,this.emit("open",Object.assign(e,{detail:{reconnects:t,attempts:i}}))},this._webSocketCloseHandler=e=>(this._reconnect(e),this.emit("close",e)),this._webSocketErrorHandler=e=>this.emit("error",new CustomEvent("error",{detail:{error:e}})),this._webSocketMessageHandler=e=>this.emit("message",e),e&&this.setOptions(e)}setOptions(e){if(!e)return;this._url=e.url,this._protocols=e.protocols;const t=Object.assign(this._options,e.robustOptions||{});if("number"!=typeof(null==t?void 0:t.timeout))throw new Error("timeout must be the number of milliseconds to timeout a connection attempt");if("function"!=typeof(null==t?void 0:t.shouldReconnect))throw new Error("shouldReconnect must be a function that returns the number of milliseconds to wait for a reconnect attempt, or null or undefined to not reconnect.");this._options=t,this._options.automaticOpen&&this._createWebSocket()}_reconnect(e){var t,i,o,n;if(!(null===(t=this._options)||void 0===t?void 0:t.should1000Reconnect)&&1e3===e.code||this._explicitlyClosed)return void(this._attempts=0);if(!1===(null===(i=null===globalThis||void 0===globalThis?void 0:globalThis.navigator)||void 0===i?void 0:i.onLine))return void(this._reconnectWhenOnlineAgain=!0);const s=null===(n=null===(o=this._options)||void 0===o?void 0:o.shouldReconnect)||void 0===n?void 0:n.call(o,e,this);"number"==typeof s&&(this._pendingReconnect=setTimeout(this._createWebSocket,s))}}class Q{get isReady(){return"open"===this._readyState}constructor(){var e,t;if(this._rsWeappBridgeMethodAdapter={},this._ws=new X,this._readyState="close",this.initialize=(e=6e3)=>x(this,void 0,void 0,(function*(){const t=[!1,null],{wssid:i,wstsp:o,wssig:n,wsmnt:s=q}=G(globalThis.location.search);if(!(i&&o&&n&&s))return t[1]=new Error("HybridBridge 参数缺失,初始化失败~"),t;const r=F("{{origin}}/{{endpoint}}/{{uuid}}/{{member}}/{{ak}}/{{ts}}/{{sign}}",{origin:s,endpoint:"proxy",uuid:i,member:"webview",ak:"vr_live_miniapp",ts:o,sign:n});try{(yield this._open(r))?(this.initBuiltInHandlers(),t[0]=yield this.waitReady(e)):t[1]=new Error("HybridBridge ws未连接,初始化失败~")}catch(e){t[1]=e}return t})),this.initBuiltInHandlers=()=>{this._registerLifecycleHandler(),this._registerHeartbeatHandler(),this._registerMessageHandler(),this._registerBridgeRequestHandler(),this._registerReadyHandler()},this._open=e=>new Promise((t=>{this._ws.once("open",(()=>{this._receivedMessage(J.ready,(()=>t(!0)),!0),this._ws.once("timeout",(()=>t(!1))),this.send(J.isReady)})),this._ws.open(e)})),this._registerLifecycleHandler=()=>{this._ws.on("connecting",(()=>{console.log("RsWeappBridge connecting"),this._readyState="connecting"})),this._ws.on("open",(()=>{console.log("RsWeappBridge open"),this._readyState="open"})),this._ws.on("close",(()=>{this._readyState="close"})),this._ws.on("error",(()=>{console.log("RsWeappBridge error"),this._readyState="close"})),this._ws.on("timeout",(()=>{console.log("RsWeappBridge timeout"),this._readyState="close"}))},this._registerHeartbeatHandler=()=>{this._receivedMessage(J.ping,(()=>setTimeout((()=>this._ws.send(J.pong)),500))),this._receivedMessage(J.pong,(()=>setTimeout((()=>this._ws.send(J.ping)),1e3)))},this._receivedMessage=(e,t,i)=>{const o=n=>{n.data===e&&(t(),i&&this._ws.off("message",o))};this._ws.on("message",o)},this._registerReadyHandler=()=>{this._receivedMessage(J.isReady,(()=>this._ws.send(J.ready)))},this.send=e=>{this._ws.send(e)},this.waitReady=(e=6e3)=>new Promise(((t,i)=>{this._receivedMessage(J.ready,(()=>t(!0))),this.send(J.isReady),setTimeout((()=>i("HybridBridge 初始化超时~")),e)})),this._parseMessage=e=>{try{return JSON.parse(e.data)}catch(t){return e.data}},this._registerMessageHandler=()=>{this._ws.on("message",(e=>{const t=this._parseMessage(e);if("object"==typeof t){const{id:e,command:i,data:o}=t;"message"===i&&"function"==typeof this._rsWeappBridgeMethodAdapter.bindMessage&&this._rsWeappBridgeMethodAdapter.bindMessage({id:e,data:o})}}))},this.getStaticData=e=>{this.callAndBackfeed(JSON.stringify({actionUrl:"common/staticData",functionName:e}))},this.callAndBackfeed=e=>{const{actionUrl:t="",functionName:i=""}=JSON.parse(e);if(!t)throw new Error("callAndBackfeed actionUrl is empty!");if(!i)throw new Error("callAndBackfeed functionName is empty!");this._callAndBackfeed(t,(e=>{"function"==typeof globalThis[i]&&globalThis[i](e)}))},this.callAndListen=e=>{const{actionUrl:t,functionName:i}=JSON.parse(e);if(!t)throw new Error("callAndListen actionUrl is empty!");if(!i)throw new Error("callAndListen functionName is empty!");const o=e=>{"function"==typeof globalThis[i]&&globalThis[i](e)};try{this._callAndListen(t,o)}catch(e){console.warn(e),o(!1)}},this.execute=(e,t)=>x(this,void 0,void 0,(function*(){return yield this._invokeBridgeMethod(e,t)})),this._invokeBridgeMethod=(e,t)=>new Promise(((i,o)=>{const n=H(),s=t=>{const r=this._parseMessage(t);"object"==typeof r&&r.method===e&&r.id===n&&(this._ws.off("message",s),r.error?o(r.error):i(r.data))};this._ws.on("message",s),this.send(JSON.stringify({method:e,args:t,id:n}))})),(null===(e=null===globalThis||void 0===globalThis?void 0:globalThis.window)||void 0===e?void 0:e.__Realsee_WxMini_HybridBridge__)instanceof Q)return null===(t=null===globalThis||void 0===globalThis?void 0:globalThis.window)||void 0===t?void 0:t.__Realsee_WxMini_HybridBridge__;(null===globalThis||void 0===globalThis?void 0:globalThis.window)&&(globalThis.window.__Realsee_WxMini_HybridBridge__=this,this.initBuiltInHandlers())}_registerBridgeRequestHandler(){this._ws.on("message",(e=>x(this,void 0,void 0,(function*(){const t=this._parseMessage(e);if("object"==typeof t){const{id:e,method:i,args:o,command:n}=t;if("request"===n&&i){let t=null,n=null,s=null;if("function"==typeof this._rsWeappBridgeMethodAdapter[i]?s=this._rsWeappBridgeMethodAdapter[i]:globalThis&&K(i,globalThis)&&(s=globalThis[i]),"function"==typeof s)try{t=yield s(o)}catch(e){n=e.message||e}else n="Method not implemented.";this.send(JSON.stringify({id:e,method:i,result:t,error:n,command:"response"}))}}}))))}_callAndBackfeed(e,t){const i=H(),o=JSON.stringify({id:i,actionUrl:e,command:"rsSchemeRequest",type:"callAndBackfeed"});let n=null;const s=e=>{const o=this._parseMessage(e);if("object"==typeof o){const{id:e,result:r,errmsg:c,command:a}=o;"rsSchemeResponse"===a&&e===i&&(this._ws.off("message",s),n&&clearTimeout(n),c?(console.warn(c),t(0)):t(r))}};this._ws.on("message",s),this.send(o),n=globalThis.setTimeout((()=>{console.warn("callAndBackfeed timeout"),t(0)}),3e4)}_callAndListen(e,t){const i=H(),o=JSON.stringify({id:i,actionUrl:e,command:"rsSchemeRequest",type:"callAndListen"});this._ws.on("message",(e=>{const o=this._parseMessage(e);if("object"==typeof o){const{id:e,result:n,errmsg:s,command:r}=o;"rsSchemeResponse"===r&&e===i&&(s?(console.warn(s),t(!1)):t(n))}})),this.send(o)}invoke(e,t){return x(this,void 0,void 0,(function*(){return new Promise(((i,o)=>{const n=H(),s=JSON.stringify({id:n,method:e,args:t,command:"request"});let r=null;const c=t=>{const s=this._parseMessage(t);if("object"==typeof s){const{id:t,result:a,error:l,command:d}=s;"response"===d&&t===n&&s.method===e&&(this._ws.off("message",c),r&&clearTimeout(r),l?o(l):i(a))}};this._ws.on("message",c),this.send(s),r=setTimeout((()=>o("method invoke timeout")),3e4)}))}))}}class ee extends M{constructor(){super(...arguments),this._hybridBridge=new Q,this.initializing=!1}get hybridBridge(){return this._hybridBridge}checkBridgeReady(e=6e4){return!!this.ready||new Promise(((t,i)=>x(this,void 0,void 0,(function*(){if(this.ready)return t(!0);if(!this.initializing){this.initializing=!0;const[i,o]=yield this._hybridBridge.initialize(e);if(!i||o)throw o||new Error("HybridBridge 初始化失败~");return this._hybridBridge.getStaticData(W("HYBRID_BRIDGE_NAME",(e=>{this.deviceInfo=(()=>{try{return JSON.parse(e)}catch(t){return e}})()}))),this.initializing=!1,t(!0)}{const e=()=>{if(this.ready)return t(!0);requestAnimationFrame(e)};e()}}))))}checkReady(e=6e4){return x(this,void 0,void 0,(function*(){const t=[null,null];if(this.ready)return t[0]=!0,t;try{t[0]=yield this.checkBridgeReady(e)}catch(e){t[0]=!1,t[1]=e}return t}))}get ready(){return!!this._hybridBridge.isReady}get scheme(){var e;return(null===(e=this.deviceInfo)||void 0===e?void 0:e.scheme)||""}createSchemeLink(e){return e.startsWith(this.scheme)?e:this.scheme+"://"+e}callAndBackfeed(e){return x(this,void 0,void 0,(function*(){const t=[!1,null],[i,o]=yield this.checkReady();return i?yield new Promise((i=>x(this,void 0,void 0,(function*(){const o=this.createSchemeLink(e),n=JSON.stringify({actionUrl:o,functionName:W(this.createSchemeLink(e),(e=>{let o=e;try{o=JSON.parse(e)}catch(e){}t[0]=1===o||0!==o&&o,i(t)}))});this._hybridBridge.callAndBackfeed(n)})))):(t[0]=!1,t[1]=o,t)}))}callAndListen(e,t){return x(this,void 0,void 0,(function*(){const i=[!1,null],[o,n]=yield this.checkReady();return o?yield new Promise((o=>x(this,void 0,void 0,(function*(){const n=this.createSchemeLink(e),s=e=>{let r=e;try{r=JSON.parse(e)}catch(e){}t(1===r||0!==r&&r),i[0]=()=>{const e=N[n];if(!e)return;const t=e.queue.findIndex((e=>e.callback===s));-1!==t&&e.queue.splice(t,1)},o(i)},r=JSON.stringify({actionUrl:n,functionName:W(n,s,!1)});this._hybridBridge.callAndListen(r)})))):(i[0]=!1,i[1]=n,i)}))}invoke(e,t){var i,o;return x(this,void 0,void 0,(function*(){const[n,s]=yield this.checkReady();if(n)return yield null===(o=(i=this._hybridBridge).invoke)||void 0===o?void 0:o.call(i,e,t);throw s}))}}var te;!function(e){e.WebView="WebKit",e.WKWebview="WKWebview",e.UIWebview="UIWebview",e.Browser="Browser",e.WeChatMPWebView="WxMiniProgramWebView",e.Unsupported="Unsupported"}(te||(te={}));class ie extends Z{constructor(){super(...arguments),this.webViewType=te.Unsupported}}const oe=globalThis.navigator.userAgent,ne=/android/gi.test(oe),se=/iPhone|iPad\s+OS/gi.test(oe),re=/MicroMessenger/gi.test(oe)&&/miniProgram/gi.test(oe),ce=/realsee/gi.test(oe),ae={timeout:6e3};class le extends ie{constructor(e={}){super(),this.options=Object.assign(ae,e),ce||console.warn("未知容器:此版本 `jsBridge` 不支持当前 WebView 容器 ... "),this.webViewType=ne?te.WebView:se?te.WKWebview:te.Browser,this._controller=ne?new V:se?new D:new M,this.callAndListen("common/webViewState",(e=>{this.emit("webViewStateChange",e)})),this.callAndListen("common/webViewError",(e=>{this.emit("error",e)}))}ready(){return x(this,void 0,void 0,(function*(){return yield this._controller.checkReady(this.options.timeout)}))}callAndBackfeed(e){return x(this,void 0,void 0,(function*(){return yield this._controller.callAndBackfeed(e)}))}callAndListen(e,t){var i;return x(this,void 0,void 0,(function*(){return yield null===(i=this._controller)||void 0===i?void 0:i.callAndListen(e,t)}))}setLeftTopBackButton(e){return x(this,void 0,void 0,(function*(){return this.webViewType===te.WebView?[!0,null]:yield this.callAndBackfeed("common/setLeftTopBackButton?enable="+(e?1:0))}))}getBangsHeight(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/getBangsHeight")}))}shock(e=4){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed(`common/shock?duration=${e}`)}))}minimize(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/minimize")}))}loadProgress(e){return x(this,void 0,void 0,(function*(){return e=e<0?0:e>100?100:e,yield this.callAndBackfeed(`common/loadProgress?progress=${e}`)}))}closeLoading(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/closeLoading")}))}setOrientation(e){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed(`common/setOrientation?orientation=${e}`)}))}keepScreenLight(e){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/keepScreenLight?enable="+(e?1:0))}))}closeWebView(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/closeWebView")}))}openWebView(e,t){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed(`common/openWebView?way=${t}&url=${encodeURIComponent(e)}`)}))}saveImage2Album(e){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed(`common/saveImage2Album?base64=${e}`)}))}actionShare(e){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed(`common/actionShare?json=${JSON.stringify(e)}`)}))}getDeviceInfo(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/getDeviceInfo")}))}getUserInfo(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/getUserInfo")}))}getWebViewState(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/getWebViewState")}))}login(){return x(this,void 0,void 0,(function*(){const e=yield this.callAndBackfeed("common/login");return e[0]?yield this.getUserInfo():e}))}logout(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/logout")}))}detectMicro(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/detectMicro")}))}preload(e){return x(this,void 0,void 0,(function*(){return e=e.map((e=>e.startsWith("//")?"https:"+e:e)),yield this.callAndBackfeed(`common/preload?urls=${JSON.stringify(e)}`)}))}createCacheProxyUrl(e){e=Array.isArray(e)?e:[e];const t=window.navigator.userAgent;if(!/supportCache/i.test(t))return e;return e.map((e=>this.webViewType===te.WKWebview?e.replace(/https*:/,"").replace(/\/\//,"realseeproxycache://"):this.webViewType===te.WebView?e+(-1!==e.indexOf("?")?"&":"?")+"realseeproxycache=1":e))}}var de;!function(e){e.Append="Append",e.Replace="Replace",e.Single="Single"}(de||(de={}));class he extends ie{constructor(){super(...arguments),this.webViewType=te.Browser}ready(){return Promise.resolve([!0,null])}callAndBackfeed(e){return Promise.resolve([!1,null])}callAndListen(e,t){return Promise.resolve([()=>{},null])}loadProgress(e){return Promise.resolve([!0,null])}closeLoading(){return Promise.resolve([!0,null])}getDeviceInfo(){return Promise.resolve([!1,null])}getWebViewState(){return Promise.resolve([!1,null])}setLeftTopBackButton(e){return Promise.resolve([!1,null])}login(){return Promise.resolve([!1,null])}logout(){return Promise.resolve([!1,null])}getUserInfo(){return Promise.resolve([!1,null])}openWebView(e,t){switch(t){case de.Replace:case de.Single:setTimeout((()=>globalThis.location.replace(e)),200);break;case de.Append:default:setTimeout((()=>globalThis.location.href=e),200)}return Promise.resolve([!0,null])}closeWebView(){return globalThis.close(),Promise.resolve([!0,null])}getBangsHeight(){return Promise.resolve([0,null])}setOrientation(e){return Promise.resolve([!1,null])}keepScreenLight(e){return Promise.resolve([!1,null])}shock(e){return Promise.resolve([!1,null])}minimize(){return Promise.resolve([!1,null])}saveImage2Album(e){return Promise.resolve([!1,null])}detectMicro(){return new Promise((e=>{const t={audio:!0,video:!1};try{globalThis.navigator.mediaDevices.getUserMedia(t).then((()=>e([!0,null]))).catch((t=>e([!1,t])))}catch(t){console.error(t),e([!1,t])}}))}actionShare(e){return Promise.resolve([!1,null])}preload(e){return Promise.resolve([!1,null])}createCacheProxyUrl(e){return[]}}const ue={timeout:6e4};class ve extends ie{constructor(e={}){super(),this._controller=new ee,this.options=Object.assign(ue,e),re||console.warn("未知容器:此版本 `jsBridge` 不支持当前 WebView 容器 ... "),this.webViewType=te.WeChatMPWebView,this.callAndListen("common/webViewState",(e=>{this.emit("webViewStateChange",e)})),this.callAndListen("common/webViewError",(e=>{this.emit("error",e)}))}ready(){return x(this,void 0,void 0,(function*(){return yield this._controller.checkReady(this.options.timeout)}))}callAndBackfeed(e){return x(this,void 0,void 0,(function*(){return yield this._controller.callAndBackfeed(e)}))}callAndListen(e,t){return x(this,void 0,void 0,(function*(){return yield this._controller.callAndListen(e,t)}))}setLeftTopBackButton(e){return x(this,void 0,void 0,(function*(){return this.webViewType===te.WebView?[!0,null]:yield this.callAndBackfeed("common/setLeftTopBackButton?enable="+(e?1:0))}))}getBangsHeight(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/getBangsHeight")}))}shock(e=4){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed(`common/shock?duration=${e}`)}))}minimize(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/minimize")}))}loadProgress(e){return x(this,void 0,void 0,(function*(){return e=e<0?0:e>100?100:e,yield this.callAndBackfeed(`common/loadProgress?progress=${e}`)}))}closeLoading(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/closeLoading")}))}setOrientation(e){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed(`common/setOrientation?orientation=${e}`)}))}keepScreenLight(e){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/keepScreenLight?enable="+(e?1:0))}))}closeWebView(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/closeWebView")}))}openWebView(e,t){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed(`common/openWebView?way=${t}&url=${encodeURIComponent(e)}`)}))}saveImage2Album(e){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed(`common/saveImage2Album?base64=${e}`)}))}actionShare(e){var t,i,o;return x(this,void 0,void 0,(function*(){const n={path:null===(t=e.miniprogram)||void 0===t?void 0:t[0].path,title:null===(i=e.miniprogram)||void 0===i?void 0:i[0].title,imageUrl:null===(o=e.miniprogram)||void 0===o?void 0:o[0].hdImageData};return yield this.callAndBackfeed(`common/actionShare?json=${JSON.stringify(n)}`)}))}getDeviceInfo(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/getDeviceInfo")}))}getUserInfo(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/getUserInfo")}))}getWebViewState(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/getWebViewState")}))}login(){return x(this,void 0,void 0,(function*(){const e=yield this.callAndBackfeed("common/login");return e[0]?yield this.getUserInfo():e}))}logout(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/logout")}))}detectMicro(){return x(this,void 0,void 0,(function*(){return yield this.callAndBackfeed("common/detectMicro")}))}preload(e){return x(this,void 0,void 0,(function*(){return e=e.map((e=>e.startsWith("//")?"https:"+e:e)),yield this.callAndBackfeed(`common/preload?urls=${JSON.stringify(e)}`)}))}createCacheProxyUrl(e){e=Array.isArray(e)?e:[e];const t=window.navigator.userAgent;if(!/supportCache/i.test(t))return e;return e.map((e=>this.webViewType===te.WKWebview?e.replace(/https*:/,"").replace(/\/\//,"realseeproxycache://"):this.webViewType===te.WebView?e+(-1!==e.indexOf("?")?"&":"?")+"realseeproxycache=1":e))}invokeNativeApi(e,t){return x(this,void 0,void 0,(function*(){return yield this._controller.invoke(e,t)}))}execute(e,t){var i,o,n;return x(this,void 0,void 0,(function*(){return yield null===(n=null===(o=null===(i=this._controller)||void 0===i?void 0:i.hybridBridge)||void 0===o?void 0:o.execute)||void 0===n?void 0:n.call(o,e,t)}))}}class me extends ie{constructor(e={}){return super(),ce&&(ne||se)?new le(e):re?new ve(e):new he}}function ge(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var fe,pe,_e=(fe=function(e,t){var i;Object.defineProperty(t,"__esModule",{value:!0}),t.LogLevel=void 0,function(e){e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e[e.OFF=4]="OFF"}(i=t.LogLevel||(t.LogLevel={})),t.default=i},fe(pe={exports:{}},pe.exports),pe.exports),ye=ge(_e);const be=globalThis.navigator.userAgent,Se=/android/gi.test(be),we=/iPhone|iPad\s+OS/gi.test(be),ke=/MicroMessenger/gi.test(be)&&/miniProgram/gi.test(be),Ee=/realsee/gi.test(be);function Ce(e){return"[object Object]"===Object.prototype.toString.call(e)}function Te(e,t){return e===t||typeof e==typeof t&&!(!Number.isNaN(e)||!Number.isNaN(t))}function Ie(e,t){return!!Te(e,t)||(Ce(e)&&Ce(t)?function(e,t){const i=Object.getOwnPropertyNames(e),o=Object.getOwnPropertyNames(t);if(i.length!==o.length)return!1;for(let o=0,n=i.length;o<n;o++){const n=i[o];if(!Te(e[n],t[n]))return!1}return!0}(e,t):!(!Array.isArray(e)||!Array.isArray(t))&&function(e,t){if(e.length!==t.length)return!1;for(let i=0,o=e.length;i<o;i++)if(!Te(e[i],t[i]))return!1;return!0}(e,t))}function Re(e,t){return!!Te(e,t)||(Ce(e)&&Ce(t)?function(e,t){const i=Object.getOwnPropertyNames(e),o=Object.getOwnPropertyNames(t);if(i.length!==o.length)return!1;for(let o=0,n=i.length;o<n;o++){const n=i[o];if(!Re(e[n],t[n]))return!1}return!0}(e,t):!(!Array.isArray(e)||!Array.isArray(t))&&function(e,t){if(e.length!==t.length)return!1;for(let i=0,o=e.length;i<o;i++)if(!Re(e[i],t[i]))return!1;return!0}(e,t))}function Oe(e,t,i={deep:!1}){return i.deep?Re(e,t):Ie(e,t)}class Be extends a{get attempts(){return this._attempts}constructor(e){super(),this._readyState=exports.WebSocketState.NOTINITIALIZED,this._options={timeout:1e4,shouldReconnect:(e,t)=>{if(1008!==e.code&&1011!==e.code)return[0,3e3,1e4][t.attempts]},should1000Reconnect:!1,ignoreConnectivityEvents:!1,automaticOpen:!1},this._attempts=0,this._reconnects=-1,this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!1,this._connectivityEventsAttached=!1,this._healthCheck=()=>d(this,void 0,void 0,(function*(){this._realWebSocket&&this._realWebSocket.readyState!==this._readyState&&(this._readyState=this._realWebSocket.readyState,this._readyState===exports.WebSocketState.CLOSING&&this.emit("closing")),yield new Promise((e=>setTimeout(e,2e3))),this._heathCheckTimer=requestAnimationFrame(this._healthCheck)})),this._clearHeathCheckIfNeed=()=>{this._heathCheckTimer&&(cancelAnimationFrame(this._heathCheckTimer),this._heathCheckTimer=void 0)},this._startHealthCheck=()=>{this._clearHeathCheckIfNeed(),this._heathCheckTimer=requestAnimationFrame(this._healthCheck)},this._stopHealthCheck=()=>{this._clearHeathCheckIfNeed()},this._clearPendingReconnectIfNeeded=()=>{this._pendingReconnect&&(clearTimeout(this._pendingReconnect),this._pendingReconnect=void 0)},this._online=e=>{this._reconnectWhenOnlineAgain&&(this._clearPendingReconnectIfNeeded(),this._reconnect(e))},this._offline=()=>{var e;this._reconnectWhenOnlineAgain=!0,null===(e=this._realWebSocket)||void 0===e||e.close(1e3,"offline")},this._detachConnectivityEvents=()=>{this._connectivityEventsAttached&&(null===globalThis||void 0===globalThis||globalThis.removeEventListener("online",this._online),null===globalThis||void 0===globalThis||globalThis.removeEventListener("offline",this._offline),this._connectivityEventsAttached=!1)},this._attachConnectivityEvents=()=>{this._connectivityEventsAttached||(null===globalThis||void 0===globalThis||globalThis.addEventListener("online",this._online),null===globalThis||void 0===globalThis||globalThis.addEventListener("offline",this._offline),this._connectivityEventsAttached=!0)},this.send=e=>{var t,i,o;(null===(t=this._realWebSocket)||void 0===t?void 0:t.readyState)===(null===(i=this._realWebSocket)||void 0===i?void 0:i.OPEN)&&(null===(o=this._realWebSocket)||void 0===o||o.send(e))},this.close=(e,t)=>{var i;return"number"!=typeof e&&(t=e,e=1e3),this._clearPendingReconnectIfNeeded(),this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!0,this._detachConnectivityEvents(),null===(i=this._realWebSocket)||void 0===i?void 0:i.close(e,t)},this.open=e=>{var t,i;e&&(this._url=e),(null===(t=this._realWebSocket)||void 0===t?void 0:t.readyState)!==WebSocket.OPEN&&(null===(i=this._realWebSocket)||void 0===i?void 0:i.readyState)!==WebSocket.CONNECTING&&(this._clearPendingReconnectIfNeeded(),this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!1,this._createWebSocket())},this._createWebSocket=()=>{var e,t,i;const o="string"==typeof this._url?this._url:null===(e=this._url)||void 0===e?void 0:e.call(this,this);if(!o)return;this._pendingReconnect=void 0,this._removeWebSocketEvent(),this._realWebSocket=new WebSocket(o,this._protocols||void 0),this._attempts=this._attempts+1,this.emit("connecting",new CustomEvent("connecting",{detail:{attempts:this._attempts,reconnects:this._reconnects}}));this._connectTimeout=setTimeout((()=>{this._connectTimeout=void 0,this._detachConnectivityEvents(),this.emit("timeout",new CustomEvent("connecting",{detail:{attempts:this._attempts,reconnects:this._reconnects}}))}),null===(t=this._options)||void 0===t?void 0:t.timeout),this._dispatchWebSocketEvent(),(null===(i=this._options)||void 0===i?void 0:i.ignoreConnectivityEvents)||this._attachConnectivityEvents()},this._removeWebSocketEvent=()=>{var e,t,i,o;null===(e=this._realWebSocket)||void 0===e||e.removeEventListener("open",this._webSocketOpenHandler),null===(t=this._realWebSocket)||void 0===t||t.removeEventListener("close",this._webSocketCloseHandler),null===(i=this._realWebSocket)||void 0===i||i.removeEventListener("error",this._webSocketErrorHandler),null===(o=this._realWebSocket)||void 0===o||o.removeEventListener("message",this._webSocketMessageHandler)},this._dispatchWebSocketEvent=()=>{var e,t,i,o;null===(e=this._realWebSocket)||void 0===e||e.addEventListener("open",this._webSocketOpenHandler),null===(t=this._realWebSocket)||void 0===t||t.addEventListener("close",this._webSocketCloseHandler),null===(i=this._realWebSocket)||void 0===i||i.addEventListener("error",this._webSocketErrorHandler),null===(o=this._realWebSocket)||void 0===o||o.addEventListener("message",this._webSocketMessageHandler)},this._webSocketOpenHandler=e=>{this._connectTimeout&&(clearTimeout(this._connectTimeout),this._connectTimeout=void 0);const t=++this._reconnects,i=this._attempts;return this._attempts=0,this._reconnectWhenOnlineAgain=!1,this._startHealthCheck(),this.emit("open",Object.assign(e,{detail:{reconnects:t,attempts:i}}))},this._webSocketCloseHandler=e=>(this._reconnect(e),this._stopHealthCheck(),this.emit("close",e)),this._webSocketErrorHandler=e=>this.emit("error",new CustomEvent("error",{detail:{error:e}})),this._webSocketMessageHandler=e=>this.emit("message",e),e&&this.setOptions(e),this._startHealthCheck()}setOptions(e){if(!e)return;this._url=e.url,this._protocols=e.protocols;const t=Object.assign(this._options,e.robustOptions||{});if("number"!=typeof(null==t?void 0:t.timeout))throw new Error("timeout must be the number of milliseconds to timeout a connection attempt");if("function"!=typeof(null==t?void 0:t.shouldReconnect))throw new Error("shouldReconnect must be a function that returns the number of milliseconds to wait for a reconnect attempt, or null or undefined to not reconnect.");this._options=t,this._options.automaticOpen&&this._createWebSocket()}_reconnect(e){var t,i,o,n;if(!(null===(t=this._options)||void 0===t?void 0:t.should1000Reconnect)&&1e3===e.code||this._explicitlyClosed)return void(this._attempts=0);if(!1===(null===(i=null===globalThis||void 0===globalThis?void 0:globalThis.navigator)||void 0===i?void 0:i.onLine))return void(this._reconnectWhenOnlineAgain=!0);const s=null===(n=null===(o=this._options)||void 0===o?void 0:o.shouldReconnect)||void 0===n?void 0:n.call(o,e,this);"number"==typeof s&&(this._pendingReconnect=setTimeout(this._createWebSocket,s))}}class Ae extends a{set state(e){const t=JSON.parse(JSON.stringify(this._state));this._state=e,this.emit("stateChange",this.state,t)}get state(){return this._state}constructor(){super(),this._ws=new Be({url:"",robustOptions:{timeout:18e4}}),this._state=exports.LiveState.NOTINITIALIZED,this._addWebSocketEventListeners=()=>{this._ws.on("close",this._handleCloseEvent),this._ws.on("closing",this._handleClosingEvent),this._ws.on("connecting",this._handleConnectingEvent),this._ws.on("error",this._handleErrorEvent),this._ws.on("message",this._handleMessageEvent),this._ws.on("open",this._handleOpenEvent),this._ws.on("timeout",this._handleTimeoutEvent)},this._removeWebSocketEventListeners=()=>{this._ws.off("close",this._handleCloseEvent),this._ws.off("closing",this._handleClosingEvent),this._ws.off("connecting",this._handleConnectingEvent),this._ws.off("error",this._handleErrorEvent),this._ws.off("message",this._handleMessageEvent),this._ws.off("open",this._handleOpenEvent),this._ws.off("timeout",this._handleTimeoutEvent)},this._handleCloseEvent=e=>{T.info(`live room closed bacause of ${e.code}-${e.reason||L(e.code)}`),this.state=exports.LiveState.CLOSED},this._handleClosingEvent=()=>{var e;T.info("live room is closing, onLine:",null===(e=null===globalThis||void 0===globalThis?void 0:globalThis.navigator)||void 0===e?void 0:e.onLine),this.state=exports.LiveState.CLOSED},this._handleConnectingEvent=()=>{T.info("live room is connecting"),this.state=exports.LiveState.CONNECTING},this._handleErrorEvent=e=>{T.error("live room error",e),this.state=exports.LiveState.CLOSED},this._handleMessageEvent=e=>{let t=(()=>{try{return JSON.parse(e.data)}catch(t){return e.data}})();this.emit("message",t)},this._handleOpenEvent=e=>{T.info("live room open",e.detail),this.state=exports.LiveState.OPEN,e.detail.reconnects>0&&this.emit("reconnected",e.detail)},this._handleTimeoutEvent=e=>{T.error("live room connect timeout!",e.detail),this.state=exports.LiveState.CLOSED},this.dispose=()=>d(this,void 0,void 0,(function*(){return this._removeWebSocketEventListeners(),yield this.close("live room close by controller disposed!")})),this.open=e=>this._ws.open(e),this.close=(e,t)=>new Promise((i=>{this._ws.once("close",(()=>i(!0))),this._ws.close(e,t)})),this._addWebSocketEventListeners()}sendMessage(e=""){if(null==e||""===e)throw new Error("live message is empty!");if(this.state===exports.LiveState.OPEN)return this._ws.send(JSON.stringify(e));throw new Error("live has not yet been initialized!")}}const Le=e=>Promise.reject("unimplemented method GetVoiceSign"),xe=(e,t={},i=[])=>({command:e,front_request_id:R(),data:Object.assign(Object.assign({},t),{to_user_ids:Array.isArray(i)?i:[i]})});class Ne extends a{get options(){return Object.freeze(this._options||{})}get state(){return this._controller.state}get readyState(){return this._controller.state}get url(){return this.options.url}get $RTC(){return this._options.rtc}get jsBridge(){return this._options.jsBridge}get snapshot(){return this._buildInData.keyframes}get selfInfo(){return this._buildInData.selfInfo}get userList(){return this._buildInData.userList||[]}get roomInfo(){return this._buildInData.roomInfo}constructor(e){var t;super(),this._options={},this.keyframes=new a,this._buildInData={keyframes:{}},this.getFramesByKey=e=>this.snapshot[e],this.sendKeyframe=(e,t)=>{if(this.state!==exports.LiveState.OPEN)return!1;this._buildInData.keyframes=Object.assign(Object.assign({},this._buildInData.keyframes),{[e]:t});const i=xe(exports.Command.KeyframeSync,this.snapshot);try{return this._controller.sendMessage(i),!0}catch(e){return T.error(e),!1}},this._controller=new Ae,this._addLiveControllerEventListeners=()=>{this._controller.on("stateChange",this._handleStateChange),this._controller.on("message",this._handleMessage)},this._removeLiveControllerEventListeners=()=>{this._controller.off("stateChange",this._handleStateChange),this._controller.off("message",this._handleMessage)},this._handleStateChange=(e,t)=>this.emit("stateChange",e,t),this._handleMessage=e=>d(this,void 0,void 0,(function*(){var t,i,o,n,s;if("object"==typeof e){const{command:r,data:c={},frontRequestId:a,code:l,message:d}=e;if("SUCCESS"===l)switch(r){case exports.Command.SelfUserInfo:{const e=c;Oe(this.selfInfo,e,{deep:!0})||(this._buildInData.selfInfo=e,this.emit("selfInfoUpdate",this._buildInData.selfInfo,a));break}case exports.Command.RoomInfo:{const e=c;this._buildInData.roomInfo=Object.assign({},e),this.emit("readyKeyframeSync",e.last_frame||{});break}case exports.Command.RTCInfo:{const{voice_id:e,type:r}=c;if(this._buildInData.rtcInfo={voiceId:e,type:r},null===(t=this.$RTC)||void 0===t?void 0:t.joined)T.warn("已加入语音房间,无需重复加入!");else{if(yield null===(i=this.$RTC)||void 0===i?void 0:i.join({voiceId:e,userId:(null===(o=this.selfInfo)||void 0===o?void 0:o.id)||"",roomId:null===(n=this.roomInfo)||void 0===n?void 0:n.info.room_code,type:r})){const e=null!==(s=this._options.initialMicroStatus)&&void 0!==s?s:exports.MicroStatus.OPEN;yield this.toggleMicro(e===exports.MicroStatus.OPEN)}else T.error("加入语音房间失败")}break}case exports.Command.UserList:{const e=c;this._buildInData.userList=e,this.emit("userListUpdate",this.userList,a);break}case exports.Command.CustomEvent:{const e=c;this.emit("broadcast",e,a);break}case exports.Command.KeyframeSync:{const e=c,t=Object.keys(e).reduce(((t,i)=>{if(Oe(e[i],this._buildInData.keyframes[i],{deep:!0}))return t;const o=[e[i],this._buildInData.keyframes[i],a],n=i;return this.keyframes.emit(n,...o),this._buildInData.keyframes[i]=e[i],t[i]=e[i],t}),{});this.emit("keyframes",t,a);break}case exports.Command.BuiltinMsg:{const e=c;this.emit("builtinEvent",e),e.event_type===exports.BuiltinEventType.UserChange&&this.emit("userChange",e),e.event_type===exports.BuiltinEventType.RoomChange&&this.emit("roomChange",e),e.event_type===exports.BuiltinEventType.UserChange&&e.action===exports.BuiltinActionType.UserMicroStatus&&(yield this.toggleMicro(e.data.status===exports.MicroStatus.OPEN)),e.event_type===exports.BuiltinEventType.RoomChange&&e.action===exports.BuiltinActionType.RoomClose&&(yield this.exit());break}case exports.Command.UserKickOut:this.emit("kickOut");break;default:console.warn("unknown command: ",r)}else this.emit("error",e)}})),this._clearLiveData=()=>{this._buildInData={keyframes:{}}},this.connect=(e={})=>d(this,void 0,void 0,(function*(){var t,i,o,n;if(this._options.url=null!==(i=null!==(t=e.url)&&void 0!==t?t:this._options.url)&&void 0!==i?i:"",this._options.getTicket=null!==(o=e.getTicket)&&void 0!==o?o:this._options.getTicket,this._options.initialMicroStatus=null!==(n=e.rtcMicStatus)&&void 0!==n?n:this._options.initialMicroStatus,!/^ws(s):\/\//.test(this._options.url)||"function"!=typeof this._options.getTicket)return/^ws(s):\/\//.test(this._options.url)?"function"!=typeof this._options.getTicket&&new Error("getTicket muse be function"):new Error("Illegal realsee live room link");const{force:s=!1}=e;if(this._options.rtc){if(!(yield this._options.rtc.detectMicro()))return new Error("Failed to obtain microphone authorization")}const r=this.state;if(r===exports.LiveState.CONNECTING||r===exports.LiveState.OPEN){if(!s)return new Error("已有Live实例正在连接中,请勿重复连接!");try{yield this._controller.close("force close by connect")}catch(e){console.warn(e)}}this._clearLiveData();const c=function(e,t={}){const i=-1!==e.indexOf("?");return e+Object.keys(t).reduce(((e,o,n)=>`${e}${0!==n||i?"&":"?"}${o}=${t[o]}`),"")}(this._options.url,{ticket:yield this._options.getTicket(),force:Number(!!s)});return this._controller.open(c),!0})),this.exit=()=>d(this,void 0,void 0,(function*(){var e;if(this._clearLiveData(),this.state!==exports.LiveState.OPEN)return!0;try{yield null===(e=this.$RTC)||void 0===e?void 0:e.quit()}catch(e){T.warn(e)}return yield this._controller.close()})),this.close=()=>d(this,void 0,void 0,(function*(){var e,t;return(null===(t=null===(e=this.selfInfo)||void 0===e?void 0:e.permission)||void 0===t?void 0:t.close_live_room)?yield this.updateStatus(exports.BuiltinEventType.RoomChange,exports.BuiltinActionType.RoomClose,{}):void 0})),this.dispose=()=>d(this,void 0,void 0,(function*(){return this._removeLiveControllerEventListeners(),this._clearLiveData(),yield this._controller.dispose()})),this.setSelfInfo=e=>d(this,void 0,void 0,(function*(){return yield this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserInfo,e)})),this.toggleMicro=e=>d(this,void 0,void 0,(function*(){var t,i,o;if(!(null===(i=null===(t=this.selfInfo)||void 0===t?void 0:t.permission)||void 0===i?void 0:i.control_own_micro))return!1;const n=yield null===(o=this.$RTC)||void 0===o?void 0:o.toggleMicro(e);return n&&(yield this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserMicroStatus,{status:e?exports.MicroStatus.OPEN:exports.MicroStatus.CLOSE},[])),n})),this.forbidMicro=(e,t)=>d(this,void 0,void 0,(function*(){var i,o;return!("function"==typeof this._options.canForbidUserMicro&&!this._options.canForbidUserMicro(t))&&(!!(null===(o=null===(i=this.selfInfo)||void 0===i?void 0:i.permission)||void 0===o?void 0:o.control_other_micro)&&(yield this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserMicroStatus,{status:e},t)))})),this.forbidSync=(e,t)=>d(this,void 0,void 0,(function*(){var i,o;return!("function"==typeof this._options.canForbidUserSync&&!this._options.canForbidUserSync(t))&&(!!(null===(o=null===(i=this.selfInfo)||void 0===i?void 0:i.permission)||void 0===o?void 0:o.control_other_sync)&&(yield this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserPermission,{sync_frame:e},t)))})),this.kick=e=>d(this,void 0,void 0,(function*(){var t,i;return!("function"==typeof this._options.canForbidUserKick&&!this._options.canForbidUserKick(e))&&(!!(null===(i=null===(t=this.selfInfo)||void 0===t?void 0:t.permission)||void 0===i?void 0:i.change_other_status)&&(yield this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserStatus,{status:"KICK_OUT"},e)))})),this._addLiveControllerEventListeners(),this._options=Object.assign({initialMicroStatus:exports.MicroStatus.OPEN},e),this._options.jsBridge=e.jsBridge?e.jsBridge:e.useBuiltInJsBridge?new me:void 0,this._options.getVoiceSign=null!==(t=e.getVoiceSign)&&void 0!==t?t:Le,this._options.autoPlayConfirm=e.autoPlayConfirm,this._options.rtc=(()=>{if(e.rtc)return e.rtc;if(e.rtcType)switch(e.getVoiceSign||T.error("GetVoiceSign method must be passed when using built-in RTC instances"),e.rtcType){case exports.RTCType.RealseeVRWebViewRTC:return this._options.jsBridge?new A({jsBridge:this._options.jsBridge,getVoiceSign:this._options.getVoiceSign}):void T.error("JsBridge instance must be passed when using built-in VRWebViewRTC instances");case exports.RTCType.RealseeBrowserChimeRTC:return new B({getVoiceSign:this._options.getVoiceSign,logLevel:e.__debug__?ye.DEBUG:ye.ERROR});case exports.RTCType.RealseeBrowserRTC:return this._options.autoPlayConfirm||T.error("autoPlayConfirm method must be passed when using built-in RealseeBrowserRTC instances"),new O({getVoiceSign:this._options.getVoiceSign,autoPlayConfirm:this._options.autoPlayConfirm});default:return void T.error("unknown built-in RTC type")}return e.useBuiltInRTC?(e.getVoiceSign||T.error("GetVoiceSign method must be passed when using built-in RTC instances"),this._options.jsBridge?Ee&&(Se||we)||ke?new A({jsBridge:this._options.jsBridge,getVoiceSign:this._options.getVoiceSign}):e.builtInRTCType===exports.BuiltInRTCType.RealseeXChimeRTC?new B({getVoiceSign:this._options.getVoiceSign}):new O({getVoiceSign:this._options.getVoiceSign,autoPlayConfirm:this._options.autoPlayConfirm}):void T.error("jsBridge instance must be passed when using built-in RTC instances")):void 0})(),this._options.rtc||T.warn("unused rtc"),this._options.url&&this._options.getTicket&&this.connect(),this._options.__debug__&&Object.assign(window,{$liveController:this._controller,$live:this})}updateStatus(e,t,i,o){return d(this,void 0,void 0,(function*(){if(this.state!==exports.LiveState.OPEN)return!1;const n=Object.assign({event_type:e,action:t},{data:i}),s=xe(exports.Command.BuiltinMsg,n,o);try{return this._controller.sendMessage(s),!0}catch(e){return T.error(e),!1}}))}broadcast(e,t,i){return this.state===exports.LiveState.OPEN&&new Promise(((o,n)=>{const s=xe(exports.Command.CustomEvent,e,t),r=s.front_request_id,c=i?setTimeout((()=>{n(new Error("RESPONSE TIMEOUT")),this.off("broadcast",a)}),i):void 0,a=(e,t)=>{t===r&&(c&&clearTimeout(c),this.off("broadcast",a),o(e))};this.on("broadcast",a);try{this._controller.sendMessage(s)}catch(e){n(e)}}))}}const We=e=>{var t,i;return(null===window||void 0===window?void 0:window.__Realsee_Live__)&&(null===(i=null===(t=null===window||void 0===window?void 0:window.__Realsee_Live__)||void 0===t?void 0:t.dispose)||void 0===i||i.call(t),window.__Realsee_Live__=null),new Ne(e)};exports.BrowserRTC=O,exports.BrowserRTC4Chime=B,exports.CoreRTC=l,exports.VRWebViewRTC=A,exports.createLive=We,exports.createLiveReact=function(e){const t=i.createContext(null),o=We(e),n=o.jsBridge,r=()=>{const e=s.default.useContext(t);if(!e)throw new Error("LiveProvider never found.");return e};return{live:o,jsBridge:n,LiveProvider:e=>s.default.createElement(t.Provider,{value:o},e.children),unsafe__useLiveInstance:()=>o,unsafe__useRTCInstance:()=>o.$RTC,useConnect:()=>e=>d(this,void 0,void 0,(function*(){return yield o.connect(e)})),useKeyframe:function(e){const t=r(),[i,o]=s.default.useState(t.getFramesByKey(e));return s.default.useEffect((()=>{const i=e,n=e=>o(e);return t.keyframes.on(i,n),()=>t.keyframes.off(i,n)}),[t]),[i,s.default.useCallback((i=>t.sendKeyframe(e,i)),[t])]},useKeyframeUpdateCallback:function(e,t,i=[]){const o=r(),n=[o,name,...i],c=()=>o.keyframes.off(e,t);return s.default.useEffect((()=>(o.keyframes.on(e,t),c)),n),c},useLiveAction:function(){const e=r();return{connect:t=>d(this,void 0,void 0,(function*(){return yield e.connect(t)})),broadcast:(t,i,o=0)=>d(this,void 0,void 0,(function*(){return yield e.broadcast(t,i,o)})),exit:()=>d(this,void 0,void 0,(function*(){return yield e.exit()})),kick:t=>d(this,void 0,void 0,(function*(){return yield e.kick(t)})),toggleMicro:t=>e.toggleMicro(t),forbidMicro:(t,i=[])=>d(this,void 0,void 0,(function*(){return yield e.forbidMicro(t,i)})),forbidSync:(t,i=[])=>e.forbidSync(t,i),sendKeyframe:(t,i)=>e.sendKeyframe(t,i),getFramesByKey:t=>e.getFramesByKey(t),setSelfInfo:t=>e.setSelfInfo(t),updateStatus:(t,i,o,n)=>e.updateStatus(t,i,o,n)}},useLiveEventCallback:function(e,t,i=[]){const o=r(),n=()=>o.off(e,t),c=[o,e,...i];return s.default.useEffect((()=>(o.on(e,t),n)),c),n},useLiveState:function(){const e=r(),[t,i]=s.default.useState(e.state);return s.default.useEffect((()=>{const t=e=>i(e);return e.on("stateChange",t),()=>e.off("stateChange",t)}),[e]),t},useRTCAction:function(){const e=r();return{join:t=>e.$RTC.join(t),quit:()=>e.$RTC.quit(),shock:()=>{var t,i;return null===(i=(t=e.$RTC).shock)||void 0===i?void 0:i.call(t)},toggleMicro:t=>e.$RTC.toggleMicro(t),detectMicro:()=>e.$RTC.detectMicro()}},useRTCEventCallback:function(e,t,i=[]){const o=r(),n=()=>o.$RTC.off(e,t),c=[o,e,...i];return s.default.useEffect((()=>(o.$RTC.on(e,t),n)),c),n},useSelfInfo:function(){const e=r(),[t,i]=s.default.useState(e.selfInfo||{}),o=e=>i(e);return s.default.useEffect((()=>(e.on("selfInfoUpdate",o),()=>e.off("selfInfoUpdate",o))),[e]),[t,s.default.useCallback((t=>d(this,void 0,void 0,(function*(){return yield e.setSelfInfo(t)}))),[e])]},useKeyframesSnapshot:function(){const e=r(),[t,i]=s.default.useState(e.snapshot);return s.default.useEffect((()=>{const t=e=>i(e);return e.on("keyframes",t),()=>e.off("keyframes",t)})),t},useUserList:function(){const e=r(),[t,i]=s.default.useState(e.userList),o=e=>i(e);return s.default.useEffect((()=>(e.on("userListUpdate",o),()=>e.off("userListUpdate",o))),[e]),t}}},exports.parseLiveMsg=function(e){try{const t=JSON.parse(e),i={code:t.code,message:t.message,command:t.command,roomCode:t.room_code,appID:t.app_id,requestId:t.request_id,frontRequestId:t.front_request_id,triggerUserID:t.trigger_user_id,data:t.data||{}},o=Object.keys(i).filter((e=>void 0===i[e]));return o.length>0&&console.warn(`推送数据格式异常:${o.join(" ")} 值不存在!`),i}catch(e){return!1}},exports.parseWSClsErr=L;
2
2
  //# sourceMappingURL=realsee-live.cjs.production.js.map