@cloudflare/realtimekit 1.2.1-staging.8 → 1.2.2-staging.1

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.
package/dist/browser.js CHANGED
@@ -7,7 +7,7 @@ var RealtimeKitClient=function(){var Yv,Bo,fr,vr,cs,qi,mt,ds,Ve,As,Sr,Rt,Be,ta,s
7
7
  `),t.sdp=t.sdp.replace(/a=rtpmap:116 red\/90000\r\n/g,""),t.sdp=t.sdp.replace(/a=rtpmap:117 ulpfec\/90000\r\n/g,""),t.sdp=t.sdp.replace(/a=rtpmap:98 rtx\/90000\r\n/g,""),t.sdp=t.sdp.replace(/a=fmtp:98 apt=116\r\n/g,"")),this.pc1.setLocalDescription(t),this.pc2.setRemoteDescription(t),this.pc2.createAnswer().then(this.gotAnswer.bind(this),this.reportFatal.bind(this))}gotAnswer(t){this.constrainVideoBitrateKbps&&(t.sdp=t.sdp.replace(/a=mid:video\r\n/g,`a=mid:video\r
8
8
  b=AS:${this.constrainVideoBitrateKbps}\r
9
9
  `)),this.pc2.setLocalDescription(t),this.pc1.setRemoteDescription(t)}establishConnection(){this.pc1.createOffer().then(this.gotOffer.bind(this),this.reportFatal.bind(this))}reportFatal(t){console.error("Error:",t)}async getRoundTripTime(){const[t,e]=await Promise.all([this.pc1.getStats(),this.pc2.getStats()]);let r,i;if(t.forEach(n=>{n.type==="candidate-pair"&&n.nominated===!0&&n.bytesSent>0&&(r=n)}),e.forEach(n=>{n.type==="candidate-pair"&&n.nominated===!0&&n.bytesReceived>0&&(i=n)}),r&&i)try{if(r.currentRoundTripTime&&i.currentRoundTripTime)return{rtt:r.currentRoundTripTime,backendRTT:i.currentRoundTripTime};const n=(i.lastPacketReceivedTimestamp-r.lastPacketSentTimestamp)/1e3;return{rtt:n,backendRTT:n}}catch(n){return}}close(){this.pc1.close(),this.pc2.close()}}class lg extends lt{constructor(e){super();p(this,"call");p(this,"timeOut");this.call=new sr(e)}start(e=1e4){this.call.establishConnection(),this.timeOut=setTimeout(this.testFailed.bind(this),e)}testComplete(e){clearTimeout(this.timeOut),this.call.close(),this.emit("done",e)}testFailed(e){this.call.close(),this.emit("failed",e)}}const DT=8,NT=1/1e3;class VT extends lg{constructor(e){super(e);p(this,"senderChannel");p(this,"recieveChannel");p(this,"startTime");p(this,"lastBitrateMeasureTime");p(this,"sentPayloadBytes",0);p(this,"recievedPayloadBytes",0);p(this,"lastReceivedPayloadBytes",0);p(this,"stopSending",!1);p(this,"testProgress",0);p(this,"samplePacket","");p(this,"finalBitrateSum",0);p(this,"bitRateSampels",0);p(this,"maxNumberOfPacketsToSend",0);p(this,"bytesToKeepBuffered",0);p(this,"testDurationSeconds",5);this.call.setIceCandidateFilter(sr.isNotHostCandidate),this.senderChannel=this.call.pc1.createDataChannel(null);for(let r=0;r<262144;r+=1)this.samplePacket+="h";this.maxNumberOfPacketsToSend=1,this.bytesToKeepBuffered=1024*this.maxNumberOfPacketsToSend,this.testDurationSeconds=4,this.senderChannel.addEventListener("open",this.sendingStep.bind(this)),this.call.pc2.addEventListener("datachannel",this.onRecieverChannel.bind(this))}sendingStep(){const e=new Date;this.startTime||(this.startTime=e,this.lastBitrateMeasureTime=e);for(let i=0;i!==this.maxNumberOfPacketsToSend&&!(this.senderChannel.bufferedAmount>=this.bytesToKeepBuffered);i+=1){this.sentPayloadBytes+=this.samplePacket.length;try{this.senderChannel.send(this.samplePacket)}catch(n){}}const r=e.getTime()-this.startTime.getTime();r>=1e3*this.testDurationSeconds?(this.stopSending=!0,this.testProgress=100):(this.testProgress=r/(10*this.testDurationSeconds),setTimeout(this.sendingStep.bind(this),1))}onMessageRecieved(e){this.recievedPayloadBytes+=e.data.length;const r=new Date,i=r.getTime()-this.lastBitrateMeasureTime.getTime();if(i>=1e3){const o=(this.recievedPayloadBytes-this.lastReceivedPayloadBytes)*DT/(i/1e3);this.finalBitrateSum+=o,this.bitRateSampels+=1,this.lastReceivedPayloadBytes=this.recievedPayloadBytes,this.lastBitrateMeasureTime=r}if(this.stopSending&&this.sentPayloadBytes===this.recievedPayloadBytes){const n=this.finalBitrateSum/this.bitRateSampels;this.testComplete({throughput:Math.round(n*NT)})}}testComplete(e){this.call.getRoundTripTime().then(({rtt:r,backendRTT:i})=>super.testComplete({RTT:r,backendRTT:i,throughput:e.throughput}))}onRecieverChannel(e){this.recieveChannel=e.channel,this.recieveChannel.addEventListener("message",this.onMessageRecieved.bind(this))}}class Iu extends lg{constructor(e,r=sr.noFilter){super(e);p(this,"ch1");p(this,"ch2");this.call.setIceCandidateFilter(r);const i=this.call.pc1.createDataChannel(null);this.ch1=i,i.addEventListener("open",()=>{i.send("hello")}),i.addEventListener("message",this.onCh1Recieve.bind(this)),this.call.pc2.addEventListener("datachannel",this.dataChannelHandler.bind(this))}onCh1Recieve(e){e.data!=="world"?this.hangup("Invalid data transmitted."):this.testComplete({connectivity:!0})}onCh2Recieve(e){if(e.data!=="hello")this.hangup("Invalid data transmitted.");else try{this.ch2.send("world")}catch(r){}}dataChannelHandler(e){const r=e.channel;this.ch2=r,r.addEventListener("message",this.onCh2Recieve.bind(this))}hangup(e){this.testFailed(e)}}class LT extends Iu{constructor(t){super(t,sr.isHost)}}class xT extends Iu{constructor(t){super(t,sr.isRelay)}}class UT extends Iu{constructor(t){super(t,sr.isReflexive)}}class FT{constructor(){p(this,"ipInformation",null)}async getIPDetails({peerId:t,apiHostnames:e,logger:r}){var i,n,o;if(!this.ipInformation){try{const c=`https://${e.location}`,l=await(await fetch(c)).json();if(((i=l.loc)==null?void 0:i.length)>5)return this.ipInformation=l,(n=this.ipInformation)!=null&&n.ip&&(this.ipInformation.ip=Ur(this.ipInformation.ip)),l;throw Error("Insufficient data")}catch(c){r.error("callstats::ipDetails:: failed to fetch ip using location service",{error:c})}try{const c=await fetch(`https://${e.locationLegacy}/?token=3c493932b0624c&peerId=${t}`,{method:"POST"});this.ipInformation=await c.json(),(o=this.ipInformation)!=null&&o.ip&&(this.ipInformation.ip=Ur(this.ipInformation.ip))}catch(c){r.error("callstats::ipDetails:: failed to fetch ip using legacy location service",{error:c})}}return this.ipInformation}resetCache(){this.ipInformation=null}}const Au=new FT,ug=[{urls:"turn:turn.dyte.in:443?transport=tcp",username:"dyte",credential:"dytein",credentialType:"password"},{urls:"turn:turn.dyte.in:3478?transport=udp",username:"dyte",credential:"dytein",credentialType:"password"}];function hg(s){const[t,e]=s.split(",");return{coords:{latitude:Number(t),longitude:Number(e)}}}class pg{constructor(){p(this,"transport");p(this,"candidatePair");p(this,"outboundVideoRtp",new Map);p(this,"inboundVideoRtp",new Map);p(this,"outboundAudioRtp",new Map);p(this,"inboundAudioRtp",new Map);p(this,"remoteInboundRtp",new Map);p(this,"producerStreamMap",new Map);p(this,"consumerStreamMap",new Map);p(this,"staleProducerStreamMap",!1);p(this,"staleConsumerStreamMap",!1)}}class gg extends lt{constructor(){super();p(this,"observer");p(this,"outboundProducerMap",new Map);p(this,"inboundConsumerMap",new Map);p(this,"consumerPeerIdMap",new Map);p(this,"pausedConsumerMap",new Map);p(this,"pausedProducerMap",new Map);p(this,"overallProducingTransportsStatsMap",{});p(this,"overallConsumingTransportsStatsMap",{});p(this,"overallConsumersStatsMap",{});p(this,"overallProducersStatsMap",{});p(this,"videoProducerToStatsMap",new Map);p(this,"audioProducerToStatsMap",new Map);p(this,"videoConsumerToStatsMap",new Map);p(this,"audioConsumerToStatsMap",new Map);p(this,"consumerIdsWithFreezedVideo",new Set);p(this,"consumerIdsWithFreezedAudio",new Set);p(this,"producerIdsWithFreezedVideo",new Set);p(this,"producerIdsWithFreezedAudio",new Set);p(this,"freezedProducingTransportIds",new Set);p(this,"freezedConsumingTransportIds",new Set);p(this,"screenShareProducers",new Set);p(this,"screenShareConsumers",new Set);p(this,"ipDetails");p(this,"callStatsInstance");this.observer=new lt}async registerProducer(e){await this.generateProducerStreamMap(e),e.on("close",this.deregisterProducer.bind(this,e)),e.on("pause",this.pauseProducer.bind(this,e.id)),e.on("resume",this.resumeProducer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareProducers.add(e.id)}pauseProducer(e){this.pausedProducerMap.set(e,{lastReportCalculated:!1})}resumeProducer(e){this.pausedProducerMap.delete(e)}processInboundConsumerVideoStats(e,r,i){var o,c;const n=((c=(o=this==null?void 0:this.callStatsInstance)==null?void 0:o.consumerSharedMediaStatesMap)==null?void 0:c.get(e))||{};r.totalVideoPacketsReceived===i.packetsReceived?(this.consumerIdsWithFreezedVideo.add(e),this.callStatsInstance&&n.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","pause",e))):(r.totalVideoPacketsReceived=i.packetsReceived,this.consumerIdsWithFreezedVideo.has(e)&&(this.consumerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&n.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","resume",e))))}processInboundConsumerAudioStats(e,r,i){var o,c;const n=((c=(o=this==null?void 0:this.callStatsInstance)==null?void 0:o.consumerSharedMediaStatesMap)==null?void 0:c.get(e))||{};r.totalAudioPacketsReceived===i.packetsReceived?(this.consumerIdsWithFreezedAudio.add(e),this.callStatsInstance&&n.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","pause",e))):(r.totalAudioPacketsReceived=i.packetsReceived,this.consumerIdsWithFreezedAudio.has(e)&&(this.consumerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&n.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","resume",e))))}processOutboundProducerVideoStats(e,r,i){var o;const n=((o=this==null?void 0:this.callStatsInstance)==null?void 0:o.currentUserMediaStates)||{};r.totalVideoPacketsSent===i.packetsSent?(this.producerIdsWithFreezedVideo.add(e),this.callStatsInstance&&n.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","pause",e))):(r.totalVideoPacketsSent=i.packetsSent,this.producerIdsWithFreezedVideo.has(e)&&(this.producerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&n.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","resume",e))))}processOutboundProducerAudioStats(e,r,i){var o;const n=((o=this==null?void 0:this.callStatsInstance)==null?void 0:o.currentUserMediaStates)||{};r.totalAudioPacketsSent===i.packetsSent?(this.producerIdsWithFreezedAudio.add(e),this.callStatsInstance&&n.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","pause",e))):(r.totalAudioPacketsSent=i.packetsSent,this.producerIdsWithFreezedAudio.has(e)&&(this.producerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&n.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","resume",e))))}processProducingTransportStats(e,r,i){var u;const n=((u=this==null?void 0:this.callStatsInstance)==null?void 0:u.currentUserMediaStates)||{},{audio:o,video:c,screen:d}=n,l=o||c||d;r.totalPacketsSent===i.packetsSent?(this.freezedProducingTransportIds.add(e),this.callStatsInstance&&l&&(this.callStatsInstance.logger.debug("callStats::measurements::producingTransportFreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("producing_transport_status","pause",e))):(r.totalPacketsSent=i.packetsSent,this.freezedProducingTransportIds.has(e)&&(this.freezedProducingTransportIds.delete(e),this.callStatsInstance&&l&&(this.callStatsInstance.logger.debug("callStats::measurements::producingTransportDefreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("producing_transport_status","resume",e))))}processConsumingTransportStats(e,r,i){var c,d;const o=!!Array.from(((d=(c=this==null?void 0:this.callStatsInstance)==null?void 0:c.consumerSharedMediaStatesMap)==null?void 0:d.values())||[]).reduce((l,u)=>l||u.audio||u.video||u.screen,!1);r.totalPacketsReceived===i.packetsSent?(this.freezedConsumingTransportIds.add(e),this.callStatsInstance&&o&&(this.callStatsInstance.logger.debug("callStats::measurements::consumingTransportFreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("consuming_transport_status","pause",e))):(r.totalPacketsReceived=i.packetsSent,this.freezedConsumingTransportIds.has(e)&&(this.freezedConsumingTransportIds.delete(e),this.callStatsInstance&&o&&(this.callStatsInstance.logger.debug("callStats::measurements::consumingTransportDefreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("consuming_transport_status","resume",e))))}async registerConsumer(e){await this.generateConsumerStreamMap(e),this.consumerPeerIdMap.set(e.id,{producerId:e.producerId,peerId:e.appData.peerId,appData:e.appData}),e.on("close",this.deregisterConsumer.bind(this,e)),e.on("pause",this.pauseConsumer.bind(this,e.id)),e.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)}pauseConsumer(e){this.pausedConsumerMap.set(e,{lastReportCalculated:!1})}resumeConsumer(e){this.pausedConsumerMap.delete(e)}async generateProducerStreamMap(e,r=!1){const i=await e.getStats(),n=r?this.getProducerStatsFromReport(this.parseRTCReport(i,["outbound-rtp","remote-inbound-rtp"],!1,e.id))[0]:void 0;for(const o of i.values())switch(o.type){case"outbound-rtp":{this.outboundProducerMap.set(o.id,e.id);break}}return n}async generateConsumerStreamMap(e,r=!1){const i=await e.getStats(),n=r?this.getConsumerStatsFromReport(this.parseRTCReport(i,["inbound-rtp"],!1,e.id))[0]:void 0;for(const o of i.values())switch(o.type){case"inbound-rtp":{this.inboundConsumerMap.set(o.id,e.id);break}}return n}deregisterProducer(e){this.outboundProducerMap.forEach((r,i)=>{r===e.id&&this.outboundProducerMap.delete(i)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.inboundConsumerMap.forEach((r,i)=>{r===e.id&&this.inboundConsumerMap.delete(i)}),this.consumerPeerIdMap.delete(e.id),this.pausedConsumerMap.delete(e.id),this.screenShareConsumers.delete(e.id)}getIceCandidateStats(e){var r;return{id:e.id,type:e.candidateType||e.type,address:e.address,port:e.port,url:e.url,protocol:(r=e.relayProtocol)!=null?r:e.protocol,networkType:e.networkType,relatedAddress:e.relatedAddress,relatedPort:e.relatedPort}}getWorkingSimulcastVideoStats(e){return e.find(i=>{const n=i.framesEncoded>0,o=i.packetsSent>0,c=i.frameWidth&&i.frameHeight;return n&&o&&!!c})||e[e.length-1]}parseRTCReport(e,r=[],i=!1,n=void 0,o=void 0){var b,_,w,L,B,N,$,Y,ae,bt,Bs,On,$s;const c=e,d=new pg,l=r.length?new Set(r):void 0,u=[],h=[],g=[],v=new Map,E=new Map;for(const I of c.values()){if(l){if(l.size===0)break;if(l.has(I.type))i&&l.delete(I.type);else continue}switch(I.type){case"local-candidate":{u.push(this.getIceCandidateStats(I));break}case"remote-candidate":{h.push(this.getIceCandidateStats(I));break}case"candidate-pair":{const{nominated:T}=I,{selected:P}=I,x=I,we={nominated:T!=null?T:P,currentRoundTripTime:x.currentRoundTripTime,totalRoundTripTime:x.totalRoundTripTime,bytesReceived:x.bytesReceived,bytesSent:x.bytesSent,availableOutgoingBitrate:x.availableOutgoingBitrate,availableIncomingBitrate:x.availableIncomingBitrate,lastPacketReceivedTimestamp:x.lastPacketReceivedTimestamp,lastPacketSentTimestamp:x.lastPacketSentTimestamp,localCandidateId:x.localCandidateId,remoteCandidateId:x.remoteCandidateId,bytesDiscardedOnSend:x.bytesDiscardedOnSend,packetsSent:x.packetsSent,packetsReceived:x.packetsReceived,packetsDiscardedOnSend:x.packetsDiscardedOnSend};g.push(we),(I.nominated===!0||I.selected===!0)&&(d.candidatePair=we);break}case"transport":{const T=I;o&&(o.producing&&(this.overallProducingTransportsStatsMap[o.id]||(this.overallProducingTransportsStatsMap[o.id]={totalPacketsSent:0})),o.consuming&&(this.overallConsumingTransportsStatsMap[o.id]||(this.overallConsumingTransportsStatsMap[o.id]={totalPacketsReceived:0})));const P={bytesReceived:T.bytesReceived,bytesSent:T.bytesSent,packetsSent:T.packetsSent,packetsReceived:T.packetsReceived,dtlsCipher:T.dtlsCipher,dtlsState:T.dtlsState,iceRole:T.iceRole};if(d.transport=P,o){if(o.producing){const x=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,x,P)}if(o.consuming){const x=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,x,P)}}break}case"remote-inbound-rtp":{const T=I,P={jitter:T.jitter,fractionLost:T.fractionLost,roundTripTime:T.roundTripTime,roundTripTimeMeasurements:T.roundTripTimeMeasurements,totalRoundTripTime:T.totalRoundTripTime,packetsLost:T.packetsLost};d.remoteInboundRtp.set(T.localId,P);break}case"outbound-rtp":{if(!this.outboundProducerMap.has(I.id))break;const T=I,P=n||this.outboundProducerMap.get(I.id),x=this.pausedProducerMap.get(P);if(x){if(x.lastReportCalculated===!0)break;this.pausedProducerMap.set(P,{lastReportCalculated:!0})}this.overallProducersStatsMap[P]||(this.overallProducersStatsMap[P]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const we=this.overallProducersStatsMap[P];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.outboundProducerMap.has(I.id)){d.staleProducerStreamMap=!0;break}const Je=this.callStatsInstance.producers.get(P);if(((b=Je==null?void 0:Je.track)==null?void 0:b.readyState)==="ended")break;d.producerStreamMap.has(P)||d.producerStreamMap.set(P,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const V={bytesSent:T.bytesSent,packetsSent:T.packetsSent,nackCount:T.nackCount,ssrc:T.ssrc,mid:T.mid,active:T.active,codecId:T.codecId,headerBytesSent:T.headerBytesSent||0,totalPacketSendDelay:T.totalPacketSendDelay||0};if(T.mediaType==="video"||T.kind==="video"){const k=T,Ke={frameHeight:k.frameHeight,frameWidth:k.frameWidth,framesEncoded:k.framesEncoded,framesDropped:k.framesDropped,framesPerSecond:k.framesPerSecond,framesSent:k.framesSent,keyFramesEncoded:k.keyFramesEncoded,firCount:k.firCount,encoderImplementation:k.encoderImplementation,hugeFramesSent:k.hugeFramesSent,pliCount:k.pliCount,qpSum:k.qpSum,qualityLimitationDurations:k.qualityLimitationDurations,qualityLimitationReason:k.qualityLimitationReason,qualityLimitationResolutionChanges:k.qualityLimitationResolutionChanges,totalEncodeTime:k.targetBitrate,totalPacketSendDelay:k.totalPacketSendDelay,retransmittedBytesSent:k.retransmittedBytesSent,retransmittedPacketsSent:k.retransmittedPacketsSent,scalabilityMode:k.scalabilityMode,powerEfficientEncoder:k.powerEfficientEncoder,...V};d.outboundVideoRtp.set(I.id,Ke),d.producerStreamMap.get(P).outboundVideoRtpId.push(I.id),this.processOutboundProducerVideoStats(P,we,Ke)}else if(T.mediaType==="audio"||T.kind==="audio"){const k=T,Ke={retransmittedBytesSent:k.retransmittedBytesSent,retransmittedPacketsSent:k.retransmittedPacketsSent,...V};d.outboundAudioRtp.set(I.id,Ke),d.producerStreamMap.get(P).outboundAudioRtpId.push(I.id),this.processOutboundProducerAudioStats(P,we,Ke)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}case"inbound-rtp":{if(!this.inboundConsumerMap.has(I.id))break;const T=I,P=n||this.inboundConsumerMap.get(I.id),x=this.pausedConsumerMap.get(P);if(x){if(x.lastReportCalculated===!0)break;this.pausedConsumerMap.set(P,{lastReportCalculated:!0})}if(T.ssrc===1234)break;this.overallConsumersStatsMap[P]||(this.overallConsumersStatsMap[P]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const we=this.overallConsumersStatsMap[P];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.inboundConsumerMap.has(I.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(P)||d.consumerStreamMap.set(P,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const Je={bytesReceived:T.bytesReceived,packetsReceived:T.packetsReceived,packetsLost:T.packetsLost>=0?T.packetsLost:0,jitter:T.jitter,nackCount:T.nackCount,jitterBufferDelay:T.jitterBufferDelay,jitterBufferEmittedCount:T.jitterBufferEmittedCount,lastPacketReceivedTimestamp:T.lastPacketReceivedTimestamp,ssrc:T.ssrc,mid:T.mid,codecId:T.codecId,headerBytesReceived:T.headerBytesReceived||0,packetsDiscarded:T.packetsDiscarded||0,jitterBufferMinimumDelay:T.jitterBufferMinimumDelay||0,jitterBufferTargetDelay:T.jitterBufferTargetDelay||0};if(T.mediaType==="video"||T.kind==="video"){const V=T,k={frameHeight:V.frameHeight,frameWidth:V.frameWidth,framesDecoded:V.framesDecoded,framesDropped:V.framesDropped,framesPerSecond:V.framesPerSecond,framesReceived:V.framesReceived,keyFramesDecoded:V.keyFramesDecoded,firCount:V.firCount,decoderImplementation:V.decoderImplementation,pliCount:V.pliCount,totalProcessingDelay:V.totalProcessingDelay,qpSum:V.qpSum||0,totalAssemblyTime:V.totalAssemblyTime||0,totalDecodeTime:V.totalDecodeTime||0,totalFreezesDuration:V.totalFreezesDuration||0,totalInterFrameDelay:V.totalInterFrameDelay||0,totalPausesDuration:V.totalPausesDuration||0,totalSquaredInterFrameDelay:V.totalSquaredInterFrameDelay||0,freezeCount:V.freezeCount||0,pauseCount:V.pauseCount||0,powerEfficientDecoder:V.powerEfficientDecoder,...Je};k.score=dg({frameWidth:k.frameWidth||0,framesDecoded:(k.framesDecoded||0)-(((_=this.videoConsumerToStatsMap.get(P))==null?void 0:_.framesDecoded)||0),framesPerSecond:k.framesPerSecond||0,packetsLost:(k.packetsLost||0)-(((w=this.videoConsumerToStatsMap.get(P))==null?void 0:w.packetsLost)||0),packetsReceived:(k.packetsReceived||0)-(((L=this.videoConsumerToStatsMap.get(P))==null?void 0:L.packetsReceived)||0),jitter:k.jitter||0,isScreenShare:this.screenShareConsumers.has(P)}),E.set(P,{score:+(k.score*10).toFixed(),frameWidth:k.frameWidth||0,frameHeight:k.frameHeight||0,framesPerSecond:k.framesPerSecond||0,packetsLostPercentage:md({packetsLost:(k.packetsLost||0)-(((B=this.videoConsumerToStatsMap.get(P))==null?void 0:B.packetsLost)||0),packetsReceived:(k.packetsReceived||0)-(((N=this.videoConsumerToStatsMap.get(P))==null?void 0:N.packetsReceived)||0)}),jitter:k.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((k.bytesReceived||0)-((($=this.videoConsumerToStatsMap.get(P))==null?void 0:$.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(P,k),d.inboundVideoRtp.set(I.id,k),d.consumerStreamMap.get(P).inboundVideoRtpId.push(I.id),this.processInboundConsumerVideoStats(P,we,k)}else if(T.mediaType==="audio"||T.kind==="audio"){const V=T,k={audioLevel:V.audioLevel,concealedSamples:V.concealedSamples,concealmentEvents:V.concealmentEvents,totalAudioEnergy:V.totalAudioEnergy,totalSamplesDuration:V.totalSamplesDuration,totalSamplesReceived:V.totalSamplesReceived,fecPacketsDiscarded:V.fecPacketsDiscarded||0,fecPacketsReceived:V.fecPacketsReceived||0,insertedSamplesForDeceleration:V.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:V.removedSamplesForAcceleration||0,silentConcealedSamples:V.silentConcealedSamples||0,playoutId:V.playoutId,...Je};k.score=cg({concealmentEvents:(k.concealmentEvents||0)-(((Y=this.audioConsumerToStatsMap.get(P))==null?void 0:Y.concealmentEvents)||0),packetsLost:(k.packetsLost||0)-(((ae=this.audioConsumerToStatsMap.get(P))==null?void 0:ae.packetsLost)||0),packetsReceived:(k.packetsReceived||0)-(((bt=this.audioConsumerToStatsMap.get(P))==null?void 0:bt.packetsReceived)||0),jitter:k.jitter||0}),E.set(P,{score:+(k.score*10).toFixed(),packetsLostPercentage:md({packetsLost:(k.packetsLost||0)-(((Bs=this.audioConsumerToStatsMap.get(P))==null?void 0:Bs.packetsLost)||0),packetsReceived:(k.packetsReceived||0)-(((On=this.audioConsumerToStatsMap.get(P))==null?void 0:On.packetsReceived)||0)}),jitter:k.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((k.bytesReceived||0)-((($s=this.audioConsumerToStatsMap.get(P))==null?void 0:$s.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(P,k),d.inboundAudioRtp.set(I.id,k),d.consumerStreamMap.get(P).inboundAudioRtpId.push(I.id),this.processInboundConsumerAudioStats(P,we,k)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}}}if(d.producerStreamMap.forEach((I,T)=>{var P,x,we,Je,V,k,Ke,fi,Lr,Gc,Wc,Jc,Kc,zc,Yc,Qc,Xc,Zc,ed,td,sd,rd,id;if(I.outboundVideoRtpId.length>0){const pe=[];I.outboundVideoRtpId.forEach(hp=>{pe.push(d.outboundVideoRtp.get(hp))});const te=this.getWorkingSimulcastVideoStats(pe);te.score=ag({frameWidth:te.frameWidth||0,framesPerSecond:te.framesPerSecond||0,jitter:((P=te.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsSent:(te.packetsSent||0)-(((x=this.videoProducerToStatsMap.get(T))==null?void 0:x.packetsSent)||0),packetsLost:(((we=te.remoteData)==null?void 0:we.packetsLost)||0)-(((V=(Je=this.videoProducerToStatsMap.get(T))==null?void 0:Je.remoteData)==null?void 0:V.packetsLost)||0),framesEncoded:(te.framesEncoded||0)-(((k=this.videoProducerToStatsMap.get(T))==null?void 0:k.framesEncoded)||0)}),v.set(T,{score:+(te.score*10).toFixed(),frameWidth:te.frameWidth||0,frameHeight:te.frameHeight||0,framesPerSecond:te.framesPerSecond||0,jitter:((Ke=te.remoteData)==null?void 0:Ke.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsLostPercentage:gd({packetsSent:(te.packetsSent||0)-(((fi=this.videoProducerToStatsMap.get(T))==null?void 0:fi.packetsSent)||0),packetsLost:(((Lr=te.remoteData)==null?void 0:Lr.packetsLost)||0)-(((Wc=(Gc=this.videoProducerToStatsMap.get(T))==null?void 0:Gc.remoteData)==null?void 0:Wc.packetsLost)||0)}),bitrate:((te.bytesSent||0)-(((Jc=this.videoProducerToStatsMap.get(T))==null?void 0:Jc.bytesSent)||0))*8/7,cpuLimitations:te.qualityLimitationReason==="cpu",bandwidthLimitations:te.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(T,te)}else if(I.outboundAudioRtpId.length>0){const pe=d.outboundAudioRtp.get(I.outboundAudioRtpId[0]);pe.score=ng({packetsSent:(pe.packetsSent||0)-(((Kc=this.audioProducerToStatsMap.get(T))==null?void 0:Kc.packetsSent)||0),packetsLost:(((zc=pe.remoteData)==null?void 0:zc.packetsLost)||0)-(((Qc=(Yc=this.audioProducerToStatsMap.get(T))==null?void 0:Yc.remoteData)==null?void 0:Qc.packetsLost)||0),jitter:((Xc=pe.remoteData)==null?void 0:Xc.jitter)||0}),v.set(T,{score:+(pe.score*10).toFixed(),bitrate:((pe.bytesSent||0)-(((Zc=this.audioProducerToStatsMap.get(T))==null?void 0:Zc.bytesSent)||0))*8/7,packetsLostPercentage:gd({packetsSent:(pe.packetsSent||0)-(((ed=this.audioProducerToStatsMap.get(T))==null?void 0:ed.packetsSent)||0),packetsLost:(((td=pe.remoteData)==null?void 0:td.packetsLost)||0)-(((rd=(sd=this.audioProducerToStatsMap.get(T))==null?void 0:sd.remoteData)==null?void 0:rd.packetsLost)||0)}),jitter:((id=pe.remoteData)==null?void 0:id.jitter)||0,isScreenShare:this.screenShareProducers.has(T)}),this.audioProducerToStatsMap.set(T,pe)}}),g.forEach(I=>{const T=u.find(x=>x.id===I.localCandidateId?(I.localCandidateId=x.id,x):null),P=h.find(x=>x.id===I.remoteCandidateId?(I.remoteCandidateId=x.id,x):null);T&&(I.localCandidateType=T.type,I.localCandidateAddress=Ur(T.address),I.localCandidatePort=T.port,I.localCandidateProtocol=T.protocol,I.localCandidateUrl=T.url,I.localCandidateNetworkType=T.networkType,I.localCandidateRelatedAddress=Ur(T.relatedAddress),I.localCandidateRelatedPort=T.relatedPort),P&&(I.remoteCandidateType=P.type,I.remoteCandidateAddress=Ur(P.address),I.remoteCandidatePort=P.port,I.remoteCandidateProtocol=P.protocol,I.remoteCandidateUrl=P.url)}),d.candidatePair&&(d.transport?(d.transport.totalRoundTripTime=d.candidatePair.totalRoundTripTime,d.transport.availableOutgoingBitrate=d.candidatePair.availableOutgoingBitrate,d.transport.availableIncomingBitrate=d.candidatePair.availableIncomingBitrate,d.transport.roundTripTime=d.candidatePair.currentRoundTripTime):d.transport={bytesReceived:d.candidatePair.bytesReceived,bytesSent:d.candidatePair.bytesSent,totalRoundTripTime:d.candidatePair.totalRoundTripTime,availableOutgoingBitrate:d.candidatePair.availableOutgoingBitrate,availableIncomingBitrate:d.candidatePair.availableIncomingBitrate,roundTripTime:d.candidatePair.currentRoundTripTime}),d.transport&&(d.transport.candidatePairs=g),d.transport&&!d.transport.roundTripTime){let I=0,T=0;d.remoteInboundRtp.forEach((P,x)=>{P.roundTripTime&&P.roundTripTime>I&&(I=P.roundTripTime,T=P.totalRoundTripTime)}),d.transport.roundTripTime=I,d.transport.totalRoundTripTime=T}if(E.size>0)try{this.observer.emit("consumer_score",E)}catch(I){}if(v.size>0)try{this.observer.emit("producer_score",v)}catch(I){}return d}async getProducersReport(e){const r=e.map(i=>this.generateProducerStreamMap(i,!0));return r.length>0?Promise.all(r):void 0}async getConsumersReport(e){const r=e.map(i=>this.generateConsumerStreamMap(i,!0));return r.length>0?Promise.all(r):void 0}async getTransportReport(e){return e.getStats()}async getProcessedStats(e,r,i){const n=await this.getTransportReport(e),o={producing:i,consuming:r,id:e.id},c=n,d=this.parseRTCReport(c,["transport","candidate-pair","inbound-rtp","outbound-rtp","remote-inbound-rtp","local-candidate","remote-candidate"],!1,void 0,o);if(!d)return;const l={stats:d.transport,transportId:e.id,consuming:r,producing:i},u=d.staleProducerStreamMap?void 0:this.getProducerStatsFromReport(d),h=d.staleConsumerStreamMap?void 0:this.getConsumerStatsFromReport(d);return{transportReport:l,producerReport:u,consumerReport:h}}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((i,n)=>{var o,c;r.push({producerId:n,videoStats:i.outboundVideoRtpId.map(d=>e.outboundVideoRtp.get(d)),audioStats:i.outboundAudioRtpId.map(d=>e.outboundAudioRtp.get(d)),appData:((c=(o=this.callStatsInstance.producers)==null?void 0:o.get(n))==null?void 0:c.appData)||null})})}catch(i){this.callStatsInstance.logger.error("callStats::measurements::getProducerStatsFromReport",{error:{reason:i.reason,message:i.message}})}return r}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((i,n)=>{const{peerId:o,producerId:c,appData:d}=this.consumerPeerIdMap.get(n);r.push({consumerId:n,peerId:o,producerId:c,appData:d,videoStats:i.inboundVideoRtpId.map(l=>e.inboundVideoRtp.get(l)),audioStats:i.inboundAudioRtpId.map(l=>e.inboundAudioRtp.get(l))})})}catch(i){console.error("getConsumersReport: ",i,e)}return r}async getUserLocation(){return new Promise((e,r)=>{try{navigator.geolocation?navigator.geolocation.getCurrentPosition(i=>{e(i)}):r()}catch(i){r(i)}})}async getConnectivity(e){try{const r={iceServers:e||ug},i=new Promise((u,h)=>{try{const g=new LT(r);g.addListener("done",u),g.addListener("failed",()=>{u({connectivity:!1})}),g.start(2e3)}catch(g){h(g)}}),n=new Promise((u,h)=>{try{const g=new xT(r);g.addListener("done",u),g.addListener("failed",()=>{u({connectivity:!1})}),g.start(2e3)}catch(g){h(g)}}),o=new Promise((u,h)=>{try{const g=new UT(r);g.addListener("done",u),g.addListener("failed",()=>{u({connectivity:!1})}),g.start(2e3)}catch(g){h(g)}}),[c,d,l]=await Promise.all([i,n,o]);return{host:c==null?void 0:c.connectivity,relay:d==null?void 0:d.connectivity,reflexive:l==null?void 0:l.connectivity}}catch(r){return{host:!1,relay:!1,reflexive:!1}}}async getThroughput(e){try{const i=await new Promise((n,o)=>{try{const c={iceServers:e||ug},d=new VT(c);d.addListener("done",n),d.addListener("failed",o),d.start(1e4)}catch(c){o(c)}});return{throughput:i.throughput,fractionalLoss:0,RTT:i.RTT,jitter:0,backendRTT:i.backendRTT}}catch(r){return}}async getIPDetails(){var e,r;try{return this.ipDetails||(this.ipDetails=await Au.getIPDetails({peerId:(e=this.callStatsInstance)==null?void 0:e.peerId,apiHostnames:(r=this.callStatsInstance)==null?void 0:r.apiHostnames,logger:this.callStatsInstance.logger})),this.ipDetails}catch(i){return}}async getNetworkQuality(e){const[r,i]=await Promise.all([this.getConnectivity(e),this.getThroughput(e)]);return{connectivity:r,throughput:i==null?void 0:i.throughput,fractionalLoss:i==null?void 0:i.fractionalLoss,RTT:i==null?void 0:i.RTT,jitter:i==null?void 0:i.jitter,backendRTT:i==null?void 0:i.backendRTT}}async getNetworkInfo(e,r=!1){var c,d;if(r){const l=await this.getIPDetails();return{ipDetails:l,effectiveNetworkType:(c=navigator.connection)==null?void 0:c.effectiveType,location:l!=null&&l.loc?hg(l==null?void 0:l.loc):void 0}}const[i,n,o]=await Promise.all([this.getConnectivity(e),this.getThroughput(e),this.getIPDetails()]);return{ipDetails:o,effectiveNetworkType:(d=navigator.connection)==null?void 0:d.effectiveType,location:o!=null&&o.loc?hg(o==null?void 0:o.loc):void 0,turnConnectivity:i?i.host||i.relay||i.reflexive:!1,connectivity:i,throughput:n==null?void 0:n.throughput,fractionalLoss:n==null?void 0:n.fractionalLoss,RTT:n==null?void 0:n.RTT,jitter:n==null?void 0:n.jitter,backendRTT:n==null?void 0:n.backendRTT}}}class BT extends gg{}class mg extends gg{constructor(){super(...arguments);p(this,"producerMap",new Map);p(this,"consumerMap",new Map)}async registerProducer(e){this.producerMap.set(e.id,e),await this.generateProducerStreamMap(e),e.on("close",this.deregisterProducer.bind(this,e)),e.on("pause",this.pauseProducer.bind(this,e.id)),e.on("resume",this.resumeProducer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareProducers.add(e.id)}async registerConsumer(e){this.consumerMap.set(e.id,e),await this.generateConsumerStreamMap(e),this.consumerPeerIdMap.set(e.id,{producerId:e.producerId,peerId:e.appData.peerId,appData:e.appData}),e.on("close",this.deregisterConsumer.bind(this,e)),e.on("pause",this.pauseConsumer.bind(this,e.id)),e.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)}async generateConsumerStreamMap(e,r=!1){const i=await e.getStats(),n=this.parseRTCReport(i,["inbound-rtp"],!1,e.id),o=[...n.consumerStreamMap.values()][0],c=r?this.getConsumerStatsFromParsedConsumerStats(n,o,e.id):void 0;for(const d of i.values())switch(d.type){case"inbound-rtp":{this.inboundConsumerMap.set(d.id,e.id);break}}return c}deregisterProducer(e){this.producerMap.delete(e.id),this.outboundProducerMap.forEach((r,i)=>{r===e.id&&this.outboundProducerMap.delete(i)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.consumerMap.delete(e.id),this.inboundConsumerMap.forEach((r,i)=>{r===e.id&&this.inboundConsumerMap.delete(i)}),this.consumerPeerIdMap.delete(e.id),this.pausedConsumerMap.delete(e.id),this.screenShareConsumers.delete(e.id)}getIceCandidateStats(e){var r;return{id:e.id,type:e.candidateType||e.type,address:e.address,port:e.port,url:e.url,protocol:(r=e.relayProtocol)!=null?r:e.protocol,networkType:e.networkType,relatedAddress:e.relatedAddress,relatedPort:e.relatedPort}}parseRTCReport(e,r=[],i=!1,n=void 0,o=void 0){var b,_,w,L,B,N,$,Y,ae,bt,Bs,On,$s;const c=e,d=new pg,l=r.length?new Set(r):void 0,u=[],h=[],g=[],v=new Map,E=new Map;for(const I of c.values()){if(l){if(l.size===0)break;if(l.has(I.type))i&&l.delete(I.type);else continue}switch(I.type){case"local-candidate":{u.push(this.getIceCandidateStats(I));break}case"remote-candidate":{h.push(this.getIceCandidateStats(I));break}case"candidate-pair":{const{nominated:T}=I,{selected:P}=I,x=I,we={nominated:T!=null?T:P,currentRoundTripTime:x.currentRoundTripTime,totalRoundTripTime:x.totalRoundTripTime,bytesReceived:x.bytesReceived,bytesSent:x.bytesSent,availableOutgoingBitrate:x.availableOutgoingBitrate,availableIncomingBitrate:x.availableIncomingBitrate,lastPacketReceivedTimestamp:x.lastPacketReceivedTimestamp,lastPacketSentTimestamp:x.lastPacketSentTimestamp,localCandidateId:x.localCandidateId,remoteCandidateId:x.remoteCandidateId,bytesDiscardedOnSend:x.bytesDiscardedOnSend,packetsSent:x.packetsSent,packetsReceived:x.packetsReceived,packetsDiscardedOnSend:x.packetsDiscardedOnSend};g.push(we),(I.nominated===!0||I.selected===!0)&&(d.candidatePair=we);break}case"transport":{const T=I;o&&(o.producing&&(this.overallProducingTransportsStatsMap[o.id]||(this.overallProducingTransportsStatsMap[o.id]={totalPacketsSent:0})),o.consuming&&(this.overallConsumingTransportsStatsMap[o.id]||(this.overallConsumingTransportsStatsMap[o.id]={totalPacketsReceived:0})));const P={bytesReceived:T.bytesReceived,bytesSent:T.bytesSent,packetsSent:T.packetsSent,packetsReceived:T.packetsReceived,dtlsCipher:T.dtlsCipher,dtlsState:T.dtlsState,iceRole:T.iceRole};if(d.transport=P,o){if(o.producing){const x=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,x,P)}if(o.consuming){const x=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,x,P)}}break}case"remote-inbound-rtp":{const T=I,P={jitter:T.jitter,fractionLost:T.fractionLost,roundTripTime:T.roundTripTime,roundTripTimeMeasurements:T.roundTripTimeMeasurements,totalRoundTripTime:T.totalRoundTripTime,packetsLost:T.packetsLost};d.remoteInboundRtp.set(T.localId,P);break}case"outbound-rtp":{if(!this.outboundProducerMap.has(I.id))break;const T=I,P=n||this.outboundProducerMap.get(I.id),x=this.pausedProducerMap.get(P);if(x){if(x.lastReportCalculated===!0)break;this.pausedProducerMap.set(P,{lastReportCalculated:!0})}this.overallProducersStatsMap[P]||(this.overallProducersStatsMap[P]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const we=this.overallProducersStatsMap[P];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.outboundProducerMap.has(I.id)){d.staleProducerStreamMap=!0;break}const Je=this.callStatsInstance.producers.get(P);if(((b=Je==null?void 0:Je.track)==null?void 0:b.readyState)==="ended")break;d.producerStreamMap.has(P)||d.producerStreamMap.set(P,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const V={bytesSent:T.bytesSent,packetsSent:T.packetsSent,nackCount:T.nackCount,ssrc:T.ssrc,mid:T.mid,active:T.active,codecId:T.codecId,headerBytesSent:T.headerBytesSent||0,totalPacketSendDelay:T.totalPacketSendDelay||0};if(T.mediaType==="video"||T.kind==="video"){const k=T,Ke={frameHeight:k.frameHeight,frameWidth:k.frameWidth,framesEncoded:k.framesEncoded,framesDropped:k.framesDropped?k.framesDropped:k.droppedFrames,framesPerSecond:k.framesPerSecond?k.framesPerSecond:k.framerateMean,framesSent:k.framesSent,keyFramesEncoded:k.keyFramesEncoded,firCount:k.firCount,encoderImplementation:k.encoderImplementation,hugeFramesSent:k.hugeFramesSent,pliCount:k.pliCount,qpSum:k.qpSum,qualityLimitationReason:k.qualityLimitationReason,qualityLimitationDurations:k.qualityLimitationDurations,qualityLimitationResolutionChanges:k.qualityLimitationResolutionChanges,totalEncodeTime:k.totalEncodeTime,totalPacketSendDelay:k.totalEncodeTime,retransmittedBytesSent:k.retransmittedBytesSent,retransmittedPacketsSent:k.retransmittedPacketsSent,scalabilityMode:k.scalabilityMode,powerEfficientEncoder:k.powerEfficientEncoder,...V};d.outboundVideoRtp.set(I.id,Ke),d.producerStreamMap.get(P).outboundVideoRtpId.push(I.id),this.processOutboundProducerVideoStats(P,we,Ke)}else if(T.mediaType==="audio"||T.kind==="audio"){const k=T,Ke={retransmittedBytesSent:k.retransmittedBytesSent,retransmittedPacketsSent:k.retransmittedPacketsSent,...V};d.outboundAudioRtp.set(I.id,Ke),d.producerStreamMap.get(P).outboundAudioRtpId.push(I.id),this.processOutboundProducerAudioStats(P,we,Ke)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}case"inbound-rtp":{if(!this.inboundConsumerMap.has(I.id))break;const T=I,P=n||this.inboundConsumerMap.get(I.id),x=this.pausedConsumerMap.get(P);if(x){if(x.lastReportCalculated===!0)break;this.pausedConsumerMap.set(P,{lastReportCalculated:!0})}if(T.ssrc===1234)break;this.overallConsumersStatsMap[P]||(this.overallConsumersStatsMap[P]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const we=this.overallConsumersStatsMap[P];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.inboundConsumerMap.has(I.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(P)||d.consumerStreamMap.set(P,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const Je={bytesReceived:T.bytesReceived,packetsReceived:T.packetsReceived,packetsLost:T.packetsLost>=0?T.packetsLost:0,jitter:T.jitter,nackCount:T.nackCount,jitterBufferDelay:T.jitterBufferDelay,jitterBufferEmittedCount:T.jitterBufferEmittedCount,lastPacketReceivedTimestamp:T.lastPacketReceivedTimestamp,ssrc:T.ssrc,mid:T.mid,codecId:T.codecId,headerBytesReceived:T.headerBytesReceived||0,packetsDiscarded:T.packetsDiscarded||0,jitterBufferMinimumDelay:T.jitterBufferMinimumDelay||0,jitterBufferTargetDelay:T.jitterBufferTargetDelay||0};if(T.mediaType==="video"||T.kind==="video"){const V=T,k={frameHeight:V.frameHeight,frameWidth:V.frameWidth,framesDecoded:V.framesDecoded,framesDropped:V.framesDropped?V.framesDropped:V.droppedFrames,framesPerSecond:V.framesPerSecond?V.framesPerSecond:V.framerateMean,framesReceived:V.framesReceived,keyFramesDecoded:V.keyFramesDecoded,firCount:V.firCount,decoderImplementation:V.decoderImplementation,pliCount:V.pliCount,totalProcessingDelay:V.totalProcessingDelay,qpSum:V.qpSum||0,totalAssemblyTime:V.totalAssemblyTime||0,totalDecodeTime:V.totalDecodeTime||0,totalFreezesDuration:V.totalFreezesDuration||0,totalInterFrameDelay:V.totalInterFrameDelay||0,totalPausesDuration:V.totalPausesDuration||0,totalSquaredInterFrameDelay:V.totalSquaredInterFrameDelay||0,freezeCount:V.freezeCount||0,pauseCount:V.pauseCount||0,powerEfficientDecoder:V.powerEfficientDecoder,...Je};k.score=dg({frameWidth:k.frameWidth||0,framesDecoded:(k.framesDecoded||0)-(((_=this.videoConsumerToStatsMap.get(P))==null?void 0:_.framesDecoded)||0),framesPerSecond:k.framesPerSecond||0,packetsLost:(k.packetsLost||0)-(((w=this.videoConsumerToStatsMap.get(P))==null?void 0:w.packetsLost)||0),packetsReceived:(k.packetsReceived||0)-(((L=this.videoConsumerToStatsMap.get(P))==null?void 0:L.packetsReceived)||0),jitter:k.jitter||0,isScreenShare:this.screenShareConsumers.has(P)}),E.set(P,{score:+(k.score*10).toFixed(),frameWidth:k.frameWidth||0,frameHeight:k.frameHeight||0,framesPerSecond:k.framesPerSecond||0,packetsLostPercentage:md({packetsLost:(k.packetsLost||0)-(((B=this.videoConsumerToStatsMap.get(P))==null?void 0:B.packetsLost)||0),packetsReceived:(k.packetsReceived||0)-(((N=this.videoConsumerToStatsMap.get(P))==null?void 0:N.packetsReceived)||0)}),jitter:k.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((k.bytesReceived||0)-((($=this.videoConsumerToStatsMap.get(P))==null?void 0:$.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(P,k),d.inboundVideoRtp.set(I.id,k),d.consumerStreamMap.get(P).inboundVideoRtpId.push(I.id),this.processInboundConsumerVideoStats(P,we,k)}else if(T.mediaType==="audio"||T.kind==="audio"){const V=T,k={audioLevel:V.audioLevel,concealedSamples:V.concealedSamples,concealmentEvents:V.concealmentEvents,totalAudioEnergy:V.totalAudioEnergy,totalSamplesDuration:V.totalSamplesDuration,totalSamplesReceived:V.totalSamplesReceived,fecPacketsDiscarded:V.fecPacketsDiscarded||0,fecPacketsReceived:V.fecPacketsReceived||0,insertedSamplesForDeceleration:V.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:V.removedSamplesForAcceleration||0,silentConcealedSamples:V.silentConcealedSamples||0,playoutId:V.playoutId,...Je};k.score=cg({concealmentEvents:(k.concealmentEvents||0)-(((Y=this.audioConsumerToStatsMap.get(P))==null?void 0:Y.concealmentEvents)||0),packetsLost:(k.packetsLost||0)-(((ae=this.audioConsumerToStatsMap.get(P))==null?void 0:ae.packetsLost)||0),packetsReceived:(k.packetsReceived||0)-(((bt=this.audioConsumerToStatsMap.get(P))==null?void 0:bt.packetsReceived)||0),jitter:k.jitter||0}),E.set(P,{score:+(k.score*10).toFixed(),packetsLostPercentage:md({packetsLost:(k.packetsLost||0)-(((Bs=this.audioConsumerToStatsMap.get(P))==null?void 0:Bs.packetsLost)||0),packetsReceived:(k.packetsReceived||0)-(((On=this.audioConsumerToStatsMap.get(P))==null?void 0:On.packetsReceived)||0)}),jitter:k.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((k.bytesReceived||0)-((($s=this.audioConsumerToStatsMap.get(P))==null?void 0:$s.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(P,k),d.inboundAudioRtp.set(I.id,k),d.consumerStreamMap.get(P).inboundAudioRtpId.push(I.id),this.processInboundConsumerAudioStats(P,we,k)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}}}if(d.producerStreamMap.forEach((I,T)=>{var P,x,we,Je,V,k,Ke,fi,Lr,Gc,Wc,Jc,Kc,zc,Yc,Qc,Xc,Zc,ed,td,sd,rd,id;if(I.outboundVideoRtpId.length>0){const pe=[];I.outboundVideoRtpId.forEach(hp=>{pe.push(d.outboundVideoRtp.get(hp))});const te=this.getWorkingSimulcastVideoStats(pe);te.score=ag({frameWidth:te.frameWidth||0,framesPerSecond:te.framesPerSecond||0,jitter:((P=te.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsSent:(te.packetsSent||0)-(((x=this.videoProducerToStatsMap.get(T))==null?void 0:x.packetsSent)||0),packetsLost:(((we=te.remoteData)==null?void 0:we.packetsLost)||0)-(((V=(Je=this.videoProducerToStatsMap.get(T))==null?void 0:Je.remoteData)==null?void 0:V.packetsLost)||0),framesEncoded:(te.framesEncoded||0)-(((k=this.videoProducerToStatsMap.get(T))==null?void 0:k.framesEncoded)||0)}),v.set(T,{score:+(te.score*10).toFixed(),frameWidth:te.frameWidth||0,frameHeight:te.frameHeight||0,framesPerSecond:te.framesPerSecond||0,jitter:((Ke=te.remoteData)==null?void 0:Ke.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsLostPercentage:gd({packetsSent:(te.packetsSent||0)-(((fi=this.videoProducerToStatsMap.get(T))==null?void 0:fi.packetsSent)||0),packetsLost:(((Lr=te.remoteData)==null?void 0:Lr.packetsLost)||0)-(((Wc=(Gc=this.videoProducerToStatsMap.get(T))==null?void 0:Gc.remoteData)==null?void 0:Wc.packetsLost)||0)}),bitrate:((te.bytesSent||0)-(((Jc=this.videoProducerToStatsMap.get(T))==null?void 0:Jc.bytesSent)||0))*8/7,cpuLimitations:te.qualityLimitationReason==="cpu",bandwidthLimitations:te.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(T,te)}else if(I.outboundAudioRtpId.length>0){const pe=d.outboundAudioRtp.get(I.outboundAudioRtpId[0]);pe.score=ng({packetsSent:(pe.packetsSent||0)-(((Kc=this.audioProducerToStatsMap.get(T))==null?void 0:Kc.packetsSent)||0),packetsLost:(((zc=pe.remoteData)==null?void 0:zc.packetsLost)||0)-(((Qc=(Yc=this.audioProducerToStatsMap.get(T))==null?void 0:Yc.remoteData)==null?void 0:Qc.packetsLost)||0),jitter:((Xc=pe.remoteData)==null?void 0:Xc.jitter)||0}),v.set(T,{score:+(pe.score*10).toFixed(),bitrate:((pe.bytesSent||0)-(((Zc=this.audioProducerToStatsMap.get(T))==null?void 0:Zc.bytesSent)||0))*8/7,packetsLostPercentage:gd({packetsSent:(pe.packetsSent||0)-(((ed=this.audioProducerToStatsMap.get(T))==null?void 0:ed.packetsSent)||0),packetsLost:(((td=pe.remoteData)==null?void 0:td.packetsLost)||0)-(((rd=(sd=this.audioProducerToStatsMap.get(T))==null?void 0:sd.remoteData)==null?void 0:rd.packetsLost)||0)}),jitter:((id=pe.remoteData)==null?void 0:id.jitter)||0,isScreenShare:this.screenShareProducers.has(T)}),this.audioProducerToStatsMap.set(T,pe)}}),g.forEach(I=>{const T=u.find(x=>x.id===I.localCandidateId?(I.localCandidateId=x.id,x):null),P=h.find(x=>x.id===I.remoteCandidateId?(I.remoteCandidateId=x.id,x):null);T&&(I.localCandidateType=T.type,I.localCandidateAddress=Ur(T.address),I.localCandidatePort=T.port,I.localCandidateProtocol=T.protocol,I.localCandidateUrl=T.url,I.localCandidateNetworkType=T.networkType,I.localCandidateRelatedAddress=Ur(T.relatedAddress),I.localCandidateRelatedPort=T.relatedPort),P&&(I.remoteCandidateType=P.type,I.remoteCandidateAddress=Ur(P.address),I.remoteCandidatePort=P.port,I.remoteCandidateProtocol=P.protocol,I.remoteCandidateUrl=P.url)}),d.candidatePair&&(d.transport?(d.transport.bytesReceived=d.candidatePair.bytesReceived,d.transport.bytesSent=d.candidatePair.bytesSent,d.transport.totalRoundTripTime=d.candidatePair.totalRoundTripTime,d.transport.availableOutgoingBitrate=d.candidatePair.availableOutgoingBitrate,d.transport.availableIncomingBitrate=d.candidatePair.availableIncomingBitrate,d.transport.roundTripTime=d.candidatePair.currentRoundTripTime):d.transport={bytesReceived:d.candidatePair.bytesReceived,bytesSent:d.candidatePair.bytesSent,totalRoundTripTime:d.candidatePair.totalRoundTripTime,availableOutgoingBitrate:d.candidatePair.availableOutgoingBitrate,availableIncomingBitrate:d.candidatePair.availableIncomingBitrate,roundTripTime:d.candidatePair.currentRoundTripTime}),d.transport&&(d.transport.candidatePairs=g),d.transport&&!d.transport.roundTripTime){let I=0,T=0;d.remoteInboundRtp.forEach((P,x)=>{P.roundTripTime&&P.roundTripTime>I&&(I=P.roundTripTime,T=P.totalRoundTripTime)}),d.transport.roundTripTime=I,d.transport.totalRoundTripTime=T}if(E.size>0)try{this.observer.emit("consumer_score",E)}catch(I){}if(v.size>0)try{this.observer.emit("producer_score",v)}catch(I){}return d}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((i,n)=>{const o=this.producerMap.get(n),c=o.track.getSettings(),d=i.outboundVideoRtpId.map(u=>{const h=e.outboundVideoRtp.get(u);return h.frameHeight||(h.frameHeight=c.height,h.frameWidth=c.width,h.framesPerSecond=c.frameRate),h}),l={producerId:n,appData:o.appData,videoStats:d,audioStats:i.outboundAudioRtpId.map(u=>e.outboundAudioRtp.get(u))};r.push(l)})}catch(i){console.error("getProducersReport: ",i,e)}return r}getConsumerStatsFromParsedConsumerStats(e,r,i){let n;try{const{peerId:o,producerId:c,appData:d}=this.consumerPeerIdMap.get(i),l=r==null?void 0:r.inboundVideoRtpId.map(u=>{const g=this.consumerMap.get(i).track.getSettings(),v=e.inboundVideoRtp.get(u);return v.frameHeight||(v.frameHeight=g.height,v.frameWidth=g.width,v.framesPerSecond=g.frameRate),v});n={consumerId:i,peerId:o,producerId:c,appData:d,videoStats:l,audioStats:r==null?void 0:r.inboundAudioRtpId.map(u=>e.inboundAudioRtp.get(u))}}catch(o){console.error("getConsumerStatsFromParsedConsumerStats: ",o,e)}return n}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((i,n)=>{r.push(this.getConsumerStatsFromParsedConsumerStats(e,i,n))})}catch(i){console.error("getConsumerStatsFromReport: ",i,e)}return r}}class $T extends mg{}function Td(s,t,e,r){if(s!=null&&s.logger&&s.logger.error("Callstats::handleError",{error:r}),typeof e=="function"&&r instanceof t)e.call(null,r,s);else throw r}function fg(s,t,e){const r=s.value;return s.value=function(...i){try{const n=r.apply(this,i);return n&&n instanceof Promise?n.catch(o=>{Td(this,t,e,o)}):n}catch(n){Td(this,t,e,n)}return null},s}const Q=(s,t)=>(e,r,i)=>{const n=i.value;return i.value=function(...o){try{const c=n.apply(this,o);return c&&c instanceof Promise?c.catch(d=>{Td(this,s,t,d)}):c}catch(c){Td(this,s,t,c)}return null},i},HT=(s,t)=>(e,r,i)=>{if(i)return fg(i,s,t);for(const n of Reflect.ownKeys(e.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(e.prototype,n);o.value instanceof Function&&Object.defineProperty(e.prototype,n,fg(o,s,t))}};var K=globalThis&&globalThis.__decorate||function(s,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(s,t,e,r);else for(var c=s.length-1;c>=0;c--)(o=s[c])&&(n=(i<3?o(n):i>3?o(t,e,n):o(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n};const z=console;let W=class extends lt{constructor(e="https://api.testingv3.dyte.in",r="Blink",i=oo.PROD,n,o,c,d){super();p(this,"observer");p(this,"eventHandler");p(this,"measurements");p(this,"producingTransport");p(this,"consumingTransport");p(this,"producers",new Map);p(this,"consumers",new Map);p(this,"iceServers");p(this,"connectionInfoPromise");p(this,"pingStatsTimeout");p(this,"logger");p(this,"env");p(this,"apiHostnames");p(this,"peerId");p(this,"consumerSharedMediaStatesMap",new Map);p(this,"currentUserMediaStates",{});switch(this.env=i,this.apiHostnames=d,this.logger=o,this.peerId=c,this.eventHandler=new CT({logger:o,peerId:c,apiHostnames:d}),this.logger.debug("callStats::engineName: ",{engineName:r}),r){case"Blink":this.measurements=new BT;break;case"Gecko":this.measurements=new mg;break;case"WebKit":this.measurements=new $T;break;default:throw Error(`Unknown engineName! ${r}`)}this.measurements.callStatsInstance=this,this.registerProducer=this.registerProducer.bind(this),this.registerConsumer=this.registerConsumer.bind(this),this.observer=new lt,this.measurements.observer.on("consumer_score",l=>{o.debug(`callStats::consumer_score ${[...l.entries()]}`),this.eventHandler.emit("consumer_score",l)}),this.measurements.observer.on("producer_score",l=>{o.debug(`callStats::producer_score ${[...l.entries()]}`),this.eventHandler.emit("producer_score",l)})}registerIceServers(e){this.iceServers=e}registerConsumer(e){var r;this.consumerSharedMediaStatesMap.has(e.id)||this.consumerSharedMediaStatesMap.set(e.id,{}),this.consumers.set(e.id,e),this.measurements.registerConsumer(e),this.logger.debug("callStats::registerConsumer",{consumerId:e.id,consumerkind:e.kind,isScreenShare:!!((r=e.appData)!=null&&r.screenShare)}),e.on("close",this.deRegisterConsumer.bind(this,e))}registerProducer(e){var r;this.producers.set(e.id,e),this.measurements.registerProducer(e),this.logger.debug("callStats::registerProducer",{producerId:e.id,producerKind:e.kind,isScreenShare:!!((r=e.appData)!=null&&r.screenShare)}),e.on("close",this.deRegisterProducer.bind(this,e))}sendConsumerSharedMediaStateEvent(e,r){this.consumerSharedMediaStatesMap.has(e)||this.consumerSharedMediaStatesMap.set(e,{});const i=this.consumerSharedMediaStatesMap.get(e);this.consumerSharedMediaStatesMap.set(e,Object.assign(i,r))}registerProducingTransport(e){var i;this.producingTransport=e,e.on("close",this.disconnectProducingTransport.bind(this,e)),e.on("disconnect",this.disconnectProducingTransport.bind(this,e)),Array.from(((i=e._producers)==null?void 0:i.values())||[]).forEach(n=>{this.registerProducer(n)}),e.on("newproducer",this.registerProducer)}registerConsumingTransport(e){var i;this.consumingTransport=e,e.on("close",this.disconnectConsumingTransport.bind(this,e)),e.on("disconnect",this.disconnectConsumingTransport.bind(this,e)),Array.from(((i=e._consumers)==null?void 0:i.values())||[]).forEach(n=>{this.registerConsumer(n)}),e.on("newconsumer",this.registerConsumer)}deRegisterConsumer(e){this.consumers.delete(e.id)}deRegisterProducer(e){var r;this.producers.delete(e.id),this.logger.debug("callStats::deRegisterProducer",{producerId:e.id,producerKind:e.kind,isScreenShare:!!((r=e.appData)!=null&&r.screenShare)})}disconnectConsumingTransport(){this.consumingTransport=void 0}disconnectProducingTransport(){this.producingTransport=void 0}callEvent(e){this.eventHandler.callEvent(e)}sendPreCallTestBeginEvent(e=!1,r){this.connectionInfoPromise=this.measurements.getNetworkInfo(this.iceServers,e),this.eventHandler.callEvent({event:D.PRECALL_TEST_BEGIN,timestamp:r}),this.connectionInfoPromise&&this.connectionInfoPromise.then(i=>{this.eventHandler.callEvent({event:D.PRECALL_TEST_COMPLETE,metaData:{connectionInfo:i},timestamp:r})})}sendScreenShareToggleEvent(e,r=null,i){this.currentUserMediaStates.screen=e,this.eventHandler.callEvent({event:e?D.SCREENSHARE_STARTED:D.SCREENSHARE_STOPPED,metaData:{ssrc:r},timestamp:i})}sendScreenShareRequestedEvent(e){this.eventHandler.callEvent({event:D.SCREENSHARE_START_REQUESTED,timestamp:e})}sendActiveSpeakerEvent(e,r){this.eventHandler.callEvent({event:D.DOMINANT_SPEAKER,metaData:{peerId:e},timestamp:r})}devices(e,r,i){this.eventHandler.callEvent({event:e===is.AUDIO&&D.AUDIO_DEVICES_UPDATES||e===is.VIDEO&&D.VIDEO_DEVICES_UPDATES||e===is.SPEAKER&&D.SPEAKER_DEVICES_UPDATES,metaData:{deviceList:r},timestamp:i})}selectedDevice(e,r,i){this.eventHandler.callEvent({event:e===is.AUDIO&&D.SELECTED_MICROHPONE_UPDATE||e===is.VIDEO&&D.SELECTED_CAMERA_UPDATE||e===is.SPEAKER&&D.SELECTED_SPEAKER_UPDATE,metaData:{device:r},timestamp:i})}mediaPermission(e,r,i){this.eventHandler.callEvent({event:D.MEDIA_PERMISSION,metaData:{deviceType:e,permission:r},timestamp:i})}mediaPlaybackFailed(e,r){this.eventHandler.callEvent({event:e===is.AUDIO&&D.AUDIO_PLAY_FAILED||e===is.VIDEO&&D.VIDEO_PLAY_FAILED,metaData:{deviceType:e},timestamp:r})}mediaTrackMuted(e,r){this.eventHandler.callEvent({event:e===is.AUDIO&&D.AUDIO_TRACK_MUTED||e===is.VIDEO&&D.VIDEO_TRACK_MUTED,metaData:{deviceType:e},timestamp:r})}tabChanged(e,r){this.eventHandler.callEvent({event:D.TAB_CHANGE,metaData:{isMeetingsTabActive:e},timestamp:r})}browserBackgrounded(e){this.eventHandler.callEvent({event:D.BROWSER_BACKGROUNDED,timestamp:e})}browserForegrounded(e){this.eventHandler.callEvent({event:D.BROWSER_FOREGROUNDED,timestamp:e})}legacySwitch(e,r){this.eventHandler.callEvent({event:D.LEGACY_SWITCH,metadata:{on:e},timestamp:r})}async getPreCallTestResults(){return this.connectionInfoPromise}sendCallJoinBeginEvent(e,r){e={...e,meetingEnv:this.env},e.deviceInfo={...e.deviceInfo,userAgent:navigator.userAgent,cpus:navigator.hardwareConcurrency,memory:navigator.deviceMemory},this.eventHandler.callEvent({event:D.CALL_JOIN_BEGIN,metaData:{peerMetaData:e},timestamp:r})}sendNetworkQualityTestBeginEvent(e,r){this.eventHandler.callEvent({event:D.NET_QUALITY_TEST_BEGIN,timestamp:r}),new Promise(async(n,o)=>{const c=[];try{for(const d of e)try{if(d.iceServers&&d.iceServers.length>0){const l=await this.measurements.getNetworkQuality(d.iceServers);c.push({...d,networkResults:l})}}catch(l){console.warn("Error handling ",l)}n({regionData:c})}catch(d){console.warn("Error in callstats, ",d),o(d)}}).then(n=>{this.eventHandler.callEvent({event:D.NET_QUALITY_TEST_END,timestamp:r,metaData:n})})}sendWebSocketConnectedEvent(e){this.eventHandler.callEvent({event:D.WEBSOCKET_CONNECTED,timestamp:e})}sendTransportConnectedEvent(e){this.eventHandler.callEvent({event:D.TRANSPORT_CONNECTED,timestamp:e})}sendAudioToggleEvent(e,r){this.currentUserMediaStates.audio=e;let i;e?i=D.AUDIO_ON:i=D.AUDIO_OFF,this.eventHandler.callEvent({event:i,timestamp:r})}sendVideoToggleEvent(e,r){this.currentUserMediaStates.video=e;let i;e?i=D.VIDEO_ON:i=D.VIDEO_OFF,this.eventHandler.callEvent({event:i,timestamp:r})}sendParticipantRoleToggleEvent(e,r){this.eventHandler.callEvent({event:D.PARTICIPANT_ROLE,timestamp:r,metaData:e})}startPingStats(e=7e3){this.sendPingStatsEvent(!1,new Date),this.pingStatsTimeout=setInterval(this.sendPingStatsEvent.bind(this),e)}stopPingStats(){clearInterval(this.pingStatsTimeout)}async sendPingStatsEvent(e=!0,r){let i,n;if(this.producingTransport&&(i=await this.measurements.getProcessedStats(this.producingTransport,!1,!0),!i||!(i!=null&&i.producerReport))){this.logger.debug("callStats::sendPingStatsEvent::staleProducingTransport",{disclaimer:"Stale producer? Regenerating Stream Maps!"});const c=await this.measurements.getProducersReport([...this.producers.values()]);i&&c?i.producerReport=c:(i=await this.measurements.getProcessedStats(this.producingTransport,!1,!0),(!i||!(i!=null&&i.producerReport))&&this.logger.debug("callStats::sendPingStatsEvent::noProducingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}if(this.consumingTransport&&(n=await this.measurements.getProcessedStats(this.consumingTransport,!0,!1),!n||!n.consumerReport)){this.logger.debug("callStats::sendPingStatsEvent::staleConsumingTransport",{disclaimer:"Stale consumer? Regenerating Stream Maps!"});const c=await this.measurements.getConsumersReport([...this.consumers.values()]);n&&c?n.consumerReport=c:(n=await this.measurements.getProcessedStats(this.consumingTransport,!0,!1),(!n||!n.consumerReport)&&this.logger.debug("callStats::sendPingStatsEvent::noConsumingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}const o={producingTransportStats:i?i==null?void 0:i.transportReport:void 0,consumingTransportStats:n?n==null?void 0:n.transportReport:void 0,producerStats:[].concat((i==null?void 0:i.producerReport)||[]).concat((n==null?void 0:n.producerReport)||[]),consumerStats:[].concat((n==null?void 0:n.consumerReport)||[]).concat((i==null?void 0:i.consumerReport)||[])};if(e&&o.producerStats.length===0&&o.consumerStats.length===0){await this.eventHandler.flush();return}this.eventHandler.callEvent({event:D.PING_STAT,metaData:o,timestamp:r})}sendIVSPlayerRebufferEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_REBUFFERING,timestamp:e})}sendIVSPlayerAudioBlockEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_AUDIO_BLOCKED,timestamp:e})}sendIVSPlayerPlaybackBlockedEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_PLAYBACK_BLOCKED,timestamp:e})}sendIVSPlayerNetworkUnavailableEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_NETWORK_UNAVAILABLE,timestamp:e})}sendIVSPlayerInitializedEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_INITIALIZED,timestamp:e})}sendIVSPlayerWorkerErrorEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_WORKER_ERROR,timestamp:e})}sendIVSPlayerErrorEvent(e,r){this.eventHandler.callEvent({event:D.IVS_PLAYER_ERROR,timestamp:r,metaData:e})}sendIVSPlayerRecoverableErrorEvent(e,r){this.eventHandler.callEvent({event:D.IVS_PLAYER_RECOVERABLE_ERROR,timestamp:r,metaData:e})}sendIVSPlayerAnalyticsEvent(e,r){this.eventHandler.callEvent({event:D.IVS_PLAYER_ANALYTICS_EVENT,timestamp:r,metaData:e})}sendIVSPlayerPlaybackRateChangedEvent(e,r){this.eventHandler.callEvent({event:D.IVS_PLAYER_PLAYBACK_RATE_CHANGED,timestamp:r,metaData:{updatedPlaybackRate:e}})}sendIVSPlayerQualityChanged(e,r){this.eventHandler.callEvent({event:D.IVS_PLAYER_QUALITY_CHANGED,timestamp:r,metaData:e})}sendPlayerLiveLatency(e,r){this.eventHandler.callEvent({event:D.LIVESTREAM_LATENCY,timestamp:r,metaData:{latency:e}})}sendDisconnectEvent(e){this.eventHandler.callEvent({event:D.DISCONNECT,timestamp:e})}sendReconnectEvent(e){this.eventHandler.callEvent({event:D.RECONNECT_ATTEMPT,timestamp:e})}expectedVideoResolution(e,r,i){this.eventHandler.callEvent({event:D.EXPECTED_VIDEO_RESOLUTION,timestamp:i,metaData:{frameWidth:e,frameHeight:r}})}expectedScreenshareResolution(e,r,i){this.eventHandler.callEvent({event:D.EXPECTED_SCREENSHARE_RESOLUTION,timestamp:i,metaData:{frameWidth:e,frameHeight:r}})}};K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"registerIceServers",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"registerConsumer",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"registerProducer",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendConsumerSharedMediaStateEvent",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"registerProducingTransport",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"registerConsumingTransport",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"deRegisterConsumer",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"deRegisterProducer",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"disconnectConsumingTransport",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"disconnectProducingTransport",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendPreCallTestBeginEvent",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendScreenShareToggleEvent",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendScreenShareRequestedEvent",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendActiveSpeakerEvent",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"devices",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"selectedDevice",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"mediaPermission",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"mediaPlaybackFailed",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"mediaTrackMuted",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"tabChanged",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"browserBackgrounded",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"browserForegrounded",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"legacySwitch",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"getPreCallTestResults",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendCallJoinBeginEvent",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendNetworkQualityTestBeginEvent",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendWebSocketConnectedEvent",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendTransportConnectedEvent",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendAudioToggleEvent",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendVideoToggleEvent",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendParticipantRoleToggleEvent",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"startPingStats",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"stopPingStats",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendPingStatsEvent",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerRebufferEvent",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerAudioBlockEvent",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerPlaybackBlockedEvent",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerNetworkUnavailableEvent",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerInitializedEvent",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerWorkerErrorEvent",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerErrorEvent",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerRecoverableErrorEvent",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerAnalyticsEvent",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerPlaybackRateChangedEvent",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerQualityChanged",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendPlayerLiveLatency",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendDisconnectEvent",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendReconnectEvent",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"expectedVideoResolution",null),K([Q(TypeError,(s,t)=>z.error(t,s))],W.prototype,"expectedScreenshareResolution",null),W=K([HT(TypeError,(s,t)=>z.error(t,s))],W);const qT=W;class vg extends lt{constructor(){super(...arguments);p(this,"stats");p(this,"peerId");p(this,"backend");p(this,"iceServers");p(this,"initialized",!1);p(this,"stalled",!1);p(this,"ipInformation");p(this,"logger")}async initialize({peerId:e,engineName:r,env:i=oo.PROD,iceServers:n,apiBase:o="https://api.cluster.dyte.in",flags:c,logger:d=console,apiHostnames:l,skipConnectivityChecks:u=!1}){var h,g,v;try{this.peerId=e,this.logger=d,this.ipInformation=await Au.getIPDetails({peerId:e,apiHostnames:l,logger:d}),this.backend=new qT(o,r,i,c,d,e,l),this.iceServers=n,(h=this.backend)==null||h.registerIceServers(this.iceServers),this.initialized=!0,(v=(g=this.backend)==null?void 0:g.eventHandler)==null||v.emit("initialized",this.ipInformation),this.emit("initialized",this.ipInformation),this.startPreCallTest(u)}catch(E){this.logger.error("callStats::CallStatsIntegration: ",{error:E}),this.stallCallStats()}}configureSendTransport(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.registerProducingTransport(e)})}configureRecvTransport(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.registerConsumingTransport(e)})}async candidateRegionalNetworkQualityTest(e){const r=new Date;this.onSafeInitialization(()=>{var i;try{(i=this.backend)==null||i.sendNetworkQualityTestBeginEvent(e,r)}catch(n){this.logger.error("callStats::sendNetworkQualityTestBeginEvent",{error:{reason:n.reason}})}})}async roomJoined(e){const r=new Date;this.onSafeInitialization(()=>{var i,n;(i=this.backend)==null||i.sendCallJoinBeginEvent(e,r),this.backend,(n=this.backend)==null||n.startPingStats()})}audioOff(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendAudioToggleEvent(!1,e)})}audioOn(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendAudioToggleEvent(!0,e)})}videoOff(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendVideoToggleEvent(!1,e)})}videoOn(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendVideoToggleEvent(!0,e)})}callEnded(){const e=new Date;this.onSafeInitialization(()=>{var r,i;(r=this.backend)==null||r.stopPingStats(),(i=this.backend)==null||i.sendDisconnectEvent(e)})}screenShareStart(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendScreenShareToggleEvent(!0,e,r)})}consumerSharedMediaState(e,r){this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendConsumerSharedMediaStateEvent(e,r)})}screenShareStop(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendScreenShareToggleEvent(!1,e,r)})}screenShareRequested(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendScreenShareRequestedEvent(e)})}activeSpeaker(e){if(e!==this.peerId)return;const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendActiveSpeakerEvent(e,r)})}devices(e,r){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.devices(e,r,i)})}selectedDevice(e,r){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.selectedDevice(e,r,i)})}mediaPermission(e,r){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.mediaPermission(e,r,i)})}mediaPlaybackFailed(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.mediaPlaybackFailed(e,r)})}mediaTrackMuted(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.mediaTrackMuted(e,r)})}tabChanged(e=!1){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.tabChanged(e,r)})}browserBackgrounded(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.browserBackgrounded(e)})}browserForegrounded(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.browserForegrounded(e)})}legacySwitch(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.legacySwitch(e,r)})}async startPreCallTest(e=!1){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendPreCallTestBeginEvent(e,r)})}onPreCallTestResults(e){return this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.once("precall_end",e)}),e}onReceivingConsumerAudioStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consumer_audio_status",e)})}onReceivingConsumerVideoStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consumer_video_status",e)})}onReceivingProducerAudioStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producer_audio_status",e)})}onReceivingProducerVideoStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producer_video_status",e)})}onReceivingProducingTransportStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producing_transport_status",e)})}onReceivingConsumingTransportStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consuming_transport_status",e)})}onProducerScore(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producer_score",e)})}onConsumerScore(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consumer_score",e)})}onSafeInitialization(e){if(this.initialized)e(this.ipInformation,!1);else if(!this.stalled){const r=i=>{e(i,!0)};return this.once("initialized",r),r}return()=>{}}removeInitializationListener(e){this.removeListener("initialized",e)}stallCallStats(){this.stalled=!0,this.removeAllListeners("initialized")}ivsPlayerEvent(e,r){const i=new Date;this.onSafeInitialization(()=>{var n,o,c,d,l,u,h,g,v,E,b;switch(e){case"PlayerRebuffering":(n=this.backend)==null||n.sendIVSPlayerRebufferEvent(i);break;case"PlayerAudioBlocked":(o=this.backend)==null||o.sendIVSPlayerAudioBlockEvent(i);break;case"PlayerPlaybackBlocked":(c=this.backend)==null||c.sendIVSPlayerPlaybackBlockedEvent(i);break;case"PlayerNetworkUnavailable":(d=this.backend)==null||d.sendIVSPlayerNetworkUnavailableEvent(i);break;case"PlayerInitialized":(l=this.backend)==null||l.sendIVSPlayerInitializedEvent(i);break;case"PlayerWorkerError":(u=this.backend)==null||u.sendIVSPlayerWorkerErrorEvent(i);break;case"PlayerError":(h=this.backend)==null||h.sendIVSPlayerErrorEvent(r,i);break;case"PlayerRecoverableError":(g=this.backend)==null||g.sendIVSPlayerRecoverableErrorEvent(r,i);break;case"PlayerAnalyticsEvent":(v=this.backend)==null||v.sendIVSPlayerAnalyticsEvent(r,i);break;case"PlayerPlaybackRateChanged":(E=this.backend)==null||E.sendIVSPlayerPlaybackRateChangedEvent(r,i);break;case"PlayerQualityChanged":(b=this.backend)==null||b.sendIVSPlayerQualityChanged(r,i);break}})}livestreamLatency(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendPlayerLiveLatency(e,r)})}expectedVideoResolution(e,r){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.expectedVideoResolution(e,r,i)})}expectedScreenshareResolution(e,r){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.expectedScreenshareResolution(e,r,i)})}}new vg().setMaxListeners(30);function jT(){this.__data__=[],this.size=0}function co(s,t){return s===t||s!==s&&t!==t}function yd(s,t){for(var e=s.length;e--;)if(co(s[e][0],t))return e;return-1}var GT=Array.prototype,WT=GT.splice;function JT(s){var t=this.__data__,e=yd(t,s);if(e<0)return!1;var r=t.length-1;return e==r?t.pop():WT.call(t,e,1),--this.size,!0}function KT(s){var t=this.__data__,e=yd(t,s);return e<0?void 0:t[e][1]}function zT(s){return yd(this.__data__,s)>-1}function YT(s,t){var e=this.__data__,r=yd(e,s);return r<0?(++this.size,e.push([s,t])):e[r][1]=t,this}function rr(s){var t=-1,e=s==null?0:s.length;for(this.clear();++t<e;){var r=s[t];this.set(r[0],r[1])}}rr.prototype.clear=jT,rr.prototype.delete=JT,rr.prototype.get=KT,rr.prototype.has=zT,rr.prototype.set=YT;function QT(){this.__data__=new rr,this.size=0}function XT(s){var t=this.__data__,e=t.delete(s);return this.size=t.size,e}function ZT(s){return this.__data__.get(s)}function ey(s){return this.__data__.has(s)}var ty=typeof global=="object"&&global&&global.Object===Object&&global;const Sg=ty;var sy=typeof self=="object"&&self&&self.Object===Object&&self,ry=Sg||sy||Function("return this")();const ys=ry;var iy=ys.Symbol;const qs=iy;var Tg=Object.prototype,ny=Tg.hasOwnProperty,ay=Tg.toString,lo=qs?qs.toStringTag:void 0;function oy(s){var t=ny.call(s,lo),e=s[lo];try{s[lo]=void 0;var r=!0}catch(n){}var i=ay.call(s);return r&&(t?s[lo]=e:delete s[lo]),i}var cy=Object.prototype,dy=cy.toString;function ly(s){return dy.call(s)}var uy="[object Null]",hy="[object Undefined]",yg=qs?qs.toStringTag:void 0;function Ti(s){return s==null?s===void 0?hy:uy:yg&&yg in Object(s)?oy(s):ly(s)}function ns(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var py="[object AsyncFunction]",gy="[object Function]",my="[object GeneratorFunction]",fy="[object Proxy]";function Mu(s){if(!ns(s))return!1;var t=Ti(s);return t==gy||t==my||t==py||t==fy}var vy=ys["__core-js_shared__"];const Ou=vy;var Eg=function(){var s=/[^.]+$/.exec(Ou&&Ou.keys&&Ou.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function Sy(s){return!!Eg&&Eg in s}var Ty=Function.prototype,yy=Ty.toString;function yi(s){if(s!=null){try{return yy.call(s)}catch(t){}try{return s+""}catch(t){}}return""}var Ey=/[\\^$.*+?()[\]{}|]/g,by=/^\[object .+?Constructor\]$/,wy=Function.prototype,_y=Object.prototype,Py=wy.toString,Cy=_y.hasOwnProperty,Ry=RegExp("^"+Py.call(Cy).replace(Ey,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function ky(s){if(!ns(s)||Sy(s))return!1;var t=Mu(s)?Ry:by;return t.test(yi(s))}function Iy(s,t){return s==null?void 0:s[t]}function Ei(s,t){var e=Iy(s,t);return ky(e)?e:void 0}var Ay=Ei(ys,"Map");const uo=Ay;var My=Ei(Object,"create");const ho=My;function Oy(){this.__data__=ho?ho(null):{},this.size=0}function Dy(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var Ny="__lodash_hash_undefined__",Vy=Object.prototype,Ly=Vy.hasOwnProperty;function xy(s){var t=this.__data__;if(ho){var e=t[s];return e===Ny?void 0:e}return Ly.call(t,s)?t[s]:void 0}var Uy=Object.prototype,Fy=Uy.hasOwnProperty;function By(s){var t=this.__data__;return ho?t[s]!==void 0:Fy.call(t,s)}var $y="__lodash_hash_undefined__";function Hy(s,t){var e=this.__data__;return this.size+=this.has(s)?0:1,e[s]=ho&&t===void 0?$y:t,this}function bi(s){var t=-1,e=s==null?0:s.length;for(this.clear();++t<e;){var r=s[t];this.set(r[0],r[1])}}bi.prototype.clear=Oy,bi.prototype.delete=Dy,bi.prototype.get=xy,bi.prototype.has=By,bi.prototype.set=Hy;function qy(){this.size=0,this.__data__={hash:new bi,map:new(uo||rr),string:new bi}}function jy(s){var t=typeof s;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?s!=="__proto__":s===null}function Ed(s,t){var e=s.__data__;return jy(t)?e[typeof t=="string"?"string":"hash"]:e.map}function Gy(s){var t=Ed(this,s).delete(s);return this.size-=t?1:0,t}function Wy(s){return Ed(this,s).get(s)}function Jy(s){return Ed(this,s).has(s)}function Ky(s,t){var e=Ed(this,s),r=e.size;return e.set(s,t),this.size+=e.size==r?0:1,this}function ir(s){var t=-1,e=s==null?0:s.length;for(this.clear();++t<e;){var r=s[t];this.set(r[0],r[1])}}ir.prototype.clear=qy,ir.prototype.delete=Gy,ir.prototype.get=Wy,ir.prototype.has=Jy,ir.prototype.set=Ky;var zy=200;function Yy(s,t){var e=this.__data__;if(e instanceof rr){var r=e.__data__;if(!uo||r.length<zy-1)return r.push([s,t]),this.size=++e.size,this;e=this.__data__=new ir(r)}return e.set(s,t),this.size=e.size,this}function Es(s){var t=this.__data__=new rr(s);this.size=t.size}Es.prototype.clear=QT,Es.prototype.delete=XT,Es.prototype.get=ZT,Es.prototype.has=ey,Es.prototype.set=Yy;function Qy(s,t){for(var e=-1,r=s==null?0:s.length;++e<r&&t(s[e],e,s)!==!1;);return s}var Xy=function(){try{var s=Ei(Object,"defineProperty");return s({},"",{}),s}catch(t){}}();const bd=Xy;function Du(s,t,e){t=="__proto__"&&bd?bd(s,t,{configurable:!0,enumerable:!0,value:e,writable:!0}):s[t]=e}var Zy=Object.prototype,eE=Zy.hasOwnProperty;function bg(s,t,e){var r=s[t];(!(eE.call(s,t)&&co(r,e))||e===void 0&&!(t in s))&&Du(s,t,e)}function po(s,t,e,r){var i=!e;e||(e={});for(var n=-1,o=t.length;++n<o;){var c=t[n],d=r?r(e[c],s[c],c,e,s):void 0;d===void 0&&(d=s[c]),i?Du(e,c,d):bg(e,c,d)}return e}function tE(s,t){for(var e=-1,r=Array(s);++e<s;)r[e]=t(e);return r}function js(s){return s!=null&&typeof s=="object"}var sE="[object Arguments]";function wg(s){return js(s)&&Ti(s)==sE}var _g=Object.prototype,rE=_g.hasOwnProperty,iE=_g.propertyIsEnumerable,nE=wg(function(){return arguments}())?wg:function(s){return js(s)&&rE.call(s,"callee")&&!iE.call(s,"callee")};const go=nE;var aE=Array.isArray;const jt=aE;function oE(){return!1}var Pg=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Cg=Pg&&typeof module=="object"&&module&&!module.nodeType&&module,cE=Cg&&Cg.exports===Pg,Rg=cE?ys.Buffer:void 0,dE=Rg?Rg.isBuffer:void 0,lE=dE||oE;const Vn=lE;var uE=9007199254740991,hE=/^(?:0|[1-9]\d*)$/;function Nu(s,t){var e=typeof s;return t=t==null?uE:t,!!t&&(e=="number"||e!="symbol"&&hE.test(s))&&s>-1&&s%1==0&&s<t}var pE=9007199254740991;function Vu(s){return typeof s=="number"&&s>-1&&s%1==0&&s<=pE}var gE="[object Arguments]",mE="[object Array]",fE="[object Boolean]",vE="[object Date]",SE="[object Error]",TE="[object Function]",yE="[object Map]",EE="[object Number]",bE="[object Object]",wE="[object RegExp]",_E="[object Set]",PE="[object String]",CE="[object WeakMap]",RE="[object ArrayBuffer]",kE="[object DataView]",IE="[object Float32Array]",AE="[object Float64Array]",ME="[object Int8Array]",OE="[object Int16Array]",DE="[object Int32Array]",NE="[object Uint8Array]",VE="[object Uint8ClampedArray]",LE="[object Uint16Array]",xE="[object Uint32Array]",ye={};ye[IE]=ye[AE]=ye[ME]=ye[OE]=ye[DE]=ye[NE]=ye[VE]=ye[LE]=ye[xE]=!0,ye[gE]=ye[mE]=ye[RE]=ye[fE]=ye[kE]=ye[vE]=ye[SE]=ye[TE]=ye[yE]=ye[EE]=ye[bE]=ye[wE]=ye[_E]=ye[PE]=ye[CE]=!1;function UE(s){return js(s)&&Vu(s.length)&&!!ye[Ti(s)]}function Lu(s){return function(t){return s(t)}}var kg=typeof exports=="object"&&exports&&!exports.nodeType&&exports,mo=kg&&typeof module=="object"&&module&&!module.nodeType&&module,FE=mo&&mo.exports===kg,xu=FE&&Sg.process,BE=function(){try{var s=mo&&mo.require&&mo.require("util").types;return s||xu&&xu.binding&&xu.binding("util")}catch(t){}}();const Ln=BE;var Ig=Ln&&Ln.isTypedArray,$E=Ig?Lu(Ig):UE;const wd=$E;var HE=Object.prototype,qE=HE.hasOwnProperty;function Ag(s,t){var e=jt(s),r=!e&&go(s),i=!e&&!r&&Vn(s),n=!e&&!r&&!i&&wd(s),o=e||r||i||n,c=o?tE(s.length,String):[],d=c.length;for(var l in s)(t||qE.call(s,l))&&!(o&&(l=="length"||i&&(l=="offset"||l=="parent")||n&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||Nu(l,d)))&&c.push(l);return c}var jE=Object.prototype;function _d(s){var t=s&&s.constructor,e=typeof t=="function"&&t.prototype||jE;return s===e}function Mg(s,t){return function(e){return s(t(e))}}var GE=Mg(Object.keys,Object);const WE=GE;var JE=Object.prototype,KE=JE.hasOwnProperty;function Og(s){if(!_d(s))return WE(s);var t=[];for(var e in Object(s))KE.call(s,e)&&e!="constructor"&&t.push(e);return t}function fo(s){return s!=null&&Vu(s.length)&&!Mu(s)}function Pd(s){return fo(s)?Ag(s):Og(s)}function zE(s,t){return s&&po(t,Pd(t),s)}function YE(s){var t=[];if(s!=null)for(var e in Object(s))t.push(e);return t}var QE=Object.prototype,XE=QE.hasOwnProperty;function ZE(s){if(!ns(s))return YE(s);var t=_d(s),e=[];for(var r in s)r=="constructor"&&(t||!XE.call(s,r))||e.push(r);return e}function vo(s){return fo(s)?Ag(s,!0):ZE(s)}function eb(s,t){return s&&po(t,vo(t),s)}var Dg=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ng=Dg&&typeof module=="object"&&module&&!module.nodeType&&module,tb=Ng&&Ng.exports===Dg,Vg=tb?ys.Buffer:void 0,Lg=Vg?Vg.allocUnsafe:void 0;function xg(s,t){if(t)return s.slice();var e=s.length,r=Lg?Lg(e):new s.constructor(e);return s.copy(r),r}function Ug(s,t){var e=-1,r=s.length;for(t||(t=Array(r));++e<r;)t[e]=s[e];return t}function sb(s,t){for(var e=-1,r=s==null?0:s.length,i=0,n=[];++e<r;){var o=s[e];t(o,e,s)&&(n[i++]=o)}return n}function Fg(){return[]}var rb=Object.prototype,ib=rb.propertyIsEnumerable,Bg=Object.getOwnPropertySymbols,nb=Bg?function(s){return s==null?[]:(s=Object(s),sb(Bg(s),function(t){return ib.call(s,t)}))}:Fg;const Uu=nb;function ab(s,t){return po(s,Uu(s),t)}function $g(s,t){for(var e=-1,r=t.length,i=s.length;++e<r;)s[i+e]=t[e];return s}var ob=Mg(Object.getPrototypeOf,Object);const Fu=ob;var cb=Object.getOwnPropertySymbols,db=cb?function(s){for(var t=[];s;)$g(t,Uu(s)),s=Fu(s);return t}:Fg;const Hg=db;function lb(s,t){return po(s,Hg(s),t)}function qg(s,t,e){var r=t(s);return jt(s)?r:$g(r,e(s))}function Bu(s){return qg(s,Pd,Uu)}function ub(s){return qg(s,vo,Hg)}var hb=Ei(ys,"DataView");const $u=hb;var pb=Ei(ys,"Promise");const Hu=pb;var gb=Ei(ys,"Set");const xn=gb;var mb=Ei(ys,"WeakMap");const qu=mb;var jg="[object Map]",fb="[object Object]",Gg="[object Promise]",Wg="[object Set]",Jg="[object WeakMap]",Kg="[object DataView]",vb=yi($u),Sb=yi(uo),Tb=yi(Hu),yb=yi(xn),Eb=yi(qu),wi=Ti;($u&&wi(new $u(new ArrayBuffer(1)))!=Kg||uo&&wi(new uo)!=jg||Hu&&wi(Hu.resolve())!=Gg||xn&&wi(new xn)!=Wg||qu&&wi(new qu)!=Jg)&&(wi=function(s){var t=Ti(s),e=t==fb?s.constructor:void 0,r=e?yi(e):"";if(r)switch(r){case vb:return Kg;case Sb:return jg;case Tb:return Gg;case yb:return Wg;case Eb:return Jg}return t});const Un=wi;var bb=Object.prototype,wb=bb.hasOwnProperty;function _b(s){var t=s.length,e=new s.constructor(t);return t&&typeof s[0]=="string"&&wb.call(s,"index")&&(e.index=s.index,e.input=s.input),e}var Pb=ys.Uint8Array;const Cd=Pb;function ju(s){var t=new s.constructor(s.byteLength);return new Cd(t).set(new Cd(s)),t}function Cb(s,t){var e=t?ju(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.byteLength)}var Rb=/\w*$/;function kb(s){var t=new s.constructor(s.source,Rb.exec(s));return t.lastIndex=s.lastIndex,t}var zg=qs?qs.prototype:void 0,Yg=zg?zg.valueOf:void 0;function Ib(s){return Yg?Object(Yg.call(s)):{}}function Qg(s,t){var e=t?ju(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.length)}var Ab="[object Boolean]",Mb="[object Date]",Ob="[object Map]",Db="[object Number]",Nb="[object RegExp]",Vb="[object Set]",Lb="[object String]",xb="[object Symbol]",Ub="[object ArrayBuffer]",Fb="[object DataView]",Bb="[object Float32Array]",$b="[object Float64Array]",Hb="[object Int8Array]",qb="[object Int16Array]",jb="[object Int32Array]",Gb="[object Uint8Array]",Wb="[object Uint8ClampedArray]",Jb="[object Uint16Array]",Kb="[object Uint32Array]";function zb(s,t,e){var r=s.constructor;switch(t){case Ub:return ju(s);case Ab:case Mb:return new r(+s);case Fb:return Cb(s,e);case Bb:case $b:case Hb:case qb:case jb:case Gb:case Wb:case Jb:case Kb:return Qg(s,e);case Ob:return new r;case Db:case Lb:return new r(s);case Nb:return kb(s);case Vb:return new r;case xb:return Ib(s)}}var Xg=Object.create,Yb=function(){function s(){}return function(t){if(!ns(t))return{};if(Xg)return Xg(t);s.prototype=t;var e=new s;return s.prototype=void 0,e}}();const Qb=Yb;function Zg(s){return typeof s.constructor=="function"&&!_d(s)?Qb(Fu(s)):{}}var Xb="[object Map]";function Zb(s){return js(s)&&Un(s)==Xb}var em=Ln&&Ln.isMap,ew=em?Lu(em):Zb;const tw=ew;var sw="[object Set]";function rw(s){return js(s)&&Un(s)==sw}var tm=Ln&&Ln.isSet,iw=tm?Lu(tm):rw;const nw=iw;var aw=1,ow=2,cw=4,sm="[object Arguments]",dw="[object Array]",lw="[object Boolean]",uw="[object Date]",hw="[object Error]",rm="[object Function]",pw="[object GeneratorFunction]",gw="[object Map]",mw="[object Number]",im="[object Object]",fw="[object RegExp]",vw="[object Set]",Sw="[object String]",Tw="[object Symbol]",yw="[object WeakMap]",Ew="[object ArrayBuffer]",bw="[object DataView]",ww="[object Float32Array]",_w="[object Float64Array]",Pw="[object Int8Array]",Cw="[object Int16Array]",Rw="[object Int32Array]",kw="[object Uint8Array]",Iw="[object Uint8ClampedArray]",Aw="[object Uint16Array]",Mw="[object Uint32Array]",ge={};ge[sm]=ge[dw]=ge[Ew]=ge[bw]=ge[lw]=ge[uw]=ge[ww]=ge[_w]=ge[Pw]=ge[Cw]=ge[Rw]=ge[gw]=ge[mw]=ge[im]=ge[fw]=ge[vw]=ge[Sw]=ge[Tw]=ge[kw]=ge[Iw]=ge[Aw]=ge[Mw]=!0,ge[hw]=ge[rm]=ge[yw]=!1;function Rd(s,t,e,r,i,n){var o,c=t&aw,d=t&ow,l=t&cw;if(e&&(o=i?e(s,r,i,n):e(s)),o!==void 0)return o;if(!ns(s))return s;var u=jt(s);if(u){if(o=_b(s),!c)return Ug(s,o)}else{var h=Un(s),g=h==rm||h==pw;if(Vn(s))return xg(s,c);if(h==im||h==sm||g&&!i){if(o=d||g?{}:Zg(s),!c)return d?lb(s,eb(o,s)):ab(s,zE(o,s))}else{if(!ge[h])return i?s:{};o=zb(s,h,c)}}n||(n=new Es);var v=n.get(s);if(v)return v;n.set(s,o),nw(s)?s.forEach(function(_){o.add(Rd(_,t,e,_,s,n))}):tw(s)&&s.forEach(function(_,w){o.set(w,Rd(_,t,e,w,s,n))});var E=l?d?ub:Bu:d?vo:Pd,b=u?void 0:E(s);return Qy(b||s,function(_,w){b&&(w=_,_=s[w]),bg(o,w,Rd(_,t,e,w,s,n))}),o}var Ow=1,Dw=4;function Gu(s){return Rd(s,Ow|Dw)}var Nw="[object Symbol]";function kd(s){return typeof s=="symbol"||js(s)&&Ti(s)==Nw}var Vw=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Lw=/^\w*$/;function Wu(s,t){if(jt(s))return!1;var e=typeof s;return e=="number"||e=="symbol"||e=="boolean"||s==null||kd(s)?!0:Lw.test(s)||!Vw.test(s)||t!=null&&s in Object(t)}var xw="Expected a function";function Ju(s,t){if(typeof s!="function"||t!=null&&typeof t!="function")throw new TypeError(xw);var e=function(){var r=arguments,i=t?t.apply(this,r):r[0],n=e.cache;if(n.has(i))return n.get(i);var o=s.apply(this,r);return e.cache=n.set(i,o)||n,o};return e.cache=new(Ju.Cache||ir),e}Ju.Cache=ir;var Uw=500;function Fw(s){var t=Ju(s,function(r){return e.size===Uw&&e.clear(),r}),e=t.cache;return t}var Bw=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,$w=/\\(\\)?/g,Hw=Fw(function(s){var t=[];return s.charCodeAt(0)===46&&t.push(""),s.replace(Bw,function(e,r,i,n){t.push(i?n.replace($w,"$1"):r||e)}),t});const qw=Hw;function jw(s,t){for(var e=-1,r=s==null?0:s.length,i=Array(r);++e<r;)i[e]=t(s[e],e,s);return i}var Gw=1/0,nm=qs?qs.prototype:void 0,am=nm?nm.toString:void 0;function om(s){if(typeof s=="string")return s;if(jt(s))return jw(s,om)+"";if(kd(s))return am?am.call(s):"";var t=s+"";return t=="0"&&1/s==-Gw?"-0":t}function Ww(s){return s==null?"":om(s)}function cm(s,t){return jt(s)?s:Wu(s,t)?[s]:qw(Ww(s))}var Jw=1/0;function Id(s){if(typeof s=="string"||kd(s))return s;var t=s+"";return t=="0"&&1/s==-Jw?"-0":t}function dm(s,t){t=cm(t,s);for(var e=0,r=t.length;s!=null&&e<r;)s=s[Id(t[e++])];return e&&e==r?s:void 0}function Kw(s,t,e){var r=s==null?void 0:dm(s,t);return r===void 0?e:r}function zw(s,t,e){t=cm(t,s);for(var r=-1,i=t.length,n=!1;++r<i;){var o=Id(t[r]);if(!(n=s!=null&&e(s,o)))break;s=s[o]}return n||++r!=i?n:(i=s==null?0:s.length,!!i&&Vu(i)&&Nu(o,i)&&(jt(s)||go(s)))}var Yw=Object.defineProperty,Qw=(s,t)=>{for(var e in t)Yw(s,e,{get:t[e],enumerable:!0})},Xw={};Qw(Xw,{permissions:()=>Zw,theme:()=>e_});var Vt=(s=>(s.GroupCall="GROUP_CALL",s.Webinar="WEBINAR",s.AudioRoom="AUDIO_ROOM",s.Livestream="LIVESTREAM",s.Chat="CHAT",s))(Vt||{}),H=(s=>(s.Allowed="ALLOWED",s.NotAllowed="NOT_ALLOWED",s.CanRequest="CAN_REQUEST",s))(H||{}),Zw={view_type:"GROUP_CALL",accept_waiting_requests:!1,accept_present_requests:!1,request_produce:!1,can_allow_participant_audio:!1,can_allow_participant_screensharing:!1,can_allow_participant_video:!1,can_spotlight:!1,request_kick_participant:!1,kick_participant:!1,pin_participant:!1,can_edit_display_name:!1,can_record:!1,can_livestream:!1,can_present:!0,waiting_room_type:"SKIP_ON_ACCEPT",recorder_type:"NONE",plugins:{can_close:!0,can_start:!0},polls:{can_create:!0,can_vote:!0,can_view:!0},produce:{video:{allow:!0,quality:"vga",frame_rate:24},audio:!0,screenshare:{allow:!0,quality:"hd",frame_rate:5}},chat:{public:{can_send:!0,text:!0,files:!0},private:{can_send:!1,can_receive:!1,text:!1,files:!1}},connected_meetings:{can_alter_connected_meetings:!1,can_switch_connected_meetings:!1,can_switch_to_parent_meeting:!1},reactions:!1,hidden_participant:!1,is_recorder:!1,show_participant_list:!0,can_change_participant_role:!1,can_change_theme:!1,max_screenshare_count:1},e_={setup_screen:{is_enabled:!0},alone_here:{is_enabled:!0},waiting_room:{is_enabled:!1,enable_preview:!0},control_bar:{is_enabled:!0,elements:{plugins:!0,screenshare:!0,invite:!0,participants:!0,chat:!0,reactions:!1,polls:!0,fullscreen:!0,layout:!0}},header:{is_enabled:!0,elements:{timer:!0,title:!0,participant_count:!0,change_layout:!0}},pip_mode:!0,auto_tune:!0,grid:{multi:{maxVideoCount:6,videoFit:"cover"},single:{maxVideoCount:6,videoFit:"cover"},defaultView:"multi"},controls:{pip_toggle:!1}},lm="hXgU8Wc8pwuGNq9ms5q9Hh";typeof process!="undefined"&&(Yv=process==null?void 0:process.env)!=null&&Yv.FLAGSMITH_ENVIRONMENT_KEY&&(lm=process.env.FLAGSMITH_ENVIRONMENT_KEY);function t_(s=[]){const t={};return s.forEach(e=>{t[e.feature.name]={enabled:e.enabled,value:e.feature_state_value}}),t}var um=class{constructor(s=lm){p(this,"flags",{});p(this,"environmentKey",null);this.environmentKey=s}async identifyAndFetchFlagsWithRetry({primaryEndpoint:s,secondaryEndpoint:t,forceEvaluate:e,timeout:r,uniqueIdentifier:i,traitsObj:n,logger:o}){const c=JSON.parse(JSON.stringify(n)),d=Object.entries(c).map(u=>({trait_key:u[0],trait_value:u[1]})),l=[s,t,t];for(const u of l)try{const h=new AbortController,g=setTimeout(()=>h.abort(),r),v="_"+(Math.random()+1).toString(36).substring(2),E=await fetch(`https://${u}/api/v1/identities/`,{method:"POST",headers:{"Content-Type":"application/json","X-Environment-Key":this.environmentKey},body:JSON.stringify({identifier:i+(e?v:""),traits:d}),signal:h.signal});if(clearTimeout(g),!E.ok)throw new Error(`Request failed with status ${E.status}`);const b=await E.json();return t_(b.flags||[])}catch(h){o.error("Flagsmith identify failed!!",{error:h,url:u})}return{}}async identify(s,t={},e=!1,r=5e3,i="edge.api.flagsmith.com",n=console){return this.flags=await this.identifyAndFetchFlagsWithRetry({traitsObj:t,uniqueIdentifier:s,forceEvaluate:e,timeout:r,primaryEndpoint:i,secondaryEndpoint:"edge.api.flagsmith.com",logger:n}),this.flags}getValue(s){return this.flags&&this.flags[s]&&this.flags[s].value}hasFeature(s){return this.flags&&this.flags[s]&&this.flags[s].enabled}getAllFlags(){return this.flags}},s_=new um;function r_(s){return new um(s)}var hm=[-2,-1,0,1,2],i_=[0,1,2,3,4];function n_(s){s=s.trim();let t="0",e="0",r="0";return s.length==4?(t="0x"+s[1]+s[1],e="0x"+s[2]+s[2],r="0x"+s[3]+s[3]):s.length>6&&(t="0x"+s[1]+s[2],e="0x"+s[3]+s[4],r="0x"+s[5]+s[6]),[+t,+e,+r]}var a_=(s,t,e)=>{let r,i,n;if(t==0)r=i=n=e;else{const o=(l,u,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?l+(u-l)*6*h:h<.5?u:h<.6666666666666666?l+(u-l)*(.6666666666666666-h)*6:l),c=e<.5?e*(1+t):e+t-e*t,d=2*e-c;r=o(d,c,s+1/3),i=o(d,c,s),n=o(d,c,s-1/3)}return[Math.round(r*255),Math.round(i*255),Math.round(n*255)]},o_=(s,t,e)=>{s/=255,t/=255,e/=255;const r=Math.max(s,t,e),i=Math.min(s,t,e);let n,o;const c=(r+i)/2;if(r==i)n=o=0;else{const d=r-i;switch(o=c>.5?d/(2-r-i):d/(r+i),r){case s:n=(t-e)/d+(t<e?6:0);break;case t:n=(e-s)/d+2;break;case e:n=(s-t)/d+4;break}n/=6}return[n,o,c]},c_=(s,t,e)=>{const r=i=>i.toString(16).padStart(2,"0");return`#${r(s)}${r(t)}${r(e)}`},pm=(s,t=hm,e=.4)=>{const r=[],[i,n,o]=n_(s),[c,d,l]=o_(i,n,o),u=Math.round(l*100);u>70?e=.8:u>60?e=.9:u<10?e=.075:u<42&&(e=.3);const h=t.findIndex(_=>_===0);if(h===-1)throw new Error("Invalid reducer provided, it must contain atleast one zero");const g=5-h,v=h+1,E=(100-u)/g,b=u/v;for(const _ of t){let w;_<0?w=u+_*b*e:_>0?w=u+_*E*e:w=u;const[L,B,N]=a_(c,d,w/100);r.push(c_(L,B,N))}return r},gm={dark:{background:{1e3:"#252525",900:"#2F2F2F",800:"#323232",700:"#3E3E3E",600:"#4A4A4A"},text:"#F5F5F5","video-bg":"#1C1C1C"},light:{background:{1e3:"#FFFFFF",900:"#F5F5F5",800:"#EBEBEB",700:"#E0E0E0",600:"#D6D6D6"},text:"#111111","text-on-brand":"#ffffff","video-bg":"#DADADA"}},d_=s=>{const[t,e,r,i,n]=pm(s,hm);return{300:t,400:e,500:r,600:i,700:n}},l_=s=>{if(s==="#FFFFFF")return gm.light.background;if(s==="#000000")return gm.dark.background;const[t,e,r,i,n]=pm(s,i_);return{1e3:t,900:e,800:r,700:i,600:n}},u_={border_radius:"rounded",border_width:"thin",spacing_base:4,theme:"dark",colors:{brand:d_("#2160FD"),background:l_("#141414"),danger:"#FF2D2D",text:"#EEEEEE",text_on_brand:"#EEEEEE",success:"#62A504",video_bg:"#191919",warning:"#FFCD07"}};function mm(){return Gu(u_)}var h_={permissions:{can_accept_production_requests:!1,can_edit_display_name:!0,accept_waiting_requests:!1,disable_participant_audio:!1,disable_participant_screensharing:!1,disable_participant_video:!1,can_spotlight:!1,kick_participant:!1,pin_participant:!1,can_record:!1,can_livestream:!1,waiting_room_type:"SKIP",plugins:{can_close:!0,can_start:!0,can_edit_config:!1,config:{}},polls:{can_create:!0,can_vote:!0,can_view:!0},media:{video:{can_produce:"ALLOWED",can_consume:"ALLOWED"},audio:{can_produce:"ALLOWED"},screenshare:{can_produce:"ALLOWED",can_consume:"ALLOWED"}},chat:{public:{can_send:!0,text:!0,files:!0},private:{can_send:!1,can_receive:!1,text:!1,files:!1},channel:{can_create:"ALL",can_delete:"ALL",can_update:"ALL",can_read_all:!1},message:{can_delete:"ALL",can_edit:"ALL",delete_cutoff_time_seconds:0,edit_cutoff_time_seconds:0}},hidden_participant:!1,is_recorder:!1,recorder_type:"NONE",show_participant_list:!0,transcription_enabled:!1,can_change_participant_permissions:!1,connected_meetings:{can_alter_connected_meetings:!1,can_switch_connected_meetings:!1,can_switch_to_parent_meeting:!1},stage_enabled:!1,stage_access:void 0,accept_stage_requests:!1},ui:{oldTheme:{setup_screen:{is_enabled:!1},alone_here:{is_enabled:!1},waiting_room:{is_enabled:!1,enable_preview:!0},control_bar:{is_enabled:!0,elements:{plugins:!0,screenshare:!0,invite:!1,participants:!0,chat:!0,reactions:!1,polls:!0,fullscreen:!0,layout:!0}},header:{is_enabled:!0,elements:{timer:!0,title:!0,participant_count:!0,change_layout:!0}},pip_mode:!0,auto_tune:!0,colors:{primary:"#2160FD",secondary:"#1A1A1A",text:"#EEEEEE",background:"#1A1A1A",textPrimary:"#EEEEEE",videoBackground:"#1A1A1A"},dimensions:{mode:"fillParent"},grid:{multi:{maxVideoCount:6,videoFit:"cover"},single:{maxVideoCount:6,videoFit:"cover"},defaultView:"MULTI"},controls:{pip_toggle:!1},plugins:[]},design_tokens:mm(),config_diff:{}},config:{view_type:"GROUP_CALL",media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate:24},screenshare:{quality:"hd",frame_rate:5}},max_video_streams:{mobile:6,desktop:6},max_screenshare_count:1,track_recording:{subscriptions:[]}},version:"hybrid"};function p_(){return Gu(h_)}var g_={permissions:{can_accept_production_requests:!1,can_edit_display_name:!0,accept_waiting_requests:!1,disable_participant_audio:!1,disable_participant_screensharing:!1,disable_participant_video:!1,can_spotlight:!1,kick_participant:!1,pin_participant:!1,can_record:!1,can_livestream:!1,waiting_room_type:"SKIP",plugins:{can_close:!0,can_start:!0,can_edit_config:!1,config:{}},polls:{can_create:!0,can_vote:!0,can_view:!0},media:{video:{can_produce:"ALLOWED"},audio:{can_produce:"ALLOWED"},screenshare:{can_produce:"ALLOWED"}},chat:{public:{can_send:!0,text:!0,files:!0},private:{can_send:!1,can_receive:!1,text:!1,files:!1}},hidden_participant:!1,is_recorder:!1,recorder_type:"NONE",show_participant_list:!0,transcription_enabled:!1,can_change_participant_permissions:!1,connected_meetings:{can_alter_connected_meetings:!1,can_switch_connected_meetings:!1,can_switch_to_parent_meeting:!1},stage_enabled:!1,stage_access:void 0,accept_stage_requests:!1},ui:{design_tokens:mm(),config_diff:{}},config:{view_type:"GROUP_CALL",media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate:24},screenshare:{quality:"hd",frame_rate:5}},max_video_streams:{mobile:6,desktop:6},max_screenshare_count:1,track_recording:{subscriptions:[]}},version:"2.0.0"};function Ku(){return Gu(g_)}class fm{constructor(){m(this,Bo,void 0)}get telemetry(){var t;return(t=a(this,Bo))==null?void 0:t.getValue("telemetry")}init(t){f(this,Bo,t)}info(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("info",t,e,r)}error(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("error",t,e,r)}debug(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("debug",t,e,r)}log(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("log",t,e,r)}warn(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("warn",t,e,r)}}Bo=new WeakMap;class m_ extends lt.EventEmitter{constructor(e){super();m(this,fr,void 0);m(this,vr,void 0);p(this,"asyncPromiseTimeout");p(this,"logger");this.logger=e,f(this,fr,new Map),f(this,vr,new Map),this.asyncPromiseTimeout=8e3}async emitAsync(e,...r){a(this,fr).set(e,[]);const i=a(this,vr).get(e).map(()=>new Promise(n=>{a(this,fr).get(e).push(n)}));super.emit(e,...r),await Promise.race([Promise.all(i),new Promise((n,o)=>setTimeout(()=>o(new Error(`emitAsync failed to resolve for event ${e}.`)),this.asyncPromiseTimeout))]),a(this,fr).delete(e)}onAsync(e,r){const i=a(this,fr),n=async(...o)=>{var d;try{await r(...o)}catch(l){this.logger.error("[onAsync]",{error:l})}const c=(d=i.get(e))==null?void 0:d.shift();c==null||c()};return a(this,vr).get(e)||a(this,vr).set(e,[]),a(this,vr).get(e).push(n),super.on(e,n)}reset(){f(this,fr,new Map),f(this,vr,new Map),super.removeAllListeners()}}fr=new WeakMap,vr=new WeakMap;var f_=/\s/;function v_(s){for(var t=s.length;t--&&f_.test(s.charAt(t)););return t}var S_=/^\s+/;function T_(s){return s&&s.slice(0,v_(s)+1).replace(S_,"")}var vm=0/0,y_=/^[-+]0x[0-9a-f]+$/i,E_=/^0b[01]+$/i,b_=/^0o[0-7]+$/i,w_=parseInt;function Sm(s){if(typeof s=="number")return s;if(kd(s))return vm;if(ns(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=ns(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=T_(s);var e=E_.test(s);return e||b_.test(s)?w_(s.slice(2),e?2:8):y_.test(s)?vm:+s}function zu(s){return s}function __(s,t,e){switch(e.length){case 0:return s.call(t);case 1:return s.call(t,e[0]);case 2:return s.call(t,e[0],e[1]);case 3:return s.call(t,e[0],e[1],e[2])}return s.apply(t,e)}function P_(){}var C_=800,R_=16,k_=Date.now;function I_(s){var t=0,e=0;return function(){var r=k_(),i=R_-(r-e);if(e=r,i>0){if(++t>=C_)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}function A_(s){return function(){return s}}var M_=bd?function(s,t){return bd(s,"toString",{configurable:!0,enumerable:!1,value:A_(t),writable:!0})}:zu,O_=I_(M_);const D_=O_;function N_(s,t,e,r){for(var i=s.length,n=e+(r?1:-1);r?n--:++n<i;)if(t(s[n],n,s))return n;return-1}function V_(s){return s!==s}function L_(s,t,e){for(var r=e-1,i=s.length;++r<i;)if(s[r]===t)return r;return-1}function x_(s,t,e){return t===t?L_(s,t,e):N_(s,V_,e)}function U_(s,t){var e=s==null?0:s.length;return!!e&&x_(s,t,0)>-1}var Tm=Math.max;function F_(s,t,e){return t=Tm(t===void 0?s.length-1:t,0),function(){for(var r=arguments,i=-1,n=Tm(r.length-t,0),o=Array(n);++i<n;)o[i]=r[t+i];i=-1;for(var c=Array(t+1);++i<t;)c[i]=r[i];return c[t]=e(o),__(s,this,c)}}function B_(s,t){return D_(F_(s,t,zu),s+"")}function $_(s,t,e){if(!ns(e))return!1;var r=typeof t;return(r=="number"?fo(e)&&Nu(t,e.length):r=="string"&&t in e)?co(e[t],s):!1}function H_(s){return B_(function(t,e){var r=-1,i=e.length,n=i>1?e[i-1]:void 0,o=i>2?e[2]:void 0;for(n=s.length>3&&typeof n=="function"?(i--,n):void 0,o&&$_(e[0],e[1],o)&&(n=i<3?void 0:n,i=1),t=Object(t);++r<i;){var c=e[r];c&&s(t,c,r,n)}return t})}var q_="[object Object]",j_=Function.prototype,G_=Object.prototype,ym=j_.toString,W_=G_.hasOwnProperty,J_=ym.call(Object);function K_(s){if(!js(s)||Ti(s)!=q_)return!1;var t=Fu(s);if(t===null)return!0;var e=W_.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&ym.call(e)==J_}var z_="__lodash_hash_undefined__";function Y_(s){return this.__data__.set(s,z_),this}function Q_(s){return this.__data__.has(s)}function So(s){var t=-1,e=s==null?0:s.length;for(this.__data__=new ir;++t<e;)this.add(s[t])}So.prototype.add=So.prototype.push=Y_,So.prototype.has=Q_;function X_(s,t){for(var e=-1,r=s==null?0:s.length;++e<r;)if(t(s[e],e,s))return!0;return!1}function Em(s,t){return s.has(t)}var Z_=1,eP=2;function bm(s,t,e,r,i,n){var o=e&Z_,c=s.length,d=t.length;if(c!=d&&!(o&&d>c))return!1;var l=n.get(s),u=n.get(t);if(l&&u)return l==t&&u==s;var h=-1,g=!0,v=e&eP?new So:void 0;for(n.set(s,t),n.set(t,s);++h<c;){var E=s[h],b=t[h];if(r)var _=o?r(b,E,h,t,s,n):r(E,b,h,s,t,n);if(_!==void 0){if(_)continue;g=!1;break}if(v){if(!X_(t,function(w,L){if(!Em(v,L)&&(E===w||i(E,w,e,r,n)))return v.push(L)})){g=!1;break}}else if(!(E===b||i(E,b,e,r,n))){g=!1;break}}return n.delete(s),n.delete(t),g}function tP(s){var t=-1,e=Array(s.size);return s.forEach(function(r,i){e[++t]=[i,r]}),e}function Yu(s){var t=-1,e=Array(s.size);return s.forEach(function(r){e[++t]=r}),e}var sP=1,rP=2,iP="[object Boolean]",nP="[object Date]",aP="[object Error]",oP="[object Map]",cP="[object Number]",dP="[object RegExp]",lP="[object Set]",uP="[object String]",hP="[object Symbol]",pP="[object ArrayBuffer]",gP="[object DataView]",wm=qs?qs.prototype:void 0,Qu=wm?wm.valueOf:void 0;function mP(s,t,e,r,i,n,o){switch(e){case gP:if(s.byteLength!=t.byteLength||s.byteOffset!=t.byteOffset)return!1;s=s.buffer,t=t.buffer;case pP:return!(s.byteLength!=t.byteLength||!n(new Cd(s),new Cd(t)));case iP:case nP:case cP:return co(+s,+t);case aP:return s.name==t.name&&s.message==t.message;case dP:case uP:return s==t+"";case oP:var c=tP;case lP:var d=r&sP;if(c||(c=Yu),s.size!=t.size&&!d)return!1;var l=o.get(s);if(l)return l==t;r|=rP,o.set(s,t);var u=bm(c(s),c(t),r,i,n,o);return o.delete(s),u;case hP:if(Qu)return Qu.call(s)==Qu.call(t)}return!1}var fP=1,vP=Object.prototype,SP=vP.hasOwnProperty;function TP(s,t,e,r,i,n){var o=e&fP,c=Bu(s),d=c.length,l=Bu(t),u=l.length;if(d!=u&&!o)return!1;for(var h=d;h--;){var g=c[h];if(!(o?g in t:SP.call(t,g)))return!1}var v=n.get(s),E=n.get(t);if(v&&E)return v==t&&E==s;var b=!0;n.set(s,t),n.set(t,s);for(var _=o;++h<d;){g=c[h];var w=s[g],L=t[g];if(r)var B=o?r(L,w,g,t,s,n):r(w,L,g,s,t,n);if(!(B===void 0?w===L||i(w,L,e,r,n):B)){b=!1;break}_||(_=g=="constructor")}if(b&&!_){var N=s.constructor,$=t.constructor;N!=$&&"constructor"in s&&"constructor"in t&&!(typeof N=="function"&&N instanceof N&&typeof $=="function"&&$ instanceof $)&&(b=!1)}return n.delete(s),n.delete(t),b}var yP=1,_m="[object Arguments]",Pm="[object Array]",Ad="[object Object]",EP=Object.prototype,Cm=EP.hasOwnProperty;function bP(s,t,e,r,i,n){var o=jt(s),c=jt(t),d=o?Pm:Un(s),l=c?Pm:Un(t);d=d==_m?Ad:d,l=l==_m?Ad:l;var u=d==Ad,h=l==Ad,g=d==l;if(g&&Vn(s)){if(!Vn(t))return!1;o=!0,u=!1}if(g&&!u)return n||(n=new Es),o||wd(s)?bm(s,t,e,r,i,n):mP(s,t,d,e,r,i,n);if(!(e&yP)){var v=u&&Cm.call(s,"__wrapped__"),E=h&&Cm.call(t,"__wrapped__");if(v||E){var b=v?s.value():s,_=E?t.value():t;return n||(n=new Es),i(b,_,e,r,n)}}return g?(n||(n=new Es),TP(s,t,e,r,i,n)):!1}function Md(s,t,e,r,i){return s===t?!0:s==null||t==null||!js(s)&&!js(t)?s!==s&&t!==t:bP(s,t,e,r,Md,i)}var wP=1,_P=2;function PP(s,t,e,r){var i=e.length,n=i,o=!r;if(s==null)return!n;for(s=Object(s);i--;){var c=e[i];if(o&&c[2]?c[1]!==s[c[0]]:!(c[0]in s))return!1}for(;++i<n;){c=e[i];var d=c[0],l=s[d],u=c[1];if(o&&c[2]){if(l===void 0&&!(d in s))return!1}else{var h=new Es;if(r)var g=r(l,u,d,s,t,h);if(!(g===void 0?Md(u,l,wP|_P,r,h):g))return!1}}return!0}function Rm(s){return s===s&&!ns(s)}function CP(s){for(var t=Pd(s),e=t.length;e--;){var r=t[e],i=s[r];t[e]=[r,i,Rm(i)]}return t}function km(s,t){return function(e){return e==null?!1:e[s]===t&&(t!==void 0||s in Object(e))}}function RP(s){var t=CP(s);return t.length==1&&t[0][2]?km(t[0][0],t[0][1]):function(e){return e===s||PP(e,s,t)}}function kP(s,t){return s!=null&&t in Object(s)}function IP(s,t){return s!=null&&zw(s,t,kP)}var AP=1,MP=2;function OP(s,t){return Wu(s)&&Rm(t)?km(Id(s),t):function(e){var r=Kw(e,s);return r===void 0&&r===t?IP(e,s):Md(t,r,AP|MP)}}function DP(s){return function(t){return t==null?void 0:t[s]}}function NP(s){return function(t){return dm(t,s)}}function VP(s){return Wu(s)?DP(Id(s)):NP(s)}function LP(s){return typeof s=="function"?s:s==null?zu:typeof s=="object"?jt(s)?OP(s[0],s[1]):RP(s):VP(s)}function xP(s){return function(t,e,r){for(var i=-1,n=Object(t),o=r(t),c=o.length;c--;){var d=o[s?c:++i];if(e(n[d],d,n)===!1)break}return t}}var UP=xP();const FP=UP;var BP=function(){return ys.Date.now()};const Xu=BP;var $P="Expected a function",HP=Math.max,qP=Math.min;function Zu(s,t,e){var r,i,n,o,c,d,l=0,u=!1,h=!1,g=!0;if(typeof s!="function")throw new TypeError($P);t=Sm(t)||0,ns(e)&&(u=!!e.leading,h="maxWait"in e,n=h?HP(Sm(e.maxWait)||0,t):n,g="trailing"in e?!!e.trailing:g);function v(Y){var ae=r,bt=i;return r=i=void 0,l=Y,o=s.apply(bt,ae),o}function E(Y){return l=Y,c=setTimeout(w,t),u?v(Y):o}function b(Y){var ae=Y-d,bt=Y-l,Bs=t-ae;return h?qP(Bs,n-bt):Bs}function _(Y){var ae=Y-d,bt=Y-l;return d===void 0||ae>=t||ae<0||h&&bt>=n}function w(){var Y=Xu();if(_(Y))return L(Y);c=setTimeout(w,b(Y))}function L(Y){return c=void 0,g&&r?v(Y):(r=i=void 0,o)}function B(){c!==void 0&&clearTimeout(c),l=0,r=d=i=c=void 0}function N(){return c===void 0?o:L(Xu())}function $(){var Y=Xu(),ae=_(Y);if(r=arguments,i=this,d=Y,ae){if(c===void 0)return E(d);if(h)return clearTimeout(c),c=setTimeout(w,t),v(d)}return c===void 0&&(c=setTimeout(w,t)),o}return $.cancel=B,$.flush=N,$}function eh(s,t,e){(e!==void 0&&!co(s[t],e)||e===void 0&&!(t in s))&&Du(s,t,e)}function jP(s){return js(s)&&fo(s)}function th(s,t){if(!(t==="constructor"&&typeof s[t]=="function")&&t!="__proto__")return s[t]}function GP(s){return po(s,vo(s))}function WP(s,t,e,r,i,n,o){var c=th(s,e),d=th(t,e),l=o.get(d);if(l){eh(s,e,l);return}var u=n?n(c,d,e+"",s,t,o):void 0,h=u===void 0;if(h){var g=jt(d),v=!g&&Vn(d),E=!g&&!v&&wd(d);u=d,g||v||E?jt(c)?u=c:jP(c)?u=Ug(c):v?(h=!1,u=xg(d,!0)):E?(h=!1,u=Qg(d,!0)):u=[]:K_(d)||go(d)?(u=c,go(c)?u=GP(c):(!ns(c)||Mu(c))&&(u=Zg(d))):h=!1}h&&(o.set(d,u),i(u,d,r,n,o),o.delete(d)),eh(s,e,u)}function Im(s,t,e,r,i){s!==t&&FP(t,function(n,o){if(i||(i=new Es),ns(n))WP(s,t,o,e,Im,r,i);else{var c=r?r(th(s,o),n,o+"",s,t,i):void 0;c===void 0&&(c=n),eh(s,o,c)}},vo)}function JP(s,t,e){for(var r=-1,i=s==null?0:s.length;++r<i;)if(e(t,s[r]))return!0;return!1}var KP="[object Map]",zP="[object Set]",YP=Object.prototype,QP=YP.hasOwnProperty;function XP(s){if(s==null)return!0;if(fo(s)&&(jt(s)||typeof s=="string"||typeof s.splice=="function"||Vn(s)||wd(s)||go(s)))return!s.length;var t=Un(s);if(t==KP||t==zP)return!s.size;if(_d(s))return!Og(s).length;for(var e in s)if(QP.call(s,e))return!1;return!0}function ZP(s,t){return Md(s,t)}var eC=H_(function(s,t,e){Im(s,t,e)});const Fr=eC;var tC=1/0,sC=xn&&1/Yu(new xn([,-0]))[1]==tC?function(s){return new xn(s)}:P_;const rC=sC;var iC=200;function Am(s,t,e){var r=-1,i=U_,n=s.length,o=!0,c=[],d=c;if(e)o=!1,i=JP;else if(n>=iC){var l=t?null:rC(s);if(l)return Yu(l);o=!1,i=Em,d=new So}else d=t?[]:c;e:for(;++r<n;){var u=s[r],h=t?t(u):u;if(u=e||u!==0?u:0,o&&h===h){for(var g=d.length;g--;)if(d[g]===h)continue e;t&&d.push(h),c.push(u)}else i(d,h,e)||(d!==c&&d.push(h),c.push(u))}return c}function nC(s){return s&&s.length?Am(s):[]}function aC(s,t){return s&&s.length?Am(s,LP(t)):[]}var sh=(s=>(s.PARTICIPANT="PARTICIPANT",s.PEER="PEER",s.CLIENT="CLIENT",s))(sh||{});const X={PROPAGATE_KICK_ALL:"propagate_kick_across_rooms",REFRESH_ID_ON_DISCONNECTION:"refresh_id_on_disconnection",SKIP_OTEL_TRACES:"skip_otel_traces",USE_USERIDS_IN_CHAT:"use_userids_in_chat",ENABLE_CF_SIMULCAST:"enable_cf_simulcast",CF_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED:"cf_transport_force_relay_on_ice_failed",LOG_LEVEL:"log_level",V1_PLUGINS:"v1_plugins",LIVESTREAM:"feat_livestream",FEAT_PAGINATED_CHAT:"feat_paginated_chat",VAL_MIN_FRAMERATE:"val_min_framerate",SCREEENSHARE_ERR_HACK:"screenshare_err_hack",SCREEENSHARE_CONSTRAINTS_RETRY:"screenshare_constraints_retry",VIDEO_CONSTRAINTS:"video_constraints",SCREENSHARE_CONSTRAINTS:"screenshare_constraints",FEAT_CHAT_SDK:"feat_chat_sdk",FEAT_CHAT_SDK_SEARCH:"chat_search",OBS_QUALITY:"obs_quality",ALLOW_SAFARI_MEDIA_MIDDLEWARES:"allow_safari_media_middlewares",EXP_RESHARE:"exp_reshare",SKIP_SETTING_IN_USE_DEVICE:"skip_setting_in_use_device",PRECALL_BANDWIDTH_TEST:"precall_bandwidth_test",DEBUG_SOCKET_JOIN:"debug_socket_join",FORCE_RELAY:"force_relay",FORCE_VIDEO_CODEC:"force_video_codec",TRACK_HINT:"track_hint",OVERRIDE_SIMULCAST_DYNAMIC:"override_simulcast_dynamic",PRECREATE_PRODUCERS:"precreate_producers",DISABLE_OPUS_DTX_CF:"disable_opus_dtx_cf",ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS:"enable_audio_activity_debug_logs",DISABLE_LAYER_SWITCH:"disable_layer_switch"};function Od(s){const t={};return typeof(s==null?void 0:s.code)=="number"&&(t.code=s.code),typeof(s==null?void 0:s.code)=="string"&&(t.code=s.code.substring(0,100)),typeof(s==null?void 0:s.name)=="string"&&(t.name=s.name.substring(0,500)),typeof(s==null?void 0:s.message)=="string"&&(t.message=s.message.substring(0,500)),typeof(s==null?void 0:s.reason)=="string"&&(t.reason=s.reason.substring(0,500)),typeof(s==null?void 0:s.stack)=="string"&&(t.stack=s.stack.substring(0,500)),t}const oC={audio:!0,video:!0,screenshareAudio:!0,screenshareVideo:!0},To={baseURL:"http://localhost:5000",createdAt:"2021-08-05T10:49:56.602Z",description:"Develop plugins locally",id:"09259e3b-7be8-46f6-9801-106bf1866e1c",name:"Localhost Dev",organizationId:"4ad15a19-80e2-4105-bf43-48039fd2963e",picture:"https://dyte-uploads.s3.ap-south-1.amazonaws.com/dyte.png",private:!1,published:!0,staggered:!1,tags:["#localhost","#dev"],type:"self_hosted",updatedAt:"2021-08-05T10:50:07.681Z"},cC={pip:!0,poll:!0,chat:!0,stage:!0,theme:!0,plugin:!0,tracing:!0,internals:!0,recording:!0,livestream:!0,participant:!0,connectedMeetings:!0,devTools:{logs:!1}};function Fn(s,t){const e=s.getValue("overrides");return e&&e[t]?e[t]:!1}function dC({baseURI:s}){return s.includes("preprod.dyte")||s.includes("preprod.realtime")?oo.PREPROD:s.includes("devel.dyte")||s.includes("devel.realtime")?oo.DEVEL:oo.PROD}function _i({servicePrefix:s,baseURI:t}){return`${s}.${t}`}function Mm(s){const t=s.getValue("baseURI");return{location:_i({servicePrefix:"location",baseURI:t}),locationLegacy:_i({servicePrefix:"location-legacy",baseURI:t}),daCollector:_i({servicePrefix:"da-collector",baseURI:t.replace("realtime.cloudflare.com","dyte.io")})}}const lC='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="m16.242 2.932 4.826 4.826a2.75 2.75 0 0 1-.715 4.404l-4.87 2.435a.75.75 0 0 0-.374.426l-1.44 4.166a1.25 1.25 0 0 1-2.065.476L8.5 16.561 4.06 21H3v-1.06l4.44-4.44-3.105-3.104a1.25 1.25 0 0 1 .476-2.066l4.166-1.44a.75.75 0 0 0 .426-.373l2.435-4.87a2.75 2.75 0 0 1 4.405-.715Zm3.766 5.886-4.826-4.826a1.25 1.25 0 0 0-2.002.325l-2.435 4.871a2.25 2.25 0 0 1-1.278 1.12l-3.789 1.31 6.705 6.704 1.308-3.789a2.25 2.25 0 0 1 1.12-1.277l4.872-2.436a1.25 1.25 0 0 0 .325-2.002Z" fill="currentColor"/></svg>',uC='<svg viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M4 12.02c0 1.06.2 2.1.6 3.08l.6 1.42c.22.55.64 1.01 1.17 1.29.27.14.56.21.86.21h2.55c.77 0 1.49-.41 1.87-1.08.5-.87 1.02-1.7 1.72-2.43l1.32-1.39c.44-.46.97-.84 1.49-1.23l.59-.45a.6.6 0 0 0 .23-.47c0-.75-.54-1.57-1.22-1.79a3.34 3.34 0 0 0-2.78.29V4.5a1.5 1.5 0 0 0-2.05-1.4 1.5 1.5 0 0 0-2.9 0A1.5 1.5 0 0 0 6 4.5v.09A1.5 1.5 0 0 0 4 6v6.02ZM8 4.5v4a.5.5 0 0 0 1 0v-5a.5.5 0 0 1 1 0v5a.5.5 0 0 0 1 0v-4a.5.5 0 0 1 1 0v6a.5.5 0 0 0 .85.37h.01c.22-.22.44-.44.72-.58.7-.35 2.22-.57 2.4.5l-.53.4c-.52.4-1.04.78-1.48 1.24l-1.33 1.38c-.75.79-1.31 1.7-1.85 2.63-.21.36-.6.58-1.01.58H7.23a.87.87 0 0 1-.4-.1 1.55 1.55 0 0 1-.71-.78l-.59-1.42a7.09 7.09 0 0 1-.53-2.7V6a.5.5 0 0 1 1 0v3.5a.5.5 0 0 0 1 0v-5a.5.5 0 0 1 1 0Z" fill="currentColor"></path></svg>',Dd=s=>{if(!s)return;if(!s.startsWith("<svg"))return new Promise(n=>{n(s)});const e=new Blob([s],{type:"image/svg+xml"}),r=new Image,i=window.URL.createObjectURL(e);return new Promise((n,o)=>{r.onload=()=>{n(r),window.URL.revokeObjectURL(i)},r.onerror=()=>{o(),window.URL.revokeObjectURL(i)},r.src=i})},Pi={logs:"https://api-silos.dyte.io/otel/logs",mock:{url:"https://mock.dyte.io",domain:"mock.dyte.io",app:"https://app.dyte.io/v2/meeting",stagingApp:"https://app.devel.dyte.io/v2/meeting"},apiBase:{prod:"https://api.dyte.io",staging:"https://api.devel.dyte.io",prodAlternate:"https://api.cluster.dyte.in"},baseURI:{prod:"dyte.io",staging:"devel.dyte.io"}};function hC(s){var r,i,n;const t=typeof navigator!="undefined"&&!navigator.isReactNative&&typeof window!="undefined"&&((r=window.location.host)==null?void 0:r.includes(Pi.baseURI.staging)),e=!!((n=(i=s==null?void 0:s.getValue("modules"))==null?void 0:i.devTools)!=null&&n.logs);return t||e}function pC(s,t){var e;if(s!=null&&s.getValue("flagsmith").hasFeature(X.LOG_LEVEL)){let r=((e=s.getValue("flagsmith").getValue(X.LOG_LEVEL))==null?void 0:e.toString())||"all";if(r=r.toLowerCase().trim(),r==="off")return!1;if(r!=="all"){const i=["debug","log","info","warn","error"],n=i.indexOf(t),o=i.indexOf(r);if(n<o)return!1}}return!0}function Om(s,t,e={}){return Object.getOwnPropertyNames(s).forEach(r=>{var n;if([null,void 0,NaN].includes(s[r])||t&&(((n=t.match(/\./g))==null?void 0:n.length)||0)>=10)return;const i=t?`${t}.${r}`:r;typeof s[r]=="object"?Om(s[r],i,e):["number","string","boolean"].includes(typeof s[r])&&(e[i]=s[r])}),e}function Dm(s,t,e={},r=""){const i={};try{const n=JSON.stringify(e),o=JSON.parse(n),c=Om(o,r),d=JSON.stringify(c);return JSON.parse(d)}catch(n){const o=Od(n);i[`${r}.error.message`]=o.message||"",i[`${r}.error.stack`]=o.stack||"",i[`${r}.error.reason`]=o.reason||"",i[`${r}.error.source`]="safelyFlattenObjForOpenTelemetry"}return i}const dp=class{constructor(){p(this,"logsCache",[]);p(this,"logsProcessorTimer");p(this,"tracingEnabled",!0);p(this,"initialized",!1);p(this,"logsProcessingInterval",7e3);p(this,"logExclusionList",["message","websocket/message","roomMessage","websocket/room-message","websocket/room-legacy-mode","chatMessage","websocket/new-chat-message","websocket/no-active-speaker","websocket/selected-peers","websocket/active-speaker","ping","websocket/new-consumer","websocket/producer-score","websocket/consumer-score","websocket/plugin-event","websocket/plugin-data","websocket/plugin-internal-data"]);p(this,"meetingMetadata",{})}get logsEndpoint(){const t=nr.getContext(this.meetingMetadata.peerId);return`https://${_i({servicePrefix:"api-silos",baseURI:t.getValue("baseURI")})}/otel/logs`}resetPeerId(t){this.meetingMetadata.peerId=t}init(t,e,r){this.tracingEnabled=!0,this.initialized=!1,this.logsCache=[];const i=t.getValue("peerId");this.meetingMetadata=e,this.tracingEnabled=r,this.meetingMetadata.peerId=i,this.meetingMetadata.sdkVersion=t.getValue("sdkVersion");const{RNDeviceInfoImpl:n}=navigator;this.meetingMetadata.deviceInfo=navigator.isReactNative?n==null?void 0:n.getDeviceInfo():Te.getDeviceInfo(),this.meetingMetadata.visitedUrl=!navigator.isReactNative&&typeof window!="undefined"&&window.location.href,this.logsProcessorTimer=setInterval(this.processCachedLogs.bind(this),this.logsProcessingInterval),r&&(this.initialized=!0)}static trace(t,e=void 0){return(r,i,n)=>{const o=n.value;return n.value=function(...d){var g;const l=this==null?void 0:this.telemetry;if(!l||!l.initialized||navigator.isReactNative||!l.tracingEnabled||(g=nr.getContext(l.meetingMetadata.peerId))!=null&&g.getValue("flagsmith").hasFeature(X.SKIP_OTEL_TRACES))return o.apply(this,d);l.addLogInCurrentSpan("info",t,e);const u=performance.now(),h=o.apply(this,d);return Promise.resolve(h).then(()=>{const v=performance.now();v-u>10&&l.addLogInCurrentSpan("info",`${t}_timing`,{execTime:v-u,country:dp.location.country})}).catch(()=>{const v=performance.now();l.addLogInCurrentSpan("info",`${t}_timing`,{execTime:v-u})}),h},n}}injectContext(t){var i;const e=Si().replace(/-/g,"").substring(0,16),r=(i=this.meetingMetadata.peerId)==null?void 0:i.replace(/-/g,"");t.TRACEPARENT=`00-${r}-${e}-01`}addLogInCurrentSpan(t,e,r={},i=!1){r!=null&&r.error&&Object.assign(r,{error:Od(r.error)});const n=nr.getContext(this.meetingMetadata.peerId);if(hC(n)&&(XP(r)?console[t]("InternalLogs:: ",t,e):console[t]("InternalLogs:: ",t,e,r)),!!pC(n,t))try{const c=Dm(n,e,r,"metadata"),d=new Date,l={message:e,level:t,...c,loggedAt:d.toISOString(),loggedAtTzOffset:d.getTimezoneOffset()};i?this.sendOtelLogsToNewRelic([l]):this.logsCache.push(l)}catch(c){this.addLogInCurrentSpan("error","opentelemetry::addLogInCurrentSpan_failed",{error:Od(c)})}}sendOtelLogsToNewRelic(t){const e=nr.getContext(this.meetingMetadata.peerId);fetch(this.logsEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({meetingMetadata:Dm(e,"sendOtelLogsToNewRelic",this.meetingMetadata,"meetingMetadata"),serviceName:e.getValue("sdkName"),logs:t})}).catch(r=>{this.addLogInCurrentSpan("error","opentelemetry::sendOtelLogToNewRelic_failed",{error:Od(r)}),this.logsCache.push(...t)})}processCachedLogs(){const t=this.logsCache.splice(0,25);t!=null&&t.length&&this.sendOtelLogsToNewRelic(t)}destruct(){clearInterval(this.logsProcessorTimer),this.processCachedLogs()}};let y=dp;p(y,"location",{country:void 0});function gC(s){const t={...s},e=new Map,r=(l,u)=>(e.has(l)||e.set(l,new Set),e.get(l).add(u),()=>{var h;return(h=e.get(l))==null?void 0:h.delete(u)}),i=(l,u)=>{var h;(h=e.get(l))==null||h.delete(u)},n=l=>{var u;(u=e.get(l))==null||u.forEach(h=>{try{h(t[l])}catch(g){}})};return{subscribe:r,unsubscribe:i,notify:n,setValue:(l,u,h=!0)=>{t[l]=u,h&&n(l)},getValue:l=>t[l],getAllValues:()=>t}}class mC{constructor(){p(this,"contexts",new Map);p(this,"mostRecentPeerId",null)}createContext(t,e){if(this.contexts.has(t))return this.contexts.get(t);const r=new y,i=new fm;this.contexts.set(t,gC(e)),this.contexts.get(t).setValue("peerSessionStore",new m_(i));const n=new vg;return n.setMaxListeners(50),this.contexts.get(t).setValue("logger",i),this.contexts.get(t).setValue("telemetry",r),this.contexts.get(t).setValue("callstats",n),this.contexts.get(t).setValue("flagsmith",r_()),this.mostRecentPeerId=t,this.contexts.get(t)}remapContext(t,e){const r=e.getValue("peerId");r!==t&&(e.setValue("peerId",t),this.mostRecentPeerId=t,this.contexts.set(t,e),this.contexts.delete(r))}getContext(t){return this.contexts.get(t)}getMostRecentPeerId(){return this.mostRecentPeerId}}const nr=new mC,fC={"00":"Client","01":"Controller","02":"RoomNodeClient","03":"HiveNodeClient","04":"SocketService","05":"Chat","06":"Plugin","07":"Polls","08":"Meta","09":"Preset",10:"Recording",11:"Self",12:"Participant",13:"Spotlight",14:"Remote Request",15:"Webinar",16:"LocalMediaHandler",17:"End-End Encryption",18:"AI",19:"Livestream",20:"Stage"},Nd={"0000":"Internal exception.","0001":"Failed to initialize.","0002":"Failed to join room.","0003":"Failed to leave room.","0004":"Invalid auth token","0010":"Browser not supported","0011":"HTTP Network Error","0012":"Websocket Network Error","0013":"Rate Limited","0100":"Internal exception","0101":"Permission denied","0102":"Prerequisite module missing","0200":"Internal exception.","0300":"Internal exception","0400":"Internal exception","0404":"Missing prerequisites to establish a websocket connection","0500":"Internal exception","0501":"Permission denied.","0502":"Invalid message body.","0503":"Text Message is too large","0504":"Message not found by the given id","0505":"Action not permitted without joining room","0506":"Message search is disabled","0510":"Invalid channel name.","0600":"Internal exception","0601":"Permission denied.","0602":"Auth token not set for plugin","0603":"Iframe was not provided","0700":"Internal exception","0705":"Action not permitted without joining room","0800":"Internal exception","0801":"Permission denied","0900":"Internal exception","0904":"Could not load preset",1e3:"Internal exception",1001:"Permission denied",1004:"Could not find specified recording",1005:"Action not permitted in given recording state",1100:"Internal exception",1101:"Permission denied",1102:"Unsupported",1103:"Name cannot be empty",1104:"No device selected while calling meeting.self.setDevice",1105:"Action not permitted without joining room",1106:"Can't set currently used device",1200:"Internal exception",1201:"Permission denied",1202:"Invalid page number was requested",1203:"Invalid participant count per page was requested",1204:"No participants exists with the given UserIds",1205:"Action not permitted without joining room",1206:"Manual Subscription Mode was not ACTIVATED",1207:"Invalid view mode",1208:"Manual Subscription not enabled for organization",1209:"Broadcast message type must be a non-empty string",1300:"Internal exception",1400:"Internal exception",1402:"No existing remote requests",1403:"No peer exists with given id",1500:"Internal exception",1600:"Internal exception",1601:"Failed to get audio track",1602:"Failed to get video track",1603:"Incorrect device",1604:"Failed to change device",1605:"Failed to get audio & video track",1606:"No audio input devices are available",1607:"No video input devices are available",1608:"No audio output devices (speakers) are available",1609:"Failed to fetch list of media devices",1610:"No media track exists",1611:"Failed to unmute track",1612:"Failed to get screenshare tracks",1701:"Crypto error",1800:"Internal exception",1801:"Can't fetch transcript file",1900:"Internal exception",1901:"Permission denied.",1902:"Livestream that has not yet started, can't be stopped",2e3:"Internal exception",2001:"Permission denied",2002:"Unsupported",2003:"Stage is disabled",2004:"Method not implemented",2005:"Action not permitted without joining room",2006:"Action not permitted in current stage status",9900:"Internal exception"};Object.keys(Nd).forEach(s=>{Nd[s]=`{${fC[s.slice(0,2)]}} ${Nd[s]}`});class C extends Error{constructor(e,r,i=void 0,n=!1){super(e);p(this,"code");this.code=r,this.name="ClientError",this.message=`[ERR${this.code}]: ${Nd[this.code]}
10
- ${this.message}`;try{let o=n&&!!i;r&&r.endsWith("00")&&i&&(o=!0),o&&i.error("ClientError",{error:{message:this.message,name:this.name,code:r}});const c=nr.getContext(nr.getMostRecentPeerId());if(c){const d=c.getValue("onError");try{d(this)}catch(l){}}typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("ClientError",{detail:this}))}catch(o){}}}function Vd(s,t,e,r){if(r instanceof C)throw r;if(r instanceof t){const i=new C(r.message,e);throw i.stack=r.stack,i}else throw r}function Nm(s,t,e){if(!s.value){const i=s.get,n=s.set;return i&&(s.get=function(){try{return i.apply(this)}catch(o){Vd(this,t,e,o)}}),n&&(s.set=function(o){try{return n.apply(this,[o])}catch(c){Vd(this,t,e,c)}}),s}const r=s.value;return s.value=function(...i){try{const n=r.apply(this,i);return n&&n instanceof Promise?n.catch(o=>{Vd(this,t,e,o)}):n}catch(n){Vd(this,t,e,n)}},s}function vC(s,t){return(e,r,i)=>{if(i)return Nm(i,s,t);for(const n of Reflect.ownKeys(e.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(e.prototype,n);(o.value instanceof Function||o.get instanceof Function||o.set instanceof Function)&&Object.defineProperty(e.prototype,n,Nm(o,s,t))}}}const ut=s=>vC(Error,s);function SC(s){let t=0,e,r;if(!s)return t;for(e=0;e<s.length;e+=1)r=s.charCodeAt(e),t=(t<<5)-t+r,t|=0;return Math.abs(t)%100+1}function TC(){Te.isElectron()&&window.electronGetDisplayMediaSource&&(navigator.mediaDevices.getDisplayMedia=async()=>{const s=await window.electronGetDisplayMediaSource({types:["window","screen"]});let t=[];if(s&&(Array.isArray(s)?t=s:t=[s]),!(t!=null&&t.length))throw new Error("Couldn't find any media source for screen share.");let e=t.find(n=>{var o;return(o=n.id)==null?void 0:o.includes("screen")});e=e!=null?e:t[0];const r={audio:!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e.id}}};return await navigator.mediaDevices.getUserMedia(r)})}var R=(s=>(s.NEW_PRODUCER="NEW_PRODUCER",s.ROOM_NODE_CONNECTION_ERROR="ROOM_NODE_CONNECTION_ERROR",s.SOCKET_SERVICE_ROOM_JOINED="SOCKET_SERVICE_ROOM_JOINED",s.SOCKET_SERVICE_RECONNECTED="SOCKET_SERVICE_RECONNECTED",s.SOCKET_SERVICE_DISCONNECTED="SOCKET_SERVICE_DISCONNECTED",s.SOCKET_SERVICE_FAILED="SOCKET_SERVICE_FAILED",s.SOCKET_STATE_UPDATE="SOCKET_STATE_UPDATE",s.ROOM_NODE_RECONNECTED="ROOM_NODE_RECONNECTED",s.ROOM_NODE_DISCONNECTED="ROOM_NODE_DISCONNECTED",s.ROOM_NODE_FAILED="ROOM_NODE_FAILED",s.TRANSPORT_STATE_UPDATE="TRANSPORT_STATE_UPDATE",s.PRODUCER_SCORE_UPDATE="PRODUCER_SCORE_UPDATE",s.CONSUMER_SCORE_UPDATE="CONSUMER_SCORE_UPDATE",s.PRODUCER_STATUS_UPDATE="PRODUCER_STATUS_UPDATE",s.CONSUMER_STATUS_UPDATE="CONSUMER_STATUS_UPDATE",s.LOW_CONSUMER_SCORE="LOW_CONSUMER_SCORE",s.MEDIA_PERMISSION_ERROR="MEDIA_PERMISSION_ERROR",s.MEDIA_PERMISSION_UPDATE="MEDIA_PERMISSION_UPDATE",s.MESSAGE="websocket/message",s.ROOM_MESSAGE="websocket/room-message",s.PEER_JOINED_INTERNAL="peer/joined-internal",s.PEER_CLOSED="websocket/peer-closed",s.CONSUMER_CLOSED="websocket/consumer-closed",s.CONSUMER_PAUSED="websocket/consumer-paused",s.CONSUMER_RESUMED="websocket/consumer-resumed",s.PRODUCER_CLOSED="websocket/producer-closed",s.NEW_CONSUMER="websocket/new-consumer",s.PRODUCER_SCORE="websocket/producer-score",s.CONSUMER_SCORE="websocket/consumer-score",s.PRODUCER_TOGGLE="cf/producer-toggle",s.UPDATE_ACTIVE="media/update-active",s.RESET_PRODUCER_STATE="cf/reset-producer-state",s.ROOM_STATE="sockethub/room-state",s.GET_STAGE_REQUESTS="GET_STAGE_REQUESTS",s.UPDATE_STAGE_REQUESTS="UPDATE_STAGE_REQUESTS",s.KICK_PEER="KICK_PEER",s.UPDATE_PEER_STAGE_STATUS="UPDATE_PEER_STAGE_STATUS",s.JOIN_MEDIA_ROOM="JOIN_MEDIA_ROOM",s.LEAVE_MEDIA_ROOM="LEAVE_MEDIA_ROOM",s.PIP_HANGUP="PIP_HANGUP",s.E2EE_ACTIVE_PRODUCER="E2EE_ACTIVE_PRODUCER",s.E2EE_INACTIVE_PRODUCER="E2EE_INACTIVE_PRODUCER",s.E2EE_ACTIVE_CONSUMER="E2EE_ACTIVE_CONSUMER",s.E2EE_INACTIVE_CONSUMER="E2EE_INACTIVE_CONSUMER",s.SOCKET_PEERS="SOCKET_PEERS",s.UPDATE_PERMISSIONS="UPDATE_PERMISSIONS",s.MAX_SPATIAL_LAYER_CHANGE="MAX_SPATIAL_LAYER_CHANGE",s.MUTE_SELF="MUTE_SELF",s.MUTE_SELF_VIDEO="MUTE_SELF_VIDEO",s))(R||{});class Bn extends lt.EventEmitter{constructor(e){super();p(this,"logger");this.logger=e,super.setMaxListeners(25)}emit(e,...r){return super.emit("*",e,...r),super.emit(e,...r)}on(e,r){var i;try{const n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(n){}return super.on(e,r)}addListener(e,r){var i;try{const n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(n){}return super.addListener(e,r)}off(e,r){return super.off(e,r)}once(e,r){return super.once(e,r)}prependListener(e,r){return super.prependListener(e,r)}prependOnceListener(e,r){return super.prependOnceListener(e,r)}removeListener(e,r){return super.removeListener(e,r)}removeAllListeners(e){return super.removeAllListeners(e)}listeners(e){return super.listeners(e)}listenerCount(e){return super.listenerCount(e)}}class Gt extends lt.EventEmitter{constructor(e){super();p(this,"logger");this.logger=e,super.setMaxListeners(25)}emit(e,...r){return super.emit("*",e,...r),super.emit(e,...r)}on(e,r){var i;try{const n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(n){}return super.on(e,r)}addListener(e,r){var i;try{const n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(n){}return super.addListener(e,r)}off(e,r){return super.off(e,r)}once(e,r){return super.once(e,r)}prependListener(e,r){return super.prependListener(e,r)}prependOnceListener(e,r){return super.prependOnceListener(e,r)}removeListener(e,r){return super.removeListener(e,r)}removeAllListeners(e){return super.removeAllListeners(e)}listeners(e){return super.listeners(e)}listenerCount(e){return super.listenerCount(e)}}function yC(s,t=2){return s.replace(/[^\u00BF-\u1FFF\u2C00-\uD7FF\w\s]/g,"").trim().split(/\s+/).slice(0,t).map(i=>i.charAt(0)).join("").toUpperCase()}const Vm=1080,Lm=1920,EC=(s,t,e,r,i,n)=>{let o=.5,c=.5;const d=i,l=n,u=Math.min(e/d,r/l);let h=d*u,g=l*u,v,E,b,_,w=1;return h<e&&(w=e/h),Math.abs(w-1)<1e-14&&g<r&&(w=r/g),h*=w,g*=w,b=d/(h/e),_=l/(g/r),v=(d-b)*o,E=(l-_)*c,v<0&&(v=0),E<0&&(E=0),b>d&&(b=d),_>l&&(_=l),[v,E,b,_,s,t,e,r]},lp=class extends Gt{constructor(e,r,i,n){const o=e.getValue("logger");super(o);m(this,cs,void 0);m(this,qi,void 0);m(this,mt,void 0);m(this,ds,void 0);m(this,Ve,{height:Vm,width:Lm});m(this,As,{brand:"#2160FD",background:"#141414",text:"#000000",videoBackground:"#191919",textOnBrand:"#EEEEEE"});m(this,Sr,void 0);m(this,Rt,{});m(this,Be,void 0);m(this,ta,void 0);m(this,sa,void 0);m(this,Tr,void 0);m(this,ra,!1);p(this,"cleanupEventListeners",()=>{a(this,qi).unsubscribe("stageStatus",this.handlePipMediaControls),a(this,Be).removeListener("videoUpdate",this.onSelfVideoUpdateListener),a(this,Be).removeListener("audioUpdate",this.onSelfAudioUpdateListener),a(this,Be).removeListener("roomLeft",()=>this.disable())});p(this,"enablePipMediaControls",()=>{this.mountAudioEvents(),this.mountVideoEvents()});p(this,"onSelfVideoUpdateListener",({videoEnabled:e})=>{this.updateMediaSession("CAMERA",e)});p(this,"onSelfAudioUpdateListener",({audioEnabled:e})=>{this.updateMediaSession("MIC",e)});p(this,"handlePipMediaControls",e=>{e==="ON_STAGE"?this.enablePipMediaControls():this.unmountEvents()});p(this,"eventCallback",e=>{e==="CAMERA"&&(a(this,Be).videoEnabled?a(this,Be).disableVideo():a(this,Be).enableVideo(),this.emit("cameraToggled")),e==="MIC"&&(a(this,Be).audioEnabled?a(this,Be).disableAudio():a(this,Be).enableAudio(),this.emit("micToggled")),e==="END"&&(a(this,qi).getValue("peerSessionStore").emit(R.PIP_HANGUP),this.cleanupEventListeners(),this.emit("hangup"),this.cleanup())});p(this,"unmountEvents",()=>{navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||(navigator.mediaSession.setActionHandler("togglemicrophone",void 0),navigator.mediaSession.setActionHandler("togglecamera",void 0))});p(this,"animate",()=>{if(!this.isActive&&a(this,Tr)==="active"){this.disable(!0);return}a(this,Rt)!==void 0&&this.paintCanvas(),a(this,Sr)!==void 0&&f(this,Sr,requestAnimationFrame(()=>this.animate()))});p(this,"disable",(e=!1)=>{f(this,Tr,"idle"),this.cleanupEventListeners(),cancelAnimationFrame(a(this,Sr)),e!==!0&&document.body.removeChild(a(this,mt)),f(this,Sr,void 0),document.pictureInPictureElement&&document.exitPictureInPicture()});f(this,qi,e),f(this,Tr,"idle"),f(this,Be,r),f(this,As,{brand:r.config.designTokens.colors.brand[500],background:r.config.designTokens.colors.background[1e3],text:r.config.designTokens.colors.text,videoBackground:r.config.designTokens.colors.videoBg,textOnBrand:r.config.designTokens.colors.textOnBrand}),i&&this.setupIcon("pin",i),n&&this.setupIcon("handRaise",n)}static async _init(e,r){let i,n;try{i=await Dd(lC),n=await Dd(uC)}catch(o){}return new lp(e,r,i,n)}async setupIcon(e,r){switch(e){case"handRaise":f(this,sa,r);break;case"pin":f(this,ta,r);break}}async overrideIcon(e,r){switch(e){case"handRaise":f(this,sa,await Dd(r));break;case"pin":f(this,ta,await Dd(r));break}}constructImage(e){const r=new Image,i=new Blob([e],{type:"image/svg+xml"}),n=window.URL.createObjectURL(i);return new Promise(o=>{r.onload=()=>{o(r),window.URL.revokeObjectURL(n)},r.src=n})}createVideoContainer(){f(this,mt,document.createElement("div")),a(this,mt).style.width="0.1px",a(this,mt).style.height="0.1px",a(this,mt).style.overflow="hidden",a(this,mt).style.position="absolute",a(this,mt).style.bottom="0",a(this,mt).style.right="0",a(this,mt).style.opacity="0",a(this,mt).appendChild(a(this,ds))}setupEventListeners(){a(this,qi).subscribe("stageStatus",this.handlePipMediaControls),a(this,Be).addListener("videoUpdate",this.onSelfVideoUpdateListener),a(this,Be).addListener("audioUpdate",this.onSelfAudioUpdateListener),a(this,Be).addListener("roomLeft",()=>this.disable())}createCanvas(){const e=document.createElement("canvas");e.height=a(this,Ve).height,e.width=a(this,Ve).width,f(this,cs,e)}setupMediaSessionEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||(navigator.mediaSession.setActionHandler("hangup",()=>{this.eventCallback("END")}),this.mountAudioEvents(),this.mountVideoEvents())}mountAudioEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setMicrophoneActive===void 0||a(this,Be).permissions.canProduceAudio&&navigator.mediaSession.setActionHandler("togglemicrophone",()=>{this.eventCallback("MIC")})}mountVideoEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||a(this,Be).permissions.canProduceVideo&&navigator.mediaSession.setActionHandler("togglecamera",()=>{this.eventCallback("CAMERA")})}getSources(){const r=Object.values(a(this,Rt)).reduce((i,n)=>(i[n.pinned?"pinned":"regular"].push(n),i),{pinned:[],regular:[]});return[...r.pinned,...r.regular]}drawEmptyTile(e,r,i,n){if(a(this,cs)===void 0)return;const o=a(this,cs).getContext("2d"),c=a(this,cs).width,d=0,l=0,u=r-d*2,h=i-d*2,g=Math.floor(c/u),v=Math.floor(e/g),b=e%g*(u+d)+d,_=v*(h+d)+d,{displayText:w,image:L}=n!=null?n:{};o.fillStyle=w||L?a(this,As).videoBackground:a(this,As).background,o.strokeStyle=a(this,As).brand,o.beginPath(),o.moveTo(b+l,_),o.arcTo(b+u,_,b+u,_+l,l),o.arcTo(b+u,_+h,b+u-l,_+h,l),o.arcTo(b,_+h,b,_+h-l,l),o.arcTo(b,_,b+l,_,l),o.closePath(),o.fill(),o.stroke();const B=u/6,N=u/2+b,$=h/2+_;o.save(),(w||L)&&(o.beginPath(),o.arc(N,$,B,0,Math.PI*2),o.fillStyle=a(this,As).brand,o.fill(),L?(o.clip(),o.drawImage(L,N-B,$-B,B*2,B*2),o.restore()):w&&(o.fillStyle=a(this,As).textOnBrand,o.font=`${B/2}px sans-serif`,o.textAlign="center",o.textBaseline="middle",o.fillText(w,N,$)),this.drawIcons(n,b,_,Math.max(u,h)))}drawIcons(e,r,i,n){const o=Math.min(Math.max(n*.15,100),200),c=o*.2,d=o*.2;let l=r+c;const u=i+c,h=g=>{const v=a(this,cs).getContext("2d");v.save(),v.fillStyle=a(this,As).background,v.beginPath(),v.moveTo(l+d,u),v.arcTo(l+o,u,l+o,u+d,d),v.arcTo(l+o,u+o,l+o-d,u+o,d),v.arcTo(l,u+o,l,u+o-d,d),v.arcTo(l,u,l+d,u,d),v.closePath(),v.fill(),typeof g=="string"?(v.font=`${o/1.5}px sans-serif`,v.fillStyle=a(this,As).text,v.textAlign="center",v.textBaseline="top",v.fillText(g,o/2+l,u+c)):v.drawImage(g,l+c,u+c,o-c*2,o-c*2),l+=o+c,v.restore()};e.pinned&&h(a(this,ta)),e.handRaised&&h(a(this,sa))}drawTile(e,r,i){var l,u;if(a(this,cs)===void 0)return;const n=a(this,cs).getContext("2d"),o=this.getSources();let c=0,d=0;for(;c<a(this,Ve).height-5;){let h=0;for(;h<a(this,Ve).width-5&&d<i;){if((l=o[d])!=null&&l.enabled){const g=o[d].element,[v,E,b,_,w,L,B,N]=EC(h,c,e,r,g.videoWidth,g.videoHeight);((u=g==null?void 0:g.classList)==null?void 0:u.contains("mirror"))?(n.save(),n.scale(-1,1),n.drawImage(g,v,E,b,_,-1*w,L,-1*B,N),n.restore()):n.drawImage(g,v,E,b,_,w,L,B,N),this.drawIcons(o[d],w,L,Math.max(B,N))}else this.drawEmptyTile(d,e,r,o[d]);d+=1,h+=e}c+=r}}calcGridElemSize(e){switch(e){case 0:case 1:return[a(this,Ve).width,a(this,Ve).height];case 2:return[Math.floor(a(this,Ve).width/2),a(this,Ve).height];case 3:case 4:return[Math.floor(a(this,Ve).width/2),Math.floor(a(this,Ve).height/2)];case 5:case 6:return[Math.floor(a(this,Ve).width/3),Math.floor(a(this,Ve).height/2)];case 7:case 8:case 9:return[Math.floor(a(this,Ve).width/3),Math.floor(a(this,Ve).height/3)];default:return[Math.floor(a(this,Ve).width/3),Math.floor(a(this,Ve).height/2)]}}paintCanvas(){let e=this.getSources().length;e!==1&&(e=e%2>0?e+1:e);const[r,i]=this.calcGridElemSize(e);this.drawTile(r,i,e)}isSupported(){var e;return!!window.chrome&&document.pictureInPictureEnabled&&((e=a(this,Be).config)==null?void 0:e.viewType)!=="LIVESTREAM"}get isActive(){return document.pictureInPictureElement!==null}cleanup(){if(f(this,ra,!1),this.isSupported()&&document.exitPictureInPicture!==void 0&&document.pictureInPictureElement!==null&&document.exitPictureInPicture(),a(this,mt))try{document.body.removeChild(a(this,mt))}catch(e){}this.removeAllSources(),f(this,cs,void 0),f(this,ds,void 0),f(this,Sr,void 0)}init({height:e,width:r}={}){if(!this.isSupported())throw this.logger.error("Pip.unsupported"),new Error("Picture-in-picture is not available in this environment");if(a(this,ra))return;f(this,ra,!0),this.createCanvas(),this.setupMediaSessionEvents();const i=document.createElement("video");f(this,Ve,{height:e!=null?e:Vm,width:r!=null?r:Lm}),i.height=a(this,Ve).height,i.width=a(this,Ve).width,i.autoplay=!0,i.muted=!0,i.srcObject=a(this,cs).captureStream(24),f(this,ds,i),a(this,ds).onloadedmetadata=()=>{try{this.emit("pipStarted"),a(this,ds).onleavepictureinpicture=()=>{this.emit("pipEnded")}}catch(n){this.emit("pipEnded")}},this.createVideoContainer(),this.paintCanvas()}updateMediaSession(e,r){navigator.mediaSession!==void 0&&(e==="CAMERA"&&navigator.mediaSession.setCameraActive!==void 0&&navigator.mediaSession.setCameraActive(r),e==="MIC"&&navigator.mediaSession.setMicrophoneActive!==void 0&&navigator.mediaSession.setMicrophoneActive(r))}enableSource(e){a(this,Rt)[e]!==void 0&&(a(this,Rt)[e].enabled=!0)}disableSource(e){a(this,Rt)[e]!==void 0&&(a(this,Rt)[e].enabled=!1)}async generateAvatar(e,r){if(!r)return;const i=new Image;try{const n=await(await fetch(r)).blob(),o=window.URL.createObjectURL(n);i.onload=()=>{this.updateSource(e,{image:i}),window.URL.revokeObjectURL(o)},i.src=o}catch(n){this.logger.error("Pip::GenerateAvatar",{error:n})}}addSource(e,r,i,n=!1,o=void 0,c=void 0,d=!1){this.logger.debug("Pip::AddSource",{pip:{id:e,handRaised:d}}),a(this,Rt)[e]={id:e,element:r,enabled:i,pinned:n,displayText:o?yC(o):void 0,imageUrl:c,handRaised:d},c&&this.generateAvatar(e,c)}updateSource(e,r){this.logger.info("Pip::UpdateSource",{pip:{id:e,handRaised:r.handRaised}});const i=a(this,Rt)[e];i&&(a(this,Rt)[e]={...i,...r})}removeSource(e){delete a(this,Rt)[e]}removePinnedSource(){Object.values(a(this,Rt)).forEach(r=>{r.pinned&&this.removeSource(r.id)})}removeAllSources(){f(this,Rt,{})}enable(){f(this,Tr,"activating"),this.setupEventListeners(),this.updateMediaSession("CAMERA",a(this,Be).videoEnabled),this.updateMediaSession("MIC",a(this,Be).audioEnabled),document.body.appendChild(a(this,mt)),f(this,Sr,requestAnimationFrame(()=>this.animate())),a(this,ds).onloadedmetadata=()=>{a(this,ds).requestPictureInPicture().then(()=>{f(this,Tr,"active")})},a(this,ds).readyState===4&&a(this,ds).requestPictureInPicture().then(()=>{f(this,Tr,"active")})}};let rh=lp;cs=new WeakMap,qi=new WeakMap,mt=new WeakMap,ds=new WeakMap,Ve=new WeakMap,As=new WeakMap,Sr=new WeakMap,Rt=new WeakMap,Be=new WeakMap,ta=new WeakMap,sa=new WeakMap,Tr=new WeakMap,ra=new WeakMap;function ih(s){let t=typeof s;if(t=="object"){if(Array.isArray(s))return"array";if(s===null)return"null"}return t}function bC(s){return s!==null&&typeof s=="object"&&!Array.isArray(s)}let ar="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),Ld=[];for(let s=0;s<ar.length;s++)Ld[ar[s].charCodeAt(0)]=s;Ld["-".charCodeAt(0)]=ar.indexOf("+"),Ld["_".charCodeAt(0)]=ar.indexOf("/");function wC(s){let t=s.length*3/4;s[s.length-2]=="="?t-=2:s[s.length-1]=="="&&(t-=1);let e=new Uint8Array(t),r=0,i=0,n,o=0;for(let c=0;c<s.length;c++){if(n=Ld[s.charCodeAt(c)],n===void 0)switch(s[c]){case"=":i=0;case`
10
+ ${this.message}`;try{let o=n&&!!i;r&&r.endsWith("00")&&i&&(o=!0),o&&i.error("ClientError",{error:{message:this.message,name:this.name,code:r}});const c=nr.getContext(nr.getMostRecentPeerId());if(c){const d=c.getValue("onError");try{d(this)}catch(l){}}typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("ClientError",{detail:this}))}catch(o){}}}function Vd(s,t,e,r){if(r instanceof C)throw r;if(r instanceof t){const i=new C(r.message,e);throw i.stack=r.stack,i}else throw r}function Nm(s,t,e){if(!s.value){const i=s.get,n=s.set;return i&&(s.get=function(){try{return i.apply(this)}catch(o){Vd(this,t,e,o)}}),n&&(s.set=function(o){try{return n.apply(this,[o])}catch(c){Vd(this,t,e,c)}}),s}const r=s.value;return s.value=function(...i){try{const n=r.apply(this,i);return n&&n instanceof Promise?n.catch(o=>{Vd(this,t,e,o)}):n}catch(n){Vd(this,t,e,n)}},s}function vC(s,t){return(e,r,i)=>{if(i)return Nm(i,s,t);for(const n of Reflect.ownKeys(e.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(e.prototype,n);(o.value instanceof Function||o.get instanceof Function||o.set instanceof Function)&&Object.defineProperty(e.prototype,n,Nm(o,s,t))}}}const ut=s=>vC(Error,s);function SC(s){let t=0,e,r;if(!s)return t;for(e=0;e<s.length;e+=1)r=s.charCodeAt(e),t=(t<<5)-t+r,t|=0;return Math.abs(t)%100+1}function TC(){Te.isElectron()&&window.electronGetDisplayMediaSource&&(navigator.mediaDevices.getDisplayMedia=async()=>{const s=await window.electronGetDisplayMediaSource({types:["window","screen"]});let t=[];if(s&&(Array.isArray(s)?t=s:t=[s]),!(t!=null&&t.length))throw new Error("Couldn't find any media source for screen share.");let e=t.find(n=>{var o;return(o=n.id)==null?void 0:o.includes("screen")});e=e!=null?e:t[0];const r={audio:!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e.id}}};return await navigator.mediaDevices.getUserMedia(r)})}var R=(s=>(s.NEW_PRODUCER="NEW_PRODUCER",s.ROOM_NODE_CONNECTION_ERROR="ROOM_NODE_CONNECTION_ERROR",s.SOCKET_SERVICE_ROOM_JOINED="SOCKET_SERVICE_ROOM_JOINED",s.SOCKET_SERVICE_RECONNECTED="SOCKET_SERVICE_RECONNECTED",s.SOCKET_SERVICE_DISCONNECTED="SOCKET_SERVICE_DISCONNECTED",s.SOCKET_SERVICE_FAILED="SOCKET_SERVICE_FAILED",s.SOCKET_STATE_UPDATE="SOCKET_STATE_UPDATE",s.ROOM_NODE_RECONNECTED="ROOM_NODE_RECONNECTED",s.ROOM_NODE_DISCONNECTED="ROOM_NODE_DISCONNECTED",s.ROOM_NODE_FAILED="ROOM_NODE_FAILED",s.TRANSPORT_STATE_UPDATE="TRANSPORT_STATE_UPDATE",s.PRODUCER_SCORE_UPDATE="PRODUCER_SCORE_UPDATE",s.CONSUMER_SCORE_UPDATE="CONSUMER_SCORE_UPDATE",s.PRODUCER_STATUS_UPDATE="PRODUCER_STATUS_UPDATE",s.CONSUMER_STATUS_UPDATE="CONSUMER_STATUS_UPDATE",s.LOW_CONSUMER_SCORE="LOW_CONSUMER_SCORE",s.MEDIA_PERMISSION_ERROR="MEDIA_PERMISSION_ERROR",s.MEDIA_PERMISSION_UPDATE="MEDIA_PERMISSION_UPDATE",s.MESSAGE="websocket/message",s.ROOM_MESSAGE="websocket/room-message",s.PEER_JOINED_INTERNAL="peer/joined-internal",s.PEER_CLOSED="websocket/peer-closed",s.CONSUMER_CLOSED="websocket/consumer-closed",s.CONSUMER_PAUSED="websocket/consumer-paused",s.CONSUMER_RESUMED="websocket/consumer-resumed",s.PRODUCER_CLOSED="websocket/producer-closed",s.NEW_CONSUMER="websocket/new-consumer",s.PRODUCER_SCORE="websocket/producer-score",s.CONSUMER_SCORE="websocket/consumer-score",s.PRODUCER_TOGGLE="cf/producer-toggle",s.UPDATE_ACTIVE="media/update-active",s.RESET_PRODUCER_STATE="cf/reset-producer-state",s.ROOM_STATE="sockethub/room-state",s.GET_STAGE_REQUESTS="GET_STAGE_REQUESTS",s.UPDATE_STAGE_REQUESTS="UPDATE_STAGE_REQUESTS",s.KICK_PEER="KICK_PEER",s.UPDATE_PEER_STAGE_STATUS="UPDATE_PEER_STAGE_STATUS",s.JOIN_MEDIA_ROOM="JOIN_MEDIA_ROOM",s.LEAVE_MEDIA_ROOM="LEAVE_MEDIA_ROOM",s.PIP_HANGUP="PIP_HANGUP",s.E2EE_ACTIVE_PRODUCER="E2EE_ACTIVE_PRODUCER",s.E2EE_INACTIVE_PRODUCER="E2EE_INACTIVE_PRODUCER",s.E2EE_ACTIVE_CONSUMER="E2EE_ACTIVE_CONSUMER",s.E2EE_INACTIVE_CONSUMER="E2EE_INACTIVE_CONSUMER",s.SOCKET_PEERS="SOCKET_PEERS",s.UPDATE_PERMISSIONS="UPDATE_PERMISSIONS",s.MAX_SPATIAL_LAYER_CHANGE="MAX_SPATIAL_LAYER_CHANGE",s.MUTE_SELF="MUTE_SELF",s.MUTE_SELF_VIDEO="MUTE_SELF_VIDEO",s))(R||{});class Bn extends lt.EventEmitter{constructor(e){super();p(this,"logger");this.logger=e,super.setMaxListeners(25)}emit(e,...r){return super.emit("*",e,...r),super.emit(e,...r)}on(e,r){var i;try{const n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(n){}return super.on(e,r)}addListener(e,r){var i;try{const n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(n){}return super.addListener(e,r)}off(e,r){return super.off(e,r)}once(e,r){return super.once(e,r)}prependListener(e,r){return super.prependListener(e,r)}prependOnceListener(e,r){return super.prependOnceListener(e,r)}removeListener(e,r){return super.removeListener(e,r)}removeAllListeners(e){return super.removeAllListeners(e)}listeners(e){return super.listeners(e)}listenerCount(e){return super.listenerCount(e)}}class Gt extends lt.EventEmitter{constructor(e){super();p(this,"logger");this.logger=e,super.setMaxListeners(25)}emit(e,...r){return super.emit("*",e,...r),super.emit(e,...r)}on(e,r){var i;try{const n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(n){}return super.on(e,r)}addListener(e,r){var i;try{const n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(n){}return super.addListener(e,r)}off(e,r){return super.off(e,r)}once(e,r){return super.once(e,r)}prependListener(e,r){return super.prependListener(e,r)}prependOnceListener(e,r){return super.prependOnceListener(e,r)}removeListener(e,r){return super.removeListener(e,r)}removeAllListeners(e){return super.removeAllListeners(e)}listeners(e){return super.listeners(e)}listenerCount(e){return super.listenerCount(e)}}function yC(s,t=2){return s.replace(/[^\u00BF-\u1FFF\u2C00-\uD7FF\w\s]/g,"").trim().split(/\s+/).slice(0,t).map(i=>i.charAt(0)).join("").toUpperCase()}const Vm=1080,Lm=1920,EC=(s,t,e,r,i,n)=>{let o=.5,c=.5;const d=i,l=n,u=Math.min(e/d,r/l);let h=d*u,g=l*u,v,E,b,_,w=1;return h<e&&(w=e/h),Math.abs(w-1)<1e-14&&g<r&&(w=r/g),h*=w,g*=w,b=d/(h/e),_=l/(g/r),v=(d-b)*o,E=(l-_)*c,v<0&&(v=0),E<0&&(E=0),b>d&&(b=d),_>l&&(_=l),[v,E,b,_,s,t,e,r]},lp=class extends Gt{constructor(e,r,i,n){const o=e.getValue("logger");super(o);m(this,cs,void 0);m(this,qi,void 0);m(this,mt,void 0);m(this,ds,void 0);m(this,Ve,{height:Vm,width:Lm});m(this,As,{brand:"#2160FD",background:"#141414",text:"#000000",videoBackground:"#191919",textOnBrand:"#EEEEEE"});m(this,Sr,void 0);m(this,Rt,{});m(this,Be,void 0);m(this,ta,void 0);m(this,sa,void 0);m(this,Tr,void 0);m(this,ra,!1);p(this,"cleanupEventListeners",()=>{a(this,qi).unsubscribe("stageStatus",this.handlePipMediaControls),a(this,Be).removeListener("videoUpdate",this.onSelfVideoUpdateListener),a(this,Be).removeListener("audioUpdate",this.onSelfAudioUpdateListener),a(this,Be).removeListener("roomLeft",()=>this.disable())});p(this,"enablePipMediaControls",()=>{this.mountAudioEvents(),this.mountVideoEvents()});p(this,"onSelfVideoUpdateListener",({videoEnabled:e})=>{this.updateMediaSession("CAMERA",e)});p(this,"onSelfAudioUpdateListener",({audioEnabled:e})=>{this.updateMediaSession("MIC",e)});p(this,"handlePipMediaControls",e=>{e==="ON_STAGE"?this.enablePipMediaControls():this.unmountEvents()});p(this,"eventCallback",e=>{e==="CAMERA"&&(a(this,Be).videoEnabled?a(this,Be).disableVideo():a(this,Be).enableVideo(),this.emit("cameraToggled")),e==="MIC"&&(a(this,Be).audioEnabled?a(this,Be).disableAudio():a(this,Be).enableAudio(),this.emit("micToggled")),e==="END"&&(a(this,qi).getValue("peerSessionStore").emit(R.PIP_HANGUP),this.cleanupEventListeners(),this.emit("hangup"),this.cleanup())});p(this,"unmountEvents",()=>{navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||(navigator.mediaSession.setActionHandler("togglemicrophone",void 0),navigator.mediaSession.setActionHandler("togglecamera",void 0))});p(this,"animate",()=>{if(!this.isActive&&a(this,Tr)==="active"){this.disable(!0);return}a(this,Rt)!==void 0&&this.paintCanvas(),a(this,Sr)!==void 0&&f(this,Sr,requestAnimationFrame(()=>this.animate()))});p(this,"disable",(e=!1)=>{f(this,Tr,"idle"),this.cleanupEventListeners(),cancelAnimationFrame(a(this,Sr)),e!==!0&&document.body.removeChild(a(this,mt)),f(this,Sr,void 0),document.pictureInPictureElement&&document.exitPictureInPicture()});f(this,qi,e),f(this,Tr,"idle"),f(this,Be,r),f(this,As,{brand:r.config.designTokens.colors.brand[500],background:r.config.designTokens.colors.background[1e3],text:r.config.designTokens.colors.text,videoBackground:r.config.designTokens.colors.videoBg,textOnBrand:r.config.designTokens.colors.textOnBrand}),i&&this.setupIcon("pin",i),n&&this.setupIcon("handRaise",n)}static async _init(e,r){let i,n;try{i=await Dd(lC),n=await Dd(uC)}catch(o){}return new lp(e,r,i,n)}async setupIcon(e,r){switch(e){case"handRaise":f(this,sa,r);break;case"pin":f(this,ta,r);break}}async overrideIcon(e,r){switch(e){case"handRaise":f(this,sa,await Dd(r));break;case"pin":f(this,ta,await Dd(r));break}}constructImage(e){const r=new Image,i=new Blob([e],{type:"image/svg+xml"}),n=window.URL.createObjectURL(i);return new Promise(o=>{r.onload=()=>{o(r),window.URL.revokeObjectURL(n)},r.src=n})}createVideoContainer(){f(this,mt,document.createElement("div")),a(this,mt).style.width="0.1px",a(this,mt).style.height="0.1px",a(this,mt).style.overflow="hidden",a(this,mt).style.position="absolute",a(this,mt).style.bottom="0",a(this,mt).style.right="0",a(this,mt).style.opacity="0",a(this,mt).appendChild(a(this,ds))}setupEventListeners(){a(this,qi).subscribe("stageStatus",this.handlePipMediaControls),a(this,Be).addListener("videoUpdate",this.onSelfVideoUpdateListener),a(this,Be).addListener("audioUpdate",this.onSelfAudioUpdateListener),a(this,Be).addListener("roomLeft",()=>this.disable())}createCanvas(){const e=document.createElement("canvas");e.height=a(this,Ve).height,e.width=a(this,Ve).width,f(this,cs,e)}setupMediaSessionEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||(navigator.mediaSession.setActionHandler("hangup",()=>{this.eventCallback("END")}),this.mountAudioEvents(),this.mountVideoEvents())}mountAudioEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setMicrophoneActive===void 0||a(this,Be).permissions.canProduceAudio&&navigator.mediaSession.setActionHandler("togglemicrophone",()=>{this.eventCallback("MIC")})}mountVideoEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||a(this,Be).permissions.canProduceVideo&&navigator.mediaSession.setActionHandler("togglecamera",()=>{this.eventCallback("CAMERA")})}getSources(){const r=Object.values(a(this,Rt)).reduce((i,n)=>(i[n.pinned?"pinned":"regular"].push(n),i),{pinned:[],regular:[]});return[...r.pinned,...r.regular]}drawEmptyTile(e,r,i,n){if(a(this,cs)===void 0)return;const o=a(this,cs).getContext("2d"),c=a(this,cs).width,d=0,l=0,u=r-d*2,h=i-d*2,g=Math.floor(c/u),v=Math.floor(e/g),b=e%g*(u+d)+d,_=v*(h+d)+d,{displayText:w,image:L}=n!=null?n:{};o.fillStyle=w||L?a(this,As).videoBackground:a(this,As).background,o.strokeStyle=a(this,As).brand,o.beginPath(),o.moveTo(b+l,_),o.arcTo(b+u,_,b+u,_+l,l),o.arcTo(b+u,_+h,b+u-l,_+h,l),o.arcTo(b,_+h,b,_+h-l,l),o.arcTo(b,_,b+l,_,l),o.closePath(),o.fill(),o.stroke();const B=u/6,N=u/2+b,$=h/2+_;o.save(),(w||L)&&(o.beginPath(),o.arc(N,$,B,0,Math.PI*2),o.fillStyle=a(this,As).brand,o.fill(),L?(o.clip(),o.drawImage(L,N-B,$-B,B*2,B*2),o.restore()):w&&(o.fillStyle=a(this,As).textOnBrand,o.font=`${B/2}px sans-serif`,o.textAlign="center",o.textBaseline="middle",o.fillText(w,N,$)),this.drawIcons(n,b,_,Math.max(u,h)))}drawIcons(e,r,i,n){const o=Math.min(Math.max(n*.15,100),200),c=o*.2,d=o*.2;let l=r+c;const u=i+c,h=g=>{const v=a(this,cs).getContext("2d");v.save(),v.fillStyle=a(this,As).background,v.beginPath(),v.moveTo(l+d,u),v.arcTo(l+o,u,l+o,u+d,d),v.arcTo(l+o,u+o,l+o-d,u+o,d),v.arcTo(l,u+o,l,u+o-d,d),v.arcTo(l,u,l+d,u,d),v.closePath(),v.fill(),typeof g=="string"?(v.font=`${o/1.5}px sans-serif`,v.fillStyle=a(this,As).text,v.textAlign="center",v.textBaseline="top",v.fillText(g,o/2+l,u+c)):v.drawImage(g,l+c,u+c,o-c*2,o-c*2),l+=o+c,v.restore()};e.pinned&&h(a(this,ta)),e.handRaised&&h(a(this,sa)),e.reaction&&h(e.reaction)}drawTile(e,r,i){var l,u;if(a(this,cs)===void 0)return;const n=a(this,cs).getContext("2d"),o=this.getSources();let c=0,d=0;for(;c<a(this,Ve).height-5;){let h=0;for(;h<a(this,Ve).width-5&&d<i;){if((l=o[d])!=null&&l.enabled){const g=o[d].element,[v,E,b,_,w,L,B,N]=EC(h,c,e,r,g.videoWidth,g.videoHeight);((u=g==null?void 0:g.classList)==null?void 0:u.contains("mirror"))?(n.save(),n.scale(-1,1),n.drawImage(g,v,E,b,_,-1*w,L,-1*B,N),n.restore()):n.drawImage(g,v,E,b,_,w,L,B,N),this.drawIcons(o[d],w,L,Math.max(B,N))}else this.drawEmptyTile(d,e,r,o[d]);d+=1,h+=e}c+=r}}calcGridElemSize(e){switch(e){case 0:case 1:return[a(this,Ve).width,a(this,Ve).height];case 2:return[Math.floor(a(this,Ve).width/2),a(this,Ve).height];case 3:case 4:return[Math.floor(a(this,Ve).width/2),Math.floor(a(this,Ve).height/2)];case 5:case 6:return[Math.floor(a(this,Ve).width/3),Math.floor(a(this,Ve).height/2)];case 7:case 8:case 9:return[Math.floor(a(this,Ve).width/3),Math.floor(a(this,Ve).height/3)];default:return[Math.floor(a(this,Ve).width/3),Math.floor(a(this,Ve).height/2)]}}paintCanvas(){let e=this.getSources().length;e!==1&&(e=e%2>0?e+1:e);const[r,i]=this.calcGridElemSize(e);this.drawTile(r,i,e)}isSupported(){var e;return!!window.chrome&&document.pictureInPictureEnabled&&((e=a(this,Be).config)==null?void 0:e.viewType)!=="LIVESTREAM"}get isActive(){return document.pictureInPictureElement!==null}cleanup(){if(f(this,ra,!1),this.isSupported()&&document.exitPictureInPicture!==void 0&&document.pictureInPictureElement!==null&&document.exitPictureInPicture(),a(this,mt))try{document.body.removeChild(a(this,mt))}catch(e){}this.removeAllSources(),f(this,cs,void 0),f(this,ds,void 0),f(this,Sr,void 0)}init({height:e,width:r}={}){if(!this.isSupported())throw this.logger.error("Pip.unsupported"),new Error("Picture-in-picture is not available in this environment");if(a(this,ra))return;f(this,ra,!0),this.createCanvas(),this.setupMediaSessionEvents();const i=document.createElement("video");f(this,Ve,{height:e!=null?e:Vm,width:r!=null?r:Lm}),i.height=a(this,Ve).height,i.width=a(this,Ve).width,i.autoplay=!0,i.muted=!0,i.srcObject=a(this,cs).captureStream(24),f(this,ds,i),a(this,ds).onloadedmetadata=()=>{try{this.emit("pipStarted"),a(this,ds).onleavepictureinpicture=()=>{this.emit("pipEnded")}}catch(n){this.emit("pipEnded")}},this.createVideoContainer(),this.paintCanvas()}updateMediaSession(e,r){navigator.mediaSession!==void 0&&(e==="CAMERA"&&navigator.mediaSession.setCameraActive!==void 0&&navigator.mediaSession.setCameraActive(r),e==="MIC"&&navigator.mediaSession.setMicrophoneActive!==void 0&&navigator.mediaSession.setMicrophoneActive(r))}enableSource(e){a(this,Rt)[e]!==void 0&&(a(this,Rt)[e].enabled=!0)}disableSource(e){a(this,Rt)[e]!==void 0&&(a(this,Rt)[e].enabled=!1)}async generateAvatar(e,r){if(!r)return;const i=new Image;try{const n=await(await fetch(r)).blob(),o=window.URL.createObjectURL(n);i.onload=()=>{this.updateSource(e,{image:i}),window.URL.revokeObjectURL(o)},i.src=o}catch(n){this.logger.error("Pip::GenerateAvatar",{error:n})}}addSource(e,r,i,n=!1,o=void 0,c=void 0,d=!1){this.logger.debug("Pip::AddSource",{pip:{id:e,handRaised:d}}),a(this,Rt)[e]={id:e,element:r,enabled:i,pinned:n,displayText:o?yC(o):void 0,imageUrl:c,handRaised:d},c&&this.generateAvatar(e,c)}updateSource(e,r){this.logger.info("Pip::UpdateSource",{pip:{id:e,handRaised:r.handRaised,reaction:r.reaction}});const i=a(this,Rt)[e];i&&(a(this,Rt)[e]={...i,...r})}removeSource(e){delete a(this,Rt)[e]}removePinnedSource(){Object.values(a(this,Rt)).forEach(r=>{r.pinned&&this.removeSource(r.id)})}removeAllSources(){f(this,Rt,{})}enable(){f(this,Tr,"activating"),this.setupEventListeners(),this.updateMediaSession("CAMERA",a(this,Be).videoEnabled),this.updateMediaSession("MIC",a(this,Be).audioEnabled),document.body.appendChild(a(this,mt)),f(this,Sr,requestAnimationFrame(()=>this.animate())),a(this,ds).onloadedmetadata=()=>{a(this,ds).requestPictureInPicture().then(()=>{f(this,Tr,"active")})},a(this,ds).readyState===4&&a(this,ds).requestPictureInPicture().then(()=>{f(this,Tr,"active")})}};let rh=lp;cs=new WeakMap,qi=new WeakMap,mt=new WeakMap,ds=new WeakMap,Ve=new WeakMap,As=new WeakMap,Sr=new WeakMap,Rt=new WeakMap,Be=new WeakMap,ta=new WeakMap,sa=new WeakMap,Tr=new WeakMap,ra=new WeakMap;function ih(s){let t=typeof s;if(t=="object"){if(Array.isArray(s))return"array";if(s===null)return"null"}return t}function bC(s){return s!==null&&typeof s=="object"&&!Array.isArray(s)}let ar="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),Ld=[];for(let s=0;s<ar.length;s++)Ld[ar[s].charCodeAt(0)]=s;Ld["-".charCodeAt(0)]=ar.indexOf("+"),Ld["_".charCodeAt(0)]=ar.indexOf("/");function wC(s){let t=s.length*3/4;s[s.length-2]=="="?t-=2:s[s.length-1]=="="&&(t-=1);let e=new Uint8Array(t),r=0,i=0,n,o=0;for(let c=0;c<s.length;c++){if(n=Ld[s.charCodeAt(c)],n===void 0)switch(s[c]){case"=":i=0;case`
11
11
  `:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(i){case 0:o=n,i=1;break;case 1:e[r++]=o<<2|(n&48)>>4,o=n,i=2;break;case 2:e[r++]=(o&15)<<4|(n&60)>>2,o=n,i=3;break;case 3:e[r++]=(o&3)<<6|n,i=0;break}}if(i==1)throw Error("invalid base64 string.");return e.subarray(0,r)}function _C(s){let t="",e=0,r,i=0;for(let n=0;n<s.length;n++)switch(r=s[n],e){case 0:t+=ar[r>>2],i=(r&3)<<4,e=1;break;case 1:t+=ar[i|r>>4],i=(r&15)<<2,e=2;break;case 2:t+=ar[i|r>>6],t+=ar[r&63],e=0;break}return e&&(t+=ar[i],t+="=",e==1&&(t+="=")),t}var xd;(function(s){s.symbol=Symbol.for("protobuf-ts/unknown"),s.onRead=(e,r,i,n,o)=>{(t(r)?r[s.symbol]:r[s.symbol]=[]).push({no:i,wireType:n,data:o})},s.onWrite=(e,r,i)=>{for(let{no:n,wireType:o,data:c}of s.list(r))i.tag(n,o).raw(c)},s.list=(e,r)=>{if(t(e)){let i=e[s.symbol];return r?i.filter(n=>n.no==r):i}return[]},s.last=(e,r)=>s.list(e,r).slice(-1)[0];const t=e=>e&&Array.isArray(e[s.symbol])})(xd||(xd={}));var Ue;(function(s){s[s.Varint=0]="Varint",s[s.Bit64=1]="Bit64",s[s.LengthDelimited=2]="LengthDelimited",s[s.StartGroup=3]="StartGroup",s[s.EndGroup=4]="EndGroup",s[s.Bit32=5]="Bit32"})(Ue||(Ue={}));function PC(){let s=0,t=0;for(let r=0;r<28;r+=7){let i=this.buf[this.pos++];if(s|=(i&127)<<r,!(i&128))return this.assertBounds(),[s,t]}let e=this.buf[this.pos++];if(s|=(e&15)<<28,t=(e&112)>>4,!(e&128))return this.assertBounds(),[s,t];for(let r=3;r<=31;r+=7){let i=this.buf[this.pos++];if(t|=(i&127)<<r,!(i&128))return this.assertBounds(),[s,t]}throw new Error("invalid varint")}function nh(s,t,e){for(let n=0;n<28;n=n+7){const o=s>>>n,c=!(!(o>>>7)&&t==0),d=(c?o|128:o)&255;if(e.push(d),!c)return}const r=s>>>28&15|(t&7)<<4,i=!!(t>>3);if(e.push((i?r|128:r)&255),!!i){for(let n=3;n<31;n=n+7){const o=t>>>n,c=!!(o>>>7),d=(c?o|128:o)&255;if(e.push(d),!c)return}e.push(t>>>31&1)}}const Ud=(1<<16)*(1<<16);function xm(s){let t=s[0]=="-";t&&(s=s.slice(1));const e=1e6;let r=0,i=0;function n(o,c){const d=Number(s.slice(o,c));i*=e,r=r*e+d,r>=Ud&&(i=i+(r/Ud|0),r=r%Ud)}return n(-24,-18),n(-18,-12),n(-12,-6),n(-6),[t,r,i]}function ah(s,t){if(t>>>0<=2097151)return""+(Ud*t+(s>>>0));let e=s&16777215,r=(s>>>24|t<<8)>>>0&16777215,i=t>>16&65535,n=e+r*6777216+i*6710656,o=r+i*8147497,c=i*2,d=1e7;n>=d&&(o+=Math.floor(n/d),n%=d),o>=d&&(c+=Math.floor(o/d),o%=d);function l(u,h){let g=u?String(u):"";return h?"0000000".slice(g.length)+g:g}return l(c,0)+l(o,c)+l(n,1)}function Um(s,t){if(s>=0){for(;s>127;)t.push(s&127|128),s=s>>>7;t.push(s)}else{for(let e=0;e<9;e++)t.push(s&127|128),s=s>>7;t.push(1)}}function CC(){let s=this.buf[this.pos++],t=s&127;if(!(s&128))return this.assertBounds(),t;if(s=this.buf[this.pos++],t|=(s&127)<<7,!(s&128))return this.assertBounds(),t;if(s=this.buf[this.pos++],t|=(s&127)<<14,!(s&128))return this.assertBounds(),t;if(s=this.buf[this.pos++],t|=(s&127)<<21,!(s&128))return this.assertBounds(),t;s=this.buf[this.pos++],t|=(s&15)<<28;for(let e=5;s&128&&e<10;e++)s=this.buf[this.pos++];if(s&128)throw new Error("invalid varint");return this.assertBounds(),t>>>0}let ue;function RC(){const s=new DataView(new ArrayBuffer(8));ue=globalThis.BigInt!==void 0&&typeof s.getBigInt64=="function"&&typeof s.getBigUint64=="function"&&typeof s.setBigInt64=="function"&&typeof s.setBigUint64=="function"?{MIN:BigInt("-9223372036854775808"),MAX:BigInt("9223372036854775807"),UMIN:BigInt("0"),UMAX:BigInt("18446744073709551615"),C:BigInt,V:s}:void 0}RC();function Fm(s){if(!s)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}const Bm=/^-?[0-9]+$/,Fd=4294967296,Bd=2147483648;class $m{constructor(t,e){this.lo=t|0,this.hi=e|0}isZero(){return this.lo==0&&this.hi==0}toNumber(){let t=this.hi*Fd+(this.lo>>>0);if(!Number.isSafeInteger(t))throw new Error("cannot convert to safe number");return t}}class ht extends $m{static from(t){if(ue)switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=="")throw new Error("string is no integer");t=ue.C(t);case"number":if(t===0)return this.ZERO;t=ue.C(t);case"bigint":if(!t)return this.ZERO;if(t<ue.UMIN)throw new Error("signed value for ulong");if(t>ue.UMAX)throw new Error("ulong too large");return ue.V.setBigUint64(0,t,!0),new ht(ue.V.getInt32(0,!0),ue.V.getInt32(4,!0))}else switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=t.trim(),!Bm.test(t))throw new Error("string is no integer");let[e,r,i]=xm(t);if(e)throw new Error("signed value for ulong");return new ht(r,i);case"number":if(t==0)return this.ZERO;if(!Number.isSafeInteger(t))throw new Error("number is no integer");if(t<0)throw new Error("signed value for ulong");return new ht(t,t/Fd)}throw new Error("unknown value "+typeof t)}toString(){return ue?this.toBigInt().toString():ah(this.lo,this.hi)}toBigInt(){return Fm(ue),ue.V.setInt32(0,this.lo,!0),ue.V.setInt32(4,this.hi,!0),ue.V.getBigUint64(0,!0)}}ht.ZERO=new ht(0,0);class me extends $m{static from(t){if(ue)switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=="")throw new Error("string is no integer");t=ue.C(t);case"number":if(t===0)return this.ZERO;t=ue.C(t);case"bigint":if(!t)return this.ZERO;if(t<ue.MIN)throw new Error("signed long too small");if(t>ue.MAX)throw new Error("signed long too large");return ue.V.setBigInt64(0,t,!0),new me(ue.V.getInt32(0,!0),ue.V.getInt32(4,!0))}else switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=t.trim(),!Bm.test(t))throw new Error("string is no integer");let[e,r,i]=xm(t);if(e){if(i>Bd||i==Bd&&r!=0)throw new Error("signed long too small")}else if(i>=Bd)throw new Error("signed long too large");let n=new me(r,i);return e?n.negate():n;case"number":if(t==0)return this.ZERO;if(!Number.isSafeInteger(t))throw new Error("number is no integer");return t>0?new me(t,t/Fd):new me(-t,-t/Fd).negate()}throw new Error("unknown value "+typeof t)}isNegative(){return(this.hi&Bd)!==0}negate(){let t=~this.hi,e=this.lo;return e?e=~e+1:t+=1,new me(e,t)}toString(){if(ue)return this.toBigInt().toString();if(this.isNegative()){let t=this.negate();return"-"+ah(t.lo,t.hi)}return ah(this.lo,this.hi)}toBigInt(){return Fm(ue),ue.V.setInt32(0,this.lo,!0),ue.V.setInt32(4,this.hi,!0),ue.V.getBigInt64(0,!0)}}me.ZERO=new me(0,0);const Hm={readUnknownField:!0,readerFactory:s=>new IC(s)};function kC(s){return s?Object.assign(Object.assign({},Hm),s):Hm}class IC{constructor(t,e){this.varint64=PC,this.uint32=CC,this.buf=t,this.len=t.length,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.textDecoder=e!=null?e:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0})}tag(){let t=this.uint32(),e=t>>>3,r=t&7;if(e<=0||r<0||r>5)throw new Error("illegal tag: field no "+e+" wire type "+r);return[e,r]}skip(t){let e=this.pos;switch(t){case Ue.Varint:for(;this.buf[this.pos++]&128;);break;case Ue.Bit64:this.pos+=4;case Ue.Bit32:this.pos+=4;break;case Ue.LengthDelimited:let r=this.uint32();this.pos+=r;break;case Ue.StartGroup:let i;for(;(i=this.tag()[1])!==Ue.EndGroup;)this.skip(i);break;default:throw new Error("cant skip wire type "+t)}return this.assertBounds(),this.buf.subarray(e,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)}int64(){return new me(...this.varint64())}uint64(){return new ht(...this.varint64())}sint64(){let[t,e]=this.varint64(),r=-(t&1);return t=(t>>>1|(e&1)<<31)^r,e=e>>>1^r,new me(t,e)}bool(){let[t,e]=this.varint64();return t!==0||e!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return new ht(this.sfixed32(),this.sfixed32())}sfixed64(){return new me(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let t=this.uint32(),e=this.pos;return this.pos+=t,this.assertBounds(),this.buf.subarray(e,e+t)}string(){return this.textDecoder.decode(this.bytes())}}function se(s,t){if(!s)throw new Error(t)}const AC=34028234663852886e22,MC=-34028234663852886e22,OC=4294967295,DC=2147483647,NC=-2147483648;function yo(s){if(typeof s!="number")throw new Error("invalid int 32: "+typeof s);if(!Number.isInteger(s)||s>DC||s<NC)throw new Error("invalid int 32: "+s)}function $d(s){if(typeof s!="number")throw new Error("invalid uint 32: "+typeof s);if(!Number.isInteger(s)||s>OC||s<0)throw new Error("invalid uint 32: "+s)}function oh(s){if(typeof s!="number")throw new Error("invalid float 32: "+typeof s);if(Number.isFinite(s)&&(s>AC||s<MC))throw new Error("invalid float 32: "+s)}const qm={writeUnknownFields:!0,writerFactory:()=>new LC};function VC(s){return s?Object.assign(Object.assign({},qm),s):qm}class LC{constructor(t){this.stack=[],this.textEncoder=t!=null?t:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let t=0;for(let i=0;i<this.chunks.length;i++)t+=this.chunks[i].length;let e=new Uint8Array(t),r=0;for(let i=0;i<this.chunks.length;i++)e.set(this.chunks[i],r),r+=this.chunks[i].length;return this.chunks=[],e}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let t=this.finish(),e=this.stack.pop();if(!e)throw new Error("invalid state, fork stack empty");return this.chunks=e.chunks,this.buf=e.buf,this.uint32(t.byteLength),this.raw(t)}tag(t,e){return this.uint32((t<<3|e)>>>0)}raw(t){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(t),this}uint32(t){for($d(t);t>127;)this.buf.push(t&127|128),t=t>>>7;return this.buf.push(t),this}int32(t){return yo(t),Um(t,this.buf),this}bool(t){return this.buf.push(t?1:0),this}bytes(t){return this.uint32(t.byteLength),this.raw(t)}string(t){let e=this.textEncoder.encode(t);return this.uint32(e.byteLength),this.raw(e)}float(t){oh(t);let e=new Uint8Array(4);return new DataView(e.buffer).setFloat32(0,t,!0),this.raw(e)}double(t){let e=new Uint8Array(8);return new DataView(e.buffer).setFloat64(0,t,!0),this.raw(e)}fixed32(t){$d(t);let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!0),this.raw(e)}sfixed32(t){yo(t);let e=new Uint8Array(4);return new DataView(e.buffer).setInt32(0,t,!0),this.raw(e)}sint32(t){return yo(t),t=(t<<1^t>>31)>>>0,Um(t,this.buf),this}sfixed64(t){let e=new Uint8Array(8),r=new DataView(e.buffer),i=me.from(t);return r.setInt32(0,i.lo,!0),r.setInt32(4,i.hi,!0),this.raw(e)}fixed64(t){let e=new Uint8Array(8),r=new DataView(e.buffer),i=ht.from(t);return r.setInt32(0,i.lo,!0),r.setInt32(4,i.hi,!0),this.raw(e)}int64(t){let e=me.from(t);return nh(e.lo,e.hi,this.buf),this}sint64(t){let e=me.from(t),r=e.hi>>31,i=e.lo<<1^r,n=(e.hi<<1|e.lo>>>31)^r;return nh(i,n,this.buf),this}uint64(t){let e=ht.from(t);return nh(e.lo,e.hi,this.buf),this}}const jm={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},Gm={ignoreUnknownFields:!1};function xC(s){return s?Object.assign(Object.assign({},Gm),s):Gm}function UC(s){return s?Object.assign(Object.assign({},jm),s):jm}const Wm=Symbol.for("protobuf-ts/message-type");function Jm(s){let t=!1;const e=[];for(let r=0;r<s.length;r++){let i=s.charAt(r);i=="_"?t=!0:/\d/.test(i)?(e.push(i),t=!0):t?(e.push(i.toUpperCase()),t=!1):r==0?e.push(i.toLowerCase()):e.push(i)}return e.join("")}var A;(function(s){s[s.DOUBLE=1]="DOUBLE",s[s.FLOAT=2]="FLOAT",s[s.INT64=3]="INT64",s[s.UINT64=4]="UINT64",s[s.INT32=5]="INT32",s[s.FIXED64=6]="FIXED64",s[s.FIXED32=7]="FIXED32",s[s.BOOL=8]="BOOL",s[s.STRING=9]="STRING",s[s.BYTES=12]="BYTES",s[s.UINT32=13]="UINT32",s[s.SFIXED32=15]="SFIXED32",s[s.SFIXED64=16]="SFIXED64",s[s.SINT32=17]="SINT32",s[s.SINT64=18]="SINT64"})(A||(A={}));var Gs;(function(s){s[s.BIGINT=0]="BIGINT",s[s.STRING=1]="STRING",s[s.NUMBER=2]="NUMBER"})(Gs||(Gs={}));var Hd;(function(s){s[s.NO=0]="NO",s[s.PACKED=1]="PACKED",s[s.UNPACKED=2]="UNPACKED"})(Hd||(Hd={}));function FC(s){var t,e,r,i;return s.localName=(t=s.localName)!==null&&t!==void 0?t:Jm(s.name),s.jsonName=(e=s.jsonName)!==null&&e!==void 0?e:Jm(s.name),s.repeat=(r=s.repeat)!==null&&r!==void 0?r:Hd.NO,s.opt=(i=s.opt)!==null&&i!==void 0?i:s.repeat||s.oneof?!1:s.kind=="message",s}function BC(s){if(typeof s!="object"||s===null||!s.hasOwnProperty("oneofKind"))return!1;switch(typeof s.oneofKind){case"string":return s[s.oneofKind]===void 0?!1:Object.keys(s).length==2;case"undefined":return Object.keys(s).length==1;default:return!1}}class $C{constructor(t){var e;this.fields=(e=t.fields)!==null&&e!==void 0?e:[]}prepare(){if(this.data)return;const t=[],e=[],r=[];for(let i of this.fields)if(i.oneof)r.includes(i.oneof)||(r.push(i.oneof),t.push(i.oneof),e.push(i.oneof));else switch(e.push(i.localName),i.kind){case"scalar":case"enum":(!i.opt||i.repeat)&&t.push(i.localName);break;case"message":i.repeat&&t.push(i.localName);break;case"map":t.push(i.localName);break}this.data={req:t,known:e,oneofs:Object.values(r)}}is(t,e,r=!1){if(e<0)return!0;if(t==null||typeof t!="object")return!1;this.prepare();let i=Object.keys(t),n=this.data;if(i.length<n.req.length||n.req.some(o=>!i.includes(o))||!r&&i.some(o=>!n.known.includes(o)))return!1;if(e<1)return!0;for(const o of n.oneofs){const c=t[o];if(!BC(c))return!1;if(c.oneofKind===void 0)continue;const d=this.fields.find(l=>l.localName===c.oneofKind);if(!d||!this.field(c[c.oneofKind],d,r,e))return!1}for(const o of this.fields)if(o.oneof===void 0&&!this.field(t[o.localName],o,r,e))return!1;return!0}field(t,e,r,i){let n=e.repeat;switch(e.kind){case"scalar":return t===void 0?e.opt:n?this.scalars(t,e.T,i,e.L):this.scalar(t,e.T,e.L);case"enum":return t===void 0?e.opt:n?this.scalars(t,A.INT32,i):this.scalar(t,A.INT32);case"message":return t===void 0?!0:n?this.messages(t,e.T(),r,i):this.message(t,e.T(),r,i);case"map":if(typeof t!="object"||t===null)return!1;if(i<2)return!0;if(!this.mapKeys(t,e.K,i))return!1;switch(e.V.kind){case"scalar":return this.scalars(Object.values(t),e.V.T,i,e.V.L);case"enum":return this.scalars(Object.values(t),A.INT32,i);case"message":return this.messages(Object.values(t),e.V.T(),r,i)}break}return!0}message(t,e,r,i){return r?e.isAssignable(t,i):e.is(t,i)}messages(t,e,r,i){if(!Array.isArray(t))return!1;if(i<2)return!0;if(r){for(let n=0;n<t.length&&n<i;n++)if(!e.isAssignable(t[n],i-1))return!1}else for(let n=0;n<t.length&&n<i;n++)if(!e.is(t[n],i-1))return!1;return!0}scalar(t,e,r){let i=typeof t;switch(e){case A.UINT64:case A.FIXED64:case A.INT64:case A.SFIXED64:case A.SINT64:switch(r){case Gs.BIGINT:return i=="bigint";case Gs.NUMBER:return i=="number"&&!isNaN(t);default:return i=="string"}case A.BOOL:return i=="boolean";case A.STRING:return i=="string";case A.BYTES:return t instanceof Uint8Array;case A.DOUBLE:case A.FLOAT:return i=="number"&&!isNaN(t);default:return i=="number"&&Number.isInteger(t)}}scalars(t,e,r,i){if(!Array.isArray(t))return!1;if(r<2)return!0;if(Array.isArray(t)){for(let n=0;n<t.length&&n<r;n++)if(!this.scalar(t[n],e,i))return!1}return!0}mapKeys(t,e,r){let i=Object.keys(t);switch(e){case A.INT32:case A.FIXED32:case A.SFIXED32:case A.SINT32:case A.UINT32:return this.scalars(i.slice(0,r).map(n=>parseInt(n)),e,r);case A.BOOL:return this.scalars(i.slice(0,r).map(n=>n=="true"?!0:n=="false"?!1:n),e,r);default:return this.scalars(i,e,r,Gs.STRING)}}}function bs(s,t){switch(t){case Gs.BIGINT:return s.toBigInt();case Gs.NUMBER:return s.toNumber();default:return s.toString()}}class HC{constructor(t){this.info=t}prepare(){var t;if(this.fMap===void 0){this.fMap={};const e=(t=this.info.fields)!==null&&t!==void 0?t:[];for(const r of e)this.fMap[r.name]=r,this.fMap[r.jsonName]=r,this.fMap[r.localName]=r}}assert(t,e,r){if(!t){let i=ih(r);throw(i=="number"||i=="boolean")&&(i=r.toString()),new Error(`Cannot parse JSON ${i} for ${this.info.typeName}#${e}`)}}read(t,e,r){this.prepare();const i=[];for(const[n,o]of Object.entries(t)){const c=this.fMap[n];if(!c){if(!r.ignoreUnknownFields)throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${n}`);continue}const d=c.localName;let l;if(c.oneof){if(o===null&&(c.kind!=="enum"||c.T()[0]!=="google.protobuf.NullValue"))continue;if(i.includes(c.oneof))throw new Error(`Multiple members of the oneof group "${c.oneof}" of ${this.info.typeName} are present in JSON.`);i.push(c.oneof),l=e[c.oneof]={oneofKind:d}}else l=e;if(c.kind=="map"){if(o===null)continue;this.assert(bC(o),c.name,o);const u=l[d];for(const[h,g]of Object.entries(o)){this.assert(g!==null,c.name+" map value",null);let v;switch(c.V.kind){case"message":v=c.V.T().internalJsonRead(g,r);break;case"enum":if(v=this.enum(c.V.T(),g,c.name,r.ignoreUnknownFields),v===!1)continue;break;case"scalar":v=this.scalar(g,c.V.T,c.V.L,c.name);break}this.assert(v!==void 0,c.name+" map value",g);let E=h;c.K==A.BOOL&&(E=E=="true"?!0:E=="false"?!1:E),E=this.scalar(E,c.K,Gs.STRING,c.name).toString(),u[E]=v}}else if(c.repeat){if(o===null)continue;this.assert(Array.isArray(o),c.name,o);const u=l[d];for(const h of o){this.assert(h!==null,c.name,null);let g;switch(c.kind){case"message":g=c.T().internalJsonRead(h,r);break;case"enum":if(g=this.enum(c.T(),h,c.name,r.ignoreUnknownFields),g===!1)continue;break;case"scalar":g=this.scalar(h,c.T,c.L,c.name);break}this.assert(g!==void 0,c.name,o),u.push(g)}}else switch(c.kind){case"message":if(o===null&&c.T().typeName!="google.protobuf.Value"){this.assert(c.oneof===void 0,c.name+" (oneof member)",null);continue}l[d]=c.T().internalJsonRead(o,r,l[d]);break;case"enum":if(o===null)continue;let u=this.enum(c.T(),o,c.name,r.ignoreUnknownFields);if(u===!1)continue;l[d]=u;break;case"scalar":if(o===null)continue;l[d]=this.scalar(o,c.T,c.L,c.name);break}}}enum(t,e,r,i){if(t[0]=="google.protobuf.NullValue"&&se(e===null||e==="NULL_VALUE",`Unable to parse field ${this.info.typeName}#${r}, enum ${t[0]} only accepts null.`),e===null)return 0;switch(typeof e){case"number":return se(Number.isInteger(e),`Unable to parse field ${this.info.typeName}#${r}, enum can only be integral number, got ${e}.`),e;case"string":let n=e;t[2]&&e.substring(0,t[2].length)===t[2]&&(n=e.substring(t[2].length));let o=t[1][n];return typeof o=="undefined"&&i?!1:(se(typeof o=="number",`Unable to parse field ${this.info.typeName}#${r}, enum ${t[0]} has no value for "${e}".`),o)}se(!1,`Unable to parse field ${this.info.typeName}#${r}, cannot parse enum value from ${typeof e}".`)}scalar(t,e,r,i){let n;try{switch(e){case A.DOUBLE:case A.FLOAT:if(t===null)return 0;if(t==="NaN")return Number.NaN;if(t==="Infinity")return Number.POSITIVE_INFINITY;if(t==="-Infinity")return Number.NEGATIVE_INFINITY;if(t===""){n="empty string";break}if(typeof t=="string"&&t.trim().length!==t.length){n="extra whitespace";break}if(typeof t!="string"&&typeof t!="number")break;let o=Number(t);if(Number.isNaN(o)){n="not a number";break}if(!Number.isFinite(o)){n="too large or small";break}return e==A.FLOAT&&oh(o),o;case A.INT32:case A.FIXED32:case A.SFIXED32:case A.SINT32:case A.UINT32:if(t===null)return 0;let c;if(typeof t=="number"?c=t:t===""?n="empty string":typeof t=="string"&&(t.trim().length!==t.length?n="extra whitespace":c=Number(t)),c===void 0)break;return e==A.UINT32?$d(c):yo(c),c;case A.INT64:case A.SFIXED64:case A.SINT64:if(t===null)return bs(me.ZERO,r);if(typeof t!="number"&&typeof t!="string")break;return bs(me.from(t),r);case A.FIXED64:case A.UINT64:if(t===null)return bs(ht.ZERO,r);if(typeof t!="number"&&typeof t!="string")break;return bs(ht.from(t),r);case A.BOOL:if(t===null)return!1;if(typeof t!="boolean")break;return t;case A.STRING:if(t===null)return"";if(typeof t!="string"){n="extra whitespace";break}try{encodeURIComponent(t)}catch(d){d="invalid UTF8";break}return t;case A.BYTES:if(t===null||t==="")return new Uint8Array(0);if(typeof t!="string")break;return wC(t)}}catch(o){n=o.message}this.assert(!1,i+(n?" - "+n:""),t)}}class qC{constructor(t){var e;this.fields=(e=t.fields)!==null&&e!==void 0?e:[]}write(t,e){const r={},i=t;for(const n of this.fields){if(!n.oneof){let l=this.field(n,i[n.localName],e);l!==void 0&&(r[e.useProtoFieldName?n.name:n.jsonName]=l);continue}const o=i[n.oneof];if(o.oneofKind!==n.localName)continue;const c=n.kind=="scalar"||n.kind=="enum"?Object.assign(Object.assign({},e),{emitDefaultValues:!0}):e;let d=this.field(n,o[n.localName],c);se(d!==void 0),r[e.useProtoFieldName?n.name:n.jsonName]=d}return r}field(t,e,r){let i;if(t.kind=="map"){se(typeof e=="object"&&e!==null);const n={};switch(t.V.kind){case"scalar":for(const[d,l]of Object.entries(e)){const u=this.scalar(t.V.T,l,t.name,!1,!0);se(u!==void 0),n[d.toString()]=u}break;case"message":const o=t.V.T();for(const[d,l]of Object.entries(e)){const u=this.message(o,l,t.name,r);se(u!==void 0),n[d.toString()]=u}break;case"enum":const c=t.V.T();for(const[d,l]of Object.entries(e)){se(l===void 0||typeof l=="number");const u=this.enum(c,l,t.name,!1,!0,r.enumAsInteger);se(u!==void 0),n[d.toString()]=u}break}(r.emitDefaultValues||Object.keys(n).length>0)&&(i=n)}else if(t.repeat){se(Array.isArray(e));const n=[];switch(t.kind){case"scalar":for(let d=0;d<e.length;d++){const l=this.scalar(t.T,e[d],t.name,t.opt,!0);se(l!==void 0),n.push(l)}break;case"enum":const o=t.T();for(let d=0;d<e.length;d++){se(e[d]===void 0||typeof e[d]=="number");const l=this.enum(o,e[d],t.name,t.opt,!0,r.enumAsInteger);se(l!==void 0),n.push(l)}break;case"message":const c=t.T();for(let d=0;d<e.length;d++){const l=this.message(c,e[d],t.name,r);se(l!==void 0),n.push(l)}break}(r.emitDefaultValues||n.length>0||r.emitDefaultValues)&&(i=n)}else switch(t.kind){case"scalar":i=this.scalar(t.T,e,t.name,t.opt,r.emitDefaultValues);break;case"enum":i=this.enum(t.T(),e,t.name,t.opt,r.emitDefaultValues,r.enumAsInteger);break;case"message":i=this.message(t.T(),e,t.name,r);break}return i}enum(t,e,r,i,n,o){if(t[0]=="google.protobuf.NullValue")return!n&&!i?void 0:null;if(e===void 0){se(i);return}if(!(e===0&&!n&&!i))return se(typeof e=="number"),se(Number.isInteger(e)),o||!t[1].hasOwnProperty(e)?e:t[2]?t[2]+t[1][e]:t[1][e]}message(t,e,r,i){return e===void 0?i.emitDefaultValues?null:void 0:t.internalJsonWrite(e,i)}scalar(t,e,r,i,n){if(e===void 0){se(i);return}const o=n||i;switch(t){case A.INT32:case A.SFIXED32:case A.SINT32:return e===0?o?0:void 0:(yo(e),e);case A.FIXED32:case A.UINT32:return e===0?o?0:void 0:($d(e),e);case A.FLOAT:oh(e);case A.DOUBLE:return e===0?o?0:void 0:(se(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e);case A.STRING:return e===""?o?"":void 0:(se(typeof e=="string"),e);case A.BOOL:return e===!1?o?!1:void 0:(se(typeof e=="boolean"),e);case A.UINT64:case A.FIXED64:se(typeof e=="number"||typeof e=="string"||typeof e=="bigint");let c=ht.from(e);return c.isZero()&&!o?void 0:c.toString();case A.INT64:case A.SFIXED64:case A.SINT64:se(typeof e=="number"||typeof e=="string"||typeof e=="bigint");let d=me.from(e);return d.isZero()&&!o?void 0:d.toString();case A.BYTES:return se(e instanceof Uint8Array),e.byteLength?_C(e):o?"":void 0}}}function ch(s,t=Gs.STRING){switch(s){case A.BOOL:return!1;case A.UINT64:case A.FIXED64:return bs(ht.ZERO,t);case A.INT64:case A.SFIXED64:case A.SINT64:return bs(me.ZERO,t);case A.DOUBLE:case A.FLOAT:return 0;case A.BYTES:return new Uint8Array(0);case A.STRING:return"";default:return 0}}class jC{constructor(t){this.info=t}prepare(){var t;if(!this.fieldNoToField){const e=(t=this.info.fields)!==null&&t!==void 0?t:[];this.fieldNoToField=new Map(e.map(r=>[r.no,r]))}}read(t,e,r,i){this.prepare();const n=i===void 0?t.len:t.pos+i;for(;t.pos<n;){const[o,c]=t.tag(),d=this.fieldNoToField.get(o);if(!d){let g=r.readUnknownField;if(g=="throw")throw new Error(`Unknown field ${o} (wire type ${c}) for ${this.info.typeName}`);let v=t.skip(c);g!==!1&&(g===!0?xd.onRead:g)(this.info.typeName,e,o,c,v);continue}let l=e,u=d.repeat,h=d.localName;switch(d.oneof&&(l=l[d.oneof],l.oneofKind!==h&&(l=e[d.oneof]={oneofKind:h})),d.kind){case"scalar":case"enum":let g=d.kind=="enum"?A.INT32:d.T,v=d.kind=="scalar"?d.L:void 0;if(u){let _=l[h];if(c==Ue.LengthDelimited&&g!=A.STRING&&g!=A.BYTES){let w=t.uint32()+t.pos;for(;t.pos<w;)_.push(this.scalar(t,g,v))}else _.push(this.scalar(t,g,v))}else l[h]=this.scalar(t,g,v);break;case"message":if(u){let _=l[h],w=d.T().internalBinaryRead(t,t.uint32(),r);_.push(w)}else l[h]=d.T().internalBinaryRead(t,t.uint32(),r,l[h]);break;case"map":let[E,b]=this.mapEntry(d,t,r);l[h][E]=b;break}}}mapEntry(t,e,r){let i=e.uint32(),n=e.pos+i,o,c;for(;e.pos<n;){let[d,l]=e.tag();switch(d){case 1:t.K==A.BOOL?o=e.bool().toString():o=this.scalar(e,t.K,Gs.STRING);break;case 2:switch(t.V.kind){case"scalar":c=this.scalar(e,t.V.T,t.V.L);break;case"enum":c=e.int32();break;case"message":c=t.V.T().internalBinaryRead(e,e.uint32(),r);break}break;default:throw new Error(`Unknown field ${d} (wire type ${l}) in map entry for ${this.info.typeName}#${t.name}`)}}if(o===void 0){let d=ch(t.K);o=t.K==A.BOOL?d.toString():d}if(c===void 0)switch(t.V.kind){case"scalar":c=ch(t.V.T,t.V.L);break;case"enum":c=0;break;case"message":c=t.V.T().create();break}return[o,c]}scalar(t,e,r){switch(e){case A.INT32:return t.int32();case A.STRING:return t.string();case A.BOOL:return t.bool();case A.DOUBLE:return t.double();case A.FLOAT:return t.float();case A.INT64:return bs(t.int64(),r);case A.UINT64:return bs(t.uint64(),r);case A.FIXED64:return bs(t.fixed64(),r);case A.FIXED32:return t.fixed32();case A.BYTES:return t.bytes();case A.UINT32:return t.uint32();case A.SFIXED32:return t.sfixed32();case A.SFIXED64:return bs(t.sfixed64(),r);case A.SINT32:return t.sint32();case A.SINT64:return bs(t.sint64(),r)}}}class GC{constructor(t){this.info=t}prepare(){if(!this.fields){const t=this.info.fields?this.info.fields.concat():[];this.fields=t.sort((e,r)=>e.no-r.no)}}write(t,e,r){this.prepare();for(const n of this.fields){let o,c,d=n.repeat,l=n.localName;if(n.oneof){const u=t[n.oneof];if(u.oneofKind!==l)continue;o=u[l],c=!0}else o=t[l],c=!1;switch(n.kind){case"scalar":case"enum":let u=n.kind=="enum"?A.INT32:n.T;if(d)if(se(Array.isArray(o)),d==Hd.PACKED)this.packed(e,u,n.no,o);else for(const h of o)this.scalar(e,u,n.no,h,!0);else o===void 0?se(n.opt):this.scalar(e,u,n.no,o,c||n.opt);break;case"message":if(d){se(Array.isArray(o));for(const h of o)this.message(e,r,n.T(),n.no,h)}else this.message(e,r,n.T(),n.no,o);break;case"map":se(typeof o=="object"&&o!==null);for(const[h,g]of Object.entries(o))this.mapEntry(e,r,n,h,g);break}}let i=r.writeUnknownFields;i!==!1&&(i===!0?xd.onWrite:i)(this.info.typeName,t,e)}mapEntry(t,e,r,i,n){t.tag(r.no,Ue.LengthDelimited),t.fork();let o=i;switch(r.K){case A.INT32:case A.FIXED32:case A.UINT32:case A.SFIXED32:case A.SINT32:o=Number.parseInt(i);break;case A.BOOL:se(i=="true"||i=="false"),o=i=="true";break}switch(this.scalar(t,r.K,1,o,!0),r.V.kind){case"scalar":this.scalar(t,r.V.T,2,n,!0);break;case"enum":this.scalar(t,A.INT32,2,n,!0);break;case"message":this.message(t,e,r.V.T(),2,n);break}t.join()}message(t,e,r,i,n){n!==void 0&&(r.internalBinaryWrite(n,t.tag(i,Ue.LengthDelimited).fork(),e),t.join())}scalar(t,e,r,i,n){let[o,c,d]=this.scalarInfo(e,i);(!d||n)&&(t.tag(r,o),t[c](i))}packed(t,e,r,i){if(!i.length)return;se(e!==A.BYTES&&e!==A.STRING),t.tag(r,Ue.LengthDelimited),t.fork();let[,n]=this.scalarInfo(e);for(let o=0;o<i.length;o++)t[n](i[o]);t.join()}scalarInfo(t,e){let r=Ue.Varint,i,n=e===void 0,o=e===0;switch(t){case A.INT32:i="int32";break;case A.STRING:o=n||!e.length,r=Ue.LengthDelimited,i="string";break;case A.BOOL:o=e===!1,i="bool";break;case A.UINT32:i="uint32";break;case A.DOUBLE:r=Ue.Bit64,i="double";break;case A.FLOAT:r=Ue.Bit32,i="float";break;case A.INT64:o=n||me.from(e).isZero(),i="int64";break;case A.UINT64:o=n||ht.from(e).isZero(),i="uint64";break;case A.FIXED64:o=n||ht.from(e).isZero(),r=Ue.Bit64,i="fixed64";break;case A.BYTES:o=n||!e.byteLength,r=Ue.LengthDelimited,i="bytes";break;case A.FIXED32:r=Ue.Bit32,i="fixed32";break;case A.SFIXED32:r=Ue.Bit32,i="sfixed32";break;case A.SFIXED64:o=n||me.from(e).isZero(),r=Ue.Bit64,i="sfixed64";break;case A.SINT32:i="sint32";break;case A.SINT64:o=n||me.from(e).isZero(),i="sint64";break}return[r,i,n||o]}}function WC(s){const t=s.messagePrototype?Object.create(s.messagePrototype):Object.defineProperty({},Wm,{value:s});for(let e of s.fields){let r=e.localName;if(!e.opt)if(e.oneof)t[e.oneof]={oneofKind:void 0};else if(e.repeat)t[r]=[];else switch(e.kind){case"scalar":t[r]=ch(e.T,e.L);break;case"enum":t[r]=0;break;case"map":t[r]={};break}}return t}function dh(s,t,e){let r,i=e,n;for(let o of s.fields){let c=o.localName;if(o.oneof){const d=i[o.oneof];if((d==null?void 0:d.oneofKind)==null)continue;if(r=d[c],n=t[o.oneof],n.oneofKind=d.oneofKind,r==null){delete n[c];continue}}else if(r=i[c],n=t,r==null)continue;switch(o.repeat&&(n[c].length=r.length),o.kind){case"scalar":case"enum":if(o.repeat)for(let l=0;l<r.length;l++)n[c][l]=r[l];else n[c]=r;break;case"message":let d=o.T();if(o.repeat)for(let l=0;l<r.length;l++)n[c][l]=d.create(r[l]);else n[c]===void 0?n[c]=d.create(r):d.mergePartial(n[c],r);break;case"map":switch(o.V.kind){case"scalar":case"enum":Object.assign(n[c],r);break;case"message":let l=o.V.T();for(let u of Object.keys(r))n[c][u]=l.create(r[u]);break}break}}}function JC(s,t,e){if(t===e)return!0;if(!t||!e)return!1;for(let r of s.fields){let i=r.localName,n=r.oneof?t[r.oneof][i]:t[i],o=r.oneof?e[r.oneof][i]:e[i];switch(r.kind){case"enum":case"scalar":let c=r.kind=="enum"?A.INT32:r.T;if(!(r.repeat?zm(c,n,o):Km(c,n,o)))return!1;break;case"map":if(!(r.V.kind=="message"?Ym(r.V.T(),qd(n),qd(o)):zm(r.V.kind=="enum"?A.INT32:r.V.T,qd(n),qd(o))))return!1;break;case"message":let d=r.T();if(!(r.repeat?Ym(d,n,o):d.equals(n,o)))return!1;break}}return!0}const qd=Object.values;function Km(s,t,e){if(t===e)return!0;if(s!==A.BYTES)return!1;let r=t,i=e;if(r.length!==i.length)return!1;for(let n=0;n<r.length;n++)if(r[n]!=i[n])return!1;return!0}function zm(s,t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(!Km(s,t[r],e[r]))return!1;return!0}function Ym(s,t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(!s.equals(t[r],e[r]))return!1;return!0}const KC=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({}));class S{constructor(t,e,r){this.defaultCheckDepth=16,this.typeName=t,this.fields=e.map(FC),this.options=r!=null?r:{},this.messagePrototype=Object.create(null,Object.assign(Object.assign({},KC),{[Wm]:{value:this}})),this.refTypeCheck=new $C(this),this.refJsonReader=new HC(this),this.refJsonWriter=new qC(this),this.refBinReader=new jC(this),this.refBinWriter=new GC(this)}create(t){let e=WC(this);return t!==void 0&&dh(this,e,t),e}clone(t){let e=this.create();return dh(this,e,t),e}equals(t,e){return JC(this,t,e)}is(t,e=this.defaultCheckDepth){return this.refTypeCheck.is(t,e,!1)}isAssignable(t,e=this.defaultCheckDepth){return this.refTypeCheck.is(t,e,!0)}mergePartial(t,e){dh(this,t,e)}fromBinary(t,e){let r=kC(e);return this.internalBinaryRead(r.readerFactory(t),t.byteLength,r)}fromJson(t,e){return this.internalJsonRead(t,xC(e))}fromJsonString(t,e){let r=JSON.parse(t);return this.fromJson(r,e)}toJson(t,e){return this.internalJsonWrite(t,UC(e))}toJsonString(t,e){var r;let i=this.toJson(t,e);return JSON.stringify(i,null,(r=e==null?void 0:e.prettySpaces)!==null&&r!==void 0?r:0)}toBinary(t,e){let r=VC(e);return this.internalBinaryWrite(t,r.writerFactory(),r).finish()}internalJsonRead(t,e,r){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){let i=r!=null?r:this.create();return this.refJsonReader.read(t,i,e),i}throw new Error(`Unable to parse message ${this.typeName} from JSON ${ih(t)}.`)}internalJsonWrite(t,e){return this.refJsonWriter.write(t,e)}internalBinaryWrite(t,e,r){return this.refBinWriter.write(t,e,r),e}internalBinaryRead(t,e,r,i){let n=i!=null?i:this.create();return this.refBinReader.read(t,n,r,e),n}}var or;(function(s){s[s.PUBLISHER=0]="PUBLISHER",s[s.SUBSCRIBER=1]="SUBSCRIBER"})(or||(or={}));var Ws;(function(s){s[s.AUDIO=0]="AUDIO",s[s.VIDEO=1]="VIDEO"})(Ws||(Ws={}));class zC extends S{constructor(){super("media.Codec",[{no:1,name:"channels",kind:"scalar",opt:!0,T:5},{no:2,name:"clock_rate",kind:"scalar",T:5},{no:3,name:"mime_type",kind:"scalar",T:9},{no:4,name:"sdp_fmtp_line",kind:"scalar",opt:!0,T:9},{no:5,name:"payload_type",kind:"scalar",opt:!0,T:13}])}}const Qm=new zC;class YC extends S{constructor(){super("media.HeaderExtension",[{no:1,name:"direction",kind:"scalar",opt:!0,T:9},{no:2,name:"uri",kind:"scalar",T:9}])}}const QC=new YC;class XC extends S{constructor(){super("media.Fingerprint",[{no:1,name:"algorithm",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:9}])}}new XC;class ZC extends S{constructor(){super("media.SessionDescription",[{no:1,name:"target",kind:"enum",T:()=>["media.Target",or]},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"sdp",kind:"scalar",T:9}])}}const ws=new ZC;class eR extends S{constructor(){super("media.ProducerPayload",[{no:1,name:"kind",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",T:8},{no:3,name:"screen_share",kind:"scalar",T:8},{no:4,name:"msid",kind:"scalar",T:9},{no:5,name:"app_data",kind:"scalar",opt:!0,T:9},{no:6,name:"mime_type",kind:"scalar",opt:!0,T:9}])}}const tR=new eR;class sR extends S{constructor(){super("media.CreateTransportRequest",[{no:1,name:"consuming",kind:"scalar",T:8},{no:2,name:"force_tcp",kind:"scalar",opt:!0,T:8},{no:3,name:"description",kind:"message",T:()=>ws},{no:4,name:"private_ice",kind:"scalar",opt:!0,T:8},{no:5,name:"producers",kind:"message",repeat:1,T:()=>tR}])}}const rR=new sR;class iR extends S{constructor(){super("media.AudioActivityRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"energy",kind:"scalar",T:5},{no:3,name:"silent",kind:"scalar",T:8}])}}const nR=new iR;class aR extends S{constructor(){super("media.CreateTransportResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>ws},{no:3,name:"transcription_enabled",kind:"scalar",opt:!0,T:8},{no:4,name:"producer_ids",kind:"scalar",repeat:2,T:9}])}}const Xm=new aR;class oR extends S{constructor(){super("media.RenegotiateRequest",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>ws}])}}const cR=new oR;class dR extends S{constructor(){super("media.RenegotiateResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>ws}])}}new dR;class lR extends S{constructor(){super("media.NestedScore",[{no:1,name:"encoding_idx",kind:"scalar",T:5},{no:2,name:"rid",kind:"scalar",T:9},{no:3,name:"score",kind:"scalar",T:5},{no:4,name:"ssrc",kind:"scalar",T:3,L:0}])}}const uR=new lR;class hR extends S{constructor(){super("media.ProducerTrack",[{no:1,name:"track_id",kind:"scalar",T:9},{no:2,name:"producer_id",kind:"scalar",T:9},{no:3,name:"stream_id",kind:"scalar",T:9}])}}const pR=new hR;class gR extends S{constructor(){super("media.ProducerEntry",[{no:1,name:"producing_transport_id",kind:"scalar",T:9},{no:2,name:"producer_id",kind:"scalar",T:9}])}}new gR;class mR extends S{constructor(){super("media.ConsumerEntry",[{no:1,name:"consuming_transport_id",kind:"scalar",T:9},{no:2,name:"consumer_id",kind:"scalar",T:9}])}}new mR;class fR extends S{constructor(){super("media.ProducerState",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"kind",kind:"enum",T:()=>["media.ProducerKind",Ws]},{no:3,name:"pause",kind:"scalar",T:8},{no:4,name:"screen_share",kind:"scalar",T:8},{no:5,name:"app_data",kind:"scalar",opt:!0,T:9},{no:6,name:"producing_transport_id",kind:"scalar",opt:!0,T:9},{no:7,name:"mime_type",kind:"scalar",opt:!0,T:9},{no:8,name:"codec",kind:"message",T:()=>Qm}])}}const Eo=new fR;class vR extends S{constructor(){super("media.ConsumerState",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Eo},{no:3,name:"producer_track",kind:"message",T:()=>pR},{no:4,name:"error_code",kind:"scalar",opt:!0,T:9}])}}const SR=new vR;class TR extends S{constructor(){super("media.ProducerIdToConsumerMap",[{no:1,name:"map",kind:"map",K:9,V:{kind:"message",T:()=>SR}}])}}const Zm=new TR;class yR extends S{constructor(){super("media.PeerRtpCapabilitites",[{no:1,name:"sender",kind:"message",T:()=>sf},{no:2,name:"receiver",kind:"message",T:()=>sf}])}}const ef=new yR;class ER extends S{constructor(){super("media.RtpCapability",[{no:1,name:"codecs",kind:"message",repeat:1,T:()=>Qm},{no:2,name:"header_extensions",kind:"message",repeat:1,T:()=>QC}])}}const tf=new ER;class bR extends S{constructor(){super("media.RtpCapabilitites",[{no:1,name:"audio",kind:"message",T:()=>tf},{no:2,name:"video",kind:"message",T:()=>tf}])}}const sf=new bR;class wR extends S{constructor(){super("media.PreferredCodec",[{no:1,name:"audio",kind:"scalar",opt:!0,T:9},{no:2,name:"video",kind:"scalar",opt:!0,T:9}])}}const _R=new wR;class PR extends S{constructor(){super("media.Simulcast",[{no:1,name:"preferred_rid",kind:"scalar",opt:!0,T:9},{no:2,name:"priority_ordering",kind:"scalar",opt:!0,T:9},{no:3,name:"rid_not_available",kind:"scalar",opt:!0,T:9}])}}const rf=new PR;class CR extends S{constructor(){super("media.edge.GeoLocation",[{no:1,name:"latitude",kind:"scalar",T:2},{no:2,name:"longitude",kind:"scalar",T:2},{no:3,name:"region",kind:"scalar",opt:!0,T:9}])}}const RR=new CR;class kR extends S{constructor(){super("media.edge.PeerJoinRequest",[{no:1,name:"display_name",kind:"scalar",opt:!0,T:9},{no:2,name:"prejoined",kind:"scalar",T:8},{no:3,name:"room_uuid",kind:"scalar",T:9},{no:4,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:5,name:"preset",kind:"scalar",opt:!0,T:12},{no:6,name:"user_id",kind:"scalar",opt:!0,T:9},{no:7,name:"organization_id",kind:"scalar",opt:!0,T:9},{no:8,name:"location",kind:"message",T:()=>RR},{no:9,name:"capabilities",kind:"message",T:()=>ef}])}}const IR=new kR;class AR extends S{constructor(){super("media.edge.PeerJoinCompleteRequest",[])}}const MR=new AR;class OR extends S{constructor(){super("media.edge.PeerLeaveRequest",[{no:1,name:"close_room",kind:"scalar",T:8}])}}const DR=new OR;class NR extends S{constructor(){super("media.edge.ConsumeMultipleProducerRequest",[{no:1,name:"producer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"paused",kind:"scalar",opt:!0,T:8}])}}new NR;class VR extends S{constructor(){super("media.edge.ConsumePeerRequest",[{no:1,name:"producing_peer_id",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",opt:!0,T:8},{no:3,name:"producer_id",kind:"scalar",opt:!0,T:9},{no:4,name:"preferred_codec",kind:"message",T:()=>_R},{no:5,name:"producing_transport_id",kind:"scalar",opt:!0,T:9},{no:6,name:"simulcast",kind:"message",T:()=>rf}])}}const LR=new VR;class xR extends S{constructor(){super("media.edge.ConsumePeersRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>LR},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const UR=new xR;class FR extends S{constructor(){super("media.edge.UpdateConsumerSimulcastConfigRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"simulcast",kind:"message",T:()=>rf},{no:3,name:"producing_transport_id",kind:"scalar",T:9},{no:4,name:"mid",kind:"scalar",T:9}])}}const BR=new FR;class $R extends S{constructor(){super("media.edge.UpdateConsumersSimulcastConfigRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>BR},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const HR=new $R;class qR extends S{constructor(){super("media.edge.ProducerCreateRequest",[{no:1,name:"kind",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",T:8},{no:3,name:"screen_share",kind:"scalar",T:8},{no:4,name:"description",kind:"message",T:()=>ws},{no:5,name:"msid",kind:"scalar",T:9},{no:6,name:"app_data",kind:"scalar",opt:!0,T:9},{no:7,name:"mime_type",kind:"scalar",opt:!0,T:9},{no:8,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const jR=new qR;class GR extends S{constructor(){super("media.edge.SelectedPeersRequest",[])}}new GR;class WR extends S{constructor(){super("media.edge.GlobalPeerPinningRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const JR=new WR;class KR extends S{constructor(){super("media.edge.ProducerToggleRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}const jd=new KR;class zR extends S{constructor(){super("media.edge.ConsumerToggleRequest",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}new zR;class YR extends S{constructor(){super("media.edge.ProducerCloseRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>ws},{no:3,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const QR=new YR;class XR extends S{constructor(){super("media.edge.ConsumerCloseRequest",[{no:1,name:"consumer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"description",kind:"message",T:()=>ws},{no:3,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const ZR=new XR;class ek extends S{constructor(){super("media.edge.KickPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new ek;class tk extends S{constructor(){super("media.edge.KickAllPeersRequest",[{no:1,name:"propagate_kick_across_rooms",kind:"scalar",T:8}])}}const nf=new tk;class sk extends S{constructor(){super("media.edge.PeerDisplayNameEditRequest",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}const rk=new sk;class ik extends S{constructor(){super("media.edge.HostMediaControlForPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"audio",kind:"scalar",T:8},{no:3,name:"video",kind:"scalar",T:8},{no:4,name:"scree_share",kind:"scalar",T:8}])}}const nk=new ik;class ak extends S{constructor(){super("media.edge.HostMediaControlForAllPeerRequest",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8},{no:3,name:"screen_share",kind:"scalar",T:8}])}}const ok=new ak;class ck extends S{constructor(){super("media.edge.GetRoomStateResponse",[{no:1,name:"display_title",kind:"scalar",T:9},{no:2,name:"locked_mode",kind:"scalar",T:8},{no:3,name:"room_uuid",kind:"scalar",T:9},{no:4,name:"room_name",kind:"scalar",T:9},{no:5,name:"current_peer_id",kind:"scalar",T:9},{no:6,name:"is_recording",kind:"scalar",opt:!0,T:8},{no:7,name:"recorder_participant_id",kind:"scalar",opt:!0,T:9},{no:8,name:"pinned_peer_ids",kind:"scalar",repeat:2,T:9}])}}const dk=new ck;class lk extends S{constructor(){super("media.edge.ErrorResponse",[{no:1,name:"error_message",kind:"scalar",T:9},{no:2,name:"event_id",kind:"scalar",T:5}])}}const uk=new lk;class hk extends S{constructor(){super("media.edge.EmptyResponse",[])}}new hk;class pk extends S{constructor(){super("media.edge.RoomParticipants",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"producer_states",kind:"message",repeat:1,T:()=>Eo},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"user_id",kind:"scalar",opt:!0,T:9},{no:5,name:"capabilities",kind:"message",T:()=>ef}])}}const af=new pk;class gk extends S{constructor(){super("media.edge.SelectedPeersResponse",[{no:1,name:"audio_peers",kind:"scalar",repeat:2,T:9},{no:2,name:"compulsory_peers",kind:"scalar",repeat:2,T:9}])}}const lh=new gk;class mk extends S{constructor(){super("media.edge.SelectedPeersDiffEntry",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"priority",kind:"scalar",T:5}])}}const fk=new mk;class vk extends S{constructor(){super("media.edge.SelectedPeersDiffResponse",[{no:1,name:"entries",kind:"message",repeat:1,T:()=>fk}])}}const of=new vk;class Sk extends S{constructor(){super("media.edge.PeerJoinResponse",[])}}new Sk;class Tk extends S{constructor(){super("media.edge.PeerJoinCompleteResponse",[{no:1,name:"room_state",kind:"message",T:()=>dk},{no:2,name:"participants",kind:"message",repeat:1,T:()=>af},{no:3,name:"selected_peers",kind:"message",T:()=>lh},{no:4,name:"max_preferred_streams",kind:"scalar",T:5}])}}const uh=new Tk;class yk extends S{constructor(){super("media.edge.PeerLeaveResponse",[{no:1,name:"closed",kind:"scalar",T:8}])}}const Ek=new yk;class bk extends S{constructor(){super("media.edge.ConsumeMultipleProducerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Zm}])}}new bk;class wk extends S{constructor(){super("media.edge.ConsumePeerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Zm},{no:3,name:"description",kind:"message",T:()=>ws}])}}const _k=new wk;class Pk extends S{constructor(){super("media.edge.ProducerCreateResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"producer_id",kind:"scalar",T:9},{no:4,name:"description",kind:"message",T:()=>ws}])}}const Ck=new Pk;class Rk extends S{constructor(){super("media.edge.ProducerScoreResponse",[{no:1,name:"responseid",kind:"scalar",T:9},{no:2,name:"score",kind:"message",T:()=>uR}])}}new Rk;class kk extends S{constructor(){super("media.edge.ActiveSpeakerResponse",[{no:1,name:"responsepeer_id",kind:"scalar",T:9},{no:2,name:"volume",kind:"scalar",T:5}])}}new kk;class Ik extends S{constructor(){super("media.edge.NoActiveSpeakerResponse",[])}}new Ik;class Ak extends S{constructor(){super("media.edge.ProducerToggleResponse",[])}}new Ak;class Mk extends S{constructor(){super("media.edge.ConsumerToggleResponse",[])}}new Mk;class Ok extends S{constructor(){super("media.edge.ProducerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>ws}])}}const Dk=new Ok;class Nk extends S{constructor(){super("media.edge.ConsumerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>ws}])}}const Vk=new Nk;class Lk extends S{constructor(){super("media.edge.GlobalPeerPinningResponse",[])}}new Lk;class xk extends S{constructor(){super("media.edge.KickPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new xk;class Uk extends S{constructor(){super("media.edge.KickAllPeersResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new Uk;class Fk extends S{constructor(){super("media.edge.HostMediaControlForPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Bk=new Fk;class $k extends S{constructor(){super("media.edge.HostMediaControlForAllPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Hk=new $k;class qk extends S{constructor(){super("media.edge.PeerDisplayNameEditResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const jk=new qk;class Gk extends S{constructor(){super("media.edge.PeerJoinBroadcastResponse",[{no:1,name:"participant",kind:"message",T:()=>af}])}}const cf=new Gk;class Wk extends S{constructor(){super("media.edge.TrackSubscriptionKind",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8}])}}const df=new Wk;class Jk extends S{constructor(){super("media.edge.TrackSubscription",[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"webcam",kind:"message",T:()=>df},{no:3,name:"screenshare",kind:"message",T:()=>df}])}}const Kk=new Jk;class zk extends S{constructor(){super("media.edge.PeerProducingTransportCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"transport_details",kind:"message",T:()=>Xm},{no:3,name:"track_subscriptions",kind:"message",repeat:1,T:()=>Kk}])}}new zk;class Yk extends S{constructor(){super("media.edge.PeerProducerCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Eo}])}}const Qk=new Yk;class Xk extends S{constructor(){super("media.edge.PeerProducerToggleBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Eo},{no:3,name:"initiator_participant_id",kind:"scalar",opt:!0,T:9}])}}const lf=new Xk;class Zk extends S{constructor(){super("media.edge.PeerProducerCloseBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Eo}])}}const eI=new Zk;class tI extends S{constructor(){super("media.edge.PeerLeaveBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const hh=new tI;class sI extends S{constructor(){super("media.edge.GlobalPeerPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const uf=new sI;class rI extends S{constructor(){super("media.edge.GlobalPeerUnPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new rI;class iI extends S{constructor(){super("media.edge.RecordingStartedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new iI;class nI extends S{constructor(){super("media.edge.RecordingStoppedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new nI;class aI extends S{constructor(){super("media.edge.PeerDisplayNameEditBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}new aI;class oI extends S{constructor(){super("media.edge.PeerPingRequestBroadcastResponse",[{no:1,name:"password",kind:"scalar",T:9}])}}new oI;class cI extends S{constructor(){super("media.edge.MediaRoomTerminationBroadcastResponse",[{no:1,name:"reason",kind:"scalar",T:9}])}}new cI;class dI extends S{constructor(){super("socket.ai.MeetingTranscript",[{no:1,name:"meeting_id",kind:"scalar",T:9},{no:2,name:"transcript",kind:"scalar",T:9},{no:3,name:"is_partial",kind:"scalar",T:8}])}}const ph=new dI;class lI extends S{constructor(){super("socket.api.BaseSocketHubMessage",[{no:1,name:"event",kind:"scalar",T:5},{no:2,name:"id",kind:"scalar",T:9},{no:3,name:"peer_id",kind:"scalar",T:9},{no:4,name:"room_id",kind:"scalar",T:9},{no:5,name:"user_id",kind:"scalar",T:9},{no:6,name:"payload",kind:"scalar",T:12},{no:7,name:"error",kind:"scalar",opt:!0,T:8},{no:8,name:"sid",kind:"scalar",opt:!0,T:9}])}}new lI;class uI extends S{constructor(){super("socket.api.ErrorMessage",[{no:1,name:"code",kind:"scalar",opt:!0,T:5},{no:2,name:"message",kind:"scalar",T:9}])}}const hI=new uI;var Ci;(function(s){s[s.BROWSER=0]="BROWSER",s[s.TRACK=1]="TRACK",s[s.COMPOSITE=2]="COMPOSITE"})(Ci||(Ci={}));var cr;(function(s){s[s.UNSPECIFIED=0]="UNSPECIFIED",s[s.ON_STAGE=1]="ON_STAGE",s[s.APPROVED_STAGE=2]="APPROVED_STAGE",s[s.REQUESTED_STAGE=3]="REQUESTED_STAGE",s[s.OFF_STAGE=4]="OFF_STAGE"})(cr||(cr={}));var gh;(function(s){s[s.NONE=0]="NONE",s[s.RECORDER=1]="RECORDER",s[s.LIVESTREAMER=2]="LIVESTREAMER"})(gh||(gh={}));var mh;(function(s){s[s.PEERS=0]="PEERS",s[s.ROOMS=1]="ROOMS"})(mh||(mh={}));var Gd;(function(s){s[s.HIVE=0]="HIVE",s[s.CHAT=1]="CHAT",s[s.PING=2]="PING"})(Gd||(Gd={}));class pI extends S{constructor(){super("socket.room.PeerFlags",[{no:1,name:"preset_name",kind:"scalar",T:9},{no:2,name:"recorder_type",kind:"scalar",T:9},{no:3,name:"hidden_participant",kind:"scalar",T:8}])}}const gI=new pI;class mI extends S{constructor(){super("socket.room.Peer",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"stage_type",kind:"enum",opt:!0,T:()=>["socket.room.StageType",cr,"STAGE_TYPE_"]},{no:5,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:6,name:"preset_id",kind:"scalar",opt:!0,T:9},{no:7,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:8,name:"waitlisted",kind:"scalar",T:8},{no:9,name:"flags",kind:"message",T:()=>gI}])}}const Wd=new mI;class fI extends S{constructor(){super("socket.room.PeerInfoResponse",[{no:1,name:"peer",kind:"message",T:()=>Wd}])}}const $n=new fI;class vI extends S{constructor(){super("socket.room.PeerStatusUpdate",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"stage_type",kind:"enum",opt:!0,T:()=>["socket.room.StageType",cr,"STAGE_TYPE_"]}])}}const hf=new vI;class SI extends S{constructor(){super("socket.room.RoomPeersInfoRequest",[{no:1,name:"seach_query",kind:"scalar",T:9},{no:2,name:"limit",kind:"scalar",T:5},{no:3,name:"offset",kind:"scalar",T:5}])}}const TI=new SI;class yI extends S{constructor(){super("socket.room.RoomPeersInfoResponse",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>Wd}])}}const fh=new yI;class EI extends S{constructor(){super("socket.room.RoomPeerCountResponse",[{no:1,name:"count",kind:"scalar",T:4,L:2}])}}const pf=new EI;class bI extends S{constructor(){super("socket.room.Room",[{no:1,name:"room_id",kind:"scalar",T:9},{no:2,name:"title",kind:"scalar",T:9},{no:4,name:"created_at",kind:"scalar",T:4,L:2},{no:5,name:"active_recordings",kind:"message",repeat:1,T:()=>_I},{no:6,name:"room_uuid",kind:"scalar",opt:!0,T:9}])}}const gf=new bI;class wI extends S{constructor(){super("socket.room.ActiveRecording",[{no:1,name:"recording_id",kind:"scalar",T:9},{no:2,name:"recording_type",kind:"enum",T:()=>["common.RecordingType",Ci]},{no:3,name:"recording_status",kind:"scalar",T:9}])}}const _I=new wI;class PI extends S{constructor(){super("socket.room.RoomInfoResponse",[{no:1,name:"room",kind:"message",T:()=>gf}])}}const mf=new PI;class CI extends S{constructor(){super("socket.room.GetPeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9}])}}const ff=new CI;class RI extends S{constructor(){super("socket.room.UpdatePeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",opt:!0,T:9}])}}new RI;class kI extends S{constructor(){super("socket.room.JoinRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>Wd},{no:3,name:"room_uuid",kind:"scalar",T:9},{no:4,name:"organization_id",kind:"scalar",opt:!0,T:9},{no:5,name:"use_hive",kind:"scalar",opt:!0,T:8},{no:6,name:"preset",kind:"scalar",opt:!0,T:12},{no:7,name:"capabilities",kind:"enum",repeat:1,T:()=>["socket.room.Capabilities",Gd,"CAPABILITIES_"]},{no:8,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const II=new kI;class AI extends S{constructor(){super("socket.room.LeaveRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>Wd},{no:2,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const MI=new AI;class OI extends S{constructor(){super("socket.room.UpdateRoomInfoRequest",[{no:1,name:"room",kind:"message",T:()=>gf}])}}new OI;class DI extends S{constructor(){super("socket.room.GetConnectedRoomsDumpRequest",[])}}new DI;class NI extends S{constructor(){super("socket.room.ServiceError",[{no:1,name:"message",kind:"scalar",opt:!0,T:9},{no:2,name:"code",kind:"scalar",opt:!0,T:9}])}}const vh=new NI;class VI extends S{constructor(){super("socket.room.ConnectedMeetingPeer",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"display_name",kind:"scalar",opt:!0,T:9},{no:3,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:4,name:"preset_id",kind:"scalar",opt:!0,T:9},{no:5,name:"display_picture_url",kind:"scalar",opt:!0,T:9}])}}const LI=new VI;class xI extends S{constructor(){super("socket.room.ConnectedMeetingDump",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"title",kind:"scalar",opt:!0,T:9},{no:3,name:"participants",kind:"message",repeat:1,T:()=>LI}])}}const vf=new xI;class UI extends S{constructor(){super("socket.room.GetConnectedRoomsDumpResponse",[{no:1,name:"parent_meeting",kind:"message",T:()=>vf},{no:2,name:"meetings",kind:"message",repeat:1,T:()=>vf}])}}const FI=new UI;class BI extends S{constructor(){super("socket.room.CreateRoomRequestPayload",[{no:1,name:"title",kind:"scalar",opt:!0,T:9}])}}const $I=new BI;class HI extends S{constructor(){super("socket.room.CreateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>$I}])}}const qI=new HI;class jI extends S{constructor(){super("socket.room.CreateRoomResponsePayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"title",kind:"scalar",opt:!0,T:9},{no:3,name:"error",kind:"message",T:()=>vh}])}}const GI=new jI;class WI extends S{constructor(){super("socket.room.CreateConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>GI}])}}const Sf=new WI;class JI extends S{constructor(){super("socket.room.UpdateRoomRequestPayload",[{no:1,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"title",kind:"scalar",opt:!0,T:9}])}}const KI=new JI;class zI extends S{constructor(){super("socket.room.UpdateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>KI}])}}new zI;class YI extends S{constructor(){super("socket.room.DisableRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9}])}}const QI=new YI;class XI extends S{constructor(){super("socket.room.DisableConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>QI}])}}const ZI=new XI;class eA extends S{constructor(){super("socket.room.DisableConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>rA}])}}const tA=new eA;class sA extends S{constructor(){super("socket.room.DisableConnectedRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"status",kind:"scalar",opt:!0,T:9},{no:3,name:"title",kind:"scalar",opt:!0,T:9},{no:4,name:"error",kind:"message",T:()=>vh}])}}const rA=new sA;class iA extends S{constructor(){super("socket.room.MovePeerPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"preset_id",kind:"scalar",opt:!0,T:9}])}}const nA=new iA;class aA extends S{constructor(){super("socket.room.MovePeersBetweenRoomsRequest",[{no:1,name:"source_meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"destination_meeting_id",kind:"scalar",opt:!0,T:9},{no:3,name:"participants",kind:"message",repeat:1,T:()=>nA}])}}const oA=new aA;class cA extends S{constructor(){super("socket.room.MovedPeer",[{no:1,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:3,name:"error",kind:"message",T:()=>vh}])}}const Tf=new cA;class dA extends S{constructor(){super("socket.room.MovePeersBetweenRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Tf}])}}new dA;class lA extends S{constructor(){super("socket.room.TransferPeer",[{no:1,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"auth_token",kind:"scalar",opt:!0,T:9}])}}const uA=new lA;class hA extends S{constructor(){super("socket.room.GetAllAddedParticipantsResponse",[{no:1,name:"participants",kind:"message",repeat:1,T:()=>mA}])}}const pA=new hA;class gA extends S{constructor(){super("socket.room.AddedParticipant",[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",opt:!0,T:9},{no:3,name:"picture",kind:"scalar",opt:!0,T:9},{no:4,name:"custom_participant_id",kind:"scalar",T:9}])}}const mA=new gA;class fA extends S{constructor(){super("socket.room.RemoveParticipantsRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const yf=new fA;class vA extends S{constructor(){super("socket.room.BroadcastMessage",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"timestamp",kind:"scalar",T:4,L:2},{no:4,name:"ids",kind:"scalar",repeat:2,T:9},{no:5,name:"broadcast_type",kind:"enum",opt:!0,T:()=>["socket.room.BroadcastType",mh,"BROADCAST_TYPE_"]}])}}const bo=new vA;class SA extends S{constructor(){super("socket.room.AcceptWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const TA=new SA;class yA extends S{constructor(){super("socket.room.DenyWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const EA=new yA;class bA extends S{constructor(){super("socket.room.WaitingRoomRequest",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"picture",kind:"scalar",opt:!0,T:9},{no:5,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:6,name:"preset_name",kind:"scalar",opt:!0,T:9}])}}const wA=new bA;class _A extends S{constructor(){super("socket.room.GetWaitingRoomRequests",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>wA}])}}const Ef=new _A;class PA extends S{constructor(){super("socket.room.GetRoomStageStateResponse",[{no:1,name:"on_stage_peers",kind:"scalar",repeat:2,T:9},{no:2,name:"approved_stage_peers",kind:"scalar",repeat:2,T:9},{no:3,name:"requested_stage_peers",kind:"scalar",repeat:2,T:9}])}}const bf=new PA;var Sh;(function(s){s[s.NONE=0]="NONE",s[s.SKIP=1]="SKIP",s[s.ON_PRIVILEGED_USER_ENTRY=2]="ON_PRIVILEGED_USER_ENTRY",s[s.SKIP_ON_ACCEPT=3]="SKIP_ON_ACCEPT"})(Sh||(Sh={}));var Br;(function(s){s[s.NONE=0]="NONE",s[s.ALLOWED=1]="ALLOWED",s[s.NOT_ALLOWED=2]="NOT_ALLOWED",s[s.CAN_REQUEST=3]="CAN_REQUEST"})(Br||(Br={}));class CA extends S{constructor(){super("socket.preset.PollsPermissionUpdate",[{no:1,name:"can_create",kind:"scalar",opt:!0,T:8},{no:2,name:"can_vote",kind:"scalar",opt:!0,T:8},{no:3,name:"can_view",kind:"scalar",opt:!0,T:8}])}}const RA=new CA;class kA extends S{constructor(){super("socket.preset.PluginsPermissionsUpdate",[{no:1,name:"can_close",kind:"scalar",opt:!0,T:8},{no:2,name:"can_start",kind:"scalar",opt:!0,T:8}])}}const IA=new kA;class AA extends S{constructor(){super("socket.preset.PublicChatPermission",[{no:1,name:"can_send",kind:"scalar",opt:!0,T:8},{no:2,name:"text",kind:"scalar",opt:!0,T:8},{no:3,name:"files",kind:"scalar",opt:!0,T:8}])}}const MA=new AA;class OA extends S{constructor(){super("socket.preset.PrivateChatPermission",[{no:1,name:"can_send",kind:"scalar",opt:!0,T:8},{no:2,name:"can_receive",kind:"scalar",opt:!0,T:8},{no:3,name:"text",kind:"scalar",opt:!0,T:8},{no:4,name:"files",kind:"scalar",opt:!0,T:8}])}}const DA=new OA;class NA extends S{constructor(){super("socket.preset.ChatPermissionUpdate",[{no:1,name:"public",kind:"message",T:()=>MA},{no:2,name:"private",kind:"message",T:()=>DA}])}}const VA=new NA;class LA extends S{constructor(){super("socket.preset.ConnectedMeetingPermissionUpdate",[{no:1,name:"can_alter_connected_meetings",kind:"scalar",opt:!0,T:8},{no:2,name:"can_switch_to_parent_meeting",kind:"scalar",opt:!0,T:8},{no:3,name:"can_switch_connected_meetings",kind:"scalar",opt:!0,T:8}])}}const xA=new LA;class UA extends S{constructor(){super("socket.preset.StreamPermission",[{no:1,name:"can_produce",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",Br,"STREAM_PERMISSION_TYPE_"]},{no:2,name:"can_consume",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",Br,"STREAM_PERMISSION_TYPE_"]}])}}const Th=new UA;class FA extends S{constructor(){super("socket.preset.MediaPermissionUpdate",[{no:1,name:"video",kind:"message",T:()=>Th},{no:2,name:"audio",kind:"message",T:()=>Th},{no:3,name:"screenshare",kind:"message",T:()=>Th}])}}const BA=new FA;class $A extends S{constructor(){super("socket.preset.PresetUpdates",[{no:1,name:"polls",kind:"message",T:()=>RA},{no:2,name:"plugins",kind:"message",T:()=>IA},{no:3,name:"chat",kind:"message",T:()=>VA},{no:4,name:"accept_waiting_requests",kind:"scalar",opt:!0,T:8},{no:5,name:"can_accept_production_requests",kind:"scalar",opt:!0,T:8},{no:6,name:"can_edit_display_name",kind:"scalar",opt:!0,T:8},{no:7,name:"can_record",kind:"scalar",opt:!0,T:8},{no:8,name:"can_livestream",kind:"scalar",opt:!0,T:8},{no:9,name:"can_spotlight",kind:"scalar",opt:!0,T:8},{no:10,name:"disable_participant_audio",kind:"scalar",opt:!0,T:8},{no:11,name:"disable_participant_screensharing",kind:"scalar",opt:!0,T:8},{no:12,name:"disable_participant_video",kind:"scalar",opt:!0,T:8},{no:13,name:"kick_participant",kind:"scalar",opt:!0,T:8},{no:14,name:"pin_participant",kind:"scalar",opt:!0,T:8},{no:15,name:"transcription_enabled",kind:"scalar",opt:!0,T:8},{no:16,name:"waiting_room_type",kind:"enum",opt:!0,T:()=>["socket.preset.WaitingRoomType",Sh,"WAITING_ROOM_TYPE_"]},{no:17,name:"is_recorder",kind:"scalar",opt:!0,T:8},{no:18,name:"recorder_type",kind:"enum",opt:!0,T:()=>["socket.room.RecorderType",gh,"RECORDER_TYPE_"]},{no:19,name:"hidden_participant",kind:"scalar",opt:!0,T:8},{no:20,name:"show_participant_list",kind:"scalar",opt:!0,T:8},{no:21,name:"can_change_participant_permissions",kind:"scalar",opt:!0,T:8},{no:22,name:"connected_meetings",kind:"message",T:()=>xA},{no:23,name:"media",kind:"message",T:()=>BA}])}}const yh=new $A;class HA extends S{constructor(){super("socket.preset.ReadPeersPresetRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const qA=new HA;class jA extends S{constructor(){super("socket.preset.PeerPreset",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"preset",kind:"scalar",T:12}])}}const GA=new jA;class WA extends S{constructor(){super("socket.preset.ReadPeersPresetResponse",[{no:1,name:"peer_presets",kind:"message",repeat:1,T:()=>GA}])}}const JA=new WA;class KA extends S{constructor(){super("socket.preset.UpdatePeerPreset",[{no:1,name:"user_ids",kind:"scalar",T:9},{no:2,name:"patch",kind:"message",T:()=>yh}])}}const wf=new KA;class zA extends S{constructor(){super("socket.preset.UpdatePeersPresetRequest",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>wf}])}}const YA=new zA;class QA extends S{constructor(){super("socket.preset.UpdatePeersPresetResponse",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>wf}])}}const _f=new QA;class XA extends S{constructor(){super("socket.preset.PeerUserIDMap",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9}])}}const ZA=new XA;class e0 extends S{constructor(){super("socket.preset.BulkUpdatePeerPresetRequest",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>ZA},{no:2,name:"patch",kind:"message",T:()=>yh}])}}new e0;class t0 extends S{constructor(){super("socket.preset.BulkUpdatePeerPresetResponse",[{no:2,name:"patch",kind:"message",T:()=>yh}])}}new t0;class s0 extends S{constructor(){super("socket.chat.ChatMessage",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"user_id",kind:"scalar",T:9},{no:4,name:"display_name",kind:"scalar",T:9},{no:5,name:"pinned",kind:"scalar",T:8},{no:6,name:"is_edited",kind:"scalar",T:8},{no:7,name:"payload_type",kind:"scalar",T:5},{no:8,name:"payload",kind:"scalar",T:9},{no:10,name:"target_user_ids",kind:"scalar",repeat:2,T:9},{no:11,name:"created_at",kind:"scalar",T:4,L:2},{no:12,name:"created_at_ms",kind:"scalar",opt:!0,T:4,L:2},{no:13,name:"channel_id",kind:"scalar",opt:!0,T:9},{no:14,name:"channel_index",kind:"scalar",opt:!0,T:9}])}}const Ri=new s0;class r0 extends S{constructor(){super("socket.chat.GetPaginatedChatMessageRoomRequest",[{no:1,name:"time_stamp",kind:"scalar",T:4,L:2},{no:2,name:"size",kind:"scalar",T:5},{no:3,name:"from",kind:"scalar",T:5},{no:4,name:"reversed",kind:"scalar",T:8},{no:5,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const i0=new r0;class n0 extends S{constructor(){super("socket.chat.GetPaginatedChatMessageRoomResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Ri},{no:2,name:"next",kind:"scalar",T:8}])}}const a0=new n0;class o0 extends S{constructor(){super("socket.chat.GetChatMessagesResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Ri}])}}const Pf=new o0;class c0 extends S{constructor(){super("socket.chat.SendChatMessageToRoomRequest",[{no:1,name:"payload_type",kind:"scalar",T:5},{no:2,name:"payload",kind:"scalar",T:9}])}}const d0=new c0;class l0 extends S{constructor(){super("socket.chat.SendChatMessageToRoomResponse",[{no:1,name:"message",kind:"message",T:()=>Ri}])}}const Eh=new l0;class u0 extends S{constructor(){super("socket.chat.SendChatMessageToPeersRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"payload_type",kind:"scalar",T:5},{no:3,name:"payload",kind:"scalar",T:9}])}}const h0=new u0;class p0 extends S{constructor(){super("socket.chat.SendChatMessageToPeersResponse",[{no:1,name:"message",kind:"message",T:()=>Ri}])}}const bh=new p0;class g0 extends S{constructor(){super("socket.chat.SendChatMessageToChannelRequest",[{no:1,name:"channel_id",kind:"scalar",T:9},{no:2,name:"payload_type",kind:"scalar",T:5},{no:3,name:"payload",kind:"scalar",T:9}])}}const m0=new g0;class f0 extends S{constructor(){super("socket.chat.SendChatMessageToChannelResponse",[{no:1,name:"message",kind:"message",T:()=>Ri}])}}new f0;class v0 extends S{constructor(){super("socket.chat.EditChatMessageRequest",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"payload_type",kind:"scalar",opt:!0,T:5},{no:3,name:"payload",kind:"scalar",opt:!0,T:9},{no:4,name:"pinned",kind:"scalar",opt:!0,T:8},{no:5,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const S0=new v0;class T0 extends S{constructor(){super("socket.chat.PinChatMessageRequest",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"pinned",kind:"scalar",T:8},{no:3,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const y0=new T0;class E0 extends S{constructor(){super("socket.chat.PinChatMessageResponse",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"pinned",kind:"scalar",T:8},{no:3,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const Jd=new E0;class b0 extends S{constructor(){super("socket.chat.EditChatMessageResponse",[{no:1,name:"message",kind:"message",T:()=>Ri}])}}const Kd=new b0;class w0 extends S{constructor(){super("socket.chat.DeleteChatMessageRequest",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const _0=new w0;class P0 extends S{constructor(){super("socket.chat.DeleteChatMessageResponse",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const zd=new P0;class C0 extends S{constructor(){super("socket.chat.SearchChatMessagesRequest",[{no:1,name:"time_stamp",kind:"scalar",T:4,L:2},{no:2,name:"size",kind:"scalar",T:5},{no:3,name:"from",kind:"scalar",T:5},{no:4,name:"reversed",kind:"scalar",T:8},{no:5,name:"channel_id",kind:"scalar",opt:!0,T:9},{no:6,name:"search_term",kind:"scalar",T:9}])}}const R0=new C0;class k0 extends S{constructor(){super("socket.chat.MarkChannelIndexAsReadRequest",[{no:1,name:"channel_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"channel_index",kind:"scalar",T:9}])}}const I0=new k0;class A0 extends S{constructor(){super("socket.chat.MarkChannelIndexAsReadResponse",[{no:1,name:"channel_index",kind:"scalar",T:9}])}}const M0=new A0;class O0 extends S{constructor(){super("socket.chat.CreateChatChannelRequest",[{no:1,name:"display_name",kind:"scalar",T:9},{no:2,name:"target_user_ids",kind:"scalar",repeat:2,T:9},{no:3,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:4,name:"visibility",kind:"scalar",T:9},{no:5,name:"is_direct_message",kind:"scalar",T:8}])}}const D0=new O0;class N0 extends S{constructor(){super("socket.chat.UpdateChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",opt:!0,T:9},{no:3,name:"target_user_ids",kind:"scalar",repeat:2,T:9},{no:4,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:5,name:"visibility",kind:"scalar",opt:!0,T:9},{no:6,name:"is_direct_message",kind:"scalar",opt:!0,T:8}])}}const V0=new N0;class L0 extends S{constructor(){super("socket.chat.CreateChatChannelResponse",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new L0;class x0 extends S{constructor(){super("socket.chat.GetChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}const U0=new x0;class F0 extends S{constructor(){super("socket.chat.LatestMessageAndUnreadCount",[{no:1,name:"message",kind:"message",T:()=>Ri},{no:2,name:"unread_count",kind:"scalar",T:4,L:2}])}}const B0=new F0;class $0 extends S{constructor(){super("socket.chat.ChatChannel",[{no:1,name:"chat_channel_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9},{no:3,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:4,name:"visibility",kind:"scalar",T:9},{no:5,name:"is_direct_message",kind:"scalar",T:8},{no:6,name:"latest_message_and_unread_count",kind:"message",T:()=>B0},{no:7,name:"target_user_ids",kind:"scalar",repeat:2,T:9}])}}const H0=new $0;class q0 extends S{constructor(){super("socket.chat.GetChatChannelResponse",[{no:1,name:"chat_channels",kind:"message",repeat:1,T:()=>H0}])}}const dr=new q0;class j0 extends S{constructor(){super("socket.chat.ChannelMember",[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",opt:!0,T:9},{no:3,name:"picture",kind:"scalar",opt:!0,T:9},{no:4,name:"custom_participant_id",kind:"scalar",T:9}])}}const G0=new j0;class W0 extends S{constructor(){super("socket.chat.GetChatChannelMembersResponse",[{no:1,name:"channel_members",kind:"message",repeat:1,T:()=>G0}])}}const J0=new W0;class K0 extends S{constructor(){super("socket.plugin.AddPluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const z0=new K0;class Y0 extends S{constructor(){super("socket.plugin.RemovePluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const Q0=new Y0;class X0 extends S{constructor(){super("socket.plugin.EnablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const Z0=new X0;class eM extends S{constructor(){super("socket.plugin.DisablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const tM=new eM;class sM extends S{constructor(){super("socket.plugin.EnablePluginForPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const rM=new sM;class iM extends S{constructor(){super("socket.plugin.DisablePluginForPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const nM=new iM;class aM extends S{constructor(){super("socket.plugin.PluginEventToRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}const oM=new aM;class cM extends S{constructor(){super("socket.plugin.PluginEventToPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9},{no:3,name:"plugin_data",kind:"scalar",T:12}])}}const dM=new cM;class lM extends S{constructor(){super("socket.plugin.StoreKeys",[{no:1,name:"store_key",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",opt:!0,T:12}])}}const wh=new lM;class uM extends S{constructor(){super("socket.plugin.PluginStoreInsertKeysRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"insert_keys",kind:"message",repeat:1,T:()=>wh}])}}const Cf=new uM;class hM extends S{constructor(){super("socket.plugin.PluginStoreGetKeysRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"get_keys",kind:"message",repeat:1,T:()=>wh}])}}const pM=new hM;class gM extends S{constructor(){super("socket.plugin.PluginStoreDeleteKeysRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"delete_keys",kind:"message",repeat:1,T:()=>wh}])}}const mM=new gM;class fM extends S{constructor(){super("socket.plugin.PluginStoreDeleteRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9}])}}const vM=new fM;class SM extends S{constructor(){super("socket.plugin.EnablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"enabled_by",kind:"scalar",T:9}])}}const _h=new SM;class TM extends S{constructor(){super("socket.plugin.EnablePluginsResponse",[{no:1,name:"plugins",kind:"message",repeat:1,T:()=>_h}])}}const yM=new TM;class EM extends S{constructor(){super("socket.plugin.DisablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"disabled_by",kind:"scalar",T:9}])}}const Rf=new EM;class bM extends S{constructor(){super("socket.plugin.PluginStoreItem",[{no:1,name:"timestamp",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"store_key",kind:"scalar",T:9},{no:4,name:"payload",kind:"scalar",T:12}])}}const wM=new bM;class _M extends S{constructor(){super("socket.plugin.PluginStoreResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"store_items",kind:"message",repeat:1,T:()=>wM}])}}const kf=new _M;class PM extends S{constructor(){super("socket.plugin.PluginEventResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}const If=new PM;class CM extends S{constructor(){super("socket.livestreaming.LiveStreamingEvent",[{no:1,name:"livestream_id",kind:"scalar",T:9},{no:2,name:"err_message",kind:"scalar",T:9},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"meeting_id",kind:"scalar",T:9},{no:5,name:"playback_url",kind:"scalar",T:9},{no:6,name:"org_id",kind:"scalar",T:9},{no:7,name:"room_name",kind:"scalar",T:9},{no:8,name:"room_uuid",kind:"scalar",T:9},{no:9,name:"status",kind:"scalar",T:9},{no:10,name:"manual_ingest",kind:"scalar",opt:!0,T:8}])}}const Af=new CM;class RM extends S{constructor(){super("socket.livestreaming.GetStagePeersResponse",[{no:1,name:"stage_peers",kind:"scalar",repeat:2,T:9}])}}const Mf=new RM;class kM extends S{constructor(){super("socket.livestreaming.StageRequest",[{no:1,name:"display_name",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"peer_id",kind:"scalar",T:9}])}}const IM=new kM;class AM extends S{constructor(){super("socket.livestreaming.GetStageRequestsResponse",[{no:1,name:"stage_requests",kind:"message",repeat:1,T:()=>IM}])}}const Ph=new AM;class MM extends S{constructor(){super("socket.livestreaming.GrantStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const OM=new MM;class DM extends S{constructor(){super("socket.livestreaming.DenyStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const NM=new DM;class VM extends S{constructor(){super("socket.livestreaming.LeaveStageRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const Of=new VM;class LM extends S{constructor(){super("socket.polls.Poll",[{no:1,name:"poll_id",kind:"scalar",T:9},{no:2,name:"created_by",kind:"scalar",T:9},{no:3,name:"created_by_user_id",kind:"scalar",T:9},{no:4,name:"question",kind:"scalar",T:9},{no:5,name:"options",kind:"message",repeat:1,T:()=>UM},{no:6,name:"hide_votes",kind:"scalar",T:8},{no:7,name:"anonymous",kind:"scalar",T:8},{no:8,name:"votes",kind:"scalar",repeat:2,T:9}])}}const Df=new LM;class xM extends S{constructor(){super("socket.polls.PollOption",[{no:1,name:"text",kind:"scalar",T:9},{no:2,name:"count",kind:"scalar",opt:!0,T:4,L:2},{no:3,name:"votes",kind:"message",repeat:1,T:()=>BM}])}}const UM=new xM;class FM extends S{constructor(){super("socket.polls.PollVote",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9}])}}const BM=new FM;class $M extends S{constructor(){super("socket.polls.NewPollRequest",[{no:1,name:"question",kind:"scalar",T:9},{no:2,name:"options",kind:"scalar",repeat:2,T:9},{no:3,name:"anonymous",kind:"scalar",T:8},{no:4,name:"hide_votes",kind:"scalar",T:8},{no:5,name:"created_by",kind:"scalar",opt:!0,T:9},{no:6,name:"created_by_user_id",kind:"scalar",opt:!0,T:9}])}}const HM=new $M;class qM extends S{constructor(){super("socket.polls.VotePollRequest",[{no:1,name:"poll_id",kind:"scalar",T:9},{no:2,name:"index",kind:"scalar",T:4,L:2}])}}const jM=new qM;class GM extends S{constructor(){super("socket.polls.UpdatePollResponse",[{no:1,name:"poll",kind:"message",T:()=>Df}])}}const Ch=new GM;class WM extends S{constructor(){super("socket.polls.GetPollsResponse",[{no:1,name:"polls",kind:"message",repeat:1,T:()=>Df}])}}const JM=new WM;class KM extends S{constructor(){super("socket.recording.RecordingEvent",[{no:1,name:"recording_id",kind:"scalar",T:9},{no:2,name:"err_message",kind:"scalar",T:9},{no:3,name:"recording_type",kind:"enum",T:()=>["common.RecordingType",Ci]}])}}const Nf=new KM;class zM extends S{constructor(){super("google.protobuf.Timestamp",[{no:1,name:"seconds",kind:"scalar",T:3,L:0},{no:2,name:"nanos",kind:"scalar",T:5}])}now(){const t=this.create(),e=Date.now();return t.seconds=me.from(Math.floor(e/1e3)).toBigInt(),t.nanos=e%1e3*1e6,t}toDate(t){return new Date(me.from(t.seconds).toNumber()*1e3+Math.ceil(t.nanos/1e6))}fromDate(t){const e=this.create(),r=t.getTime();return e.seconds=me.from(Math.floor(r/1e3)).toBigInt(),e.nanos=r%1e3*1e6,e}internalJsonWrite(t,e){let r=me.from(t.seconds).toNumber()*1e3;if(r<Date.parse("0001-01-01T00:00:00Z")||r>Date.parse("9999-12-31T23:59:59Z"))throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");if(t.nanos<0)throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative.");let i="Z";if(t.nanos>0){let n=(t.nanos+1e9).toString().substring(1);n.substring(3)==="000000"?i="."+n.substring(0,3)+"Z":n.substring(6)==="000"?i="."+n.substring(0,6)+"Z":i="."+n+"Z"}return new Date(r).toISOString().replace(".000Z",i)}internalJsonRead(t,e,r){if(typeof t!="string")throw new Error("Unable to parse Timestamp from JSON "+ih(t)+".");let i=t.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw new Error("Unable to parse Timestamp from JSON. Invalid format.");let n=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(n))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(n<Date.parse("0001-01-01T00:00:00Z")||n>Date.parse("9999-12-31T23:59:59Z"))throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");return r||(r=this.create()),r.seconds=me.from(n/1e3).toBigInt(),r.nanos=0,i[7]&&(r.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),r}}new zM;class YM extends S{constructor(){super("common.BaseHubMessage",[{no:1,name:"event",kind:"scalar",T:5},{no:2,name:"id",kind:"scalar",T:9},{no:3,name:"peer_id",kind:"scalar",T:9},{no:4,name:"room_id",kind:"scalar",T:9},{no:5,name:"user_id",kind:"scalar",T:9},{no:6,name:"payload",kind:"scalar",T:12},{no:7,name:"error",kind:"scalar",opt:!0,T:8},{no:8,name:"sid",kind:"scalar",opt:!0,T:9},{no:9,name:"room_object_id",kind:"scalar",opt:!0,T:9},{no:10,name:"preset",kind:"scalar",opt:!0,T:9},{no:11,name:"use_start_session",kind:"scalar",opt:!0,T:8}])}}const Rh=new YM;class QM extends S{constructor(){super("common.BulkedHubMessage",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Rh}])}}new QM;class XM extends S{constructor(){super("common.CFWorkersResponse",[{no:1,name:"responses",kind:"message",repeat:1,T:()=>Rh},{no:2,name:"broadcast_responses",kind:"message",repeat:1,T:()=>Rh}])}}new XM;const ZM=0,eO=1,tO=2,sO=3,rO=4,iO=5,nO={getPeerInfo:0,updatePeerInfo:1,getRoomPeersInfo:2,joinRoom:3,leaveRoom:4,getRoomInfo:5,updateRoomInfo:6,closeRoom:7,startedLivestream:8,stoppedLivestream:9,erroredLivestream:10,getStagePeers:11,getStageRequests:12,requestStageAccess:13,cancelStageRequest:14,grantStageAccess:15,denyStageAccess:16,roomPeerCount:17,joinStage:18,leaveStage:19,getConnectedRoomsDump:20,createConnectedRooms:21,deleteConnectedRooms:22,movePeers:23,transferPeer:24,movedPeer:25,connectedRoomsUpdated:26,connectedRoomsDeleted:27,getAllAddedParticipants:28,broadcastMessage:29,kick:30,kickAll:31,transcript:32,getWaitingRoomRequests:33,acceptWaitingRoomRequests:34,waitingRoomRequestAccepted:35,denyWaitingRoomRequests:36,waitingRoomRequestDenied:37,peerStageStatusUpdate:38,broadcastToEntity:39,recordingStarted:40,recordingStopped:41,recordingPaused:42,getRoomStageState:43,livestreamingInvoked:44},aO={getMessages:0,sendMessageToRoom:1,sendMessageToPeers:2,editMessage:3,deleteMessage:4,getPaginatedMessages:5,sendMessageToChannel:6,searchChannelMessages:7,getAllChatChannels:8,markChannelIndexAsRead:9,pinMessage:10},oO={getPlugins:0,addPlugin:1,enablePluginForRoom:2,disablePluginForPeers:3,enablePluginForPeers:4,disablePluginForRoom:5,removePlugin:6,customPluginEventToRoom:7,customPluginEventToPeers:8,storeInsertKeys:9,storeGetKeys:10,storeDeleteKeys:11,storeDelete:12},cO={createPoll:0,getPolls:1,votePoll:2,updatePoll:3},Vf={unknown:0,createWebRTCTransport:1,produce:2,consume:3,toggleProducer:4,toggleConsumer:5,closeProducer:6,closeConsumer:7,updateConsumersSimulcastConfig:8,joinRoom:16,leaveRoom:17,selectedPeer:18,globalPinPeer:19,selfJoinComplete:20,peerJoinedBroadcast:25,peerLeaveBroadcast:26,peerProducerCreateBroadcast:27,peerProducerToggleBroadcast:28,peerProducerCloseBroadcast:29,globalPeerPinBroadcast:30,recordingStartedBroadcast:31,recordingStoppedBroadcast:32,peerDisplayNameEditBroadcast:33,mediaRoomTerminationBroadcastResponse:36,selectedPeerDiff:40,renegotiateSessionDescription:50,errorResponse:60,kickPeer:90,kickAll:91,changeDisplayName:92,hostControlPeer:93,hostControlAllPeers:94,audioActivity:100},dO={createChatChannel:0,getChatChannel:1,deprecatedGetAllChatChannels:2,getChannelMembers:3,updateChatChannel:4},lO={getUserPresets:0,updateUserPreset:1};function Hn(s,t){return Object.keys(t).reduce((e,r)=>(e[r]=(s<<16)+t[r],e),{})}function Lf(s,t){return Object.keys(s).reduce((e,r)=>(e[r]=t|s[r],e),{})}const F=Hn(ZM,nO),Ae=Hn(eO,aO),G=Hn(tO,oO),lr=Hn(sO,cO),ki=Hn(rO,dO),$r=Lf(Vf,16777216),_s=Lf(Vf,50331648),Yd=Hn(iO,lO);var uO=Object.defineProperty,hO=Object.getOwnPropertyDescriptor,kh=(s,t,e,r)=>{for(var i=r>1?void 0:r?hO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&uO(t,e,i),i};const Ih=(Qv=class{constructor(s,t){m(this,Yr,void 0);m(this,ia,void 0);f(this,Yr,t),f(this,ia,s)}get telemetry(){return a(this,ia).getValue("telemetry")}get logger(){return a(this,ia).getValue("logger")}async createChannel(s,t,e,r="public",i=!1){const n={displayName:s,targetUserIds:t,displayPictureUrl:e,visibility:r,isDirectMessage:i};i&&(n.visibility="private");const o=await a(this,Yr).sendMessagePromise(ki.createChatChannel,D0.toBinary(n)),c=dr.fromBinary(o.payload).chatChannels;return Ih.formatChannel(c[0])}async updateChannel(s,t){const e=await a(this,Yr).sendMessagePromise(ki.updateChatChannel,V0.toBinary({chatChannelId:s,targetUserIds:t.memberIds,displayName:t.displayName,displayPictureUrl:t.displayPictureUrl,visibility:t.visibility})),r=dr.fromBinary(e.payload).chatChannels;return Ih.formatChannel(r[0])}static formatChannel(s){var r;const{latestMessageAndUnreadCount:t}=s,e={...s,id:s.chatChannelId,memberIds:s.targetUserIds,unreadCount:(r=t==null?void 0:t.unreadCount)!=null?r:0};return t!=null&&t.message&&(e.latestMessage=Rs.formatSocketPeerMessage(t.message)),delete e.chatChannelId,delete e.targetUserIds,delete e.latestMessageAndUnreadCount,e}async getChannelMembers(s){try{const t=await a(this,Yr).sendMessagePromise(ki.getChannelMembers,U0.toBinary({chatChannelId:s}));return J0.fromBinary(t.payload).channelMembers.map(({id:e,...r})=>({...r,userId:e}))}catch(t){return[]}}on(s,t){let e,r;switch(s){case ki.createChatChannel:{e=dr.fromBinary.bind(dr),r=dr.create();break}case ki.updateChatChannel:{e=dr.fromBinary.bind(dr),r=dr.create();break}}if(!e){this.logger.warn(`ChatChannelSocketHandler::Event ${s} is not recognized`);return}a(this,Yr).on(s,({payload:i})=>{let n=r;try{n=e(i)}catch(o){this.logger.error("ChatChannelSocketHandler::on::binary_decode_error",{error:o})}return t(n)})}},Yr=new WeakMap,ia=new WeakMap,Qv);let Ii=Ih;kh([y.trace("ChatChannelHandler.createChannel")],Ii.prototype,"createChannel",1),kh([y.trace("ChatChannelHandler.updateChannel")],Ii.prototype,"updateChannel",1),kh([y.trace("ChatChannelHandler.getChannelMembers")],Ii.prototype,"getChannelMembers",1);var pO=Object.defineProperty,gO=Object.getOwnPropertyDescriptor,Ps=(s,t,e,r)=>{for(var i=r>1?void 0:r?gO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&pO(t,e,i),i},_t=(s=>(s[s.TEXT=0]="TEXT",s[s.IMAGE=1]="IMAGE",s[s.FILE=2]="FILE",s[s.CUSTOM=3]="CUSTOM",s))(_t||{});class as{constructor(t,e){m(this,ft,void 0);m(this,na,void 0);f(this,ft,e),f(this,na,t)}get telemetry(){return a(this,na).getValue("telemetry")}get logger(){return a(this,na).getValue("logger")}getChatMessages(){return a(this,ft).sendMessagePromise(Ae.getMessages)}async getChatMessagesPaginated(t,e,r,i=0,n=""){const o={timeStamp:t,size:e,from:i,reversed:r,channelId:n},c=await a(this,ft).sendMessagePromise(Ae.getPaginatedMessages,i0.toBinary(o));return c.payload?a0.fromBinary(c.payload):{messages:[],next:!1}}sendMessageToRoom(t,e){const r={payloadType:e,payload:t};a(this,ft).sendMessage(Ae.sendMessageToRoom,d0.toBinary(r))}sendMessageToPeers(t,e,r){const i={payloadType:e,peerIds:r,payload:t};a(this,ft).sendMessage(Ae.sendMessageToPeers,h0.toBinary(i))}sendMessageToChannel(t,e,r){const i={payloadType:e,channelId:r,payload:t};a(this,ft).sendMessage(Ae.sendMessageToChannel,m0.toBinary(i))}sendMessage(t,e,r,i){if(i&&this.sendMessageToChannel(t,e,i),r&&r.length>0){this.sendMessageToPeers(t,e,r);return}this.sendMessageToRoom(t,e)}async editMessage(t,e,r,i,n){const o={chatId:t,payloadType:r,payload:e};i&&(o.channelId=i),n!==void 0&&(o.pinned=n);const c=await a(this,ft).sendMessagePromise(Ae.editMessage,S0.toBinary(o));return Kd.fromBinary(c.payload).message}async deleteMessage(t,e){const r={chatId:t};e&&(r.channelId=e);const i=await a(this,ft).sendMessagePromise(Ae.deleteMessage,_0.toBinary(r)),n=zd.fromBinary(i.payload);return{id:n.chatId,...n.channelId?{channelId:n.channelId}:{}}}async searchMessages(t,e){var i,n,o;const r={searchTerm:t,timeStamp:(i=e.timestamp)!=null?i:Date.now(),size:(n=e.size)!=null?n:75,from:0,reversed:(o=e.reversed)!=null?o:!0};e.channelId&&(r.channelId=e.channelId);try{const c=await a(this,ft).sendMessagePromise(Ae.searchChannelMessages,R0.toBinary(r));return Pf.fromBinary(c.payload).messages}catch(c){return[]}}async getAllChannels(){try{const t=await a(this,ft).sendMessagePromise(Ae.getAllChatChannels);return dr.fromBinary(t.payload).chatChannels.map(Ii.formatChannel)}catch(t){return[]}}async markLastReadMessage(t,e){const r=await a(this,ft).sendMessagePromise(Ae.markChannelIndexAsRead,I0.toBinary({channelId:t,userId:e.userId,channelIndex:e.channelIndex}));return M0.fromBinary(r.payload).channelIndex}async setPinState(t,e){const r={chatId:t.id,pinned:e,channelId:t.channelId},i=await a(this,ft).sendMessagePromise(Ae.pinMessage,y0.toBinary(r));return Jd.fromBinary(i.payload)}on(t,e){let r,i;switch(t){case Ae.sendMessageToRoom:{r=Eh.fromBinary.bind(Eh),i=Eh.create();break}case Ae.sendMessageToPeers:{r=bh.fromBinary.bind(bh),i=bh.create();break}case Ae.editMessage:{r=Kd.fromBinary.bind(Kd),i=Kd.create();break}case Ae.pinMessage:{r=Jd.fromBinary.bind(Jd),i=Jd.create();break}case Ae.deleteMessage:{r=zd.fromBinary.bind(zd),i=zd.create();break}}if(!r){this.logger.warn(`ChatSocketHandler::Event ${t} is not recognized`);return}a(this,ft).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("chatSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}ft=new WeakMap,na=new WeakMap,Ps([y.trace("SocketService.getChatMessages")],as.prototype,"getChatMessages",1),Ps([y.trace("SocketService.getChatMessagesPaginated")],as.prototype,"getChatMessagesPaginated",1),Ps([y.trace("SocketService.sendMessageToRoom")],as.prototype,"sendMessageToRoom",1),Ps([y.trace("SocketService.sendMessageToPeers")],as.prototype,"sendMessageToPeers",1),Ps([y.trace("SocketService.sendMessageToChannel")],as.prototype,"sendMessageToChannel",1),Ps([y.trace("SocketService.sendMessage")],as.prototype,"sendMessage",1),Ps([y.trace("SocketService.editMessage")],as.prototype,"editMessage",1),Ps([y.trace("SocketService.deleteMessage")],as.prototype,"deleteMessage",1),Ps([y.trace("SocketService.searchMessages")],as.prototype,"searchMessages",1),Ps([y.trace("SocketService.getAllChannels")],as.prototype,"getAllChannels",1),Ps([y.trace("SocketService.markLastReadMessage")],as.prototype,"markLastReadMessage",1);function mO(s){return s.replace(/([-_]\w)/g,t=>t[1].toUpperCase())}function Cs(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>Cs(e));const t={};return Object.keys(s).forEach(e=>{const r=Cu(e)?e:mO(e);t[r]=Cs(s[e])}),t}function fO(s){return s.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function xf(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>xf(e));const t={};return Object.keys(s).forEach(e=>{const r=Cu(e)?e:fO(e);t[r]=s[e]}),t}function Qd(s,t={}){return s==null?{}:(Object.getOwnPropertyNames(s).forEach(e=>{if(typeof s[e]!="function"){if(typeof s[e]=="object"){Qd(s[e],t[e]={});return}t[e]=s[e]}}),t)}class Uf{constructor(t){p(this,"defaults");this.defaults={baseURL:t.baseURL,headers:{common:{}},timeout:t.timeout,retry:t.retry,retryDelay:t.retryDelay}}buildURL(t,e){const{baseURL:r}=this.defaults,i=t.startsWith("http")?t:`${r}${t.startsWith("/")?t:`/${t}`}`;if(e){const n=new URLSearchParams;return Object.entries(e).forEach(([o,c])=>{n.append(o,c)}),`${i}${i.includes("?")?"&":"?"}${n.toString()}`}return i}async request(t){var h;const e=((h=t.method)==null?void 0:h.toUpperCase())||"GET",r=this.buildURL(t.url||"",t.params),i={...this.defaults.headers.common,...t.headers};e!=="GET"&&e!=="HEAD"&&t.data&&!i["Content-Type"]&&(i["Content-Type"]="application/json");const o=i["Content-Type"]==="application/json"?JSON.stringify(t.data):t.data,c={method:e,headers:i,body:e!=="GET"&&e!=="HEAD"&&t.data?o:void 0},d=t.timeout||this.defaults.timeout,l=t.retry!==void 0?t.retry:this.defaults.retry,u=t.retryDelay||this.defaults.retryDelay;try{const g=new AbortController,v=setTimeout(()=>g.abort(),d);c.signal=g.signal;const E=await fetch(r,c);clearTimeout(v);let b=null;const _=E.headers.get("content-type");_&&_.includes("application/json")?b=await E.json():b=await E.text();const w={};E.headers.forEach((B,N)=>{w[N]=B});const L={data:b,status:E.status,statusText:E.statusText,headers:w,config:t};if(!E.ok)throw L;return L}catch(g){if(g instanceof Error&&l>0)return await new Promise(v=>setTimeout(v,u)),this.defaults.baseURL===Pi.apiBase.prod?this.defaults.baseURL=Pi.apiBase.prodAlternate:this.defaults.baseURL===Pi.apiBase.prodAlternate&&(this.defaults.baseURL=Pi.apiBase.prod),this.request({...t,retry:l-1});throw g}}async get(t,e={}){return this.request({...e,method:"GET",url:t})}async post(t,e,r={}){return this.request({...r,method:"POST",url:t,data:e})}async put(t,e,r={}){return this.request({...r,method:"PUT",url:t,data:e})}}const vO=3,SO=30,TO=8e3;class yO{constructor(t,e){p(this,"ipInfo");p(this,"fetchClient");p(this,"requests");p(this,"roomName");p(this,"roomUUID");p(this,"authToken");p(this,"organizationId");p(this,"iceServers");p(this,"pluginInformation");p(this,"userDetails");p(this,"roomDetails");p(this,"context");this.context=t;const{timeout:r=TO,retry:i=vO,retryDelay:n=SO,baseURL:o=Pi.apiBase.prod,authToken:c,cachedUserDetails:d}=e||{};this.iceServers=d==null?void 0:d.iceServers,this.pluginInformation=d==null?void 0:d.pluginInformation,this.userDetails=d==null?void 0:d.userDetails,this.roomDetails=d==null?void 0:d.roomDetails,this.requests=new Uf({baseURL:o,timeout:r,retry:i,retryDelay:n,responseType:"json"}),this.fetchClient=new Uf({baseURL:"",timeout:r,retry:i,retryDelay:n,responseType:"json"}),this.setAuthToken(c,{bearer:!0});const l=this.requests.request.bind(this.requests);this.requests.request=async u=>{var g,v,E,b,_;const h=t.getValue("telemetry");try{h.injectContext(this.requests.defaults.headers.common);const w=await l(u);return u.url!==h.logsEndpoint&&this.logger.debug("xhr::fetch",{networkCall:{status:w.status,statusText:w.statusText,baseURL:u.baseURL||this.requests.defaults.baseURL,url:u.url,method:u.method}}),w}catch(w){throw w?(((g=w.config)==null?void 0:g.url)!==h.logsEndpoint&&this.logger.error("xhr::fetch",{error:w,networkCall:{status:w.status,statusText:w.statusText,baseURL:((v=w.config)==null?void 0:v.baseURL)||this.requests.defaults.baseURL,url:(E=w.config)==null?void 0:E.url,retries:(b=w.config)==null?void 0:b.retry,method:(_=w.config)==null?void 0:_.method,isOnline:navigator.onLine?"online":"offline"}}),new C(w.message||"Network request failed","0011")):new C("Unknown network error occurred","0011")}}}get peerId(){return this.context.getValue("peerId")}get logger(){return this.context.getValue("logger")}setAuthToken(t,e){const{bearer:r}=e||{};this.authToken=t,this.requests.defaults.headers.common.Authorization=r?`Bearer ${t}`:t}setHeader(t,e){this.requests.defaults.headers.common[t]=e}setRoomName(t){this.roomName=t}setRoomUUID(t){this.roomUUID=t}setOrganizationId(t){this.organizationId=t}}var EO=Object.defineProperty,bO=Object.getOwnPropertyDescriptor,os=(s,t,e,r)=>{for(var i=r>1?void 0:r?bO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&EO(t,e,i),i};class Wt extends yO{constructor(e,r){super(e,r);p(this,"telemetry");this.telemetry=e.getValue("telemetry"),this.setHeader("x-realtimekit-version",e.getValue("sdkVersion"))}async getIPDetails(){var r;const{peerId:e}=this;try{const i=await Au.getIPDetails({peerId:e,apiHostnames:Mm(this.context),logger:fm});if(this.logger.log("ipInfo",{ipInfo:i}),((r=i==null?void 0:i.loc)==null?void 0:r.length)>5)return i;throw Error("Insufficient data")}catch(i){this.logger.warn("APIClient.getIPDetails Failed to get ip details",{error:{name:i.name,message:i.message}});return}}async getICEServers(){if(this.iceServers)return this.iceServers;const{success:e,iceServers:r}=(await this.requests.get("/iceservers")).data;if(e)return(r==null?void 0:r.length)>0&&(this.iceServers=r),r}async getPlugins(){var n,o,c,d,l,u,h;if(this.pluginInformation)return this.pluginInformation;const{plugins:e}=(await this.requests.get("/v2/plugins/user")).data.data,r=((o=(n=this.context.getValue("flagsmith").getValue(X.V1_PLUGINS))==null?void 0:n.toString())==null?void 0:o.split(","))||[],i=e.reduce((g,v)=>(g[r.includes(v.id)?"v1":"v2"].push({...v,name:v.name.replace("v2","")}),g),{v1:[],v2:[]});return(l=(d=(c=this.context.getValue("modules"))==null?void 0:c.devTools)==null?void 0:d.plugins)!=null&&l.length&&((h=(u=this.context.getValue("modules"))==null?void 0:u.devTools)==null||h.plugins.forEach(g=>{var E,b,_;const v={...To,tags:[...To.tags],baseUrl:`http://localhost:${g.port}`,name:g.name,picture:(E=g.picture)!=null?E:To.picture,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),id:g.id,organizationId:this.organizationId,description:(b=g.description)!=null?b:To.description,staggered:(_=g.staggered)!=null?_:To.staggered};i.v2.push(v)})),i.v2}async getPluginDetails(e){const{plugin:r}=(await this.requests.get(`/v2/plugins/view/${e}`)).data.data;return r}async getPluginConfig(e){return(await this.fetchClient.get(`${e}/dyte-config.json`)).data}async authorizePlugin(e){const r={peerId:this.peerId},{token:i}=(await this.requests.post(`/v2/plugins/authorize/${e}`,r)).data.data;return i}async getPresignedUrls(e,r){const i=Fn(this.context,"chat_upload_expiry"),n={roomUUID:this.roomUUID,filename:e,expiry:typeof i=="number"?i:void 0};this.context.getValue("flagsmith").hasFeature(X.FEAT_CHAT_SDK)&&(n.viewType=r);const{getLocation:o,putLocation:c}=(await this.requests.post("/v1/meetings/genPreSignedUploadUrl",n)).data.data;return{getLocation:o,putLocation:c}}async uploadFile(e,r){if(navigator.isReactNative&&"uri"in e)try{await fetch(r,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:{uri:e.uri,name:e.name}})}catch(i){this.logger.error(`sendFileMessage::${i}`)}else await this.fetchClient.put(r,e,{headers:{"Content-Type":e.type}})}async startLivestreaming({manualIngestion:e}){const r=Cs(await this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/livestreams`,{manual_ingest:!!e})).data.data;return{playbackUrl:r.playbackUrl,status:r.status,manualIngest:r.manualIngest,ingestionCredentials:r.streamKey?{ingestionServer:r.ingestServer,streamKey:r.streamKey}:null}}async stopLivestreaming(){return this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/active-livestream/stop`)}async getActiveLivestream(){const e=Cs((await this.requests.get(`/v2/meetings/${this.context.getValue("meetingId")}/active-livestream`)).data.data);return{playbackUrl:e.playbackUrl,status:e.status,manualIngest:e.manualIngest,ingestionCredentials:e.streamKey?{ingestionServer:e.ingestServer,streamKey:e.streamKey}:null}}async getUserDetails(){if(this.userDetails)return this.userDetails;const e=(await this.requests.get("v2/internals/participant-details")).data.data;return Cs(e)}async startRecording(e,r){return(await this.requests.post("/v2/recordings",{...xf(e),meeting_id:this.context.getValue("meetingId"),allow_multiple_recordings:!!r})).data.data.id}async updateRecording(e,r){return this.requests.put(`v2/recordings/${e}`,{action:r})}async getActiveRecording(){const{status:e,id:r}=(await this.requests.get(`v2/recordings/active-recording/${this.context.getValue("meetingId")}`)).data.data;return{status:e,id:r}}async getActiveTranscript(){const{transcript_download_url:e}=(await this.requests.get(`v2/meetings/${this.context.getValue("meetingId")}/active-transcript`)).data.data;try{return{transcript:(await this.fetchClient.get(e)).data}}catch(r){throw new C("Cant fetch transcript s3 url","1801")}}async getRoomNodeData(){const e=await this.getIPDetails();if(this.ipInfo=e,this.roomDetails)return this.roomDetails;const{title:r}=Cs((await this.requests.post("v2/internals/rooms",{ip_information:e})).data.data);return{meetingTitle:r}}}os([y.trace("APIClient.getIPDetails")],Wt.prototype,"getIPDetails",1),os([y.trace("APIClient.getICEServers")],Wt.prototype,"getICEServers",1),os([y.trace("APIClient.getPlugins")],Wt.prototype,"getPlugins",1),os([y.trace("APIClient.startLivestreaming")],Wt.prototype,"startLivestreaming",1),os([y.trace("APIClient.stopLivestreaming")],Wt.prototype,"stopLivestreaming",1),os([y.trace("APIClient.getActiveLivestream")],Wt.prototype,"getActiveLivestream",1),os([y.trace("APIClient.getUserDetails")],Wt.prototype,"getUserDetails",1),os([y.trace("APIClient.startRecording")],Wt.prototype,"startRecording",1),os([y.trace("APIClient.stopRecording")],Wt.prototype,"updateRecording",1),os([y.trace("APIClient.getActiveRecording")],Wt.prototype,"getActiveRecording",1),os([y.trace("APIClient.getActiveTranscript")],Wt.prototype,"getActiveTranscript",1),os([y.trace("APIClient.getRoomNodeData")],Wt.prototype,"getRoomNodeData",1);let Ah;function wO(s,t){return Ah=new Wt(s,t),Ah}function pt(){return Ah}function _O(s,t){return`<blockquote>${t.replace(/<blockquote>[.\s\S]*<\/blockquote>\n\n/m,"")}</blockquote>
12
12
 
13
13
  ${s}`}const qn={maxInvocations:5,period:1};function Lt(s,t){return function(e,r,i){const n=i.value;let o=0,c=Date.now();return i.value=function(...d){const l=Date.now(),u=t?this[t]:s;if(l-c>u.period*1e3&&(c=l,o=0),o>=u.maxInvocations)throw new C(`Method rate limit ${u.maxInvocations} invocations/${u.period}sec exceeded`,"0013");return o+=1,n.apply(this,d)},i}}var PO=Object.defineProperty,CO=Object.getOwnPropertyDescriptor,gt=(s,t,e,r)=>{for(var i=r>1?void 0:r?CO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&PO(t,e,i),i};const RO=["text","image","file","custom","poll"],Xd={maxInvocations:180,period:60};let et=(Xv=class extends Gt{constructor(t,e,r,i,n){const o=t.getValue("logger");super(o);m(this,Il);m(this,$o);p(this,"messages");p(this,"channels",[]);m(this,Z,void 0);m(this,ji,void 0);m(this,Ge,void 0);m(this,Gi,void 0);m(this,Wi,void 0);p(this,"maxTextLimit",2e3);f(this,Wi,t),f(this,Ge,e),f(this,Gi,r),f(this,Z,i),f(this,ji,n),this.messages=[]}get telemetry(){return a(this,Wi).getValue("telemetry")}setMaxTextLimit(t){this.maxTextLimit=t}async sendMessageInternal(t,e,r,i={}){switch(t.type){case"text":{const n=i.replyTo&&i.replyTo.type==="text"?_O(t.message,i.replyTo.message):t.message;await this.sendTextMessageInternal(n,e,r);break}case"image":await this.sendImageMessageInternal(t.image,e,r);break;case"file":await this.sendFileMessageInternal(t.file,e,r);break;default:this.logger.error("sendMessage::message_type_not_supported",{chat:{messageType:t.type}});break}}async sendTextMessageInternal(t,e,r){var n,o,c,d,l,u;if(t.length>this.maxTextLimit)throw new C("Max character limit breached","0503");if(e&&e.length>0){if(!((n=a(this,Z).permissions)!=null&&n.chatPrivate.canSend)||!((o=a(this,Z).permissions)!=null&&o.chatPrivate.text))throw this.logger.error("sendTextMessage::private_chat_permission_denied"),new C("Could not send message to private chat.","0501")}else if(!((d=(c=a(this,Z).permissions)==null?void 0:c.chatPublic)!=null&&d.canSend)||!((u=(l=a(this,Z).permissions)==null?void 0:l.chatPublic)!=null&&u.text))throw this.logger.error("sendTextMessage::public_chat_permission_denied"),new C("Could not send message to public chat.","0501");if(!t)throw this.logger.error("sendTextMessage::message_can_not_be_empty"),new C("Message can not be empty.","0502");if(r){a(this,Ge).sendMessageToChannel(t,_t.TEXT,r);return}let i=[];e&&e.length>0&&(e.push(a(this,Z).id),i=a(this,ji).joined.toArray().filter(h=>e.includes(h.id)).map(h=>h.userId),i.push(a(this,Z).userId)),a(this,Ge).sendMessage(t,_t.TEXT,e)}async sendImageMessageInternal(t,e,r){var n,o,c,d,l,u;if(e&&e.length>0){if(!((n=a(this,Z).permissions)!=null&&n.chatPrivate.canSend)||!((o=a(this,Z).permissions)!=null&&o.chatPrivate.files)){this.logger.error("sendImageMessage::private_chat_permission_denied");return}}else if(!((d=(c=a(this,Z).permissions)==null?void 0:c.chatPublic)!=null&&d.canSend)||!((u=(l=a(this,Z).permissions)==null?void 0:l.chatPublic)!=null&&u.files)){this.logger.error("sendImageMessage::permission_denied");return}if(!t){this.logger.error("sendImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(t.type)){this.logger.error("sendImageMessage::image_type_not_supported",{chat:{imageType:t.type}});return}try{const h=pt(),{getLocation:g,putLocation:v}=await h.getPresignedUrls(t.name,a(this,Z).config.viewType);if(await h.uploadFile(t,v),r){a(this,Ge).sendMessageToChannel(g,_t.IMAGE,r);return}let E=[];e&&e.length>0&&(e.push(a(this,Z).id),E=a(this,ji).joined.toArray().filter(b=>e.includes(b.id)).map(b=>b.userId),E.push(a(this,Z).userId)),a(this,Ge).sendMessage(g,_t.IMAGE,e)}catch(h){throw new C("Error sending image message.","0500",this.logger)}}async sendFileMessageInternal(t,e,r){var i,n,o,c,d,l;if(e&&e.length>0){if(!((i=a(this,Z).permissions)!=null&&i.chatPrivate.canSend)||!((n=a(this,Z).permissions)!=null&&n.chatPrivate.files)){this.logger.error("sendFileMessage::private_chat_permission_denied");return}}else if(!((c=(o=a(this,Z).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=a(this,Z).permissions)==null?void 0:d.chatPublic)!=null&&l.files)){this.logger.error("sendFileMessage::permission_denied");return}if(!t){this.logger.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const u=pt(),{getLocation:h,putLocation:g}=await u.getPresignedUrls(t.name,a(this,Z).config.viewType);if(await u.uploadFile(t,g),r){a(this,Ge).sendMessageToChannel(JSON.stringify({link:h,name:t.name,size:"size"in t?t.size:0}),_t.FILE,r);return}let v=[];e&&e.length>0&&(e.push(a(this,Z).id),v=a(this,ji).joined.toArray().filter(b=>e.includes(b.id)).map(b=>b.userId),v.push(a(this,Z).userId));const E=JSON.stringify({link:h,name:t.name,size:"size"in t?t.size:0});a(this,Ge).sendMessage(E,_t.FILE,e)}catch(u){throw new C("Error sending file message.","0500",this.logger)}}get rateLimits(){return Xd}updateRateLimits(t,e){Xd.maxInvocations=t,Xd.period=e}async sendTextMessage(t,e){return this.sendTextMessageInternal(t,e)}async sendCustomMessage(t,e){var n,o,c,d,l,u,h,g,v,E,b,_,w,L,B;if(e&&e.length>0){if(!((n=a(this,Z).permissions)!=null&&n.chatPrivate.canSend)||!((o=a(this,Z).permissions)!=null&&o.chatPrivate.files)||!((c=a(this,Z).permissions)!=null&&c.chatPrivate.text)){this.logger.error("sendCustomMessage::private_chat_permission_denied");return}}else if(!((l=(d=a(this,Z).permissions)==null?void 0:d.chatPublic)!=null&&l.canSend)||!((h=(u=a(this,Z).permissions)==null?void 0:u.chatPublic)!=null&&h.files)||!((v=(g=a(this,Z).permissions)==null?void 0:g.chatPublic)!=null&&v.text)){this.logger.error("sendCustomMessage::permission_denied");return}const r=async N=>{try{if(typeof N=="string")return{link:N};const $=pt(),{getLocation:Y,putLocation:ae}=await $.getPresignedUrls(N.name,a(this,Z).config.viewType);return await $.uploadFile(N,ae),{link:Y,type:N.type,name:N.name,size:N.size}}catch($){throw new C("Error sending image message.","0500",this.logger)}},i={...t,files:await Promise.all((b=(E=t.files)!=null?E:[])==null?void 0:b.map(async N=>r(N))),images:await Promise.all((w=(_=t.images)!=null?_:[])==null?void 0:w.map(async N=>r(N))),videos:await Promise.all((B=(L=t.videos)!=null?L:[])==null?void 0:B.map(async N=>r(N)))};a(this,Ge).sendMessage(JSON.stringify(i),_t.CUSTOM,e)}async sendImageMessage(t,e){return this.sendImageMessageInternal(t,e)}async sendFileMessage(t,e){return this.sendFileMessageInternal(t,e)}async sendMessage(t,e){return this.sendMessageInternal(t,e)}async editTextMessage(t,e,r){var i,n,o,c,d,l;if(((n=(i=a(this,Z).permissions)==null?void 0:i.chatMessage)==null?void 0:n.canEdit)==="NONE")throw new C("Not permitted to edit messages","0501");if(!((c=(o=a(this,Z).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=a(this,Z).permissions)==null?void 0:d.chatPublic)!=null&&l.text)){this.logger.error("editTextMessage::permission_denied");return}if(!e){this.logger.error("editTextMessage::message_can_not_be_empty");return}a(this,Ge).editMessage(t,e,_t.TEXT,r)}async editImageMessage(t,e,r){var n,o,c,d;if(!((o=(n=a(this,Z).permissions)==null?void 0:n.chatPublic)!=null&&o.canSend)||!((d=(c=a(this,Z).permissions)==null?void 0:c.chatPublic)!=null&&d.files)){this.logger.error("editImageMessage::permission_denied");return}if(!e){this.logger.error("editImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(e.type)){this.logger.error("sendImageMessage::image_type_not_supported",{chat:{imageType:e.type}});return}try{const l=pt(),{getLocation:u,putLocation:h}=await l.getPresignedUrls(e.name,a(this,Z).config.viewType);await l.uploadFile(e,h),a(this,Ge).editMessage(t,u,_t.IMAGE,r)}catch(l){throw new C("Error editing image message.","0500",this.logger)}}async editFileMessage(t,e,r){var i,n,o,c;if(!((n=(i=a(this,Z).permissions)==null?void 0:i.chatPublic)!=null&&n.canSend)||!((c=(o=a(this,Z).permissions)==null?void 0:o.chatPublic)!=null&&c.files)){this.logger.error("sendFileMessage::permission_denied");return}if(!e){this.logger.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const d=pt(),{getLocation:l,putLocation:u}=await d.getPresignedUrls(e.name,a(this,Z).config.viewType);await d.uploadFile(e,u),a(this,Ge).editMessage(t,JSON.stringify({link:l,name:e.name,size:"size"in e?e.size:0}),_t.FILE,r)}catch(d){throw new C("Error editing file message.","0500",this.logger)}}async editMessage(t,e,r){switch(e.type){case"text":{this.editTextMessage(t,e.message,r);break}case"image":{this.editImageMessage(t,e.image,r);break}case"file":{this.editFileMessage(t,e.file,r);break}default:{this.logger.error("editMessage::message_type_not_supported",{chat:{messageType:e.type}});break}}}async deleteMessage(t,e){var r,i;if(((i=(r=a(this,Z).permissions)==null?void 0:r.chatMessage)==null?void 0:i.canDelete)==="NONE")throw new C("Not permitted to delete messages","0501");a(this,Ge).deleteMessage(t,e)}getMessagesByUser(t){return this.messages.filter(e=>e.userId===t)}getMessagesByType(t){return this.messages.filter(e=>e.type===t)}async pin(t){if(!a(this,$o,gp))throw new C("Can`t pin message without joining room","0505");if(!a(this,Z).permissions.pinParticipant)throw new C("You do not have permission to pin messages.","0501");const e=this.messages.find(r=>r.id===t);if(e){a(this,Ge).setPinState(e,!0);return}throw new C(`No message found with id: ${t}`,"0504")}async unpin(t){if(!a(this,$o,gp))throw new C("Can`t unpin message without joining room","0505");if(!a(this,Z).permissions.pinParticipant)throw new C("You do not have permission to unpin messages.","0501");const e=this.messages.find(r=>r.id===t);if(e){a(this,Ge).setPinState(e,!1);return}throw new C(`No message found with id: ${t}`,"0504")}async getMessages(t,e,r,i=0,n=void 0){const o=await a(this,Ge).getChatMessagesPaginated(t,e,r,i,n);return{messages:o.messages.map(c=>Rs.formatSocketPeerMessage(c)),next:o.next}}async createChannel(t,e,r={}){var c;const i=(c=a(this,Z).permissions)==null?void 0:c.chatChannel;if(i){if(i.canCreate==="NONE")throw new C("Not permitted to create channels","0501");if(r.visibility==="public"&&!(i.canCreate==="PUBLIC"||i.canCreate==="ALL"))throw new C("Not permitted to create public channels","0501");if(r.visibility==="private"&&!(i.canCreate==="PRIVATE"||i.canCreate==="ALL"))throw new C("Not permitted to create private channels","0501")}if(!t||t.trim().length===0)throw new C("channel name cannot be empty.","0510");const n=[...new Set([...e,a(this,Z).userId])];return await a(this,Gi).createChannel(t.trim(),n,r.displayPictureUrl,r.visibility,r.isDirectMessage)}updateChannel(t,e){var o,c,d,l,u;const r=this.channels.find(h=>h.id===t),i=(o=a(this,Z).permissions)==null?void 0:o.chatChannel;if(i){if(i.canUpdate==="NONE")throw new C("Not permitted to update channels","0501");if(r.visibility==="public"&&!(i.canUpdate==="PUBLIC"||i.canUpdate==="ALL"))throw new C("Not permitted to update public channels","0501");if(r.visibility==="private"&&!(i.canUpdate==="PRIVATE"||i.canUpdate==="ALL"))throw new C("Not permitted to update private channels","0501")}const n={memberIds:(c=e.memberIds)!=null?c:r.memberIds,displayName:(d=e.displayName)!=null?d:r.displayName,displayPictureUrl:(l=e.displayPictureUrl)!=null?l:r.displayPictureUrl,visibility:(u=e.visibility)!=null?u:r.visibility};return a(this,Gi).updateChannel(t,n)}async sendMessageToChannel(t,e,r={}){return this.sendMessageInternal(t,null,e,r)}async getChannelMembers(t){return a(this,Gi).getChannelMembers(t)}async searchMessages(t,e={}){if(!a(this,Wi).getValue("flagsmith").hasFeature(X.FEAT_CHAT_SDK_SEARCH))throw new C("searchMessages is temporarily disabled!","0506");return(await a(this,Ge).searchMessages(t,e)).map(Rs.formatSocketPeerMessage)}async markLastReadMessage(t,e){await a(this,Ge).markLastReadMessage(t,e);const r=this.channels.find(i=>i.id===t);if(r){const i={...r,unreadCount:0};this.channels=this.channels.map(n=>n.id===t?i:n),this.emit("channelMessageUpdate",i)}}get pinned(){return this.messages.filter(t=>t.pinned)}},Z=new WeakMap,ji=new WeakMap,Ge=new WeakMap,Gi=new WeakMap,Wi=new WeakMap,Il=new WeakSet,vS=function(){return a(this,Wi).getValue("connectionHandler")},$o=new WeakSet,gp=function(){return a(this,Il,vS).socketJoined===!0},Xv);gt([y.trace("Chat.sendTextMessage"),Lt(Xd)],et.prototype,"sendTextMessage",1),gt([y.trace("Chat.sendImageMessage"),Lt({maxInvocations:20,period:60})],et.prototype,"sendImageMessage",1),gt([y.trace("Chat.sendFileMessage"),Lt({maxInvocations:20,period:60})],et.prototype,"sendFileMessage",1),gt([y.trace("Chat.sendMessage"),Lt({maxInvocations:180,period:60})],et.prototype,"sendMessage",1),gt([y.trace("Chat.editTextMessage")],et.prototype,"editTextMessage",1),gt([y.trace("Chat.editImageMessage")],et.prototype,"editImageMessage",1),gt([y.trace("Chat.editFileMessage")],et.prototype,"editFileMessage",1),gt([y.trace("Chat.editMessage")],et.prototype,"editMessage",1),gt([y.trace("Chat.deleteMessage")],et.prototype,"deleteMessage",1),gt([y.trace("Chat.createChannel")],et.prototype,"createChannel",1),gt([y.trace("Chat.updateChannel")],et.prototype,"updateChannel",1),gt([y.trace("Chat.sendMessageToChannel")],et.prototype,"sendMessageToChannel",1),gt([y.trace("Chat.getChannelMembers")],et.prototype,"getChannelMembers",1),gt([y.trace("Chat.searchMessages")],et.prototype,"searchMessages",1),gt([y.trace("Chat.markLastReadMessage")],et.prototype,"markLastReadMessage",1),et=gt([ut("0500")],et);var kO=Object.defineProperty,IO=Object.getOwnPropertyDescriptor,AO=(s,t,e,r)=>{for(var i=r>1?void 0:r?IO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&kO(t,e,i),i};const Ai=(Zv=class{constructor(s,t,e,r,i){p(this,"chat");p(this,"chatSocketHandler");p(this,"chatChannelSocketHandler");p(this,"self");m(this,Qr,void 0);f(this,Qr,s),this.chatSocketHandler=t,this.chatChannelSocketHandler=e,this.chat=new et(s,t,e,r,i),this.self=r,this.setupEvents()}get telemetry(){return a(this,Qr).getValue("telemetry")}get logger(){return a(this,Qr).getValue("logger")}static async init(s,t,e,r,i){return new Ai(s,t,e,r,i)}static formatMessage(s){return{...s,time:new Date(s.time),type:RO[s.type]}}static formatSocketPeerMessage(s){const t=s.createdAt*1e3,e={displayName:s.displayName,id:s.chatId,time:t,timeMs:s.createdAtMs,type:s.payloadType,isEdited:s.isEdited,userId:s.userId,targetUserIds:s.targetUserIds,channelId:s.channelId,channelIndex:s.channelIndex,message:"",link:"",name:"",html:"",images:[],videos:[],files:[],size:0,pinned:s.pinned};switch(e.type){case _t.TEXT:{e.message=s.payload;break}case _t.IMAGE:{e.link=s.payload;break}case _t.FILE:{const{link:r,name:i,size:n}=JSON.parse(s.payload);e.link=r,e.name=i,e.size=n;break}case _t.CUSTOM:{const{html:r,images:i,message:n,videos:o,files:c}=JSON.parse(s.payload);e.message=n,e.html=r,e.images=i,e.videos=o,e.files=c;break}}return Ai.formatMessage(e)}async getChatMessages(){if(this.self.config.viewType==="LIVESTREAM"||this.self.config.viewType==="CHAT"||a(this,Qr).getValue("flagsmith").hasFeature(X.FEAT_PAGINATED_CHAT))return;const s=await this.chatSocketHandler.getChatMessages();if(!(s!=null&&s.payload))return;const t=Pf.fromBinary(s.payload).messages;this.chat.messages=t.map(e=>Ai.formatSocketPeerMessage(e))}setupEvents(){a(this,Qr).getValue("peerSessionStore").on(R.SOCKET_SERVICE_ROOM_JOINED,async()=>{this.getChatMessages()}),this.chatSocketHandler.on(Ae.sendMessageToRoom,s=>{const t=Ai.formatSocketPeerMessage(s.message);if(!t.channelId)this.chat.messages=[...this.chat.messages,t];else{const e=this.chat.channels.find(r=>r.id===t.channelId);e&&(e.latestMessage=t,e.unreadCount+=1,this.chat.emit("channelMessageUpdate",e))}this.chat.emit("chatUpdate",{action:"add",message:t,messages:this.chat.messages})}),this.chatSocketHandler.on(Ae.sendMessageToPeers,s=>{const t=Ai.formatSocketPeerMessage(s.message);this.chat.messages=[...this.chat.messages,t],this.chat.emit("chatUpdate",{action:"add",message:t,messages:this.chat.messages})}),this.chatSocketHandler.on(Ae.editMessage,s=>{const t=Ai.formatSocketPeerMessage(s.message);if(t.channelId){this.chat.emit("chatUpdate",{action:"edit",message:t,messages:this.chat.messages});return}const e=this.chat.messages.findIndex(r=>r.id===t.id);e!==-1&&(this.chat.messages[e]=t,this.chat.emit("chatUpdate",{action:"edit",message:t,messages:this.chat.messages}))}),this.chatSocketHandler.on(Ae.deleteMessage,s=>{if(s.channelId){this.chat.emit("chatUpdate",{action:"delete",message:{id:s.chatId,channelId:s.channelId},messages:this.chat.messages});return}const t=this.chat.messages.findIndex(r=>r.id===s.chatId);if(t===-1)return;const[e]=this.chat.messages.splice(t,1);this.chat.emit("chatUpdate",{action:"delete",message:e,messages:this.chat.messages})}),this.chatChannelSocketHandler.on(ki.createChatChannel,s=>{const[t]=s.chatChannels,e=Ii.formatChannel(t);this.chat.channels.push(e),this.chat.emit("channelCreate",e)}),this.chatSocketHandler.on(Ae.pinMessage,s=>{const t=this.chat.messages.findIndex(r=>r.id===s.chatId);if(t===-1)return;const e=this.chat.messages[t];e.pinned=s.pinned,this.chat.messages[t]=e,this.chat.emit("chatUpdate",{action:"edit",message:e,messages:this.chat.messages})}),this.chatChannelSocketHandler.on(ki.updateChatChannel,s=>{const[t]=s.chatChannels,e=Ii.formatChannel(t);this.chat.channels=this.chat.channels.map(r=>r.id===e.id?e:r),this.chat.emit("channelUpdate",e)})}},Qr=new WeakMap,Zv);let Rs=Ai;AO([y.trace("ChatController.setupEvents")],Rs.prototype,"setupEvents",1);var MO=Object.defineProperty,OO=Object.getOwnPropertyDescriptor,DO=(s,t,e,r)=>{for(var i=r>1?void 0:r?OO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&MO(t,e,i),i};let Mh=(eS=class extends Gt{constructor(t,e,r){const i=t.getValue("logger");super(i);m(this,Al);m(this,Ml);p(this,"items");m(this,aa,void 0);m(this,oa,void 0);m(this,Ho,void 0);f(this,Ho,t),f(this,aa,e),f(this,oa,r),this.items=[]}async create(t,e,r=!1,i=!1){if(!a(this,Ml,TS))throw new C("Can't create polls without joining room","0705");if(!a(this,aa).permissions.polls.canCreate){this.logger.error("Polls::create::permission_denied");return}if(!t||!e){this.logger.error("Polls::question_and_options_can_not_be_empty",{polls:{hasQuestion:!!t,optionsLength:e==null?void 0:e.length}});return}if(e.length<2){this.logger.error("Polls::there_must_be_at_least_two_options",{polls:{hasQuestion:!!t,optionsLength:e.length}});return}await a(this,oa).createPoll(t,e,r,i)}async vote(t,e){if(!a(this,aa).permissions.polls.canVote){this.logger.error("Polls::vote::permission_denied");return}await a(this,oa).votePoll(t,e)}},Al=new WeakSet,SS=function(){return a(this,Ho).getValue("connectionHandler")},Ml=new WeakSet,TS=function(){var t;return((t=a(this,Al,SS))==null?void 0:t.socketJoined)===!0},aa=new WeakMap,oa=new WeakMap,Ho=new WeakMap,eS);Mh=DO([ut("0700")],Mh);var NO=Object.defineProperty,VO=Object.getOwnPropertyDescriptor,LO=(s,t,e,r)=>{for(var i=r>1?void 0:r?VO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&NO(t,e,i),i};const jn=(tS=class{constructor(s,t,e){p(this,"polls");m(this,Xr,void 0);m(this,ca,void 0);m(this,Ji,void 0);this.polls=new Mh(s,t,e),f(this,ca,t),f(this,Xr,s),f(this,Ji,e),this.setupEvents()}get telemetry(){return a(this,Xr).getValue("telemetry")}get logger(){return a(this,Xr).getValue("logger")}static async init(s,t,e){return new jn(s,t,e)}canViewPolls(){return a(this,ca).permissions.polls.canView}setupEvents(){const s={[lr.createPoll]:r=>{r.poll&&this.updatePoll(jn.formatSocketServicePoll(r.poll))},[lr.updatePoll]:r=>{r.poll&&this.updatePoll(jn.formatSocketServicePoll(r.poll))},[lr.votePoll]:r=>{r.poll&&this.updatePoll(jn.formatSocketServicePoll(r.poll))}},t=()=>{a(this,Xr).getValue("peerSessionStore").on(R.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{a(this,Ji).on(r,s[r])})},e=()=>{a(this,Xr).getValue("peerSessionStore").on(R.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{a(this,Ji).removeListeners(r)})};a(this,ca).permissions.on("permissionsUpdate",async r=>{var i;r!=null&&r.polls&&((i=r==null?void 0:r.polls)!=null&&i.canView?(await this.getPolls(),t()):(this.polls.items=[],e()))}),this.canViewPolls()&&t()}updatePoll(s){if(!this.canViewPolls())return;const t=this.polls.items.findIndex(e=>e.id===s.id);if(t>-1){const e=JSON.stringify(this.polls.items[t]);this.polls.items[t]=s,e!==JSON.stringify(s)&&this.polls.emit("pollsUpdate",{polls:this.polls.items,newPoll:!1});return}this.polls.items=[...this.polls.items,s],this.polls.emit("pollsUpdate",{polls:this.polls.items,newPoll:!0})}async getPolls(){const s=await a(this,Ji).getPolls();if(!(s!=null&&s.payload))return;const{polls:t}=JM.fromBinary(s.payload);this.polls.items=t.map(e=>jn.formatSocketServicePoll(e))}static formatSocketServicePoll(s){const t=s.options.map(e=>({count:e.count,text:e.text,votes:e.votes.map(r=>({id:r.userId,name:r.name}))}));return{anonymous:s.anonymous,createdBy:s.createdBy,createdByUserId:s.createdByUserId,hideVotes:s.hideVotes,id:s.pollId,options:t,question:s.question,voted:s.votes}}},Xr=new WeakMap,ca=new WeakMap,Ji=new WeakMap,tS);let Ff=jn;LO([y.trace("PollController.setupEvents")],Ff.prototype,"setupEvents",1);var xO=Object.defineProperty,UO=Object.getOwnPropertyDescriptor,FO=(s,t,e,r)=>{for(var i=r>1?void 0:r?UO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&xO(t,e,i),i},Bf=(s=>(s[s.User=0]="User",s[s.Meeting=1]="Meeting",s))(Bf||{});let Oh=(sS=class extends Gt{constructor(t,e,r,i,n){const o=t.getValue("logger");super(o);m(this,qo);p(this,"selfActiveTab");p(this,"broadcastTabChanges");m(this,da,void 0);m(this,Ki,void 0);m(this,jo,void 0);p(this,"viewType");p(this,"meetingStartedTimestamp");p(this,"meetingTitle");p(this,"sessionId");f(this,da,t),f(this,Ki,e),this.viewType=r,f(this,jo,i),this.meetingTitle=n,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){return a(this,qo,mp).socketState}get mediaState(){return a(this,qo,mp).mediaState}get meetingId(){return a(this,da).getValue("meetingId")}setBroadcastTabChanges(t){if(!a(this,Ki).permissions.canSpotlight)throw this.logger.error("Spotlight::setSpotlighted::permission_denied"),new C("User does not have permission to toggle spotlight","0801");this.broadcastTabChanges=t,this.emit("broadcastTabChangesUpdate",this.broadcastTabChanges),this.broadcastTabChanges&&this.assertActiveTabToRoom()}setSelfActiveTab(t,e){var r;this.logger.info("Spotlight::setActiveTab",{spotlight:{currentTab:{id:t.id,type:t.type}}}),this.selfActiveTab=t,e===0&&this.emit("selfTabUpdate",t),(r=a(this,Ki).permissions)!=null&&r.canSpotlight&&this.broadcastTabChanges&&e===0&&this.assertActiveTabToRoom()}assertActiveTabToRoom(){a(this,jo).broadcastMessage("spotlight",{userId:a(this,Ki).userId,currentTab:this.selfActiveTab})}},da=new WeakMap,qo=new WeakSet,mp=function(){return a(this,da).getValue("connectionHandler")},Ki=new WeakMap,jo=new WeakMap,sS);Oh=FO([ut("0800")],Oh);function BO(s){let t="",e=[""];const r=[e];let i=0,n=0,o=!0,c;for(c of s)c==='"'?(o&&c===t&&(e[i]+=c),o=!o):c===","&&o?c=e[++i]="":c===`
@@ -20,4 +20,4 @@ slogScale: ${i}, isVoice: ${r}, minEnergy: ${a(this,Mr)},
20
20
  maxEnergy: ${a(this,hi)}`),i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!a(this,Mr)||i<a(this,Mr))&&f(this,Mr,i),(!a(this,hi)||i>a(this,hi))&&f(this,hi,i),{energy:(i-a(this,Mr))/(a(this,hi)-a(this,Mr))*10||0,isVoice:r})},Mc=new WeakSet,Rp=function(t){return t<5},cu=new WeakSet,HS=function(t=a(this,yn)){var r;if(!a(this,xs)||!t){a(this,Or).getValue("flagsmith").hasFeature(X.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: No producerId or energy to report: ${a(this,xs)}`);return}const e={producerId:a(this,xs),energy:Math.round(t),silent:U(r=Oc,Mc,Rp).call(r,t)};f(this,to,e.silent),this.reportRequest(e)},du=new WeakSet,qS=function(t){const e=Math.log10(t);return Math.round(e)},m(Oo,Mc),m(Oo,du);const q1=(s=!1)=>{if("MediaStreamTrackGenerator"in window&&"AudioData"in window)try{const e=new window.MediaStreamTrackGenerator({kind:"audio"}),r=e.writable.getWriter(),i=48e3,n=128,o=1;let c=0,d=null;const l=async()=>{try{const g=new Float32Array(n*o),v=new window.AudioData({format:"f32",sampleRate:i,numberOfFrames:n,numberOfChannels:o,timestamp:c,data:g});c+=n/i*1e6,await r.ready,await r.write(v)}catch(g){d&&clearInterval(d),r.releaseLock(),e.writable.abort()}};d=window.setInterval(l,100);const h=new MediaStream([e]).getAudioTracks()[0];return h.addEventListener("ended",()=>{d&&clearInterval(d),r.releaseLock(),e.writable.abort()}),Object.assign(h,{fakeTracks:"fakeTracks:fakeAudioTrack"}),h.enabled=s,h}catch(e){}const t=window.AudioContext||window.webkitAudioContext;if(t)try{const e=new t;if(!e||e.state!=="running"||!e.destination)return;const r=e.createOscillator();r.frequency.value=0,r.type="sine";const i=e.createGain();i.gain.value=0,r.connect(i);const n=e.createMediaStreamDestination();i.connect(n),r.start();const o=n.stream.getAudioTracks()[0];return o?(Object.assign(o,{fakeTracks:"fakeTracks:fakeAudioTrack"}),o.enabled=s,o):void 0}catch(e){return}},j1=(s=!1)=>{var n,o;const t=new MediaStream().getVideoTracks()[0],e=document.createElement("canvas");e.height=(n=t==null?void 0:t.getSettings().height)!=null?n:720,e.width=(o=t==null?void 0:t.getSettings().width)!=null?o:1280;const r=e.getContext("2d");r.fillStyle="black",r.fillRect(0,0,e.width,e.height),setInterval(()=>{r.fillStyle="black",r.fillRect(0,0,e.width,e.height)},1e3);const i=e.captureStream().getVideoTracks()[0];return Object.assign(i,{fakeTracks:"fakeTracks:fakeVideoTrack"}),i.enabled=s,i};var G1=Object.defineProperty,W1=Object.getOwnPropertyDescriptor,ce=(s,t,e,r)=>{for(var i=r>1?void 0:r?W1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&G1(t,e,i),i};const Yt=["video/VP9","video/VP8"],bv=(up=class{constructor(s,t){m(this,pi);m(this,lu);m(this,uu);m(this,hu);m(this,xc);m(this,gu);m(this,mu);m(this,fu);m(this,ot);m(this,Cn);m(this,vu);m(this,Su);m(this,Tu);p(this,"context");p(this,"authToken");p(this,"e2ee");m(this,Dc,void 0);m(this,Nc,void 0);m(this,Et,void 0);m(this,j,void 0);m(this,so,void 0);m(this,Mt,void 0);m(this,En,void 0);m(this,bn,void 0);m(this,wn,void 0);m(this,Vc,void 0);m(this,Ss,null);m(this,Nr,void 0);m(this,Lc,void 0);m(this,_n,void 0);m(this,Pn,void 0);m(this,Ot,void 0);m(this,Ht,void 0);var r,i;this.context=s;const{socket:e}=t;this.mediaJoined=!1,f(this,_n,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,Pn,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,Et,e),f(this,En,!1),f(this,j,new F1(s,e)),f(this,Mt,a(this,j).events),f(this,Nr,new Set),f(this,Ot,new Map),f(this,bn,!1),f(this,wn,new Wh(s.getValue("logger"))),f(this,Ht,new Oo(this.context,a(this,j).socketHandler.audioActivity.bind(a(this,j).socketHandler))),this.e2ee=(i=(r=s.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?i:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,Vc,Zu(async()=>{if(!a(this,pi,no).mediaJoinAttempted)return;const{roomJoined:n}=await this.joinRoom(a(this,Nc),a(this,Dc),!0,!0);n&&(this.context.getValue("peerSessionStore").emit(R.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(R.ROOM_NODE_RECONNECTED))},5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get mediaJoined(){return a(this,pi,no).mediaJoined}set mediaJoined(s){a(this,pi,no).mediaJoined=s}reset(){a(this,j).closeAllProducers(),a(this,j).closeAllConsumers(),a(this,Ot).clear(),a(this,Nr).clear(),f(this,Ss,null),a(this,wn).stop(),a(this,j).stopAllTransports(),a(this,j).reset(),f(this,wn,new Wh)}async joinRoom(s,t,e=!1,r=!1,i={}){a(this,pi,no).mediaJoinAttempted=!0,f(this,En,!0),e&&this.reset();try{return await a(this,wn).push(()=>U(this,lu,jS).call(this,s,t,r,i),"joinRoom")}catch(n){return this.logger.error("Error in room joining process",{error:n}),this.context.getValue("peerSessionStore").emit(R.ROOM_NODE_FAILED),{roomJoined:!1}}}async initializeConnection(s,t,e=!1,r={}){return a(this,Ss)?a(this,Ss):(f(this,Ss,(async()=>{try{await U(this,xc,kp).call(this,s,t,e,r)}catch(i){throw f(this,Ss,null),i}})()),a(this,Ss))}getConsumers(){return a(this,j).consumers}getProducers(){return a(this,j).producers}async leaveRoom(){a(this,j).stopAllTransports(),f(this,bn,!1),a(this,pi,no).mediaJoinAttempted=!1;const s={closeRoom:!1};a(this,Et).sendMessagePromise(a(this,Mt).leaveRoom,DR.toBinary(s)).then(e=>{var r;(r=Ek.fromBinary(e.payload))!=null&&r.closed&&this.logger.warn("Weird state on peer closed and should not happen")}).catch(e=>{this.logger.error("error on sending leave room request",{error:e})}),this.context.getValue("callstats").callEnded(),this.context.getValue("telemetry").destruct()}async activatePeers(s){return this.createConsumers(s)}async createConsumers(s){return s.length===0?Promise.resolve():a(this,j).createConsumers(s)}async closeConsumers(s){if(!s.length)return;const t=s.reduce((e,r)=>{const i=a(this,j).producerIdToConsumerIdMap.get(r.producerId);return i?(e.push(i),e):(this.logger.warn(`consumer not found in close consumers: ${r.producerId}`),e)},[]);await a(this,j).closeConsumers(t)}async _shareWebcam(s,t){var h,g;const e=t==="video/VP9"?fe.WEBCAM:fe.WEBCAM_BACKUP,r=U(this,ot,Nt).call(this,e);if(r){const v=await r;if(a(this,j).producers.has(v)){const E=a(this,j).producers.get(v);if(!E.closed)return await E.replaceTrack({track:s}),await this.resumeWebcam(e),s;await this.disableWebcam(t)}return this._shareWebcam(s,t)}const i=[t].concat(Yt.filter(v=>v!==t)),n=U(this,Tu,ZS).call(this,s,i),o=Fn(this.context,"disableSimulcast"),c=(g=(h=this.context)==null?void 0:h.getValue("overrides"))==null?void 0:g.simulcastConfig;!(o||c&&c.disable)&&this.context.getValue("flagsmith").hasFeature(X.ENABLE_CF_SIMULCAST)?(this.logger.info("Simulcast enabled for SFU: CF"),n.encodings=_D(this.context,s)):this.logger.info("Simulcast disabled for webcam producer, SFU: CF"),this.context.getValue("flagsmith").hasFeature(X.TRACK_HINT)&&(n.track.contentHint=this.context.getValue("flagsmith").getValue(X.TRACK_HINT));const l=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,Ot).delete(e)},u=a(this,j).createProducer(n,l);return U(this,Cn,dd).call(this,e,u.then(v=>v.id)),u.then(v=>v.track)}async shareWebcam(s){var r;if(s===void 0)return null;const t=(r=this.context.getValue("flagsmith").getValue(X.FORCE_VIDEO_CODEC))==null?void 0:r.toString();if(t)return this.logger.debug(`Calling _shareWebcam with forced video codec: ${t}`),this._shareWebcam(s,t);const e=Yt.filter(i=>{var n,o;return((o=(n=a(this,so).sender)==null?void 0:n.video)==null?void 0:o.codecs.findIndex(c=>c.mimeType===i))>=0&&a(this,Pn).get(i).size>0});return e.length===0&&e.push(Yt[0]),await Promise.all(e.map(i=>(this.logger.debug(`Calling _shareWebcam with video codec: ${i}`),this._shareWebcam(s,i)))),s}async shareScreen(s){const{video:t,audio:e}=s;if(t===void 0)return;const r={track:t,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Te.isElectron()},stopTracks:!1},i=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,Ot).delete(fe.SCREENSHARE_VIDEO),a(this,Ot).delete(fe.SCREENSHARE_AUDIO)},n=a(this,j).createProducer(r,i);U(this,Cn,dd).call(this,fe.SCREENSHARE_VIDEO,n.then(c=>c.id));let o;if(e){const c={track:e,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Te.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},d=()=>{};o=a(this,j).createProducer(c,d),U(this,Cn,dd).call(this,fe.SCREENSHARE_AUDIO,o.then(l=>l.id))}await Promise.all([n,o||Promise.resolve()]),this.context.getValue("callstats").screenShareStart()}async shareMic(s){try{if(s===void 0)throw new Ut("track undefined");const t=U(this,ot,Nt).call(this,fe.MIC);if(t){const n=await t;if(a(this,j).producers.has(n)){const o=a(this,j).producers.get(n);if(!o.closed){await o.replaceTrack({track:s}),await this.resumeMic(),a(this,Ht)&&(a(this,Ht).audioTrack=s,a(this,Ht).producerId=n,a(this,Ht).start());return}await a(this,j).closeProducer(n,{stopTrack:!1})}await this.shareMic(s);return}const e=U(this,Su,XS).call(this,s),r=()=>{a(this,Ot).delete(fe.MIC)},i=a(this,j).createProducer(e,r);U(this,Cn,dd).call(this,fe.MIC,i.then(n=>n.id)),await i.then(n=>{a(this,Ht)&&(a(this,Ht).audioTrack=n.track,a(this,Ht).producerId=n.id,a(this,Ht).start())})}catch(t){throw new C(t)}}async pauseMic(){var r;const s=await U(this,ot,Nt).call(this,fe.MIC),t=a(this,j).producers.get(s);if(!t){this.logger.error("pauseMic::could_not_find_mic_producer");return}if(t.paused){this.logger.info("pauseMic::mic_producer_already_paused");return}t.pause(),(r=a(this,Ht))==null||r.stop();const e={producerId:t.id,pause:!0};a(this,Et).sendMessage(a(this,Mt).toggleProducer,jd.toBinary(e))}async pauseWebcam(){const s=await U(this,ot,Nt).call(this,fe.WEBCAM),t=await U(this,ot,Nt).call(this,fe.WEBCAM_BACKUP),e=a(this,j).producers.get(s),r=a(this,j).producers.get(t);if(!e&&!r){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}const i=n=>{const o={producerId:n.id,pause:!0};a(this,Et).sendMessage(a(this,Mt).toggleProducer,jd.toBinary(o))};e&&(e.pause(),i(e)),r&&(r.pause(),i(r))}async resumeMic(){const s=await U(this,ot,Nt).call(this,fe.MIC),t=a(this,j).producers.get(s);if(!t){this.logger.error("resumeMic::could_not_find_mic_producer");return}if(!t.pause){this.logger.info("resumeMic::mic_producer_already_resumed");return}t.resume(),t.appData.e2ee&&this.context.getValue("peerSessionStore").emit(R.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};a(this,Et).sendMessage(a(this,Mt).toggleProducer,jd.toBinary(e))}async resumeWebcam(s=fe.WEBCAM){const t=await U(this,ot,Nt).call(this,s),e=a(this,j).producers.get(t);if(!e){this.logger.error("resumeWebcam::could_not_find_webcam_producer");return}if(!e.paused){this.logger.info("resumeWebcam::webcam_producer_already_resumed");return}e.resume(),e.appData.e2ee&&this.context.getValue("peerSessionStore").emit(R.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};a(this,Et).sendMessage(a(this,Mt).toggleProducer,jd.toBinary(r))}async disableWebcam(s){const t=s==="video/VP9"?fe.WEBCAM:fe.WEBCAM_BACKUP,e=await U(this,ot,Nt).call(this,t);U(this,vu,QS).call(this,t),e&&await a(this,j).closeProducer(e)}async disableMic(){var t;const s=await U(this,ot,Nt).call(this,fe.MIC);s&&await a(this,j).closeProducer(s),(t=a(this,Ht))==null||t.stop(),a(this,Ot).delete(fe.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const s=await U(this,ot,Nt).call(this,fe.SCREENSHARE_VIDEO),t=await U(this,ot,Nt).call(this,fe.SCREENSHARE_AUDIO);s&&await a(this,j).closeProducer(s),t&&await a(this,j).closeProducer(t),a(this,Nr).clear(),a(this,Ot).delete(fe.SCREENSHARE_VIDEO),a(this,Ot).delete(fe.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(s,t){if(s){const e=await U(this,ot,Nt).call(this,fe.WEBCAM),r=await U(this,ot,Nt).call(this,fe.WEBCAM_BACKUP);await a(this,j).closeProducer(e,{stopTrack:!1}),await a(this,j).closeProducer(r,{stopTrack:!1}),this.shareWebcam(s)}if(t){const e=await U(this,ot,Nt).call(this,fe.SCREENSHARE_VIDEO);await a(this,j).closeProducer(e,{stopTrack:!1}),this.shareScreen({video:t})}}async changeDisplayName(s,t){const e={displayName:s,participantId:t!=null?t:this.peerId};if(!await a(this,j).socketHandler.changeDisplayName(e))throw new Error("failed to change display name!")}kick(s){const t={peerIds:[s]};a(this,j).socketHandler.kickPeer(t)}kickAll(){a(this,j).socketHandler.kickAll()}async muteAll(s){if(!await a(this,j).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await a(this,j).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(s){if(!await a(this,j).socketHandler.hostControlForPeer(s,"audio"))throw new Error("failed to mute given participant")}async disableVideo(s){if(!await a(this,j).socketHandler.hostControlForPeer(s,"video"))throw new Error("failed to mute video of given participant")}async pinPeer(s){const t={participantId:s!=null?s:""};try{await a(this,Et).sendMessagePromise(a(this,Mt).globalPinPeer,JR.toBinary(t))}catch(e){this.logger.error("Error in pinning peer:",{error:e})}}validateScreenShare(s){return this.peerId===s.peerId&&a(this,j).producers.get(s.producerId)&&a(this,Nr).add(s.consumerPeerId),a(this,Nr).size}async switchConsumersToLayer(s,t){const e=s.map(r=>this.getConsumers().get(r));a(this,j).switchConsumersToLayer(e,t)}async handleSocketEvents(){a(this,Et).on(a(this,Mt).peerProducerCreateBroadcast,({payload:s})=>{var t,e;if(this.mediaJoined)try{const{participantId:r,producerState:i}=Qk.fromBinary(s);if(r===this.peerId)return;if(i!=null&&i.mimeType||(i.mimeType=i.kind===Ws.AUDIO?"audio/opus":"video/VP8"),i.kind===Ws.VIDEO&&!i.screenShare&&((e=(t=a(this,so).receiver)==null?void 0:t.video)==null?void 0:e.codecs.findIndex(n=>n.mimeType===Yt[0]))>=0&&a(this,_n).get(Yt[0]).has(r)&&i.mimeType!==Yt[0]){this.logger.warn(`Ignoring producer: ${i.producerId}`);return}this.logger.info(`producer created broadcast: ${r}, producer state: ${i}`),this.context.getValue("peerSessionStore").emit(R.NEW_PRODUCER,{peerId:r,producer:{...i,kind:i.kind===Ws.AUDIO?"audio":"video",producingPeerId:r}})}catch(r){this.logger.error("error in peer-producer-create-broadcast",{error:r})}}),a(this,Et).on(a(this,Mt).peerProducerToggleBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,initiatorParticipantId:e,producerState:{kind:r,pause:i,producerId:n,screenShare:o}}=lf.fromBinary(s);if(o)return;const c=r===Ws.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${t}, producerId: ${n}, kind:${c}, paused:${i} payload: ${JSON.stringify(lf.fromBinary(s))}`),t===this.peerId&&e!==this.peerId&&i&&this.context.getValue("peerSessionStore").emit(c==="audio"?R.MUTE_SELF:R.MUTE_SELF_VIDEO),t===this.peerId)return;this.context.getValue("peerSessionStore").emit(R.PRODUCER_TOGGLE,{peerId:t,producerId:n,paused:i,kind:c}),Array.from(this.getConsumers().values()).filter(l=>l.producerId===n).forEach(l=>{l.kind==="video"&&i||l.paused!==i&&(this.logger.debug(`consumer state mismatched for ${l.id}. updating consumer pause state ${l.paused} to ${i}`),i?(l.pause(),this.context.getValue("peerSessionStore").emit(R.CONSUMER_PAUSED,{id:l.id})):(l.resume(),this.context.getValue("peerSessionStore").emit(R.CONSUMER_RESUMED,{id:l.id})))})}catch(t){this.logger.error("error in producer toggle broadcast handler",{error:t})}}),a(this,Et).on(a(this,Mt).peerLeaveBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t}=hh.fromBinary(s);if(t===this.peerId)return;this.logger.info(`peer left broadcast:${t}`),a(this,Nr).delete(t),a(this,j).consumers.forEach(e=>{e.peerId===t&&e.close()}),this.context.getValue("peerSessionStore").emit(R.PEER_CLOSED,{id:t})}catch(t){this.logger.error("error in peer left broadcast",{error:t})}}),a(this,Et).on(a(this,Mt).peerProducerCloseBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,producerState:{producerId:e}}=eI.fromBinary(s);if(t===this.peerId)return;this.logger.info(`producer closed broadcast:${t}`),this.context.getValue("peerSessionStore").emit(R.PRODUCER_CLOSED,{peerId:t,producerId:e});const r=a(this,j).producerIdToConsumerIdMap.get(e);if(!r){this.logger.warn(`no consumer found for producer:${e}`);return}this.logger.info(`closing consumer ${r}, producer id: ${e}`),a(this,j).closeConsumer(r).then(()=>{this.logger.info(`closed consumer: ${r}`),a(this,j).producerIdToConsumerIdMap.delete(e),this.context.getValue("peerSessionStore").emit(R.CONSUMER_CLOSED,{id:r})}).catch(i=>{this.logger.error("error closing consumer",{error:i})})}catch(t){this.logger.error("error on producer close broadcast",{error:t})}}),a(this,Et).on(a(this,Mt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,En)&&!a(this,bn)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(R.ROOM_NODE_DISCONNECTED),a(this,Vc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(s=>{s.forEach((t,e)=>{const r=a(this,j).consumers.get(e);r&&this.context.getValue("peerSessionStore").emit(R.CONSUMER_SCORE_UPDATE,{id:e,kind:r.kind,peerId:r.peerId,score:t.score,scoreStats:t})})}),this.context.getValue("callstats").onProducerScore(s=>{s.forEach((t,e)=>{const r=Array.from(a(this,j).producers.values()).find(i=>i.id===e);r&&this.context.getValue("peerSessionStore").emit(R.PRODUCER_SCORE_UPDATE,{id:e,kind:r.kind,appData:r.appData,score:t.score,scoreStats:t})})})}handlePeerCapabilities(s,t){var e,r,i,n;for(let o=0;o<=Yt.length;o+=1){const c=Yt[o];if(((r=(e=t==null?void 0:t.receiver)==null?void 0:e.video)==null?void 0:r.codecs.findIndex(d=>d.mimeType===c))>=0||o===Yt.length-1){a(this,Pn).get(c).add(s);break}}for(let o=0;o<=Yt.length;o+=1){const c=Yt[o];if(((n=(i=t==null?void 0:t.sender)==null?void 0:i.video)==null?void 0:n.codecs.findIndex(d=>d.mimeType===c))>=0||o===Yt.length-1){a(this,_n).get(c).add(s);break}}}handlePeerLeaving(s){this.context.getValue("flagsmith").hasFeature(X.FORCE_VIDEO_CODEC)||(a(this,_n).forEach(t=>t.delete(s)),a(this,Pn).forEach((t,e)=>{t.delete(s),!(t.size!==0||e===Yt[0])&&this.disableWebcam(e)}))}},Dc=new WeakMap,Nc=new WeakMap,Et=new WeakMap,j=new WeakMap,so=new WeakMap,Mt=new WeakMap,En=new WeakMap,bn=new WeakMap,wn=new WeakMap,Vc=new WeakMap,Ss=new WeakMap,Nr=new WeakMap,Lc=new WeakMap,_n=new WeakMap,Pn=new WeakMap,Ot=new WeakMap,Ht=new WeakMap,pi=new WeakSet,no=function(){return this.context.getValue("connectionHandler")},lu=new WeakSet,jS=async function(s,t,e,r){f(this,Nc,s);try{return a(this,Ss)?await a(this,Ss):await U(this,xc,kp).call(this,s,t,e,r),U(this,hu,WS).call(this,t),{roomJoined:await U(this,uu,GS).call(this)}}catch(i){return this.logger.error("Failed to complete room join",{error:i}),{roomJoined:!1}}finally{f(this,Ss,null)}},uu=new WeakSet,GS=async function(){try{this.mediaJoined=!0;const{roomState:s}=await a(this,j).socketHandler.notifySelfJoinComplete();return f(this,Dc,s.roomUuid),f(this,bn,!0),f(this,En,!1),!0}catch(s){return this.logger.error("Error completing room join",{error:s}),this.mediaJoined=!1,!1}},hu=new WeakSet,WS=function(s){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:s,roomViewType:"groupCall",deviceInfo:{...Te.getDeviceInfo(),userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency},sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};this.context.getValue("callstats").roomJoined(e)}catch(t){this.logger.error("Error reporting room joined analytics",{error:t})}},0)},xc=new WeakSet,kp=async function(s,t,e,r){var i,n;try{(n=a(this,Lc))!=null||f(this,Lc,U(i=bv,pu,JS).call(i));const o=U(this,gu,KS).call(this);await U(this,mu,zS).call(this,s,t,e,o),await a(this,j).setupTransports({send:!0,recv:!0}),await U(this,fu,YS).call(this,r)}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}},pu=new WeakSet,JS=function(){const{ipInfo:s}=pt();if(!(s!=null&&s.loc))return;const[t,e]=s.loc.split(",").map(parseFloat);return{latitude:t,longitude:e}},gu=new WeakSet,KS=function(){var e;const s=(e=this.context.getValue("flagsmith").getValue(X.FORCE_VIDEO_CODEC))==null?void 0:e.toString(),t=y1(s);return f(this,so,t),t},mu=new WeakSet,zS=async function(s,t,e,r){await mv(async(i,n)=>{if(!a(this,Et).isConnected){n(new Error("Socket is not connected"));return}i>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${i}`});try{await a(this,j).socketHandler.joinRoom(t,s,r,e,a(this,Lc))}catch(o){throw this.logger.error("Failed to send joinRoom message after retries",{error:o}),o}},{delayTime:1e3,strategy:"exponential",maxRetryCount:1/0})},fu=new WeakSet,YS=async function(s){if(!(!this.context.getValue("flagsmith").hasFeature(X.PRECREATE_PRODUCERS)||!s))try{const e=[];if(s.canProduceVideo===H.Allowed&&e.push(this.shareWebcam(j1(!1))),s.canProduceAudio===H.Allowed){const r=q1(!1);r&&e.push(this.shareMic(r))}e.length>0&&await Promise.all(e)}catch(e){this.logger.warn("Failed to precreate producers",{error:e})}},ot=new WeakSet,Nt=function(s){return a(this,Ot).get(s)},Cn=new WeakSet,dd=function(s,t){return a(this,Ot).set(s,t)},vu=new WeakSet,QS=function(s){return a(this,Ot).delete(s)},Su=new WeakSet,XS=function(s){return{track:s,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},Tu=new WeakSet,ZS=function(s,t){return{track:s,codecOptions:t?t.map(e=>({name:e.split("/")[1]})):[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},m(up,pu),up);let re=bv;ce([y.trace("MediaNodeClient.reset",{country:y.location.country})],re.prototype,"reset",1),ce([y.trace("MediaNodeClient.joinRoom")],re.prototype,"joinRoom",1),ce([y.trace("MediaNodeClient.leaveRoom")],re.prototype,"leaveRoom",1),ce([y.trace("MediaNodeClient.activatePeers")],re.prototype,"activatePeers",1),ce([y.trace("MediaNodeClient.createConsumers")],re.prototype,"createConsumers",1),ce([y.trace("MediaNodeClient.closeConsumers")],re.prototype,"closeConsumers",1),ce([y.trace("MediaNodeClient._shareWebcam")],re.prototype,"_shareWebcam",1),ce([y.trace("MediaNodeClient.shareWebcam")],re.prototype,"shareWebcam",1),ce([y.trace("MediaNodeClient.shareScreen")],re.prototype,"shareScreen",1),ce([y.trace("MediaNodeClient.shareMic")],re.prototype,"shareMic",1),ce([y.trace("MediaNodeClient.pauseMic")],re.prototype,"pauseMic",1),ce([y.trace("MediaNodeClient.pauseWebcam")],re.prototype,"pauseWebcam",1),ce([y.trace("MediaNodeClient.resumeMic")],re.prototype,"resumeMic",1),ce([y.trace("MediaNodeClient.resumeWebcam")],re.prototype,"resumeWebcam",1),ce([y.trace("MediaNodeClient.disableWebcam")],re.prototype,"disableWebcam",1),ce([y.trace("MediaNodeClient.disableMic")],re.prototype,"disableMic",1),ce([y.trace("MediaNodeClient.disableScreenShare")],re.prototype,"disableScreenShare",1),ce([y.trace("MediaNodeClient.muteSelf")],re.prototype,"muteSelf",1),ce([y.trace("MediaNodeClient.resetVideoProducers")],re.prototype,"resetVideoProducers",1),ce([y.trace("MediaNodeClient.changeDisplayName")],re.prototype,"changeDisplayName",1),ce([y.trace("MediaNodeClient.kickPeer")],re.prototype,"kick",1),ce([y.trace("MediaNodeClient.kickAllPeers")],re.prototype,"kickAll",1),ce([y.trace("MediaNodeClient.muteAll")],re.prototype,"muteAll",1),ce([y.trace("MediaNodeClient.muteAllVideo")],re.prototype,"muteAllVideo",1),ce([y.trace("MediaNodeClient.disableAudio")],re.prototype,"disableAudio",1),ce([y.trace("MediaNodeClient.disableVideo")],re.prototype,"disableVideo",1),ce([y.trace("MediaNodeClient.pinPeer")],re.prototype,"pinPeer",1),ce([y.trace("MediaNodeClient.validateScreenShare")],re.prototype,"validateScreenShare",1);function wv(s,t){const e=s.getValue("roomNodeClient");if(e){if(e)return e;throw new Error("Room node client already set up.")}const r=new re(s,t);return s.setValue("roomNodeClient",r),r}function _v(s){const t=s.getValue("roomNodeClient");try{t==null||t.leaveRoom()}catch(e){s.getValue("logger").error("roomNodeClient::cleanupRoomNodeClient")}s.setValue("roomNodeClient",void 0)}var J1=Object.defineProperty,K1=Object.getOwnPropertyDescriptor,Bi=(s,t,e,r)=>{for(var i=r>1?void 0:r?K1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&J1(t,e,i),i};const Pv=(pS=class{constructor(s,t,e,r){m(this,Dt);p(this,"self");p(this,"authToken");m(this,Rn,void 0);p(this,"viewType");m(this,Us,void 0);m(this,ee,void 0);const{socket:i}=e,n=s.getValue("authToken");this.self=t,f(this,ee,s),this.viewType=r,this.authToken=n,f(this,Rn,i),f(this,Us,e),t.config.viewType!==Vt.Chat&&this.setupEvents()}get peerId(){return a(this,ee).getValue("peerId")}get telemetry(){return a(this,ee).getValue("telemetry")}get logger(){return a(this,ee).getValue("logger")}get mediaJoined(){return a(this,ee).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const n=pt(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=await tt.__init__(s,e,r,i,i.name,c);s.setValue("self",d);const l=s.getValue("logger");if(navigator.product!=="ReactNative"){const u=!s.getValue("flagsmith").hasFeature(X.PRECALL_BANDWIDTH_TEST);setTimeout(async()=>{const h=await d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(h)}),s.getValue("callstats").devices("AUDIO",h==null?void 0:h.filter(g=>g.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",h==null?void 0:h.filter(g=>g.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",h==null?void 0:h.filter(g=>g.kind==="audiooutput")),l.info("Callstats:: initializing");try{await s.getValue("callstats").initialize({peerId:o,engineName:Te.getDeviceInfo().engineName,env:s.getValue("env"),iceServers:await n.getICEServers(),apiBase:s.getValue("apiBase"),flags:s.getValue("flagsmith").getAllFlags(),logger:l,apiHostnames:Mm(s),skipConnectivityChecks:u}),l.info("Callstats:: initialized")}catch(g){l.error("Callstats:: initialization failed",{error:g})}},0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new Pv(s,d,t,i.viewType)}async shareMediaTracks(){var c;const{audioTrack:s,videoTrack:t,permissions:e,audioEnabled:r,videoEnabled:i,screenShareEnabled:n,screenShareTracks:o}=this.self;if(e.canProduceAudio===H.Allowed&&r)try{await a(this,Dt,rs).shareMic(s),this.self.audioEnabled||a(this,Dt,rs).pauseMic()}catch(d){this.self.disableAudio()}if(e.canProduceVideo===H.Allowed&&i)try{const d=await a(this,Dt,rs).shareWebcam(t);d&&d.id!==t.id&&a(this,ee).getValue("flagsmith").hasFeature(X.EXP_RESHARE)&&await a(this,Dt,rs).shareWebcam(d),this.self.videoEnabled||a(this,Dt,rs).pauseWebcam()}catch(d){this.self.disableVideo()}if(e.canProduceScreenshare===H.Allowed&&n)try{await((c=a(this,Dt,rs))==null?void 0:c.shareScreen({video:o.video,audio:o.audio}))}catch(d){this.self.disableScreenShare()}}async kickHandler(s){let t="kicked";(s==null?void 0:s.kickType)==="kickAll"&&(t="ended"),this.leaveRoom(t)}waitlistedHandler(){this.logger.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(this.logger.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){this.logger.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(this.logger.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){this.logger.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}async resetSelf(s){a(this,ee).getValue("callstats").callEnded(),a(this,Dt,rs).reset(),s&&await this.joinRoom(s)}setupEvents(){a(this,ee).getValue("peerSessionStore").on(R.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&this.shareMediaTracks()}),a(this,ee).getValue("peerSessionStore").on(R.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,ee).getValue("peerSessionStore").on(R.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,ee).getValue("peerSessionStore").on(R.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,ee).getValue("peerSessionStore").on(R.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),a(this,ee).getValue("peerSessionStore").on(R.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;let{peerId:t}=this;s&&a(this,ee).getValue("flagsmith").hasFeature(X.REFRESH_ID_ON_DISCONNECTION)&&(t=Si()),a(this,Rn).updateURL(t),a(this,ee).getValue("telemetry").resetPeerId(t),pt().setHeader("tracing-id",t),nr.remapContext(t,a(this,ee)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,ee).getValue("peerSessionStore").on(R.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,Us).on(F.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,Us).on(Yd.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&a(this,ee).getValue("peerSessionStore").emit(R.UPDATE_PERMISSIONS,t.patch)})}),a(this,Us).on(F.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,Us).on(F.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,Us).on(F.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,ee).getValue("peerSessionStore").onAsync(R.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,ee).getValue("peerSessionStore").on(R.PRODUCER_SCORE_UPDATE,({score:s,kind:t,appData:e,scoreStats:r})=>{var n;const i=(n=e==null?void 0:e.screenShare)!=null?n:!1;this.self.emit("mediaScoreUpdate",{kind:t,isScreenshare:i,score:s,participantId:this.self.id,scoreStats:r})}),a(this,ee).getValue("peerSessionStore").on(R.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),a(this,ee).getValue("callstats").audioOff())}),a(this,ee).getValue("peerSessionStore").on(R.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),a(this,ee).getValue("callstats").videoOff())}),a(this,ee).getValue("peerSessionStore").onAsync(R.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,ee).getValue("peerSessionStore").on(R.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{const{peer:t}=await a(this,Us).joinRoom(this.self);a(this,Us).socket.flush();const e=Dh(t.stageType);if(a(this,ee).setValue("stageStatus",e,!1),t.waitlisted){this.waitlistedHandler();return}await this.joinMediaRoom(s),a(this,ee).notify("stageStatus")}catch(t){throw this.logger.error("Error in joinRoom",{error:t}),t}}async leaveRoom(s="left"){var t,e;if(this.logger.info(`Leaving room with state: ${s}`),(t=a(this,ee).getValue("roomSocketHandler"))==null||t.cleanup(),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),a(this,ee).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),a(this,ee).notify("stageStatus");try{(e=a(this,Rn))==null||e.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}_v(a(this,ee)),this.self.roomState=s,this.self.emit("roomLeft",{state:s}),this.logger.info(`roomLeft event emitted with state: ${s}`)}async joinMediaRoom(s=!1){var n,o;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=a(this,ee).getAllValues();try{if(e===Vt.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}wv(a(this,ee),{socket:a(this,Rn),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:u}=(o=await((n=a(this,Dt,rs))==null?void 0:n.joinRoom(this.self.name,r,s,s,{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l})))!=null?o:{};if(!u)return;i==="ON_STAGE"&&await this.shareMediaTracks(),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s})}catch(c){throw this.logger.error("Error:SelfController.mediaRoomJoin",{error:c}),new C("Error: could not join media room","0002")}}async leaveMediaRoom(s){const t=a(this,ee).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===Vt.Webinar)&&a(this,Dt,rs)&&(a(this,Dt,rs).mediaJoined&&s!=="disconnected"&&await a(this,Dt,rs).leaveRoom(),!(s==="stageLeft"&&t===Vt.Livestream)&&(a(this,Dt,rs).mediaJoined=!1))}async cleanupSelf(){await this.self.disableAudio(),await this.self.disableVideo(),await this.self.disableScreenShare(),this.self.cleanUpTracks(),this.self.destructMediaHandler(),navigator.isReactNative||this.self.removeDocumentEventListeners()}},Rn=new WeakMap,Us=new WeakMap,ee=new WeakMap,Dt=new WeakSet,rs=function(){return a(this,ee).getValue("roomNodeClient")},pS);let jr=Pv;Bi([y.trace("SelfController.resetSelf")],jr.prototype,"resetSelf",1),Bi([y.trace("SelfController.setupEvents")],jr.prototype,"setupEvents",1),Bi([y.trace("SelfController.joinRoom")],jr.prototype,"joinRoom",1),Bi([y.trace("SelfController.leaveRoom")],jr.prototype,"leaveRoom",1),Bi([y.trace("SelfController.joinMediaRoom")],jr.prototype,"joinMediaRoom",1),Bi([y.trace("SelfController.leaveMediaRoom")],jr.prototype,"leaveMediaRoom",1),Bi([y.trace("SelfController.init")],jr,"init",1);class z1{constructor(t){m(this,Uc,void 0);f(this,Uc,t)}on(t,e){let r;t===F.roomPeerCount?r=pf.fromBinary.bind(pf):r=Af.fromBinary.bind(Af),a(this,Uc).on(t,({payload:i})=>{if(t===F.roomPeerCount&&!i)return;const n=r(i);e(n)})}}Uc=new WeakMap;class Y1{constructor(t,e){m(this,Fc,void 0);m(this,Bc,void 0);f(this,Fc,e),f(this,Bc,t)}get logger(){return a(this,Bc).getValue("logger")}on(t,e){let r,i;switch(t){case F.transcript:{r=ph.fromBinary.bind(ph),i=ph.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,Fc).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("aiSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}Fc=new WeakMap,Bc=new WeakMap;var Q1=Object.defineProperty,X1=Object.getOwnPropertyDescriptor,ep=(s,t,e,r)=>{for(var i=r>1?void 0:r?X1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&Q1(t,e,i),i};class ml{constructor(t,e){m(this,Vr,void 0);m(this,ro,void 0);f(this,Vr,e),f(this,ro,t)}get logger(){return a(this,ro).getValue("logger")}get telemetry(){return a(this,ro).getValue("telemetry")}getPolls(){return a(this,Vr).sendMessagePromise(lr.getPolls)}createPoll(t,e,r=!1,i=!1){const n={anonymous:r,hideVotes:i,question:t,options:e};return a(this,Vr).sendMessage(lr.createPoll,HM.toBinary(n))}votePoll(t,e){const r={index:e,pollId:t};return a(this,Vr).sendMessage(lr.votePoll,jM.toBinary(r))}on(t,e){let r,i;switch(t){case lr.updatePoll:case lr.createPoll:case lr.votePoll:{r=Ch.fromBinary.bind(Ch),i=Ch.create();break}}a(this,Vr).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("pollSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}removeListeners(t){a(this,Vr).removeListeners(t)}}Vr=new WeakMap,ro=new WeakMap,ep([y.trace("PollSocketHandler.getPolls")],ml.prototype,"getPolls",1),ep([y.trace("PollSocketHandler.createPoll")],ml.prototype,"createPoll",1),ep([y.trace("PollSocketHandler.votePoll")],ml.prototype,"votePoll",1);var Z1=Object.defineProperty,eN=Object.getOwnPropertyDescriptor,tN=(s,t,e,r)=>{for(var i=r>1?void 0:r?eN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&Z1(t,e,i),i};class Cv{constructor(t,e){p(this,"socket");m(this,ts,void 0);f(this,ts,t),this.socket=e,this.handleSocketEvents(),a(this,ts).setValue("roomSocketHandler",this)}get telemetry(){return a(this,ts).getValue("telemetry")}get logger(){return a(this,ts).getValue("logger")}cleanup(){var t;try{(t=this.socket)==null||t.disconnect()}catch(e){this.logger.error("roomSocketHandler::cleanup")}}async joinRoom(t){var i;this.socket.joinAttempted=!0;const e={capabilities:[],peer:{displayName:(i=t.name)!=null?i:"Participant",customParticipantId:t.customParticipantId,peerId:t.id,userId:t.userId,displayPictureUrl:t.picture,waitlisted:!1},roomUuid:""},r=this.socket.sendMessagePromise(F.joinRoom,II.toBinary(e));try{const{peer:n}=$n.fromBinary((await r).payload);a(this,ts).getValue("connectionHandler").socketJoined=!0,a(this,ts).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_ROOM_JOINED,{peer:n});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=await Promise.all([o,c]);return a(this,ts).getValue("peerSessionStore").emit(R.ROOM_STATE,d),a(this,ts).getValue("peerSessionStore").emit(R.SOCKET_PEERS,l),{peer:n}}catch(n){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:n}),new C("Error: RoomSocketHandler.joinRoom failed.","0002",this.logger,n)}}async getAllAddedParticipants(){try{return pA.fromBinary((await this.socket.sendMessagePromise(F.getAllAddedParticipants)).payload).participants.map(({id:e,...r})=>({...r,userId:e}))}catch(t){return[]}}async getRoomPeers(t,e,r){let i;try{const n={seachQuery:t,limit:e,offset:r},o=await this.socket.sendMessagePromise(F.getRoomPeersInfo,TI.toBinary(n));i=fh.fromBinary(o.payload)}catch(n){this.logger.error("getRoomPeers::binary_decode_error",{error:n})}return i}async getRoomPeersNonPaginated(){let t;try{const e=await this.socket.sendMessagePromise(F.getRoomPeersInfo);t=fh.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getStagePeers(){let t;try{const e=await this.socket.sendMessagePromise(F.getRoomPeersInfo);t=fh.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getPeerInfo(t){let e;try{const r=await this.socket.sendMessagePromise(F.getPeerInfo,ff.toBinary({peerId:t}));e=$n.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=mf.create();try{const e=await this.socket.sendMessagePromise(F.getRoomInfo);t=mf.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=bf.create();try{const e=await this.socket.sendMessagePromise(F.getRoomStageState);t=bf.fromBinary(e.payload)}catch(e){this.logger.error("getRoomStageState::binary_decode_error",{error:e})}return t}async broadcastMessage(t,e){const r={type:t,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(F.broadcastMessage,bo.toBinary(r))}async broadcastToMeetings(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:1};return this.socket.sendMessagePromise(F.broadcastToEntity,bo.toBinary(i))}async broadcastToPeers(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:0};return this.socket.sendMessage(F.broadcastToEntity,bo.toBinary(i))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(F.leaveRoom,MI.toBinary({}))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(F.kick,yf.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(F.kickAll,nf.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(F.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(F.acceptWaitingRoomRequests,TA.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(F.denyWaitingRoomRequests,EA.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(Yd.updateUserPreset,YA.toBinary(r))}handleSocketEvents(){this.socket.on(F.broadcastMessage,({payload:t})=>{try{const e=bo.fromBinary(t);a(this,ts).getValue("peerSessionStore").emit(R.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode broadcast message:",e)}}),this.socket.on(F.broadcastToEntity,({payload:t})=>{try{const e=bo.fromBinary(t);a(this,ts).getValue("peerSessionStore").emit(R.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode peer broadcast message:",e)}})}on(t,e){let r,i;switch(t){case F.joinRoom:case F.leaveRoom:case F.kick:case F.kickAll:{r=$n.fromBinary.bind($n),i=$n.create();break}case F.getWaitingRoomRequests:{r=(n,o)=>n?Ef.fromBinary(n,o):{requests:[]},i=Ef.create();break}case F.recordingPaused:case F.recordingStarted:case F.recordingStopped:{r=Nf.fromBinary.bind(Nf);break}case Yd.updateUserPreset:{r=_f.fromBinary.bind(_f);break}case _s.peerJoinedBroadcast:case $r.peerJoinedBroadcast:{r=cf.fromBinary.bind(cf);break}case _s.selfJoinComplete:case $r.selfJoinComplete:{r=uh.fromBinary.bind(uh);break}case _s.globalPeerPinBroadcast:case $r.globalPeerPinBroadcast:{r=uf.fromBinary.bind(uf);break}case _s.selectedPeer:case $r.selectedPeer:{r=lh.fromBinary.bind(lh);break}case _s.selectedPeerDiff:case $r.selectedPeerDiff:{r=of.fromBinary.bind(of);break}case _s.leaveRoom:case $r.leaveRoom:{r=hh.fromBinary.bind(hh);break}}this.socket.on(t,({payload:n})=>{let o=i;if(!r)return e(void 0);try{o=r(n)}catch(c){this.logger.error("roomSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}async getUserPermissions(t){const e={userIds:[t]};try{const r=await this.socket.sendMessagePromise(Yd.getUserPresets,qA.toBinary(e)),i=JA.fromBinary(r.payload).peerPresets[0],n=new TextDecoder().decode(i.preset),o=JSON.parse(n).permissions;return{chat:o.chat,polls:o.polls,plugins:o.plugins}}catch(r){throw this.logger.error("Error in getting user preset",{error:r}),r}}}ts=new WeakMap,tN([y.trace("RoomSocketHandler.joinRoom")],Cv.prototype,"joinRoom",1);class sN{constructor(t){m(this,qt,void 0);f(this,qt,t)}async getStageRequests(){const{payload:t}=await a(this,qt).sendMessagePromise(F.getStageRequests);return t?Ph.fromBinary(t):{stageRequests:[]}}requestAccess(){a(this,qt).sendMessage(F.requestStageAccess)}cancelRequestAccess(){a(this,qt).sendMessage(F.cancelStageRequest)}async grantAccess(t){const e={userIds:t};a(this,qt).sendMessage(F.grantStageAccess,OM.toBinary(e))}async denyAccess(t){const e={userIds:t};a(this,qt).sendMessage(F.denyStageAccess,NM.toBinary(e))}joinStage(){return a(this,qt).sendMessagePromise(F.joinStage,void 0,void 0,F.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return a(this,qt).sendMessagePromise(F.leaveStage,Of.toBinary(e),void 0,F.peerStageStatusUpdate)}kick(t){const e={userIds:t};return a(this,qt).sendMessagePromise(F.leaveStage,Of.toBinary(e))}on(t,e){let r;switch(t){case F.grantStageAccess:case F.denyStageAccess:{r=void 0;break}case F.getStagePeers:{r=Mf.fromBinary.bind(Mf);break}case F.getStageRequests:case F.requestStageAccess:case F.cancelStageRequest:{r=Ph.fromBinary.bind(Ph);break}case F.peerStageStatusUpdate:{r=hf.fromBinary.bind(hf);break}}a(this,qt).on(t,({payload:i,id:n})=>{if(!i||!r)return e(void 0,n);const o=r(i);return e(o,n)})}async getPeerInfo(t){const e=await a(this,qt).sendMessagePromise(F.getPeerInfo,ff.toBinary({peerId:t}));return $n.fromBinary(e.payload)}}qt=new WeakMap;class rN{constructor(t,e){m(this,Qe,void 0);m(this,$c,void 0);f(this,Qe,e),f(this,$c,t)}get logger(){return a(this,$c).getValue("logger")}addPlugin(t,e){a(this,Qe).sendMessage(G.addPlugin,z0.toBinary({pluginId:t,staggered:e}))}removePlugin(t){a(this,Qe).sendMessage(G.removePlugin,Q0.toBinary({pluginId:t,staggered:!1}))}async getActivePlugins(){const{payload:t}=await a(this,Qe).sendMessagePromise(G.getPlugins);return t?yM.fromBinary(t):{plugins:[]}}customPluginEventToRoom(t,e,r){const i={pluginId:t,pluginData:new TextEncoder().encode(JSON.stringify(e))};a(this,Qe).sendMessage(G.customPluginEventToRoom,oM.toBinary(i),r)}customPluginEventToPeers(t,e,r,i){const n={pluginId:t,peerIds:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};a(this,Qe).sendMessage(G.customPluginEventToPeers,dM.toBinary(n),i)}enablePluginForRoom(t,e){a(this,Qe).sendMessage(G.enablePluginForRoom,Z0.toBinary({pluginId:t}),e)}enablePluginForPeers(t,e,r){a(this,Qe).sendMessage(G.enablePluginForPeers,rM.toBinary({pluginId:t,peerIds:e}),r)}disablePluginForRoom(t,e){a(this,Qe).sendMessage(G.disablePluginForRoom,tM.toBinary({pluginId:t}),e)}disablePluginForPeers(t,e,r){a(this,Qe).sendMessage(G.disablePluginForPeers,nM.toBinary({pluginId:t,peerIds:e}),r)}storeInsertKeys(t,e,r,i){const n={pluginId:t,storeName:e,insertKeys:r.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};a(this,Qe).sendMessage(G.storeInsertKeys,Cf.toBinary(n),i)}storeGetKeys(t,e,r,i){const n={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};a(this,Qe).sendMessage(G.storeGetKeys,pM.toBinary(n),i)}storeDeleteKeys(t,e,r,i){const n={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,Qe).sendMessage(G.storeDeleteKeys,mM.toBinary(n),i)}storeDelete(t,e,r){a(this,Qe).sendMessage(G.storeDelete,vM.toBinary({pluginId:t,storeName:e}),r)}getPluginDataOld(t,e){this.logger.info("getPluginDataOld",{plugin:{id:t,storeName:e}})}storePluginDataOld(t,e,r){const i={pluginId:t,storeName:e,insertKeys:[{storeKey:r.key,payload:new TextEncoder().encode(JSON.stringify(r))}]};a(this,Qe).sendMessage(G.storeInsertKeys,Cf.toBinary(i))}on(t,e){let r;switch(t){case G.addPlugin:case G.enablePluginForPeers:case G.enablePluginForRoom:{r=_h.fromBinary.bind(_h);break}case G.removePlugin:case G.disablePluginForPeers:case G.disablePluginForRoom:{r=Rf.fromBinary.bind(Rf);break}case G.customPluginEventToPeers:case G.customPluginEventToRoom:{r=If.fromBinary.bind(If);break}case G.storeInsertKeys:case G.storeGetKeys:case G.storeDeleteKeys:case G.storeDelete:{r=kf.fromBinary.bind(kf);break}}a(this,Qe).on(t,({payload:i,id:n})=>{const o=r(i);return e(o,n)})}}Qe=new WeakMap,$c=new WeakMap;var iN=Object.defineProperty,nN=(s,t,e)=>t in s?iN(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,aN=(s,t,e)=>(nN(s,typeof t!="symbol"?t+"":t,e),e),tp=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},O=(s,t,e)=>(tp(s,t,"read from private field"),e?e.call(s):t.get(s)),Ee=(s,t,e)=>{if(t.has(s))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(s):t.set(s,e)},ie=(s,t,e,r)=>(tp(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),Pe=(s,t,e)=>(tp(s,t,"access private method"),e),fl={},oN={get exports(){return fl},set exports(s){fl=s}},Yn=typeof Reflect=="object"?Reflect:null,Rv=Yn&&typeof Yn.apply=="function"?Yn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},vl;Yn&&typeof Yn.ownKeys=="function"?vl=Yn.ownKeys:Object.getOwnPropertySymbols?vl=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:vl=function(s){return Object.getOwnPropertyNames(s)};function cN(s){console&&console.warn&&console.warn(s)}var kv=Number.isNaN||function(s){return s!==s};function de(){de.init.call(this)}oN.exports=de,fl.once=hN,de.EventEmitter=de,de.prototype._events=void 0,de.prototype._eventsCount=0,de.prototype._maxListeners=void 0;var Iv=10;function Sl(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(de,"defaultMaxListeners",{enumerable:!0,get:function(){return Iv},set:function(s){if(typeof s!="number"||s<0||kv(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");Iv=s}}),de.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},de.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||kv(s))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+s+".");return this._maxListeners=s,this};function Av(s){return s._maxListeners===void 0?de.defaultMaxListeners:s._maxListeners}de.prototype.getMaxListeners=function(){return Av(this)},de.prototype.emit=function(s){for(var t=[],e=1;e<arguments.length;e++)t.push(arguments[e]);var r=s==="error",i=this._events;if(i!==void 0)r=r&&i.error===void 0;else if(!r)return!1;if(r){var n;if(t.length>0&&(n=t[0]),n instanceof Error)throw n;var o=new Error("Unhandled error."+(n?" ("+n.message+")":""));throw o.context=n,o}var c=i[s];if(c===void 0)return!1;if(typeof c=="function")Rv(c,this,t);else for(var d=c.length,l=Vv(c,d),e=0;e<d;++e)Rv(l[e],this,t);return!0};function Mv(s,t,e,r){var i,n,o;if(Sl(e),n=s._events,n===void 0?(n=s._events=Object.create(null),s._eventsCount=0):(n.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),n=s._events),o=n[t]),o===void 0)o=n[t]=e,++s._eventsCount;else if(typeof o=="function"?o=n[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=Av(s),i>0&&o.length>i&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=s,c.type=t,c.count=o.length,cN(c)}return s}de.prototype.addListener=function(s,t){return Mv(this,s,t,!1)},de.prototype.on=de.prototype.addListener,de.prototype.prependListener=function(s,t){return Mv(this,s,t,!0)};function dN(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Ov(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=dN.bind(r);return i.listener=e,r.wrapFn=i,i}de.prototype.once=function(s,t){return Sl(t),this.on(s,Ov(this,s,t)),this},de.prototype.prependOnceListener=function(s,t){return Sl(t),this.prependListener(s,Ov(this,s,t)),this},de.prototype.removeListener=function(s,t){var e,r,i,n,o;if(Sl(t),r=this._events,r===void 0)return this;if(e=r[s],e===void 0)return this;if(e===t||e.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[s],r.removeListener&&this.emit("removeListener",s,e.listener||t));else if(typeof e!="function"){for(i=-1,n=e.length-1;n>=0;n--)if(e[n]===t||e[n].listener===t){o=e[n].listener,i=n;break}if(i<0)return this;i===0?e.shift():lN(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this},de.prototype.off=de.prototype.removeListener,de.prototype.removeAllListeners=function(s){var t,e,r;if(e=this._events,e===void 0)return this;if(e.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):e[s]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete e[s]),this;if(arguments.length===0){var i=Object.keys(e),n;for(r=0;r<i.length;++r)n=i[r],n!=="removeListener"&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=e[s],typeof t=="function")this.removeListener(s,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(s,t[r]);return this};function Dv(s,t,e){var r=s._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i=="function"?e?[i.listener||i]:[i]:e?uN(i):Vv(i,i.length)}de.prototype.listeners=function(s){return Dv(this,s,!0)},de.prototype.rawListeners=function(s){return Dv(this,s,!1)},de.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):Nv.call(s,t)},de.prototype.listenerCount=Nv;function Nv(s){var t=this._events;if(t!==void 0){var e=t[s];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}de.prototype.eventNames=function(){return this._eventsCount>0?vl(this._events):[]};function Vv(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function lN(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function uN(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function hN(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,n),r(o)}function n(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}Lv(s,t,n,{once:!0}),t!=="error"&&pN(s,i,{once:!0})})}function pN(s,t,e){typeof s.on=="function"&&Lv(s,"error",t,e)}function Lv(s,t,e,r){if(typeof s.on=="function")r.once?s.once(t,e):s.on(t,e);else if(typeof s.addEventListener=="function")s.addEventListener(t,function i(n){r.once&&s.removeEventListener(t,i),e(n)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}class gN extends S{constructor(){super("message.v1.SocketMessage",[{no:1,name:"event",kind:"scalar",T:13},{no:2,name:"id",kind:"scalar",opt:!0,T:9},{no:3,name:"payload",kind:"scalar",opt:!0,T:12},{no:4,name:"metadata",kind:"scalar",opt:!0,T:12}])}}const xv=new gN;class Uv{static encode(t){return xv.toBinary(t)}static decode(t){return xv.fromBinary(new Uint8Array(t))}}function mN(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Gr;class fN{constructor(t={}){aN(this,"opts"),Ee(this,Gr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},ie(this,Gr,0)}async wait(){ie(this,Gr,O(this,Gr)+1);const t=mN(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**O(this,Gr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return O(this,Gr)}reset(){ie(this,Gr,0)}}Gr=new WeakMap;const Wr={debug:0,info:1,warn:2,error:3};var $i,Hi;class vN{constructor(t){Ee(this,$i,void 0),Ee(this,Hi,void 0),ie(this,$i,console),ie(this,Hi,t)}debug(...t){Wr[O(this,Hi)]>Wr.debug||O(this,$i).debug("[Sockrates]:",...t)}info(...t){Wr[O(this,Hi)]>Wr.info||O(this,$i).info("[Sockrates]:",...t)}warn(...t){Wr[O(this,Hi)]>Wr.warn||O(this,$i).warn("[Sockrates]:",...t)}error(...t){Wr[O(this,Hi)]>Wr.error||O(this,$i).error("[Sockrates]:",...t)}}$i=new WeakMap,Hi=new WeakMap;var Fv=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(Fv||{});const SN="2",TN="3";var Ne,Qn,Ce,Fe,Jr,st,gr,Kr,Is,Xn,mr,sp,Bv,Do,Tl,rp,$v,ip,Hv,yl,np,ap,qv,No,El,Vo,bl,wl,op,Zn,Lo,xo,_l;class yN{constructor(t,e){var g,v,E,b,_,w,L,B,N,$;Ee(this,sp),Ee(this,Do),Ee(this,rp),Ee(this,ip),Ee(this,yl),Ee(this,ap),Ee(this,No),Ee(this,Vo),Ee(this,wl),Ee(this,Zn),Ee(this,xo),Ee(this,Ne,void 0),Ee(this,Qn,void 0),Ee(this,Ce,void 0),Ee(this,Fe,void 0),Ee(this,Jr,void 0),Ee(this,st,void 0),Ee(this,gr,void 0),Ee(this,Kr,void 0),Ee(this,Is,void 0),Ee(this,Xn,void 0),Ee(this,mr,void 0);var r,i,n,o,c,d,l,u,h;ie(this,Qn,t),ie(this,Jr,[]),ie(this,st,new fl),ie(this,gr,!0),ie(this,Is,!1),ie(this,Ce,e!=null?e:{}),(g=(r=O(this,Ce)).autoReconnect)!=null||(r.autoReconnect=!0),(v=(i=O(this,Ce)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(E=(n=O(this,Ce)).pingTimeout)!=null||(n.pingTimeout=3e4),(b=(o=O(this,Ce)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(_=(c=O(this,Ce)).debug)!=null||(c.debug=!0),(w=(d=O(this,Ce)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(L=(l=O(this,Ce)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(B=(u=O(this,Ce)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),(N=(h=O(this,Ce)).flushOnReconnect)!=null||(h.flushOnReconnect=!1),ie(this,Kr,{code:void 0,reason:void 0}),ie(this,Fe,($=O(this,Ce).logger)!=null?$:new vN(O(this,Ce).debug?"debug":"info")),ie(this,mr,new fN)}get readyState(){var t;return(t=O(this,Ne))==null?void 0:t.readyState}get url(){return O(this,Qn)}updateURL(t){ie(this,Qn,t),Pe(this,ap,qv).call(this)}get config(){return O(this,Ce)}get sendQueue(){return O(this,Jr)}flush(){if(!O(this,Ce).queueOnDisconnect)return!1;const t=[];return O(this,Jr).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),ie(this,Jr,t),O(this,Jr)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){O(this,Fe).debug("Websocket was already connecting or connected.");return}if(O(this,gr)!==!1)return new Promise((e,r)=>{Pe(this,Zn,Lo).call(this),Pe(this,xo,_l).call(this);try{ie(this,Ne,new WebSocket(Pe(this,sp,Bv).call(this,O(this,Qn)))),O(this,Ne).binaryType="arraybuffer",O(this,Fe).debug("Connecting");const i=setTimeout(()=>{O(this,Fe).debug("Connection timeout. Closing socket"),ie(this,gr,!0),Pe(this,xo,_l).call(this),O(this,Ne).close(3001,"Connection Timeout"),O(this,Ce).autoReconnect&&!O(this,Is)&&(O(this,st).emit("reconnecting"),Pe(this,No,El).call(this)),r(new Error("Connection timed out!"))},O(this,Ce).connectionTimeout);O(this,Ne).onopen=()=>{O(this,Fe).debug(`Ready State: ${Fv[O(this,Ne).readyState]}`),i&&clearTimeout(i),Pe(this,wl,op).call(this),ie(this,Kr,{code:void 0,reason:void 0}),O(this,st).emit("connected"),O(this,Ce).flushOnReconnect&&this.flush(),e()},O(this,Ne).onclose=n=>{try{i&&clearTimeout(i);const{code:o,reason:c}=n;r(c),O(this,Fe).debug("Socket closed. Close event:",{event:n}),O(this,Fe).debug(`Connection closed code: ${o}`),O(this,Fe).debug(`Connection closed reason: ${c}`),O(this,Is)||Pe(this,yl,np).call(this,o,c)}catch(o){Pe(this,Do,Tl).call(this,o)}},O(this,Ne).onerror=n=>{Pe(this,Do,Tl).call(this,n)},O(this,Ne).onmessage=n=>Pe(this,rp,$v).call(this,n)}catch(i){Pe(this,Do,Tl).call(this,i,r)}})}send(t,e,r,i){const n={event:t,id:e,payload:r,metadata:i};if(O(this,Ce).queueOnDisconnect&&(!O(this,Ne)||O(this,Ne).readyState!==1))return O(this,Fe).debug("Queuing message since socket is not connected!",n),O(this,Jr).push(n),!1;const o=Uv.encode(n);return Pe(this,Vo,bl).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return Pe(this,Vo,bl).call(this,t)}receive(t,e){return O(this,st).on(t.toString(),e)}on(t,e){if(typeof t=="string"&&(t==="connected"||t==="disconnected"||t==="errored"||t==="reconnected"||t==="reconnecting"||t==="reconnectAttempt"||t==="reconnectFailure"||t==="failed")){O(this,st).on(t,e);return}this.receive(t,e)}removeAllListeners(){O(this,st).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){O(this,st).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){O(this,st).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){ie(this,gr,!1),Pe(this,Zn,Lo).call(this),this.removeAllListeners(),ie(this,Kr,{code:1e3,reason:"Sockrates disconnect method called"}),O(this,Ne).close(1e3,"Sockrates disconnect method called.")}}Ne=new WeakMap,Qn=new WeakMap,Ce=new WeakMap,Fe=new WeakMap,Jr=new WeakMap,st=new WeakMap,gr=new WeakMap,Kr=new WeakMap,Is=new WeakMap,Xn=new WeakMap,mr=new WeakMap,sp=new WeakSet,Bv=function(s){if(s.startsWith("ws://")||s.startsWith("wss://"))return s;if(s.startsWith("https://"))return`wss://${s.substring(8)}`;if(s.startsWith("http://"))return`ws://${s.substring(7)}`;throw new Error("Invalid URL. URL must start with http(s):// or ws(s)://.")},Do=new WeakSet,Tl=function(s,t){O(this,Fe).error("Error:",{error:s}),O(this,st).emit("errored",{error:s}),t==null||t(s)},rp=new WeakSet,$v=function(s){if(Pe(this,wl,op).call(this),s.data===SN){O(this,Fe).debug("Received ping from server"),Pe(this,Vo,bl).call(this,TN);return}const t=Uv.decode(s.data),{id:e,payload:r}=t;O(this,Fe).debug("Received message",{event:t.event,messageID:e}),O(this,st).emit(t.event.toString(),{id:e,payload:r})},ip=new WeakSet,Hv=function(){return O(this,Ne).readyState===1},yl=new WeakSet,np=function(s,t){ie(this,Kr,{reason:t,code:s}),O(this,st).emit("disconnected",{code:s,reason:t})},ap=new WeakSet,qv=function(){const{reason:s,code:t}=O(this,Kr);t&&t!==1e3&&O(this,gr)&&O(this,Ce).autoReconnect&&!O(this,Is)&&(O(this,Fe).debug(`Triggering reconnection due to ${s}.`),O(this,st).emit("reconnecting"),Pe(this,No,El).call(this))},No=new WeakSet,El=async function(s=!0){if(s&&O(this,Is)){O(this,Fe).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(O(this,Is)||O(this,mr).reset(),O(this,Ce).maxReconnectionAttempts!==null&&O(this,mr).getAttempts()>=O(this,Ce).maxReconnectionAttempts){O(this,st).emit("failed"),ie(this,Is,!1);return}ie(this,Is,!0),Pe(this,xo,_l).call(this),Pe(this,Zn,Lo).call(this);try{if(await O(this,mr).wait(),O(this,gr)===!1)return;if(O(this,Fe).debug(`Reconnection attempt ${O(this,mr).getAttempts()}`),O(this,st).emit("reconnectAttempt",{attempt:O(this,mr).getAttempts()}),await this.connect(),!Pe(this,ip,Hv).call(this))throw Error("Reconnect Failed");ie(this,Is,!1),ie(this,Kr,{code:void 0,reason:void 0}),O(this,st).emit("reconnected")}catch(t){O(this,Fe).debug("Failed to reconnect."),O(this,st).emit("reconnectFailure",{attempt:O(this,mr).getAttempts()}),Pe(this,No,El).call(this,!1)}},Vo=new WeakSet,bl=function(s){try{return O(this,Ne).send(s),!0}catch(t){return O(this,Fe).error(t.message),!1}},wl=new WeakSet,op=function(){this.config.disconnectOnPingTimeout&&(O(this,Fe).debug("Resetting ping timeout"),Pe(this,Zn,Lo).call(this),ie(this,Xn,setTimeout(()=>{var s;O(this,Fe).debug("Disconnecting the socket due to ping timeout"),ie(this,gr,!0);const t=3002,e="Ping timeout";(s=O(this,Ne))==null||s.close(t,e),Pe(this,yl,np).call(this,t,e)},O(this,Ce).pingTimeout)))},Zn=new WeakSet,Lo=function(){O(this,Xn)&&(clearTimeout(O(this,Xn)),ie(this,Xn,void 0))},xo=new WeakSet,_l=function(){O(this,Ne)&&(O(this,Ne).onopen=void 0,O(this,Ne).onerror=void 0,O(this,Ne).onmessage=void 0,O(this,Ne).onclose=void 0)};var EN=Object.defineProperty,bN=Object.getOwnPropertyDescriptor,Pl=(s,t,e,r)=>{for(var i=r>1?void 0:r?bN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&EN(t,e,i),i};const jv=65535,wN=3e3,Gv=(gS=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){m(this,Oe);m(this,Hc);m(this,qc);m(this,gi,void 0);m(this,Me,void 0);p(this,"roomName");p(this,"authToken");p(this,"capabilities");m(this,Ts,void 0);m(this,ct,void 0);var n;if(!t||!e||!r)throw new C("peerId, meetingId, or authToken can not be empty","0404");f(this,Ts,void 0),f(this,ct,s),this.capabilities=i,this.roomName=e,this.authToken=r,f(this,gi,U(this,Hc,Ip).call(this,t)),f(this,Me,new yN(a(this,gi),{autoReconnect:!0,disconnectOnPingTimeout:(n=i.includes("PING"))!=null?n:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,Oe,je).socketJoinAttempted}set joinAttempted(s){a(this,Oe,je).socketJoinAttempted=s}get telemetry(){return a(this,ct).getValue("telemetry")}get logger(){return a(this,ct).getValue("logger")}get peerId(){return a(this,ct).getValue("peerId")}updateURL(s){s!==this.peerId&&(f(this,gi,U(this,Hc,Ip).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),a(this,Me).updateURL(a(this,gi))}static getSocketEdgeDomain(s){return _i({servicePrefix:"socket-edge",baseURI:s})}get url(){return a(this,gi)}async connect(){a(this,Oe,je).socketJoinAttempted=!0,await a(this,Me).connect(),a(this,Oe,je).socketJoinAttempted=!0,a(this,Oe,je).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}disconnect(){a(this,Oe,je).socketJoinAttempted=!1,a(this,Me).disconnect(),a(this,Oe,je).socketJoinAttempted=!0,a(this,Oe,je).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return a(this,Me).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return a(this,ct).getValue("telemetry").injectContext(r),a(this,Me).send(s,e!=null?e:U(this,qc,Ap).call(this),t,new TextEncoder().encode(JSON.stringify(r)))}sendMessagePromise(s,t,e,r){const i=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:s,timeout:i,protobuf:t,messageId:e,resp:r})}sendMessagePromiseWithTimeout({event:s,timeout:t,protobuf:e,messageId:r,resp:i}){const n=i!=null?i:s;return new Promise((o,c)=>{const d=(E,b)=>{a(this,Me).removeListener(n,E),a(this,Me).removeListener(jv,b),a(this,Me).removeListener($r.errorResponse,b),a(this,Me).removeListener(_s.errorResponse,b)},l=r!=null?r:U(this,qc,Ap).call(this),u={};a(this,ct).getValue("telemetry").injectContext(u);const g=({id:E,payload:b})=>{if(l===E){let _;try{const w=uk.fromBinary(b);_=new Error(w.errorMessage)}catch(w){_=new Error("failed to parse error message",{cause:w});try{const L=hI.fromBinary(b);_=new Error(L.message)}catch(L){_=new Error("failed to parse error message",{cause:L})}}c(_),d(v,g)}},v=({id:E,payload:b})=>{l===E&&(o({id:E,payload:b}),d(v,g))};a(this,Me).on(n,v),a(this,Me).on(jv,g),a(this,Me).on($r.errorResponse,g),a(this,Me).on(_s.errorResponse,g),setTimeout(()=>{d(v,g),c(new Error(`request timeout for callback eventId:${s}`))},t),a(this,Me).send(s,l,e,new TextEncoder().encode(JSON.stringify(u)))})}on(s,t){a(this,Me).on(s,t)}onStateEvent(s,t){a(this,Me).on(s,t)}removeListener(s,t){a(this,Me).removeListener(s,t)}removeListeners(s){a(this,Me).removeListeners(s)}flush(){return a(this,Me).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{this.logger.info("SocketService::Connected to socket-edge"),a(this,Ts)&&(clearTimeout(a(this,Ts)),f(this,Ts,void 0)),a(this,Oe,je).updateSocketConnectionState("connected")}),this.onStateEvent("disconnected",({code:s,reason:t})=>{var i;this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:s,reason:t},country:y.location.country});const{recv:e,send:r}=(i=a(this,Oe,je).mediaState)!=null?i:{};e!=null&&e.state&&(e==null?void 0:e.state)!==zn.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==zn.CONNECTED?a(this,ct).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Oe,je).joinAttempted}):f(this,Ts,setTimeout(()=>{a(this,ct).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Oe,je).joinAttempted}),f(this,Ts,void 0)},wN)),a(this,Oe,je).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",async()=>{this.logger.info("SocketService::Reconnecting to socket-edge",{country:y.location.country}),a(this,Oe,je).updateSocketConnectionState("reconnecting")}),this.onStateEvent("reconnectAttempt",async({attempt:s})=>{this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),a(this,Oe,je).updateSocketConnectionState("reconnectAttempt",s)}),this.onStateEvent("reconnectFailure",({attempt:s})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),a(this,Oe,je).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",async()=>{this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,Oe,je).mediaJoinAttempted}}),a(this,Ts)&&(clearTimeout(a(this,Ts)),f(this,Ts,void 0)),a(this,ct).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,Oe,je).mediaJoinAttempted}),a(this,Oe,je).updateSocketConnectionState("reconnected")}),this.onStateEvent("failed",async()=>{this.logger.info("SocketService::Failed to connect to socket-edge",{country:y.location.country}),a(this,ct).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_FAILED),a(this,Oe,je).updateSocketConnectionState("failed")})}},gi=new WeakMap,Me=new WeakMap,Oe=new WeakSet,je=function(){return a(this,ct).getValue("connectionHandler")},Ts=new WeakMap,ct=new WeakMap,Hc=new WeakSet,Ip=function(s){let t=Gv.getSocketEdgeDomain(a(this,ct).getValue("baseURI"));typeof Fn(a(this,ct),"socket_server_base")=="string"&&(t=Fn(a(this,ct),"socket_server_base"));const e=`wss://${t}`,r=new URL(`${e}/ws`),i=this.peerId,n={roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0,...i!==s&&{oldPeerID:i},ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(o=>Gd[o]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0};return Object.entries(n).forEach(([o,c])=>{r.searchParams.append(o,c.toString())}),r.href},qc=new WeakSet,Ap=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},gS);let Uo=Gv;Pl([y.trace("SocketService.connect")],Uo.prototype,"connect",1),Pl([y.trace("SocketService.disconnect")],Uo.prototype,"disconnect",1),Pl([y.trace("SocketService.sendMessagePromise")],Uo.prototype,"sendMessagePromise",1),Pl([y.trace("SocketService.sendMessagePromiseWithTimeout")],Uo.prototype,"sendMessagePromiseWithTimeout",1);class _N{constructor(t){p(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var n;const e=FI.fromBinary(t),r=e.meetings.map(o=>{var c;return{id:o.id,title:o.title,participants:(c=o.participants)!=null?c:[]}});return{parentMeeting:{id:e.parentMeeting.id,title:e.parentMeeting.title,participants:(n=e.parentMeeting.participants)!=null?n:[]},meetings:r}}handleTransferPeerRaw({payload:t}){const e=uA.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=Tf.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return Sf.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return tA.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise(F.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const{payload:e}=await this.socketService.sendMessagePromise(F.createConnectedRooms,qI.toBinary({payloads:t}));return Sf.fromBinary(e).payloads.map(i=>({id:i.id,title:i.title}))}async updateConnectedRooms(t){}async disableConnectedRooms(t){const e=t.map(i=>({id:i})),r=await this.socketService.sendMessagePromise(F.deleteConnectedRooms,ZI.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(F.movePeers,oA.toBinary({sourceMeetingId:t.sourceMeetingId,destinationMeetingId:t.destinationMeetingId,participants:t.participants}));return new TextDecoder().decode(e.payload).includes("error")?{success:!1,error:"failed to move participants"}:{success:!0}}catch(e){return{success:!1,error:e}}}}var PN=Object.defineProperty,CN=Object.getOwnPropertyDescriptor,RN=(s,t,e,r)=>{for(var i=r>1?void 0:r?CN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&PN(t,e,i),i};class Wv extends Gt{constructor(e){const r=e.getValue("logger");super(r);p(this,"meetings",[]);p(this,"parentMeeting",null);m(this,Fs,void 0);f(this,Fs,e)}get supportsConnectedMeetings(){return a(this,Fs).getValue("self").id!==""}get isActive(){return this.meetings.length!==0}validateConnectedMeetingsAction(){if(!this.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
21
21
  Please connect with our support team to enable connected meetings.`)}async getConnectedMeetings(){return this.validateConnectedMeetingsAction(),await a(this,Fs).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump()}async createMeetings(e){return this.validateConnectedMeetingsAction(),(await a(this,Fs).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e)).map(i=>({id:i.id,title:i.title}))}async updateMeetings(e){this.validateConnectedMeetingsAction(),await a(this,Fs).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title})))}async deleteMeetings(e){this.validateConnectedMeetingsAction();const r=this.meetings.map(n=>e.includes(n.id)&&n.participants.length!==0?this.moveParticipants(n.id,this.parentMeeting.id,n.participants.map(o=>o.id)):Promise.resolve());return await Promise.all(r),await a(this,Fs).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e)}async moveParticipants(e,r,i){this.validateConnectedMeetingsAction();const n=await a(this,Fs).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(o=>({id:o}))});return n.success&&this.moveSuccessHandler(e,r,i),n}async moveParticipantsWithCustomPreset(e,r,i){this.validateConnectedMeetingsAction();const n=await a(this,Fs).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return n.success&&this.moveSuccessHandler(e,r,i.map(o=>o.id)),n}moveSuccessHandler(e,r,i){const n=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(o=>o.participants)].forEach(o=>n.set(o.id,o)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(o=>n.get(o)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(o=>!i.includes(o.id))),this.meetings=this.meetings.map(o=>{if(r===o.id){const c=o.participants.concat(i.map(d=>n.get(d)));return{...o,participants:c}}if(e===o.id){const c=o.participants.filter(d=>!i.includes(d.id));return{...o,participants:c}}return o})}}Fs=new WeakMap,RN([Lt({maxInvocations:60,period:60})],Wv.prototype,"getConnectedMeetings",1);var kN=Object.defineProperty,IN=Object.getOwnPropertyDescriptor,cp=(s,t,e,r)=>{for(var i=r>1?void 0:r?IN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&kN(t,e,i),i};const Jv=(mS=class{constructor(s){p(this,"connectedMeetings");m(this,Se,void 0);f(this,Se,s),this.connectedMeetings=new Wv(s)}get telemetry(){return a(this,Se).getValue("telemetry")}get logger(){return a(this,Se).getValue("logger")}static init(s){const t=new Jv(s);return t.connectedMeetings.supportsConnectedMeetings&&(t.setupEvents(),s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings())),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(F.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(F.transferPeer,this.handleTransferPeer.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(F.movedPeer,this.handleMovedPeer.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(F.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(F.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){const t=a(this,Se).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(s);return this.switchMeeting(t)}async switchMeeting({authToken:s,meetingId:t}){var i,n,o,c;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
22
22
  Please connect with our support team to enable connected meetings.`);this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",t);const e={video:a(this,Se).getValue("self").videoEnabled,audio:a(this,Se).getValue("self").audioEnabled};try{a(this,Se).getValue("self").cleanupEvents(),await a(this,Se).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(n=(i=a(this,Se).getValue("meeting"))==null?void 0:i.meta)==null?void 0:n.meetingId}`,{error:d})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${t}`);const r=await zv.init({...a(this,Se).getValue("options"),cachedUserDetails:null,defaults:{...a(this,Se).getValue("options").defaults,...e,mediaHandler:a(this,Se).getValue("self")},authToken:s});this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(o=r==null?void 0:r.meta)==null?void 0:o.meetingId}`);try{const{hidden:d}=a(this,Se).getValue("self");r.self.setName(a(this,Se).getValue("self").name),await r.join(),d&&r.self.hide()}catch(d){this.logger.error("ConnectedMeetingsController.joinRoom",{error:d})}return this.logger.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(c=r==null?void 0:r.meta)==null?void 0:c.meetingId}`),this.connectedMeetings.emit("meetingChanged",r),r}handleConnectedRoomsDump(s){const t=a(this,Se).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDumpRaw(s);this.connectedMeetings.meetings=t.meetings.map(e=>({id:e.id,title:e.title,participants:e.participants||[]})),this.connectedMeetings.parentMeeting={id:t.parentMeeting.id,title:t.parentMeeting.title,participants:t.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(s){return a(this,Se).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=a(this,Se).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsUpdatedRaw(s),e=new Map;this.connectedMeetings.meetings.forEach(r=>{e.set(r.id,r)}),t.forEach(r=>{e.has(r.id)?e.get(r.id).title=r.title:e.set(r.id,{...r,participants:[]})}),this.connectedMeetings.meetings=Array.from(e.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(s){const e=a(this,Se).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDeletedRaw(s).map(r=>r.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(r=>!e.includes(r.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},Se=new WeakMap,mS);let Cl=Jv;cp([y.trace("ConnectedMeetingsController.getConnectedMeetings")],Cl.prototype,"getConnectedMeetings",1),cp([y.trace("ConnectedMeetingsController.setupEvents")],Cl.prototype,"setupEvents",1),cp([y.trace("ConnectedMeetingsController.switchMeeting")],Cl.prototype,"switchMeeting",1);var AN=Object.defineProperty,MN=Object.getOwnPropertyDescriptor,Rl=(s,t,e,r)=>{for(var i=r>1?void 0:r?MN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&AN(t,e,i),i};const ea=class{constructor(s,t,e){p(this,"apiBase");p(this,"selfController");p(this,"pollController");p(this,"chatController");p(this,"metaController");p(this,"storesManager");p(this,"stageController");p(this,"pluginController");p(this,"internalsController");p(this,"recordingController");p(this,"livestreamController");p(this,"participantController");p(this,"connectedMeetingsController");p(this,"telemetry");p(this,"logger");this.apiBase=s,this.storesManager=t.storesManager,this.metaController=t.metaController,this.selfController=t.selfController,this.chatController=t.chatController,this.pollController=t.pollController,this.stageController=t.stageController,this.pluginController=t.pluginController,this.recordingController=t.recordingController,this.internalsController=t.internalsController,this.participantController=t.participantController,this.livestreamController=t.livestreamController,this.connectedMeetingsController=t.connectedMeetingsController,this.telemetry=e.getValue("telemetry"),this.logger=e.getValue("logger")}static async init(s){var N,$;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:n,cachedUserDetails:o,logger:c}=s.getAllValues();if(_v(s),Te.isSupported()===!1)throw new C("Browser not supported","0010",c,!0);const d=wO(s,{authToken:r,baseURL:e,cachedUserDetails:o});d.setRoomName(i),d.setRoomUUID(i),d.setOrganizationId(n),d.setHeader("tracing-id",t),s.setValue("apiClient",d);const l=new nD(s);s.setValue("connectionHandler",l);const u=ea.createSocketService(s),h=u.connect(),g=d.getUserDetails(),v=d.getPlugins();let E,b="";try{await ea.setupFlagsmith(s)}catch(Y){c.error("Failed to setup flagsmith",{error:Y})}try{await h}catch(Y){c.error("[Controller]: Failed to connect to socket server:",{error:Y})}try{({meetingTitle:b}=await d.getRoomNodeData()),E=await g,c.info("CF SFU is being used."),s.setValue("presetName",E.preset.name)}catch(Y){c.error("Failed to get room metadata",{error:Y})}const _=$h.init(E.preset,!s.getValue("modules").theme),w=qh.init(s,_.viewType,E.preset.permissions),L=ea.setupControllers(u,s,E,v,b,_,w);KO(_)&&((N=ea.createRoomNodeClient(s,u).initializeConnection(E.participant.name,i,!1,w))==null||N.catch(ae=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:ae})})),y.location.country=($=d.ipInfo)==null?void 0:$.country;const{controllers:B}=await L;return TC(),new ea(e,B,s)}static async setupFlagsmith(s){var l;const{peerId:t,baseURI:e,overrides:r,meetingId:i,organizationId:n,logger:o}=s.getAllValues(),c=SC(i),d={entity:sh.PEER,clientId:n,isAnonUser:!n,sdkVersion:s.getValue("sdkVersion"),presetName:s.getValue("presetName"),meetingHash:c,roomName:i,...Te.getDeviceInfo(),isReactNative:navigator.isReactNative};try{const u=(l=r==null?void 0:r.whitelabelled_flags_endpoint)==null||l?_i({servicePrefix:"flags",baseURI:e}):"edge.api.flagsmith.com";await s.getValue("flagsmith").identify(`${sh.PEER}_${t}`,JSON.parse(JSON.stringify(d)),!1,5e3,u,o),o.info("flagsmith::allFlags",{flags:JSON.stringify(s.getValue("flagsmith").getAllFlags())},!0)}catch(u){o.error("Failed to fetch flagsmith flags")}}static async setupControllers(s,t,e,r,i,n,o){var k,Ke,fi;const c=t.getValue("modules"),{participant:d}=e,l=t.getValue("defaults"),u=t.getValue("logger"),{viewType:h,mediaConstraints:{audio:g}}=n;t.setValue("viewType",h),t.setValue("defaults",{mediaConfiguration:{audio:{enableHighBitrate:(k=g.enableHighBitrate)!=null?k:!1,enableStereo:(Ke=g.enableStereo)!=null?Ke:!1}},...l}),t.setValue("maxPreferredStreams",Te.isMobile()?n.maxVideoStreams.mobile:n.maxVideoStreams.desktop);let v,E,b,_,w,L,B,N,$;const Y=new Y1(t,s),ae=new _N(s);t.setValue("connectedMeetingsSocketHandler",ae);const bt=new ml(t,s),Bs=new as(t,s),On=new sN(s),$s=new Cv(t,s),I=new rN(t,s),T=new z1(s),P=new Ii(t,s),x=await jr.init(t,$s,d,o,n);t.setValue("selfController",x);const we=await qf.init(t,x.self,$s,Y,i);if(c.participant&&(N=new pr(t,x.self,$s)),(fi=c.e2ee)!=null&&fi.enabled&&c.e2ee.manager.init(u,t.getValue("peerSessionStore")),c.chat&&(E=await Rs.init(t,Bs,P,x.self,N.participants)),c.internals&&(w=await Lh.init(t)),c.livestream&&n.viewType===Vt.Livestream&&t.getValue("flagsmith").hasFeature(X.LIVESTREAM)&&(B=new lv(t,x.self,T)),n.viewType!==Vt.Chat){if(c.poll&&(v=await Ff.init(t,x.self,bt)),c.recording&&(L=new Kf(t,x.self,$s)),c.stage&&(b=new jf(t,On,$s,x.self,N.participants)),c.plugin){if(!N)throw new C("The plugin module cannot be initialized without the `participant` module","0102");const Lr=await r;_=await _o.init(t,Lr,I,Bs,E==null?void 0:E.chat,x.self,N.participants,i)}if(c.connectedMeetings&&($=await Cl.init(t)),c.pip){const Lr=await rh._init(t,x.self);t.setValue("pip",Lr)}}const V={storesManager:new s1(t,I),pollController:v,selfController:x,metaController:we,chatController:E,stageController:b,pluginController:_,recordingController:L,internalsController:w,livestreamController:B,participantController:N,connectedMeetingsController:$};return{theme:n,permissions:o,controllers:V}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return wv(s,{socket:t,peerId:e})}static createSocketService(s){const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),i=["PING"];return new Uo(s,{peerId:t,meetingId:e,authToken:r,capabilities:i})}};let Fo=ea;Rl([y.trace("Controller.init")],Fo,"init",1),Rl([y.trace("setupFlagsmith")],Fo,"setupFlagsmith",1),Rl([y.trace("Controller.createRoomNodeClient")],Fo,"createRoomNodeClient",1),Rl([y.trace("Controller.createSocketService")],Fo,"createSocketService",1);class ON{constructor(){p(this,"battery");p(this,"logger");p(this,"init",async t=>{this.logger=t;try{"getBattery"in navigator&&(this.battery=await navigator.getBattery(),this.battery.addEventListener("chargingchange",this.updateChargeInfo),this.battery.addEventListener("levelchange",this.updateLevelInfo),this.updateLevelInfo(),this.updateChargeInfo())}catch(e){t.error("Error getting battery",e)}});p(this,"updateChargeInfo",()=>{var t;this.logger.log(`Battery charging? ${(t=this.battery)!=null&&t.charging?"Yes":"No"}`)});p(this,"updateLevelInfo",()=>{if(!this.battery){this.logger.log("Battery level: Not known");return}this.logger.log(`Battery level: ${this.battery.level*100}%`)});p(this,"cleanup",()=>{var t,e;"getBattery"in navigator&&((t=this.battery)==null||t.removeEventListener("chargingchange",this.updateChargeInfo),(e=this.battery)==null||e.removeEventListener("levelchange",this.updateLevelInfo))})}}const Kv=new ON;function DN(s,t){s.startsWith("eyJ")||console.error("Invalid auth token provided. Ensure you are passing a %cparticipant `authToken`%c — not an Org API Key or an incorrectly formatted token.\nYou get the participant token from the Add Participant API: https://docs.realtime.cloudflare.com/api#/operations/add_participant","font-weight: bold","font-weight: normal");try{const{meetingId:e,orgId:r,participantId:i}=JSON.parse(atob(s.split(".")[1]));if(!e)throw Error(`Received V1 auth token ${s}`);let n=Pi.baseURI.prod;t&&(n=t);const o=`https://${_i({servicePrefix:"api",baseURI:n})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:n,apiBase:o}}catch(e){throw new C("Invalid auth token","0004")}}class NN{constructor(){m(this,yu);m(this,mi,new Audio);m(this,kn,new MediaStream);m(this,In,new Map);m(this,jc,void 0);a(this,mi).srcObject=a(this,kn),a(this,mi).autoplay=!0}async playTracks(t){return t.forEach(e=>{a(this,In).has(e.id)||(a(this,kn).addTrack(e),a(this,In).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,mi).setSinkId(t)}removeTrack(t){const e=a(this,In).get(t);e&&(a(this,kn).removeTrack(e),a(this,In).delete(t))}async play(){return a(this,mi).srcObject=a(this,kn),a(this,mi).play().catch(t=>{U(this,yu,eT).call(this,t)})}onError(t){f(this,jc,t)}}mi=new WeakMap,kn=new WeakMap,In=new WeakMap,jc=new WeakMap,yu=new WeakSet,eT=function(t){var e;(e=a(this,jc))==null||e.call(this,t)};class VN extends NN{constructor(){super();m(this,An,void 0);f(this,An,new Map)}addParticipantTrack(e,r){a(this,An).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=a(this,An).get(e);r&&this.removeTrack(r),a(this,An).delete(e)}}An=new WeakMap;var LN=Object.defineProperty,xN=Object.getOwnPropertyDescriptor,kl=(s,t,e,r)=>{for(var i=r>1?void 0:r?xN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&LN(t,e,i),i};let zr=(fS=class{constructor(t,e){m(this,Xe,void 0);m(this,Mn,void 0);f(this,Mn,t),f(this,Xe,e)}get peerId(){return a(this,Mn).getValue("peerId")}static initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:Si(),n=nr.createContext(i,{peerId:i}),o=n.getValue("logger");o.init(n);const c=new pv(o);return c.init(t,e,n),n.setValue("defaults",{mediaHandler:c}),c}static async init(t){var v,E,b,_,w,L,B;Te.init();const{mediaHandler:e}=(v=t.defaults)!=null?v:{},r=(e==null?void 0:e.peerId)||((b=(E=t==null?void 0:t.cachedUserDetails)==null?void 0:E.peerId)!=null?b:Si()),{authToken:i,baseURI:n}=t,{meetingId:o,...c}=DN(i,n);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const d=zr.setupContext(r,t,o,c),l=d.getValue("telemetry"),u=d.getValue("logger");iT(u),Kv.init(u),l.init(d,{roomName:o,userId:c.participantId,organizationId:c.orgId,peerId:r},(w=(_=t.modules)==null?void 0:_.tracing)!=null?w:!0),u.init(d),u.info("Client::init::options",{clientInitOptions:{...t,authToken:`${(L=t.authToken)==null?void 0:L.slice(0,10)}...
23
- ${(B=t.authToken)==null?void 0:B.slice(-10)}`}});const h=await Fo.init(d),g=new zr(d,h);return d.setValue("meeting",g),g}static setupContext(t,e,r,i){var d,l;const n=nr.createContext(t,e),o={...cC,...e==null?void 0:e.modules},c=e.defaults||{audio:!0,video:!0};return n.setValue("options",e),n.setValue("peerId",t),n.setValue("modules",o),n.setValue("sdkName","web-core"),n.setValue("meetingId",r),n.setValue("apiBase",i.apiBase),n.setValue("baseURI",i.baseURI),n.setValue("userId",i.participantId),n.setValue("organizationId",i.orgId),n.setValue("authToken",e.authToken),n.setValue("overrides",(d=e.overrides)!=null?d:{}),n.setValue("env",dC({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",Cs(e.cachedUserDetails)),n.setValue("sdkVersion","1.2.1-staging.8"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new VN),n}async join(){const{selfController:t}=a(this,Xe);return t.self.roomJoined?null:t.joinRoom()}async leave(t){Kv.cleanup(),a(this,Mn).getValue("peerSessionStore").reset();const{selfController:e}=a(this,Xe);return e.leaveRoom(t)}get participants(){var t;return(t=a(this,Xe).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,Xe).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,Xe).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,Xe).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,Xe).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,Xe).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,Xe).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,Xe).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,Xe).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,Xe).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,Xe).stageController)==null?void 0:t.stage}get stores(){return a(this,Xe).storesManager}get audio(){return a(this,Mn).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,Xe).internalsController)==null?void 0:t.internals}async joinRoom(){return this.join()}async leaveRoom(t){return this.leave(t)}},Xe=new WeakMap,Mn=new WeakMap,fS);kl([ut("0002"),ur.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],zr.prototype,"join",1),kl([ut("0003")],zr.prototype,"leave",1),kl([ut("0001"),ur.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],zr,"init",1),zr=kl([ut("0000")],zr);const zv=zr;return zv}();
23
+ ${(B=t.authToken)==null?void 0:B.slice(-10)}`}});const h=await Fo.init(d),g=new zr(d,h);return d.setValue("meeting",g),g}static setupContext(t,e,r,i){var d,l;const n=nr.createContext(t,e),o={...cC,...e==null?void 0:e.modules},c=e.defaults||{audio:!0,video:!0};return n.setValue("options",e),n.setValue("peerId",t),n.setValue("modules",o),n.setValue("sdkName","web-core"),n.setValue("meetingId",r),n.setValue("apiBase",i.apiBase),n.setValue("baseURI",i.baseURI),n.setValue("userId",i.participantId),n.setValue("organizationId",i.orgId),n.setValue("authToken",e.authToken),n.setValue("overrides",(d=e.overrides)!=null?d:{}),n.setValue("env",dC({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",Cs(e.cachedUserDetails)),n.setValue("sdkVersion","1.2.2-staging.1"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new VN),n}async join(){const{selfController:t}=a(this,Xe);return t.self.roomJoined?null:t.joinRoom()}async leave(t){Kv.cleanup(),a(this,Mn).getValue("peerSessionStore").reset();const{selfController:e}=a(this,Xe);return e.leaveRoom(t)}get participants(){var t;return(t=a(this,Xe).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,Xe).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,Xe).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,Xe).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,Xe).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,Xe).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,Xe).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,Xe).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,Xe).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,Xe).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,Xe).stageController)==null?void 0:t.stage}get stores(){return a(this,Xe).storesManager}get audio(){return a(this,Mn).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,Xe).internalsController)==null?void 0:t.internals}async joinRoom(){return this.join()}async leaveRoom(t){return this.leave(t)}},Xe=new WeakMap,Mn=new WeakMap,fS);kl([ut("0002"),ur.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],zr.prototype,"join",1),kl([ut("0003")],zr.prototype,"leave",1),kl([ut("0001"),ur.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],zr,"init",1),zr=kl([ut("0000")],zr);const zv=zr;return zv}();