@cloudflare/realtimekit 1.2.2-staging.3 → 1.2.2-staging.4

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/index.es5.js CHANGED
@@ -29129,10 +29129,10 @@ var MD = /* @__PURE__ */ function() {
29129
29129
  for (; ; )
29130
29130
  switch (s.prev = s.next) {
29131
29131
  case 0:
29132
- return this.validateConnectedMeetingsAction(), s.next = 3, l(this, lt)[lt].getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump();
29133
- case 3:
29134
- return a = s.sent, s.abrupt("return", a);
29135
- case 5:
29132
+ return this.validateConnectedMeetingsAction(), this.logger.info("Getting connected meetings dump"), s.next = 4, l(this, lt)[lt].getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump();
29133
+ case 4:
29134
+ return a = s.sent, this.logger.info("Got connected meetings dump"), s.abrupt("return", a);
29135
+ case 7:
29136
29136
  case "end":
29137
29137
  return s.stop();
29138
29138
  }
@@ -29153,12 +29153,12 @@ var MD = /* @__PURE__ */ function() {
29153
29153
  for (; ; )
29154
29154
  switch (u.prev = u.next) {
29155
29155
  case 0:
29156
- return this.validateConnectedMeetingsAction(), u.next = 3, l(this, lt)[lt].getValue("connectedMeetingsSocketHandler").createConnectedRooms(a);
29157
- case 3:
29158
- return i = u.sent, u.abrupt("return", i.map(function(c) {
29156
+ return this.validateConnectedMeetingsAction(), this.logger.info("Creating connected meetings ".concat(JSON.stringify(a))), u.next = 4, l(this, lt)[lt].getValue("connectedMeetingsSocketHandler").createConnectedRooms(a);
29157
+ case 4:
29158
+ return i = u.sent, this.logger.info("Created connected meetings ".concat(JSON.stringify(i))), u.abrupt("return", i.map(function(c) {
29159
29159
  return { id: c.id, title: c.title };
29160
29160
  }));
29161
- case 5:
29161
+ case 7:
29162
29162
  case "end":
29163
29163
  return u.stop();
29164
29164
  }
@@ -29174,10 +29174,12 @@ var MD = /* @__PURE__ */ function() {
29174
29174
  for (; ; )
29175
29175
  switch (s.prev = s.next) {
29176
29176
  case 0:
29177
- return this.validateConnectedMeetingsAction(), s.next = 3, l(this, lt)[lt].getValue("connectedMeetingsSocketHandler").updateConnectedRooms(a.map(function(u) {
29177
+ return this.validateConnectedMeetingsAction(), this.logger.info("Updating connected meetings ".concat(JSON.stringify(a))), s.next = 4, l(this, lt)[lt].getValue("connectedMeetingsSocketHandler").updateConnectedRooms(a.map(function(u) {
29178
29178
  return { meetingId: u.id, title: u.title };
29179
29179
  }));
29180
- case 3:
29180
+ case 4:
29181
+ this.logger.info("Updated connected meetings ".concat(JSON.stringify(a)));
29182
+ case 5:
29181
29183
  case "end":
29182
29184
  return s.stop();
29183
29185
  }
@@ -29194,16 +29196,16 @@ var MD = /* @__PURE__ */ function() {
29194
29196
  for (; ; )
29195
29197
  switch (d.prev = d.next) {
29196
29198
  case 0:
29197
- return this.validateConnectedMeetingsAction(), s = this.meetings.map(function(p) {
29199
+ return this.validateConnectedMeetingsAction(), this.logger.info("Moving participants before deleting connected meetings ".concat(JSON.stringify(a))), s = this.meetings.map(function(p) {
29198
29200
  return a.includes(p.id) && p.participants.length !== 0 ? i.moveParticipants(p.id, i.parentMeeting.id, p.participants.map(function(v) {
29199
29201
  return v.id;
29200
29202
  })) : Promise.resolve();
29201
- }), d.next = 4, Promise.all(s);
29202
- case 4:
29203
- return d.next = 6, l(this, lt)[lt].getValue("connectedMeetingsSocketHandler").disableConnectedRooms(a);
29203
+ }), this.logger.info("Moved participants before deleting connected meetings ".concat(JSON.stringify(a), ". Deleting now.")), d.next = 6, Promise.all(s);
29204
29204
  case 6:
29205
- return u = d.sent, d.abrupt("return", u);
29205
+ return d.next = 8, l(this, lt)[lt].getValue("connectedMeetingsSocketHandler").disableConnectedRooms(a);
29206
29206
  case 8:
29207
+ return u = d.sent, this.logger.info("Deleted connected meetings ".concat(JSON.stringify(a))), d.abrupt("return", u);
29208
+ case 11:
29207
29209
  case "end":
29208
29210
  return d.stop();
29209
29211
  }
@@ -29220,12 +29222,12 @@ var MD = /* @__PURE__ */ function() {
29220
29222
  for (; ; )
29221
29223
  switch (d.prev = d.next) {
29222
29224
  case 0:
29223
- return this.validateConnectedMeetingsAction(), d.next = 3, l(this, lt)[lt].getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({ sourceMeetingId: a, destinationMeetingId: i, participants: s.map(function(p) {
29225
+ return this.validateConnectedMeetingsAction(), this.logger.info("Moving connected meetings participants ".concat(JSON.stringify(s), " from ").concat(a, " to ").concat(i)), d.next = 4, l(this, lt)[lt].getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({ sourceMeetingId: a, destinationMeetingId: i, participants: s.map(function(p) {
29224
29226
  return { id: p };
29225
29227
  }) });
29226
- case 3:
29227
- return u = d.sent, u.success && this.moveSuccessHandler(a, i, s), d.abrupt("return", u);
29228
- case 6:
29228
+ case 4:
29229
+ return u = d.sent, u.success ? (this.logger.info("Moved connected meetings participants ".concat(JSON.stringify(s), " from ").concat(a, " to ").concat(i)), this.moveSuccessHandler(a, i, s)) : this.logger.error("Failed to move connected meetings participants ".concat(JSON.stringify(s), " from ").concat(a, " to ").concat(i)), d.abrupt("return", u);
29230
+ case 7:
29229
29231
  case "end":
29230
29232
  return d.stop();
29231
29233
  }
@@ -29242,12 +29244,12 @@ var MD = /* @__PURE__ */ function() {
29242
29244
  for (; ; )
29243
29245
  switch (d.prev = d.next) {
29244
29246
  case 0:
29245
- return this.validateConnectedMeetingsAction(), d.next = 3, l(this, lt)[lt].getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({ sourceMeetingId: a, destinationMeetingId: i, participants: s });
29246
- case 3:
29247
- return u = d.sent, u.success && this.moveSuccessHandler(a, i, s.map(function(p) {
29247
+ return this.validateConnectedMeetingsAction(), this.logger.info("Moving connected meetings participants (custom preset) ".concat(JSON.stringify(s), " from ").concat(a, " to ").concat(i)), d.next = 4, l(this, lt)[lt].getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({ sourceMeetingId: a, destinationMeetingId: i, participants: s });
29248
+ case 4:
29249
+ return u = d.sent, u.success ? (this.logger.info("Moved connected meetings participants (custom preset) ".concat(JSON.stringify(s), " from ").concat(a, " to ").concat(i)), this.moveSuccessHandler(a, i, s.map(function(p) {
29248
29250
  return p.id;
29249
- })), d.abrupt("return", u);
29250
- case 6:
29251
+ }))) : this.logger.error("Failed to move connected meetings participants (custom preset) ".concat(JSON.stringify(s), " from ").concat(a, " to ").concat(i)), d.abrupt("return", u);
29252
+ case 7:
29251
29253
  case "end":
29252
29254
  return d.stop();
29253
29255
  }
@@ -29319,8 +29321,9 @@ var LD = Object.defineProperty, $D = Object.getOwnPropertyDescriptor, Zp = funct
29319
29321
  }
29320
29322
  // event handlers
29321
29323
  }, { key: "handleTransferPeer", value: function(e) {
29324
+ this.logger.info("Received backend request to switch connected meetings");
29322
29325
  var r = l(this, he)[he].getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(e);
29323
- return this.switchMeeting(r);
29326
+ return this.logger.info("Honoring request to switch connected meetings. Going to ".concat(r == null ? void 0 : r.meetingId)), this.switchMeeting(r);
29324
29327
  } }, { key: "switchMeeting", value: function() {
29325
29328
  var t = m(/* @__PURE__ */ h().mark(function r(n) {
29326
29329
  var a, i, s, u, c, d, p, v, f;
package/dist/index.rn.js CHANGED
@@ -10,6 +10,6 @@ ${s}`}const Ua={maxInvocations:5,period:1};function kt(s,t){return function(e,r,
10
10
  `}this.midTransceiverMap.set(a.mid,a);const c=async d=>(this.logger.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(d)}]`),await this.pc.setRemoteDescription(d),a.mid);return this.logger.debug(`send() | calling pc.setLocalDescription() [offer: ${JSON.stringify(o,void 0,2)}]`),{offerSdp:o,callback:c,sender:a.sender,mid:a.mid}}addCustomEventListeners(){this.pc.addEventListener("datachannel",t=>{const{channel:e}=t;e.onmessage=r=>{this.safeEmit("datachannel",t.channel,String.fromCharCode(...new Uint8Array(r.data)))}})}}class Cd extends Nh{constructor(e,r){super(e);u(this,"supportsSendEncodings",!1);this.supportsSendEncodings=r.supportsSendEncodings}static createFactory(e,r){return()=>new Cd(e,r)}get name(){return"Firefox60"}async send({track:e,encodings:r,codecOptions:i,screenShare:a}){this._assertSendDirection();const o=this.supportsSendEncodings&&r!==void 0?{sendEncodings:r}:{},c=this.pc.addTransceiver(e,{direction:"sendonly",streams:[a?this._sendScreenShareStream:this._sendWebStream],...o});if(!this.supportsSendEncodings&&r){r.reverse();const p=c.sender.getParameters();p.encodings=r,await c.sender.setParameters(p)}const d=(p,f)=>{var U;const T=ds.parse(p),E=T.media[T.media.length-1],P=E.rtp.filter(D=>f.some($=>$.name===D.codec)),C=E.fmtp.filter(D=>P.some($=>$.payload===D.payload)),_=(U=E.rtcpFb)==null?void 0:U.filter(D=>P.some($=>$.payload===D.payload)),N=P.map(D=>D.payload);return T.media[T.media.length-1].rtp=P,T.media[T.media.length-1].fmtp=C,T.media[T.media.length-1].rtcpFb=_,T.media[T.media.length-1].payloads=N.join(" "),ds.write(T)},l=await this.pc.createOffer();if(l.sdp=d(l.sdp,i),this.logger.debug(`send() | calling pc.setLocalDescription() [offer:${JSON.stringify(l)}]`),await this.pc.setLocalDescription(l),e==="audio"||e.kind==="audio"){const{enableDtx:p,enableStereo:f}=this,T=this.enableHighBitrate?f?128e3:64e3:f?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${p?"usedtx=1;":""}${f?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${T}`)}return this.midTransceiverMap.set(c.mid,c),{offerSdp:l,callback:async p=>(this.logger.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(p)}]`),await this.pc.setRemoteDescription(p),c.mid),sender:c.sender,mid:c.mid}}async setMaxSpatialLayer(e,r){this._assertSendDirection(),this.logger.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const a=i.sender.getParameters(),o=a.encodings.length-1-r;a.encodings.forEach((c,d)=>{d>=o?c.active=!0:c.active=!1}),await i.sender.setParameters(a)}addCustomEventListeners(){this.pc.addEventListener("datachannel",e=>{const{channel:r}=e;r.onmessage=async i=>{const a=await i.data.arrayBuffer();this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(a)))}})}}class Vh extends Nh{static createFactory(t){return()=>new Vh(t)}get name(){return"Safari12"}async send({track:t,encodings:e,codecOptions:r,screenShare:i}){this._assertSendDirection(),this.logger.debug("Safari12::creating new transceiver");const a=this.pc.addTransceiver(t,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:e}),o=RTCRtpSender.getCapabilities(typeof t=="string"?t:t.kind);this.logger.info(`Safari12::senders available params: ${JSON.stringify(o)}`);const c=[];r&&r.length>0&&r.forEach(h=>{var f;const p=o.codecs.find(T=>T.mimeType.includes(h.name));if(h.parameters){this.logger.info(`Safari12::codecOption.parameters:, ${JSON.stringify(h.parameters)}`);const T=((f=p.sdpFmtpLine)==null?void 0:f.split(";"))||[];T.push(...h.parameters);const E=[...new Set(T).values()];p.sdpFmtpLine=E.join(";")}c.push(p)}),this.logger.info(`Safari12::selected codecs: ${JSON.stringify(c)}`),a.setCodecPreferences(c);const d=await this.pc.createOffer();if(await this.pc.setLocalDescription(d),t==="audio"||t.kind==="audio"){const{enableStereo:h,enableDtx:p}=this,f=this.enableHighBitrate?h?128e3:64e3:h?64e3:32e3;d.sdp=d.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${p?"usedtx=1;":""}${h?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${f}`)}return this.midTransceiverMap.set(a.mid,a),{offerSdp:d,callback:async h=>(this.logger.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(h)}]`),await this.pc.setRemoteDescription(h),a.mid),sender:a.sender,mid:a.mid}}addCustomEventListeners(){this.pc.ondatachannel=t=>{const{channel:e}=t;e.onmessage=async r=>{const i=String.fromCharCode(...new Uint8Array(r.data));this.safeEmit("datachannel",t.channel,i)}}}}function MD(s,t){return typeof s=="undefined"?t:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(s):JSON.parse(JSON.stringify(s))}var Xo,Oi,Ds,Hd,Os,wr,Zo,Bu,qd,jf,jd,Gf;class DD extends Fl{constructor(e,r){var i;super(e);g(this,Os);g(this,Zo);g(this,qd);g(this,jd);u(this,"rtpReceiver");u(this,"id");u(this,"localId");u(this,"producerId");u(this,"producingTransportId");u(this,"mimeType");u(this,"track");u(this,"peerId");u(this,"appData");u(this,"transceiver");g(this,Xo,void 0);g(this,Oi,void 0);g(this,Ds,void 0);g(this,Hd,void 0);this.id=r.id,this.localId=r.localId,m(this,Xo,r.handler),this.appData=r.appData,this.peerId=r.producingPeerId,this.producingTransportId=r.producingTransportId,m(this,Ds,!1),this.producerId=r.producerId,this.track=r.track,m(this,Oi,(i=r.paused)!=null?i:!1),this.mimeType=r.mimeType,this.transceiver=r.transceiver,this.rtpReceiver=r.rtpReceiver,V(this,qd,jf).call(this),m(this,Hd,e)}get closed(){return n(this,Ds)}get kind(){return this.track.kind}get paused(){return n(this,Oi)}close(e,r){n(this,Ds)||(this.logger.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,n(this,Os,wr)),m(this,Ds,!0),r&&(V(this,jd,Gf).call(this),this.transceiver.stop()),this.safeEmit("close",e))}async getStats(){if(n(this,Ds))throw new Rt("closed");return n(this,Xo).getReceiverStats(this.localId)}pause(){if(this.logger.debug("consumer::pause()",n(this,Os,wr)),n(this,Ds)){this.logger.error("consumer::pause() | Consumer closed",n(this,Os,wr));return}m(this,Oi,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(this.logger.debug("consumer::resume()",n(this,Os,wr)),n(this,Ds)){this.logger.error("Consumer::resume() | Consumer closed",n(this,Os,wr));return}m(this,Oi,!1),this.track.enabled=!0,this.safeEmit("resume")}}Xo=new WeakMap,Oi=new WeakMap,Ds=new WeakMap,Hd=new WeakMap,Os=new WeakSet,wr=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},Zo=new WeakSet,Bu=function(){this.logger.debug('Consumer::track "ended" event',n(this,Os,wr)),this.safeEmit("trackended")},qd=new WeakSet,jf=function(){this.track.addEventListener("ended",V(this,Zo,Bu).bind(this))},jd=new WeakSet,Gf=function(){try{this.track.removeEventListener("ended",V(this,Zo,Bu)),this.track.stop()}catch(e){this.logger.error("Consumer::destroyTrack()",{...n(this,Os,wr),error:e})}};var gs,ga,ma,Ni,Zt,ze,Hr,fa,Gd,Vt,cs;class OD extends Fl{constructor(e,r){var i,a;super(e);g(this,Vt);u(this,"id");u(this,"localId");g(this,gs,void 0);u(this,"kind");u(this,"appData");u(this,"rtpSender");g(this,ga,void 0);g(this,ma,void 0);g(this,Ni,void 0);g(this,Zt,!1);g(this,ze,void 0);g(this,Hr,void 0);g(this,fa,void 0);g(this,Gd,void 0);this.id=r.id,this.localId=r.localId,m(this,ze,r.track),this.kind=(i=r.track)==null?void 0:i.kind,m(this,Hr,r.disableTrackOnPause?!((a=r.track)!=null&&a.enabled):!1),m(this,fa,void 0),m(this,ga,r.stopTracks),m(this,ma,r.disableTrackOnPause),m(this,Ni,r.zeroRtpOnPause),this.appData=r.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),m(this,gs,r.handler),this.rtpSender=r.rtpSender,this._handleTrack(),m(this,Gd,e)}get closed(){return n(this,Zt)}get track(){return n(this,ze)}get paused(){return n(this,Hr)}get maxSpatialLayer(){return n(this,fa)}async close(e){if(n(this,Zt))return;if(this.logger.debug(`Producer::close() ${e?`with reason ${e}`:""}`,n(this,Vt,cs)),m(this,Zt,!0),this._destroyTrack(),e===wd){this.safeEmit("close",{reason:e});return}const{offerSdp:r,callback:i}=await n(this,gs).stopSending(this.localId),{answer:a}=await this.safeEmitAsPromise("close",{offer:r,reason:e});i(a)}async getStats(){if(n(this,Zt))throw new Rt("closed");return n(this,gs).getSenderStats(this.localId)}pause(){this.logger.debug("Producer::pause()",n(this,Vt,cs)),n(this,Zt)&&this.logger.error("Producer::pause() | Producer closed",n(this,Vt,cs)),m(this,Hr,!0),n(this,ze)&&n(this,ma)&&(n(this,ze).enabled=!1),n(this,Ni)&&n(this,gs).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(this.logger.debug("Producer::resume()",n(this,Vt,cs)),n(this,Zt)){this.logger.error("Producer::resume() | Producer closed",n(this,Vt,cs));return}m(this,Hr,!1),n(this,ze)&&n(this,ma)&&(n(this,ze).enabled=!0),n(this,Ni)&&n(this,gs).replaceTrack(this.localId,n(this,ze)),this.emit("resume")}async replaceTrack({track:e}){if(this.logger.debug(`Producer::replaceTrack() trackId: ${e==null?void 0:e.id}`,n(this,Vt,cs)),n(this,Zt)){if(e&&n(this,ga))try{e.stop()}catch(r){this.logger.error("Producer::replaceTrack",{...n(this,Vt,cs),error:r})}throw new Rt("closed")}else if(e&&e.readyState==="ended")throw new Rt("track ended");if(e===n(this,ze)){this.logger.debug(`replaceTrack() | same track, ignored trackId: ${e.id}`,n(this,Vt,cs));return}(!n(this,Ni)||!n(this,Hr))&&await n(this,gs).replaceTrack(this.localId,e),this._destroyTrack(),m(this,ze,e),this._handleTrack()}async setMaxSpatialLayer(e){if(n(this,Zt))throw new Rt("closed");if(this.kind!=="video")throw new bo("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");await n(this,gs).setMaxSpatialLayer(this.localId,e),m(this,fa,e)}async setRtpEncodingParameters(e){if(n(this,Zt))throw new Rt("closed");if(typeof e!="object")throw new TypeError("invalid params");await n(this,gs).setRtpEncodingParameters(this.localId,e)}_onTrackEnded(){this.logger.debug(`Producer::track "ended" event trackId: ${this.track.id}`,n(this,Vt,cs)),this.safeEmit("trackended",this.track.id)}_handleTrack(){n(this,ze)&&n(this,ze).addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(n(this,ze))try{n(this,ze).removeEventListener("ended",this._onTrackEnded),n(this,ga)&&n(this,ze).stop()}catch(r){this.logger.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,{...n(this,Vt,cs),error:r})}}}gs=new WeakMap,ga=new WeakMap,ma=new WeakMap,Ni=new WeakMap,Zt=new WeakMap,ze=new WeakMap,Hr=new WeakMap,fa=new WeakMap,Gd=new WeakMap,Vt=new WeakSet,cs=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};function Wf(s){return typeof s=="object"&&!Array.isArray(s)&&s!==null}function cu(s){return Math.random().toString(36).substring(2,2+s)}const Xc=1;function ag(s){const t=s;return delete t.payload._bolt,t}function ND(s){return s.payload&&Wf(s.payload)}function LD(s){var t,e;return ND(s)&&(e=(t=s.payload._bolt)==null?void 0:t.id)!=null?e:""}var qr,Wd,Li;const wn=class extends ot.EventEmitter{constructor(e,r,i,a){super();u(this,"channel");u(this,"queue");u(this,"serverProtocolVersion");g(this,qr,new Map);g(this,Wd,void 0);g(this,Li,void 0);u(this,"respond",(e,r,i=!1)=>{let a;i?a=wn.createErrorResponse(e,r):a=wn.createResponse(e,r),this.channel.send(JSON.stringify(a))});u(this,"notify",e=>{const r=wn.createNotification(e);this.channel.send(JSON.stringify(r))});u(this,"request",async e=>{const r=wn.createRequest(e),i=new Promise((a,o)=>{const{id:d}=r.payload._bolt,l={id:d,method:r.type,resolve:h=>{this.queue.delete(d)&&(clearTimeout(l.timer),a(h))},timer:setTimeout(()=>{this.queue.delete(d)&&o(new Error(`request timeout for message id: ${d}`))},2e4),cancel:h=>{this.queue.delete(d)&&(clearTimeout(l.timer),o(h))}};this.queue.set(d,l)});return this.channel.send(JSON.stringify(r)),i});u(this,"send",e=>{const r=JSON.stringify(e),i=16384;if(r.length>i){const a=i-200,o=Math.ceil(r.length/a),c=[];for(let l=0;l<o;l+=1){const h=l*a,p=(l+1)*a;c.push(r.slice(h,p))}const d=gr.v4();for(let l=0;l<o;l+=1){const h=c[l],f=JSON.stringify({id:d,count:o,chunkIndex:l,chunk:h});n(this,Li).debug(`Sending message chunk over dc: ${f}`),this.channel.send(f)}}else n(this,Li).debug(`Sending message over dc: ${r}`),this.channel.send(r)});u(this,"processMessage",e=>{var i;n(this,qr).has(e.id)||n(this,qr).set(e.id,[]);const r=n(this,qr).get(e.id);if(r[e.chunkIndex]=e,(r==null?void 0:r.length)===e.count&&!r.some(a=>a===void 0)){const a=n(this,qr).get(e.id),o=a==null?void 0:a.reduce((d,l)=>d+l.chunk,"");n(this,qr).delete(e.id);const c=JSON.parse(o);if(!c.payload||!Wf(c.payload))throw new Error("corrupted incoming message over dc",{cause:{code:"CORRUPT_DC_MESSAGE",values:c}});if(this.processBoltHandshake(c))return;if(this.serverProtocolVersion=(i=c.payload._bolt)==null?void 0:i.version,!this.processResponseMsg(c))return c}});u(this,"processResponseMsg",e=>{const{id:r}=e.payload._bolt,i=this.queue.get(r);return i?(n(this,Li).debug(`resolving pending request with id: ${r}, complete response: ${JSON.stringify(e)}`),e.type==="error"?i.cancel(ag(e)):i.resolve(ag(e)),!0):!1});u(this,"processBoltHandshake",e=>{var r,i;return e.type==="_bolt"||e.type==="handshake"?(this.respond((i=(r=e.payload._bolt)==null?void 0:r.id)!=null?i:cu(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1});this.label=i,this.transportId=a,m(this,Wd,e),m(this,Li,e.getValue("logger")),this.channel=r,this.queue=new Map}};let ai=wn;qr=new WeakMap,Wd=new WeakMap,Li=new WeakMap,u(ai,"createRequest",e=>{var r;if((r=e.payload)!=null&&r._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:{...e.payload,_bolt:{id:cu(8),type:"REQUEST",version:Xc}}}}),u(ai,"createResponse",(e,r)=>{var i;if((i=r.payload)!=null&&i._bolt)throw new Error("rpc fields are internal values");return{type:r.type,payload:{...r.payload,_bolt:{id:e,type:"RESPONSE",version:Xc}}}}),u(ai,"createNotification",e=>{var r;if((r=e.payload)!=null&&r._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:{...e.payload,bolt:{id:cu(8),type:"NOTIFY",version:Xc}}}}),u(ai,"createErrorResponse",(e,r)=>({type:"error",payload:{error:r.message,_bolt:{id:e,type:"RESPONSE",version:Xc}}}));const wd="transport closed";var Vi;const Rn=class extends Fl{constructor(e,{id:r,direction:i,handlerFactory:a,iceServers:o,iceTransportPolicy:c,proprietaryConstraints:d,additionalSettings:l,appData:h,config:p}){var E,P,C;super(e);u(this,"awaitQueue");u(this,"observer");u(this,"id");u(this,"serverId");u(this,"direction");u(this,"maxSctpMessageSize");u(this,"handler");u(this,"connectionState","new");u(this,"producers");u(this,"consumers");u(this,"datachannels");u(this,"connected",!1);u(this,"eventsDCReadyPromise");u(this,"eventsDCReadyPromiseResolver");u(this,"eventsDCFailureTimer");u(this,"transportConnectionPromise");u(this,"consumerTrackEvents");u(this,"unknownTracksMap");u(this,"appData");g(this,Vi,void 0);m(this,Vi,e);const f=e.getValue("logger");f.debug(`constructor() [id: ${r}, direction: ${i}]`),this.id=r,this.direction=i;const T=MD(l,{});delete T.iceServers,delete T.iceTransportPolicy,delete T.bundlePolicy,delete T.rtcpMuxPolicy,delete T.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.datachannels=new Map,this.consumerTrackEvents=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new Fu(f,!0),this.handler=a(),this.handler.enableHighBitrate=(E=p==null?void 0:p.enableHighBitrate)!=null?E:!1,this.handler.enableStereo=(P=p==null?void 0:p.enableStereo)!=null?P:!1,this.handler.enableDtx=(C=p==null?void 0:p.enableDtx)!=null?C:!0,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:i,iceServers:o,iceTransportPolicy:c,additionalSettings:l,proprietaryConstraints:d}),this.appData=h||{},this.transportConnectionPromise=new Promise(_=>{this.once("connected",()=>{_(!0)}),this.once("disconnect",()=>{_(!1)}),this.once("close",()=>{_(!1)})}),this.eventsDCReadyPromise=new Promise(_=>{this.eventsDCReadyPromiseResolver=_}),this.handler.on("@connectionstatechange",_=>{_!==this.connectionState&&(this.logger.debug(`connection state changed to ${_}`),this.connectionState=_,_==="connected"&&(this.connected=!0,this.emit("connected")),_==="disconnected"&&(this.connected=!1,this.emit("disconnect")),(_==="failed"||_==="closed")&&(this.connected=!1,this.emit("close")),this.closed||this.safeEmit("connectionstatechange",_))}),this.handler.on("@icecandidate",({candidate:_})=>{this.closed||this.safeEmit("icecandidate",_)}),this.handler.on("dc_open",_=>{let N=this.datachannels.get(_.label);N||(N||(N=new ai(n(this,Vi),_,_.label,this.serverId),this.datachannels.set(_.label,N)),this.eventsDCFailureTimer=setTimeout(()=>{_.label==="events"&&(this.eventsDCReadyPromiseResolver(!1),this.safeEmit("dc_error",_.label))},5e3))}),this.handler.on("datachannel",(_,N)=>{_.label==="events"&&(this.eventsDCReadyPromiseResolver(!0),this.eventsDCFailureTimer&&clearTimeout(this.eventsDCFailureTimer));const U=this.datachannels.get(_.label);if(!U){this.logger.error("unregistered datachannel for message",{rtcChannel:{label:_.label,message:N}});return}try{const D=JSON.parse(N);this.logger.debug("datachannel message chunk recieved",{dataChannelMessageChunk:{id:D.id,count:D.count,chunkIndex:D.chunkIndex,chunk:D.chunk,transprtId:this.serverId}});const $=U.processMessage(D);if(!$)return;this.logger.debug(`datachannel message with id:${D.id} on transport:${this.serverId}complete - ${JSON.stringify($)}`),this.emit(`datachannel:${_.label}`,U.label,$)}catch(D){this.logger.error("error parsing message",{error:D})}})}get closed(){return this.connectionState==="closed"}setServerId(e){this.serverId=e}getDatachannel(e){return this.datachannels.get(e)}get isEventsDCReady(){return this.eventsDCReadyPromise}close(){this.closed||(this.logger.debug("Transport close called"),this.connectionState="closed",this.awaitQueue.stop(),this.awaitQueue=void 0,this.connected=!1,this.handler.close(),Array.from(this.producers.values()).forEach(e=>{e.close(wd).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(wd)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"))}async getStats(){if(this.closed)throw new Rt("closed");return this.handler.getTransportStats()}async connect(e){try{if(await this.awaitQueue.push(async()=>{const{offerSdp:r,callback:i}=await this.handler.connect(),{transportId:a,answer:o}=await e(r);this.setServerId(a),await i(o)}),!await this.transportConnectionPromise)throw new Error("ice connection failed")}catch(r){throw this.logger.error("transport failed to connect:",{error:r}),r}}async restartIce(){if(this.logger.debug("restartIce()"),this.closed)throw new Rt("closed");return this.handler.restartIce()}async canProduce(e){const{track:r,appData:i}=e;if(r){if(this.direction!=="send")throw new bo("not a sending Transport");if(r.readyState==="ended")throw new Rt("track ended");if(i&&typeof i!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!await this.transportConnectionPromise)throw new ui("transport not connected");return!0}async produce(e,r){if(!await this.canProduce(e))throw new Error("Cannot produce");const{track:a,encodings:o,codecOptions:c,stopTracks:d=!0,disableTrackOnPause:l=!0,zeroRtpOnPause:h=!1,appData:p={}}=e;this.logger.debug(`produce() [track:${a.id}]`);const{producerId:f,localId:T,rtpSender:E}=await this.awaitQueue.push(async()=>{const{offerSdp:P,callback:C,sender:_,mid:N}=await this.handler.send({track:a,encodings:o,codecOptions:c,screenShare:p==null?void 0:p.screenShare}),{answer:U,producerId:D}=await r({offer:P,kind:a.kind,paused:l?!a.enabled||Object.hasOwn(a,"fakeTracks"):!1,appData:{...p||{},mid:N},codecOptions:c,producingTransportId:this.serverId}),$=await C(U);return{producerId:D,localId:$,rtpSender:_}},"Transport.produce");return this.createProducerObject({id:f,localId:T,track:a,stopTracks:d,disableTrackOnPause:l,zeroRtpOnPause:h,appData:p,handler:this.handler,rtpSender:E})}async createProducerObject(e){const r=new OD(n(this,Vi),e);return this.producers.set(r.id,r),r.once("close",()=>{this.producers.delete(r.id)}),this.emit("newproducer",r),r}async closeProducer(e){await this.awaitQueue.push(e.close.bind(e),"Transport.closeProducer")}async canConsume(){if(this.closed)throw new Rt("closed");if(this.direction!=="recv")throw new bo("not a receiving transport");if(!await this.transportConnectionPromise)throw new ui("transport not connected");return!0}async consume(e,r,i){return this.awaitQueue.push(async()=>{const a={},{consumerStates:o,sessionDescription:c,failedProducers:d}=await r(e);o.forEach((h,p)=>{a[p]=this.createConsumerObjectAndWaitForTrack({...h,producerId:p})}),c&&(this.logger.info("Session description found, sending negotiation request"),await i(c));const l=[];return await Promise.all(Object.entries(a).map(([h,p])=>p.then(f=>l.push(f)).catch(()=>{this.logger.error(`Failed to create consumer object, producer: ${h}`,{error:{message:"This should not happen"},transport:{serverId:this.serverId}})}))),{consumers:l,failedProducers:d}},"Transport.consume",{producersLength:e.length})}static parseCodecAndFmtpMappings(e,r){const i=ds.parse(e.sdp),a={};return i.media.forEach(o=>{r.includes(o.mid.toString())&&(a[o.mid.toString()]={rtp:o.rtp,fmtp:o.fmtp,payloads:o.payloads,rtcpFb:o.rtcpFb})}),a}static setCodecAndFmtpMappings(e,r,i){const a=ds.parse(e.sdp);return a.media=a.media.map(c=>{if(r.includes(c.mid.toString())){const d={...c};return d.rtp=i[c.mid.toString()].rtp,d.fmtp=i[c.mid.toString()].fmtp,d.payloads=i[c.mid.toString()].payloads,d.rtcpFb=i[c.mid.toString()].rtcpFb,d}return c}),{...e,sdp:ds.write(a)}}static parseHeaderExtensionMappings(e){const r=ds.parse(e.sdp),i={};return r.media.forEach(a=>{i[a.mid]=a.ext}),i}static setHeaderExtensionMappings(e,r){const i=ds.parse(e.sdp);return i.media=i.media.map(o=>{const c={...o};return c.ext=r[o.mid],c}),{...e,sdp:ds.write(i)}}async closeConsumers(e,r){try{const i=e.map(l=>l.transceiver.mid),a=Rn.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,i),o=Rn.parseHeaderExtensionMappings(this.handler.pc.remoteDescription);this.logger.info("Stopping transceivers",{consumerIds:e.map(({id:l})=>l)}),e.forEach(l=>l.close(void 0,!0));let c=await this.handler.pc.createOffer();this.logger.info("Created offer for closing consumers",{sdp:c.sdp}),c=Rn.setCodecAndFmtpMappings(c,i,a),c=Rn.setHeaderExtensionMappings(c,o),this.logger.info("Updated codec and fmtp mappings in close consumer offer",{sdp:c.sdp}),await this.setLocalDescription(c),this.logger.info("Successfully set local description in close consumers");const d=await r(e,c);this.logger.info("Received answer in close consumers",{sdp:d.sdp}),await this.setRemoteDescription(d),this.logger.info("Remote description was set successfully in close consumers",{sdp:d.sdp})}catch(i){this.logger.error("Failed to close consumers",{error:i})}}async setRemoteOffer(e){try{this.logger.info("Received offer from SFU",{sdp:e.sdp}),await this.setRemoteDescription(e);const r=await this.handler.pc.createAnswer();this.logger.info("Created answer corresponding to received offer",{sdp:r.sdp});const i=ds.parse(r.sdp);return i.media=i.media.map(a=>{if(a.type==="audio"){const o={...a},c=o.fmtp.find(l=>l.payload===111);return c&&(c.config+=";stereo=1;sprop-stereo=1"),o.rtcpFb||(o.rtcpFb=[]),o.rtcpFb.some(l=>l.type==="nack")||o.rtcpFb.push({payload:parseInt(o.payloads,10),type:"nack"}),o}return a}),r.sdp=ds.write(i),this.logger.info("Setting munged SDP",{sdp:r.sdp}),await this.setLocalDescription(r),this.logger.info("Successfully set local description",{sdp:r.sdp}),r}catch(r){throw this.logger.error("Set remote offer failed",{error:r}),r}}_ontrack(e){const{track:r,transceiver:i}=e;this.logger.info(`track event received [trackId: ${r.id}] [mid: ${i.mid}]`);const a=`${i.mid}:${r.kind}`;r.addEventListener("ended",()=>{this.logger.info(`rtc consumer track ended [trackId: ${r.id}]`),this.unknownTracksMap.delete(a)});const o=this.consumerTrackEvents.get(a);o?(o(r,i),this.consumerTrackEvents.delete(a)):(this.logger.warn(`track event handler not found ${a}`),this.unknownTracksMap.set(a,e))}sendErrorOverDC(e,r,i){const a=this.getDatachannel(e);if(!a)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});a.respond(r,i,!0)}sendResponseOverDC(e,r,i){const a=this.getDatachannel(e);if(!a)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});a.respond(r,i)}async createConsumerObjectAndWaitForTrack(e){const{consumerId:r,producerId:i,producingPeerId:a,producingTransportId:o,streamId:c,paused:d,screenShare:l,appData:h,kind:p,mimeType:f}=e,T=`${c}:${p}`,E={...e,name:"consumer creation task error",message:"consumer creation failed"};return new Promise(async(P,C)=>{const _=setTimeout(()=>{this.logger.warn(`Timed out waiting for track event ${T} producingPeerId: ${a}`),this.consumerTrackEvents.delete(T),E.isTimedout=!0,C(E)},5e3),N=(D,$)=>{try{if(D.readyState==="ended")clearTimeout(_),C(E);else{const G=D;G.enabled=!0,this.handler.midTransceiverMap.set($.mid,$);const ee=new DD(n(this,Vi),{id:r,localId:$.mid,transceiver:$,track:G,paused:d,producerId:i,producingPeerId:a,producingTransportId:o,handler:this.handler,appData:{...h,screenShare:l,peerId:a},rtpReceiver:$.receiver,mimeType:f});this.consumers.set(r,ee),ee.once("close",()=>{this.consumers.delete(ee.id),this.handler.midTransceiverMap.delete($.mid)}),this.logger.info("consumer created for ",{consumer:{id:r,kind:p,appData:{screenShare:l},peerId:a,producerId:i}}),this.emit("newconsumer",ee),clearTimeout(_),P(ee)}}catch(G){this.logger.warn("error while creating consumer:",G),clearTimeout(_),C(E)}},U=this.unknownTracksMap.get(T);U?(this.logger.info(`track event already received [trackId: ${U.track.id}] [mid: ${U.transceiver.mid}]`),this.unknownTracksMap.delete(T),N(U.track,U.transceiver)):(this.logger.info(`Registering onTrack handler for key ${T} [producingPeerId: ${a}]`),this.consumerTrackEvents.set(T,N))})}async setRemoteDescription(e){await this.handler.pc.setRemoteDescription(e)}async setLocalDescription(e){this.logger.debug(`${this.direction}() {transportId: ${this.serverId}} | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),await this.handler.pc.setLocalDescription(e)}async sendDataChannelMessage(e,r){const i=this.getDatachannel(e);if(!i)throw RD("DC_NOT_READY",`${e} datachannel not ready`);const a=(await i.request(r)).payload;return this.logger.info(`sendDataChannelMessage::response ${JSON.stringify(a)}`),a}};let Hu=Rn;Vi=new WeakMap;function VD(s){if(typeof navigator=="object"&&navigator.product==="ReactNative"){if(typeof RTCPeerConnection=="undefined"){s.warn("Device::this._detectDevice() | unsupported ReactNative without RTCPeerConnection");return}return s.debug("Device::this._detectDevice() | ReactNative handler chosen"),"Chrome74"}if(typeof navigator=="object"&&typeof navigator.userAgent=="string"){const t=navigator.userAgent,e=Vg.getParser(t),r=e.getEngine();if(e.satisfies({chrome:">=74",chromium:">=74","microsoft edge":">=88"}))return"Chrome74";if(e.satisfies({chrome:">=55",chromium:">=55"}))return;if(e.satisfies({firefox:">=110"}))return"Firefox110";if(e.satisfies({firefox:">=60"}))return"Firefox60";if(e.satisfies({ios:{OS:">=14.3",firefox:">=30.0"}})||e.satisfies({safari:">=12.0"})&&typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(e.satisfies({safari:">=11"})||e.satisfies({"microsoft edge":">=11"})&&e.satisfies({"microsoft edge":"<=18"}))return;if(r.name&&r.name.toLowerCase()==="blink"){const i=t.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);return i?Number(i[1])>=74?"Chrome74":void 0:"Chrome74"}if(r.name.toLowerCase()==="webkit"&&e.getOS().name.toLowerCase()==="ios")return typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection")?"Safari12":void 0;s.warn("Device::this._detectDevice() | browser not supported");return}s.warn("Device::this._detectDevice() | unknown device")}var er,xi;class xD{constructor(t,{handlerName:e,handlerFactory:r}={}){u(this,"handlerFactory");g(this,er,void 0);g(this,xi,void 0);const i=t.getValue("logger");if(i.debug("constructor()"),m(this,er,t),m(this,xi,i),e&&r)throw new TypeError("just one of handlerName or handlerInterface can be given");if(r)this.handlerFactory=r;else{if(e)n(this,xi).debug(`Device::constructor() | handler given: ${e}`);else if(e=VD(n(this,xi)),e)n(this,xi).debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=Lh.createFactory(n(this,er));break;case"Safari12":this.handlerFactory=Vh.createFactory(n(this,er));break;case"Firefox60":this.handlerFactory=Cd.createFactory(n(this,er),{supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=Cd.createFactory(n(this,er),{supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}}createTransport(t){const e=gr.v4();return new Hu(n(this,er),{id:e,...t,handlerFactory:this.handlerFactory})}}er=new WeakMap,xi=new WeakMap;const UD=2e3;var Ta,rt,it,ec,tc,Ui,va,sc,ya,$i,Ns,Sa,ld,rc,qu,Jd,Jf,ic,ju,Kd,Kf,zd,zf,Yd,Yf,Qd,Qf,Xd,Xf,nc,Gu,ac,Wu;class $D extends ot.EventEmitter{constructor(e,r){super();g(this,Sa);g(this,rc);g(this,Jd);g(this,ic);g(this,Kd);g(this,zd);g(this,Yd);g(this,Qd);g(this,Xd);g(this,nc);g(this,ac);u(this,"context");g(this,Ta,void 0);g(this,rt,void 0);g(this,it,void 0);g(this,ec,void 0);g(this,tc,void 0);g(this,Ui,void 0);g(this,va,void 0);g(this,sc,void 0);g(this,ya,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0});g(this,$i,void 0);g(this,Ns,"all");this.context=e,m(this,Ui,r),m(this,Ta,new xD(e)),m(this,va,new AD(r)),m(this,sc,Es),n(this,Sa,ld).mediaState={send:{state:In.NEW},recv:{state:In.NEW}},(Na(this.context,"forceRelay")||this.context.getValue("flagsmith").hasFeature(Q.FORCE_RELAY))&&m(this,Ns,"relay"),this.logger.info(`ICE Transport Policy initially set to ${n(this,Ns)}`),V(this,rc,qu).call(this)}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get socket(){return n(this,Ui)}get socketHandler(){return n(this,va)}get sendTransport(){return n(this,rt)}get recvTransport(){return n(this,it)}get events(){return n(this,sc)}set sendTransportConnectedCallback(e){m(this,ec,e)}set recvTransportConnectedCallback(e){m(this,tc,e)}async setupTransports(e){await V(this,Jd,Jf).call(this,e);let r,i;e.send&&(r=V(this,ic,ju).call(this,n(this,rt)).then(a=>{try{n(this,ec).call(this,a)}catch(o){this.logger.error("Failed to run send transport callback")}})),e.recv&&(i=V(this,ic,ju).call(this,n(this,it)).then(a=>{try{n(this,tc).call(this,a)}catch(o){this.logger.error("Failed to run recv transport callback")}})),await Promise.all([r,i])}stopTransports(e){var r,i;if(e.send&&this.sendTransport!==void 0){const{id:a,serverId:o,direction:c}=n(this,rt);this.logger.info("Closing send transport",{transport:{id:a,serverId:o,type:c}}),n(this,rt).close(),n(this,rt).removeAllListeners(),m(this,rt,void 0)}if(e.recv&&this.recvTransport!==void 0){const{id:a,serverId:o,direction:c}=n(this,it);this.logger.info("Closing recv transport",{transport:{id:a,serverId:o,type:c}}),(r=n(this,it))==null||r.close(),(i=n(this,it))==null||i.removeAllListeners(),m(this,it,void 0)}V(this,rc,qu).call(this)}stopAllTransports(){this.logger.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}handleErrors(e){throw new Error("Method not implemented.")}}Ta=new WeakMap,rt=new WeakMap,it=new WeakMap,ec=new WeakMap,tc=new WeakMap,Ui=new WeakMap,va=new WeakMap,sc=new WeakMap,ya=new WeakMap,$i=new WeakMap,Ns=new WeakMap,Sa=new WeakSet,ld=function(){return this.context.getValue("connectionHandler")},rc=new WeakSet,qu=function(){m(this,$i,{send:void 0,recv:void 0})},Jd=new WeakSet,Jf=async function(e){var o,c,d,l,h,p,f,T;(Na(this.context,"forceRelay")||this.context.getValue("flagsmith").hasFeature(Q.FORCE_RELAY))&&m(this,Ns,"relay"),this.logger.info(`ICE Transport Policy set to ${n(this,Ns)}`);const a=await at().getICEServers().catch(E=>(this.logger.warn(`failed to get iceservers from server: ${E.message}`),[]));if(e.send){const E=this.context.getValue("flagsmith").hasFeature(Q.DISABLE_OPUS_DTX_CF);V(this,zd,zf).call(this,{iceServers:a,additionalSettings:{encodedInsertableStreams:(o=this.context.getValue("modules").e2ee)==null?void 0:o.enabled},config:{enableHighBitrate:(l=(d=(c=this.context.getValue("defaults").mediaConfiguration)==null?void 0:c.audio)==null?void 0:d.enableHighBitrate)!=null?l:!1,enableStereo:(f=(p=(h=this.context.getValue("defaults").mediaConfiguration)==null?void 0:h.audio)==null?void 0:p.enableStereo)!=null?f:!1,enableDtx:!!E},iceTransportPolicy:n(this,Ns)})}e.recv&&V(this,Yd,Yf).call(this,{iceServers:a,additionalSettings:{encodedInsertableStreams:(T=this.context.getValue("modules").e2ee)==null?void 0:T.enabled},iceTransportPolicy:n(this,Ns)})},ic=new WeakSet,ju=async function(e){const{id:r,serverId:i,direction:a}=e;V(this,Qd,Qf).call(this,e);try{return await qf(async(c,d)=>{c>0&&this.logger.debug(`Retrying transport connect, count: ${c}`,{transport:{id:r,serverId:i,type:a}});try{if(e.closed)throw new ui("Cannot reconnect closed transport");await V(this,Kd,Kf).call(this,e)}catch(l){if(l instanceof ui){d(l);return}throw this.logger.error("Failed to connect transport, retrying",{transport:e,error:l}),l}},{delayTime:100,strategy:"exponential",maxRetryCount:1/0}),e}catch(o){throw this.logger.error(`Failed to connect send transport after retry: ${e.id}`,{error:o,transport:{id:r,serverId:i,type:a}}),e.close(),e.removeAllListeners(),o}},Kd=new WeakSet,Kf=async function(e){const{id:r,direction:i}=e;if(this.logger.info(`Connecting ${i} transport`,{transport:{id:r,type:i}}),!n(this,Ui).isConnected)throw new ui("Socket is not connected");if(e.connectionState==="closed")throw new ui("Transport is closed");try{await e.connect(a=>V(this,Xd,Xf).call(this,i,a)),this.logger.info(`Connected ${i} transport`,{transport:{id:r,serverId:e.serverId,type:i}})}catch(a){throw n(this,ya).transportFailureCount[i]+=1,a.message==="ice connection failed"?new ui(a.message):a}},zd=new WeakSet,zf=function(e){var r,i;if(n(this,rt)&&n(this,rt).connected){this.logger.info("Transport send is already connected",{transport:{id:(r=n(this,rt))==null?void 0:r.id,serverId:(i=n(this,rt))==null?void 0:i.serverId,type:"send"}});return}m(this,rt,n(this,Ta).createTransport({...e,direction:"send"})),this.context.getValue("callstats").configureSendTransport(n(this,rt))},Yd=new WeakSet,Yf=function(e){var r,i;if(n(this,it)&&n(this,it).connected){this.logger.info("Transport recv is already connected",{transport:{id:(r=n(this,it))==null?void 0:r.id,serverId:(i=n(this,it))==null?void 0:i.serverId,type:"recv"}});return}m(this,it,n(this,Ta).createTransport({...e,direction:"recv"})),this.context.getValue("callstats").configureRecvTransport(n(this,it))},Qd=new WeakSet,Qf=function(e){const{direction:r,id:i}=e;e.on("connectionstatechange",async a=>{V(this,ac,Wu).call(this,{state:a,direction:r}),this.logger.info(`Transport connection state changed for ${r} transport`,{transport:{id:i,serverId:e.serverId,type:r,status:a}});const o=()=>{const c=n(this,$i)[r];c!==void 0&&(clearTimeout(c),n(this,$i)[r]=void 0)};switch(a){case"connected":o(),n(this,ya).lastConnectionTime=performance.now();break;case"disconnected":n(this,$i)[r]=setTimeout(async()=>{this.logger.warn(`${r} transport is in disconnected state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await V(this,nc,Gu).call(this,e.direction)},UD);break;case"failed":if(e.closed)return;o(),this.logger.warn(`${r} transport is in failed state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await V(this,nc,Gu).call(this,e.direction);break}}),e.on("icecandidate",async a=>{this.logger.debug("Sending iceCandidate:",{iceCandidate:a})}),e.on("datachannel:events",async(a,o)=>{var c,d;this.logger.debug("Got data channel message on event:",{rtcChannel:{label:a,message:o}});try{switch(o.type){case"handshake":{const l={type:"handshake",payload:{message:"pong"}};e.sendResponseOverDC(a,LD(o),l);break}case"hub-disconnect":{this.logger.debug(`media hub disconnected, full_reconnect: ${(c=o.payload)==null?void 0:c.full_reconnect}`),((d=o.payload)==null?void 0:d.full_reconnect)===!0&&this.handleErrors("rejoin");break}case"error":break;default:break}}catch(l){this.logger.error(`Unable to handle the incoming datachannel message on channel ${a}`)}}),e.on("dc_error",()=>{e.direction==="recv"&&(this.logger.warn("Events datachannel did not open in 5s",{country:S.location.country}),this.handleErrors("reconnectRecvTransport"))})},Xd=new WeakSet,Xf=async function(e,r){const i=e==="recv";try{const{sdp:a,type:o}=r,c={consuming:i,description:{sdp:a,type:o,target:i?fr.SUBSCRIBER:fr.PUBLISHER},producers:[]};return n(this,va).connectTransport(c)}catch(a){throw this.logger.error(`Error in ${e} transport connection:`,{error:a,country:S.location.country}),a}},nc=new WeakSet,Gu=async function(e){switch(this.logger.info("Called reconnect transport",{transport:{type:e}}),this.stopTransports({[e]:!0}),this.context.getValue("flagsmith").hasFeature(Q.CF_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED)&&n(this,Ui).isConnected&&n(this,ya).transportFailureCount[e]>2&&(this.logger.warn(`Multiple disconnections in ${e} transport, forcing relay`),m(this,Ns,"relay")),await this.setupTransports({[e]:!0}),e){case"send":{this.logger.info("Transport reconnected",{transport:n(this,rt)}),this.context.getValue("peerSessionStore").emit(b.RESET_PRODUCER_STATE);break}case"recv":{this.logger.info("Transport reconnected",{transport:n(this,it)}),this.context.getValue("peerSessionStore").emit(b.UPDATE_ACTIVE,{createAllConsumers:!0});break}default:this.logger.warn("Unknown transport direction",{transport:{type:e}})}V(this,ac,Wu).call(this,{state:In.CONNECTED,direction:e})},ac=new WeakSet,Wu=function(e){const{state:r,direction:i}=e;n(this,Sa,ld).mediaState[i]={state:r},this.context.getValue("peerSessionStore").emit(b.TRANSPORT_STATE_UPDATE,{transport:i,...n(this,Sa,ld).mediaState[i]})};var oc,es;class FD{constructor(t,e,r,i,a){g(this,oc,void 0);g(this,es,void 0);this.events=e,this.recvTransport=r,this.socket=i,this.socketHandler=a,m(this,oc,t),m(this,es,t.getValue("logger"))}async create(t){if(!t||t&&t.length===0)throw new Error("List of producers is required");const e=new Map,r=[];t.forEach(d=>{const{producingPeerId:l,producerId:h,producingTransportId:p}=d,f=n(this,oc).getValue("flagsmith").hasFeature(Q.ENABLE_CF_SIMULCAST)?{simulcast:{preferredRid:"h",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}}:{};e.set(h,l),r.push({producingPeerId:l,producerId:h,producingTransportId:p,...f})});const i=await this.socketHandler.consume({requests:r,consumingTransportId:this.recvTransport.serverId}),a=new Map;t.forEach(d=>a.set(d.producerId,d));const o=new Map,c=[];return Object.entries(i.consumerStateMap).forEach(([d,l])=>{const h=a.get(d);if(!h)return;if(l.errorCode){n(this,es).warn(`Consumer request failed for producer ${d}`,{error:{message:l.errorCode}}),c.push({...h,errorCode:l.errorCode});return}let p={};try{p=JSON.parse(l.producerState.appData)}catch(f){}o.set(d,{consumerId:l.consumerId,producingTransportId:h.producingTransportId,producingPeerId:h.producingPeerId,kind:h.kind,paused:h.pause,streamId:l.producerTrack.streamId,trackId:l.producerTrack.trackId,screenShare:h.screenShare,mimeType:h.mimeType,appData:p})}),{consumerStates:o,sessionDescription:i.sessionDescription,failedProducers:c}}async negotiate(t){try{n(this,es).info("Negotiating socket consumer",{transport:this.recvTransport}),n(this,es).debug(`setting remote offer: ${JSON.stringify(t)} on recvTransport`,{transport:this.recvTransport});const e=await this.recvTransport.setRemoteOffer(t),r={transportId:this.recvTransport.serverId,description:{sdp:e.sdp,type:e.type,target:fr.SUBSCRIBER}};return n(this,es).debug(`sending renegotiate request: ${JSON.stringify(r)} on recvTransport`,{transport:this.recvTransport}),await this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,_w.toBinary(r)),n(this,es).info("Renegotiation done",{transport:this.recvTransport}),e}catch(e){n(this,es).error("Failed to renegotiate",{error:e});return}}async close(t){if(!t.length)return{};const e=async(r,i)=>{const a=r.map(l=>l.localId);n(this,es).info(`Closing consumers: ${JSON.stringify(a)}`);const o={description:{sdp:i.sdp,type:i.type,target:fr.SUBSCRIBER},consumerIds:a,consumingTransportId:this.recvTransport.serverId},c=await this.socketHandler.closeConsumer(o),d=YR.fromBinary(c).description;return{sdp:d.sdp,type:d.type}};return await this.recvTransport.awaitQueue.push(()=>this.recvTransport.closeConsumers(t,e),"ConsumerStrategy.close",{consumersLength:t.length}),{}}async switchConsumersToLayer(t,e){const r={requests:[],consumingTransportId:this.recvTransport.serverId},i=t.filter(a=>a&&a.id);i.forEach(({id:a,producingTransportId:o,localId:c})=>{r.requests.push({producerId:a,producingTransportId:o,mid:c,simulcast:{preferredRid:e===0?"q":"h",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}})}),await this.socketHandler.updateConsumersSimulcastConfig(r),n(this,es).info(`Consumers switched layers to ${e}`,{consumerIds:i==null?void 0:i.map(({id:a})=>a)})}}oc=new WeakMap,es=new WeakMap;class xh{constructor(t){this.socketHandler=t}static getMSIDFromSDP(t,e){return ds.parse(t).media.filter(a=>e==="video"?a.type==="video":a.type==="audio").at(-1).msid}async create({offer:t,kind:e,paused:r,appData:i,codecOptions:a,producingTransportId:o}){var p,f;const c=xh.getMSIDFromSDP(t.sdp,e),d={description:{sdp:t.sdp,type:t.type,target:fr.PUBLISHER},paused:r,kind:e,msid:c,appData:JSON.stringify(i),screenShare:(p=i.screenShare)!=null?p:!1,mimeType:`${e}/${(f=a[0])==null?void 0:f.name}`,producingTransportId:o},{answer:l,producerId:h}=await this.socketHandler.produce(d);return{answer:l,producerId:h}}}var Fi,jr,Ea,cc,Ls,Zd,tr,Pa,dc,Ju,el,Zf,tl,eT,sl,tT,rl,sT;class BD extends $D{constructor(e,r){super(e,r);g(this,dc);g(this,el);g(this,tl);g(this,sl);g(this,rl);g(this,Fi,void 0);g(this,jr,void 0);g(this,Ea,void 0);g(this,cc,void 0);g(this,Ls,void 0);g(this,Zd,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0});g(this,tr,[]);g(this,Pa,void 0);this.context=e,this.sendTransportConnectedCallback=async()=>{m(this,cc,new xh(this.socketHandler))},this.recvTransportConnectedCallback=async i=>{n(this,Ea).clear(),m(this,Ls,new FD(this.context,this.events,i,this.socket,this.socketHandler))},this.reset()}get socketHandler(){return super.socketHandler}get producers(){return n(this,Fi)}get consumers(){return n(this,jr)}get producerIdToConsumerIdMap(){return n(this,Ea)}get logger(){return this.context.getValue("logger")}reset(){m(this,Fi,new Map),m(this,jr,new Map),m(this,Ea,new Map)}async createProducer(e,r){var i;if(!this.sendTransport||this.sendTransport.closed)throw new Error("Send transport is closed");try{const a=await this.sendTransport.produce(e,V(this,el,Zf).bind(this));return(i=e.appData)!=null&&i.e2ee&&this.context.getValue("peerSessionStore").emit(b.E2EE_ACTIVE_PRODUCER,a),V(this,tl,eT).call(this,a,r),a}catch(a){throw this.logger.error("Failed to create producer",{error:a}),n(this,Zd).producerCreationFailureCount+=1,a}}async closeProducer(e,r){var a;const i=this.producers.get(e);if(!i){this.logger.warn(`Producer with ID ${e} was not found`);return}r!=null&&r.stopTrack&&i.track.stop();try{await this.sendTransport.closeProducer(i),(a=this.context.getValue("modules").e2ee)!=null&&a.enabled&&this.context.getValue("peerSessionStore").emit(b.E2EE_INACTIVE_PRODUCER,i)}catch(o){this.logger.error("Failed to close producer on server",{error:o,producer:i})}}closeAllProducers(){return Promise.all(Array.from(n(this,Fi).entries()).map(([,e])=>e.close()))}createConsumer(e){return this.createConsumers([e])}async createConsumers(e){n(this,Pa)||clearTimeout(n(this,Pa)),m(this,tr,n(this,tr).concat(e)),await V(this,dc,Ju).call(this)}closeConsumer(e){return this.closeConsumers([e])}async closeConsumers(e){if(!n(this,Ls))return;const r=e.map(a=>this.consumers.get(a)).filter(a=>a!==void 0);if(r.length===0)return;const{failedConsumers:i}=await n(this,Ls).close(r);i!=null&&i.length&&this.logger.warn("Failed to close some consumers",{consumerIds:i})}closeAllConsumers(){return this.closeConsumers(Array.from(n(this,jr).keys()))}async switchConsumersToLayer(e,r){n(this,Ls).switchConsumersToLayer(e,r)}}Fi=new WeakMap,jr=new WeakMap,Ea=new WeakMap,cc=new WeakMap,Ls=new WeakMap,Zd=new WeakMap,tr=new WeakMap,Pa=new WeakMap,dc=new WeakSet,Ju=async function(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const e=500,r=n(this,tr).splice(0,n(this,tr).length);try{const i=new Set(Array.from(this.consumers.values()).map(({producerId:d})=>d)),a=r.filter(({producerId:d})=>!this.producers.get(d)&&!i.has(d));if(a.length===0)return;const{consumers:o,failedProducers:c}=await this.recvTransport.consume(a,V(this,sl,tT).bind(this),n(this,Ls).negotiate.bind(n(this,Ls)));if(o.forEach(V(this,rl,sT).bind(this)),c!=null&&c.length){this.logger.error("Failed to create consumers for producers",{producers:c});const d=c.filter(({errorCode:l,producerId:h})=>l==="not_found_track_error"?(this.logger.error(`Track not found for producer: ${h}. This will not be retried.`),!1):l==="backend_error"?(this.logger.error("Unrecoverable error: backend error"),!1):!0);m(this,tr,n(this,tr).concat(d)),m(this,Pa,setTimeout(V(this,dc,Ju).bind(this),e))}}catch(i){if(this.logger.error("failed to consume on transport",{error:i}),i.errorCode==="internal_error"&&i.errorDescription==="Backend error"||i.errorCode==="invalid_session_description"){this.logger.error("Irrecoverable error, closing current recvTransport to create a new one",{transport:this.recvTransport,error:{code:i.errorCode,message:i.errorDescription}});try{this.stopTransports({recv:!0})}catch(a){}await this.setupTransports({recv:!0})}}},el=new WeakSet,Zf=function(e){return n(this,cc).create(e)},tl=new WeakSet,eT=function(e,r){e.on("close",async(i,a)=>{const{offer:o,reason:c}=i;if(this.logger.info("producer::closing",{debuggingHint:c,producer:{...e,status:"closing"}}),c!==wd){const d={producerId:e.id,description:{sdp:o.sdp,type:o.type,target:fr.PUBLISHER}};try{const l=await this.socketHandler.closeProducer(d),h={sdp:l==null?void 0:l.sdp,type:l==null?void 0:l.type};this.logger.info("producer::closed",{producer:{...e,status:"closed"}}),a({answer:h})}catch(l){this.logger.error("producer close error",l)}}this.producers.delete(e.id),r()}),e.on("trackended",()=>{this.logger.info("producer::trackended",{producer:{...e,status:"UNKNOWN"}})}),n(this,Fi).set(e.id,e)},sl=new WeakSet,tT=async function(e){try{return await this.recvTransport.canConsume(),await n(this,Ls).create(e)}catch(r){throw this.logger.error("Error in consume request",{error:r}),r}},rl=new WeakSet,sT=function(e){e.on("close",async r=>{this.logger.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),n(this,jr).delete(e.id),this.context.getValue("peerSessionStore").emit(b.CONSUMER_CLOSED,{id:e.id})}),n(this,jr).set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),this.context.getValue("peerSessionStore").emit(b.NEW_CONSUMER,{id:e.id,appData:e.appData,peerId:e.peerId})};var lc,uc,hc,_a,Ca,wa,pc,gc,Ra,_t,ms,fs,Bi,Hi,sr,mc,il,rT,nl,iT,al,nT,ol,aT;const cl=class{constructor({initialEnergyThreshold:t=.015,zeroCrossingThreshold:e=20,minVoiceDuration:r=3,hangoverFrames:i=5,noiseAdaptationRate:a=.95,voiceAdaptationRate:o=.99,minEnergyThreshold:c=.005,maxEnergyThreshold:d=.2,energyRatioThreshold:l=1.5,noiseHistorySize:h=50}={}){g(this,il);g(this,nl);g(this,lc,void 0);g(this,uc,void 0);g(this,hc,void 0);g(this,_a,void 0);g(this,Ca,void 0);g(this,wa,void 0);g(this,pc,void 0);g(this,gc,void 0);g(this,Ra,void 0);g(this,_t,void 0);g(this,ms,void 0);g(this,fs,!1);g(this,Bi,0);g(this,Hi,0);g(this,sr,[]);g(this,mc,void 0);m(this,_a,t),m(this,_t,t),m(this,lc,e),m(this,uc,r),m(this,hc,i),m(this,Ca,a),m(this,wa,o),m(this,pc,c),m(this,gc,d),m(this,Ra,l),m(this,mc,h),m(this,ms,t/2)}get voiceDetected(){return n(this,fs)}processAudioChunk(t){var o,c;const e=V(o=cl,al,nT).call(o,t),r=V(c=cl,ol,aT).call(c,t);return V(this,il,rT).call(this,e),e/n(this,ms)>n(this,Ra)&&e>n(this,_t)&&r>n(this,lc)?(m(this,Bi,n(this,Bi)+1),m(this,Hi,n(this,hc)),n(this,Bi)>=n(this,uc)&&m(this,fs,!0)):(m(this,Bi,0),n(this,Hi)>0?m(this,Hi,n(this,Hi)-1):n(this,fs)&&m(this,fs,!1),n(this,fs)||V(this,nl,iT).call(this,e)),{energy:e,isVoice:n(this,fs)}}reset(){m(this,fs,!1),m(this,Bi,0),m(this,Hi,0),m(this,_t,n(this,_a)),m(this,ms,n(this,_a)/2),m(this,sr,[])}getThresholdInfo(){return{currentEnergyThreshold:n(this,_t),backgroundNoiseEnergy:n(this,ms),energyRatioThreshold:n(this,Ra)}}};let uo=cl;lc=new WeakMap,uc=new WeakMap,hc=new WeakMap,_a=new WeakMap,Ca=new WeakMap,wa=new WeakMap,pc=new WeakMap,gc=new WeakMap,Ra=new WeakMap,_t=new WeakMap,ms=new WeakMap,fs=new WeakMap,Bi=new WeakMap,Hi=new WeakMap,sr=new WeakMap,mc=new WeakMap,il=new WeakSet,rT=function(t){n(this,fs)?m(this,_t,n(this,wa)*n(this,_t)+(1-n(this,wa))*t):m(this,_t,n(this,Ca)*n(this,_t)+(1-n(this,Ca))*n(this,ms)),m(this,_t,Math.max(n(this,pc),Math.min(n(this,gc),n(this,_t))))},nl=new WeakSet,iT=function(t){if(t<n(this,_t)*1.2)if(n(this,sr).push(t),n(this,sr).length>n(this,mc)&&n(this,sr).shift(),n(this,sr).length>=10){const e=[...n(this,sr)].sort((i,a)=>i-a),r=Math.floor(e.length/2);m(this,ms,e[r])}else m(this,ms,.95*n(this,ms)+.05*t)},al=new WeakSet,nT=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,r)=>e+r)/t.length)},ol=new WeakSet,aT=function(t){let e=0;for(let r=1;r<t.length;r+=1)(t[r]>=0&&t[r-1]<0||t[r]<0&&t[r-1]>=0)&&(e+=1);return e},g(uo,al),g(uo,ol);var fc;class og{constructor(t){u(this,"RNAudioSampleHandler");g(this,fc,void 0);m(this,fc,t);const{RNAudioSampleHandlerImpl:e}=navigator;e==null||e.init().then(r=>{this.RNAudioSampleHandler=r}).catch(r=>{this.logger.error("ReactNativeAudioSampler: Failed to initialize audio sampler",r)})}get logger(){return n(this,fc).getValue("logger")}get samples(){var e;const t=new Float32Array(1024);return(e=this.RNAudioSampleHandler)==null||e.getFloatTimeDomainData(t),t}stop(){var t;(t=this.RNAudioSampleHandler)==null||t.destructor()}}fc=new WeakMap;var Tc;class cg{constructor(t){u(this,"audioContext");u(this,"analyser");g(this,Tc,void 0);m(this,Tc,t),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048}get logger(){return n(this,Tc).getValue("logger")}get samples(){if(this.audioContext.state==="suspended")try{this.audioContext.resume()}catch(e){this.logger.error("AudioContextSampler: Failed to resume audio context",e)}const t=new Float32Array(this.analyser.frequencyBinCount);return this.analyser.getFloatTimeDomainData(t),t}set audioTrack(t){const e=new MediaStream;e.addTrack(t),this.audioContext.createMediaStreamSource(e).connect(this.analyser)}}Tc=new WeakMap;class HD{static setInterval(t,e=0,...r){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.setInterval(t,e,...r):global.setInterval(t,e,...r)}static clearInterval(t){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.clearInterval(t):global.clearInterval(t)}static setTimeout(t,e=0,...r){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.setTimeout(t,e,...r):global.setTimeout(t,e,...r)}static clearTimeout(t){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.clearTimeout(t):global.clearTimeout(t)}}const qD=60,jD=400;var rr,ir,Ts,vc,qi,ba,nr,Gr,ka,ar,or,Vs,dl,oT,yc,Ku,ll,cT,ul,dT;const Eo=class{constructor(t,e){g(this,dl);g(this,ll);g(this,rr,void 0);g(this,ir,void 0);g(this,Ts,void 0);g(this,vc,void 0);g(this,qi,void 0);g(this,ba,void 0);g(this,nr,void 0);g(this,Gr,void 0);g(this,ka,void 0);g(this,ar,void 0);g(this,or,void 0);g(this,Vs,void 0);this.reportRequest=e,m(this,ar,t),m(this,ba,new uo);const{isReactNative:r}=navigator;m(this,or,r?new og(n(this,ar)):new cg(n(this,ar))),m(this,Vs,r?HD:Zc)}get logger(){return n(this,ar).getValue("logger")}set producerId(t){m(this,Ts,t)}set audioTrack(t){m(this,vc,t),n(this,or)instanceof cg&&(n(this,or).audioTrack=t)}start(){this.logger.debug(`AudioActivityReporter: Starting audio activity reporter: ${n(this,Ts)}`),n(this,rr)&&n(this,Vs).clearInterval(n(this,rr)),m(this,rr,n(this,Vs).setInterval(async()=>{var i;if(!n(this,vc)||!n(this,Ts))return;const{energy:t}=V(this,dl,oT).call(this),e=V(i=Eo,yc,Ku).call(i,t);let r=.9;n(this,ka)!==e&&n(this,ka)?r=.9:e?r=.3:r=.5,m(this,qi,(n(this,qi)||0)*(1-r)+t*r)},qD)),n(this,ir)&&n(this,Vs).clearInterval(n(this,ir)),m(this,ir,n(this,Vs).setInterval(V(this,ll,cT).bind(this),jD))}stop(){try{this.logger.debug(`AudioActivityReporter: Stopping audio activity reporter: ${n(this,Ts)}`),n(this,rr)&&(n(this,Vs).clearInterval(n(this,rr)),m(this,rr,void 0)),n(this,ir)&&(n(this,Vs).clearInterval(n(this,ir)),m(this,ir,void 0))}catch(t){}n(this,ba).reset(),n(this,or)instanceof og&&n(this,or).stop()}};let ho=Eo;rr=new WeakMap,ir=new WeakMap,Ts=new WeakMap,vc=new WeakMap,qi=new WeakMap,ba=new WeakMap,nr=new WeakMap,Gr=new WeakMap,ka=new WeakMap,ar=new WeakMap,or=new WeakMap,Vs=new WeakMap,dl=new WeakSet,oT=function(){var o;const{samples:t}=n(this,or),{energy:e,isVoice:r}=n(this,ba).processAudioChunk(t),i=V(o=Eo,ul,dT).call(o,e);return n(this,ar).getValue("flagsmith").hasFeature(Q.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: producer: ${n(this,Ts)}, energy: ${n(this,qi)},
11
11
  slogScale: ${i}, isVoice: ${r}, minEnergy: ${n(this,nr)},
12
12
  maxEnergy: ${n(this,Gr)}`),i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!n(this,nr)||i<n(this,nr))&&m(this,nr,i),(!n(this,Gr)||i>n(this,Gr))&&m(this,Gr,i),{energy:(i-n(this,nr))/(n(this,Gr)-n(this,nr))*10||0,isVoice:r})},yc=new WeakSet,Ku=function(t){return t<5},ll=new WeakSet,cT=function(t=n(this,qi)){var r;if(!n(this,Ts)||!t){n(this,ar).getValue("flagsmith").hasFeature(Q.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: No producerId or energy to report: ${n(this,Ts)}`);return}const e={producerId:n(this,Ts),energy:Math.round(t),silent:V(r=Eo,yc,Ku).call(r,t)};m(this,ka,e.silent),this.reportRequest(e)},ul=new WeakSet,dT=function(t){const e=Math.log10(t);return Math.round(e)},g(ho,yc),g(ho,ul);const GD=(s=!1)=>{if("MediaStreamTrackGenerator"in window&&"AudioData"in window)try{const e=new window.MediaStreamTrackGenerator({kind:"audio"}),r=e.writable.getWriter(),i=48e3,a=128,o=1;let c=0,d=null;const l=async()=>{try{const f=new Float32Array(a*o),T=new window.AudioData({format:"f32",sampleRate:i,numberOfFrames:a,numberOfChannels:o,timestamp:c,data:f});c+=a/i*1e6,await r.ready,await r.write(T)}catch(f){d&&clearInterval(d),r.releaseLock(),e.writable.abort()}};d=window.setInterval(l,100);const p=new MediaStream([e]).getAudioTracks()[0];return p.addEventListener("ended",()=>{d&&clearInterval(d),r.releaseLock(),e.writable.abort()}),Object.assign(p,{fakeTracks:"fakeTracks:fakeAudioTrack"}),p.enabled=s,p}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 a=e.createMediaStreamDestination();i.connect(a),r.start();const o=a.stream.getAudioTracks()[0];return o?(Object.assign(o,{fakeTracks:"fakeTracks:fakeAudioTrack"}),o.enabled=s,o):void 0}catch(e){return}},WD=(s=!1)=>{var a,o;const t=new MediaStream().getVideoTracks()[0],e=document.createElement("canvas");e.height=(a=t==null?void 0:t.getSettings().height)!=null?a: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 JD=Object.defineProperty,KD=Object.getOwnPropertyDescriptor,ae=(s,t,e,r)=>{for(var i=r>1?void 0:r?KD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&JD(t,e,i),i};const At=["video/VP9","video/VP8"];var Sc,Ec,nt,H,Ia,mt,ji,Gi,Wi,Pc,ts,cr,_c,Ji,Ki,ft,Ct,Wr,yn,hl,uT,pl,hT,gl,pT,Cc,zu,ml,du,gT,fl,mT,Tl,fT,vl,TT,Ye,lt,zi,po,yl,vT,Sl,yT,El,ST;const lT=(du=class{constructor(s,t){g(this,Wr);g(this,hl);g(this,pl);g(this,gl);g(this,Cc);g(this,fl);g(this,Tl);g(this,vl);g(this,Ye);g(this,zi);g(this,yl);g(this,Sl);g(this,El);u(this,"context");u(this,"authToken");u(this,"e2ee");g(this,Sc,void 0);g(this,Ec,void 0);g(this,nt,void 0);g(this,H,void 0);g(this,Ia,void 0);g(this,mt,void 0);g(this,ji,void 0);g(this,Gi,void 0);g(this,Wi,void 0);g(this,Pc,void 0);g(this,ts,null);g(this,cr,void 0);g(this,_c,void 0);g(this,Ji,void 0);g(this,Ki,void 0);g(this,ft,void 0);g(this,Ct,void 0);var r,i;this.context=s;const{socket:e}=t;this.mediaJoined=!1,m(this,Ji,new Map([["video/VP9",new Set],["video/VP8",new Set]])),m(this,Ki,new Map([["video/VP9",new Set],["video/VP8",new Set]])),m(this,nt,e),m(this,ji,!1),m(this,H,new BD(s,e)),m(this,mt,n(this,H).events),m(this,cr,new Set),m(this,ft,new Map),m(this,Gi,!1),m(this,Wi,new Fu(s.getValue("logger"))),m(this,Ct,new ho(this.context,n(this,H).socketHandler.audioActivity.bind(n(this,H).socketHandler))),this.e2ee=(i=(r=s.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?i:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),m(this,Pc,Eh(async()=>{if(!n(this,Wr,yn).mediaJoinAttempted)return;const{roomJoined:a}=await this.joinRoom(n(this,Ec),n(this,Sc),!0,!0);a&&(this.context.getValue("peerSessionStore").emit(b.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(b.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 n(this,Wr,yn).mediaJoined}set mediaJoined(s){n(this,Wr,yn).mediaJoined=s}reset(){n(this,H).closeAllProducers(),n(this,H).closeAllConsumers(),n(this,ft).clear(),n(this,cr).clear(),m(this,ts,null),n(this,Wi).stop(),n(this,H).stopAllTransports(),n(this,H).reset(),m(this,Wi,new Fu)}async joinRoom(s,t,e=!1,r=!1,i={}){n(this,Wr,yn).mediaJoinAttempted=!0,m(this,ji,!0),e&&this.reset();try{return await n(this,Wi).push(()=>V(this,hl,uT).call(this,s,t,r,i),"joinRoom")}catch(a){return this.logger.error("Error in room joining process",{error:a}),this.context.getValue("peerSessionStore").emit(b.ROOM_NODE_FAILED),{roomJoined:!1}}}async initializeConnection(s,t,e=!1,r={}){return n(this,ts)?n(this,ts):(m(this,ts,(async()=>{try{await V(this,Cc,zu).call(this,s,t,e,r)}catch(i){throw m(this,ts,null),i}})()),n(this,ts))}getConsumers(){return n(this,H).consumers}getProducers(){return n(this,H).producers}async leaveRoom(){n(this,H).stopAllTransports(),m(this,Gi,!1),n(this,Wr,yn).mediaJoinAttempted=!1;const s={closeRoom:!1};n(this,nt).sendMessagePromise(n(this,mt).leaveRoom,Kw.toBinary(s)).then(e=>{var r;(r=VR.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():n(this,H).createConsumers(s)}async closeConsumers(s){if(!s.length)return;const t=s.reduce((e,r)=>{const i=n(this,H).producerIdToConsumerIdMap.get(r.producerId);return i?(e.push(i),e):(this.logger.warn(`consumer not found in close consumers: ${r.producerId}`),e)},[]);await n(this,H).closeConsumers(t)}async _shareWebcam(s,t){var p,f;const e=t==="video/VP9"?de.WEBCAM:de.WEBCAM_BACKUP,r=V(this,Ye,lt).call(this,e);if(r){const T=await r;if(n(this,H).producers.has(T)){const E=n(this,H).producers.get(T);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(At.filter(T=>T!==t)),a=V(this,El,ST).call(this,s,i),o=Na(this.context,"disableSimulcast"),c=(f=(p=this.context)==null?void 0:p.getValue("overrides"))==null?void 0:f.simulcastConfig;!(o||c&&c.disable)&&this.context.getValue("flagsmith").hasFeature(Q.ENABLE_CF_SIMULCAST)?(this.logger.info("Simulcast enabled for SFU: CF"),a.encodings=O0(this.context,s)):this.logger.info("Simulcast disabled for webcam producer, SFU: CF"),this.context.getValue("flagsmith").hasFeature(Q.TRACK_HINT)&&(a.track.contentHint=this.context.getValue("flagsmith").getValue(Q.TRACK_HINT));const l=()=>{this.logger.info("Disabling video due to the producer closure"),n(this,ft).delete(e)},h=n(this,H).createProducer(a,l);return V(this,zi,po).call(this,e,h.then(T=>T.id)),h.then(T=>T.track)}async shareWebcam(s){var r;if(s===void 0)return null;const t=(r=this.context.getValue("flagsmith").getValue(Q.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=At.filter(i=>{var a,o;return((o=(a=n(this,Ia).sender)==null?void 0:a.video)==null?void 0:o.codecs.findIndex(c=>c.mimeType===i))>=0&&n(this,Ki).get(i).size>0});return e.length===0&&e.push(At[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"),n(this,ft).delete(de.SCREENSHARE_VIDEO),n(this,ft).delete(de.SCREENSHARE_AUDIO)},a=n(this,H).createProducer(r,i);V(this,zi,po).call(this,de.SCREENSHARE_VIDEO,a.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=n(this,H).createProducer(c,d),V(this,zi,po).call(this,de.SCREENSHARE_AUDIO,o.then(l=>l.id))}await Promise.all([a,o||Promise.resolve()]),this.context.getValue("callstats").screenShareStart()}async shareMic(s){try{if(s===void 0)throw new Rt("track undefined");const t=V(this,Ye,lt).call(this,de.MIC);if(t){const a=await t;if(n(this,H).producers.has(a)){const o=n(this,H).producers.get(a);if(!o.closed){await o.replaceTrack({track:s}),await this.resumeMic(),n(this,Ct)&&(n(this,Ct).audioTrack=s,n(this,Ct).producerId=a,n(this,Ct).start());return}await n(this,H).closeProducer(a,{stopTrack:!1})}await this.shareMic(s);return}const e=V(this,Sl,yT).call(this,s),r=()=>{n(this,ft).delete(de.MIC)},i=n(this,H).createProducer(e,r);V(this,zi,po).call(this,de.MIC,i.then(a=>a.id)),await i.then(a=>{n(this,Ct)&&(n(this,Ct).audioTrack=a.track,n(this,Ct).producerId=a.id,n(this,Ct).start())})}catch(t){throw new R(t)}}async pauseMic(){var r;const s=await V(this,Ye,lt).call(this,de.MIC),t=n(this,H).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=n(this,Ct))==null||r.stop();const e={producerId:t.id,pause:!0};n(this,nt).sendMessage(n(this,mt).toggleProducer,Wc.toBinary(e))}async pauseWebcam(){const s=await V(this,Ye,lt).call(this,de.WEBCAM),t=await V(this,Ye,lt).call(this,de.WEBCAM_BACKUP),e=n(this,H).producers.get(s),r=n(this,H).producers.get(t);if(!e&&!r){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}const i=a=>{const o={producerId:a.id,pause:!0};n(this,nt).sendMessage(n(this,mt).toggleProducer,Wc.toBinary(o))};e&&(e.pause(),i(e)),r&&(r.pause(),i(r))}async resumeMic(){const s=await V(this,Ye,lt).call(this,de.MIC),t=n(this,H).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(b.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};n(this,nt).sendMessage(n(this,mt).toggleProducer,Wc.toBinary(e))}async resumeWebcam(s=de.WEBCAM){const t=await V(this,Ye,lt).call(this,s),e=n(this,H).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(b.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};n(this,nt).sendMessage(n(this,mt).toggleProducer,Wc.toBinary(r))}async disableWebcam(s){const t=s==="video/VP9"?de.WEBCAM:de.WEBCAM_BACKUP,e=await V(this,Ye,lt).call(this,t);V(this,yl,vT).call(this,t),e&&await n(this,H).closeProducer(e)}async disableMic(){var t;const s=await V(this,Ye,lt).call(this,de.MIC);s&&await n(this,H).closeProducer(s),(t=n(this,Ct))==null||t.stop(),n(this,ft).delete(de.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const s=await V(this,Ye,lt).call(this,de.SCREENSHARE_VIDEO),t=await V(this,Ye,lt).call(this,de.SCREENSHARE_AUDIO);s&&await n(this,H).closeProducer(s),t&&await n(this,H).closeProducer(t),n(this,cr).clear(),n(this,ft).delete(de.SCREENSHARE_VIDEO),n(this,ft).delete(de.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(s,t){if(s){const e=await V(this,Ye,lt).call(this,de.WEBCAM),r=await V(this,Ye,lt).call(this,de.WEBCAM_BACKUP);await n(this,H).closeProducer(e,{stopTrack:!1}),await n(this,H).closeProducer(r,{stopTrack:!1}),this.shareWebcam(s)}if(t){const e=await V(this,Ye,lt).call(this,de.SCREENSHARE_VIDEO);await n(this,H).closeProducer(e,{stopTrack:!1}),this.shareScreen({video:t})}}async changeDisplayName(s,t){const e={displayName:s,participantId:t!=null?t:this.peerId};if(!await n(this,H).socketHandler.changeDisplayName(e))throw new Error("failed to change display name!")}kick(s){const t={peerIds:[s]};n(this,H).socketHandler.kickPeer(t)}kickAll(){n(this,H).socketHandler.kickAll()}async muteAll(s){if(!await n(this,H).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await n(this,H).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(s){if(!await n(this,H).socketHandler.hostControlForPeer(s,"audio"))throw new Error("failed to mute given participant")}async disableVideo(s){if(!await n(this,H).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 n(this,nt).sendMessagePromise(n(this,mt).globalPinPeer,cR.toBinary(t))}catch(e){this.logger.error("Error in pinning peer:",{error:e})}}validateScreenShare(s){return this.peerId===s.peerId&&n(this,H).producers.get(s.producerId)&&n(this,cr).add(s.consumerPeerId),n(this,cr).size}async switchConsumersToLayer(s,t){const e=s.map(r=>this.getConsumers().get(r));n(this,H).switchConsumersToLayer(e,t)}async handleSocketEvents(){n(this,nt).on(n(this,mt).peerProducerCreateBroadcast,({payload:s})=>{var t,e;if(this.mediaJoined)try{const{participantId:r,producerState:i}=hb.fromBinary(s);if(r===this.peerId)return;if(i!=null&&i.mimeType||(i.mimeType=i.kind===xs.AUDIO?"audio/opus":"video/VP8"),i.kind===xs.VIDEO&&!i.screenShare&&((e=(t=n(this,Ia).receiver)==null?void 0:t.video)==null?void 0:e.codecs.findIndex(a=>a.mimeType===At[0]))>=0&&n(this,Ji).get(At[0]).has(r)&&i.mimeType!==At[0]){this.logger.warn(`Ignoring producer: ${i.producerId}`);return}this.logger.info(`producer created broadcast: ${r}, producer state: ${i}`),this.context.getValue("peerSessionStore").emit(b.NEW_PRODUCER,{peerId:r,producer:{...i,kind:i.kind===xs.AUDIO?"audio":"video",producingPeerId:r}})}catch(r){this.logger.error("error in peer-producer-create-broadcast",{error:r})}}),n(this,nt).on(n(this,mt).peerProducerToggleBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,initiatorParticipantId:e,producerState:{kind:r,pause:i,producerId:a,screenShare:o}}=Lp.fromBinary(s);if(o)return;const c=r===xs.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${t}, producerId: ${a}, kind:${c}, paused:${i} payload: ${JSON.stringify(Lp.fromBinary(s))}`),t===this.peerId&&e!==this.peerId&&i&&this.context.getValue("peerSessionStore").emit(c==="audio"?b.MUTE_SELF:b.MUTE_SELF_VIDEO),t===this.peerId)return;this.context.getValue("peerSessionStore").emit(b.PRODUCER_TOGGLE,{peerId:t,producerId:a,paused:i,kind:c}),Array.from(this.getConsumers().values()).filter(l=>l.producerId===a).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(b.CONSUMER_PAUSED,{id:l.id})):(l.resume(),this.context.getValue("peerSessionStore").emit(b.CONSUMER_RESUMED,{id:l.id})))})}catch(t){this.logger.error("error in producer toggle broadcast handler",{error:t})}}),n(this,nt).on(n(this,mt).peerLeaveBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t}=Su.fromBinary(s);if(t===this.peerId)return;this.logger.info(`peer left broadcast:${t}`),n(this,cr).delete(t),n(this,H).consumers.forEach(e=>{e.peerId===t&&e.close()}),this.context.getValue("peerSessionStore").emit(b.PEER_CLOSED,{id:t})}catch(t){this.logger.error("error in peer left broadcast",{error:t})}}),n(this,nt).on(n(this,mt).peerProducerCloseBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,producerState:{producerId:e}}=mb.fromBinary(s);if(t===this.peerId)return;this.logger.info(`producer closed broadcast:${t}`),this.context.getValue("peerSessionStore").emit(b.PRODUCER_CLOSED,{peerId:t,producerId:e});const r=n(this,H).producerIdToConsumerIdMap.get(e);if(!r){this.logger.warn(`no consumer found for producer:${e}`);return}this.logger.info(`closing consumer ${r}, producer id: ${e}`),n(this,H).closeConsumer(r).then(()=>{this.logger.info(`closed consumer: ${r}`),n(this,H).producerIdToConsumerIdMap.delete(e),this.context.getValue("peerSessionStore").emit(b.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})}}),n(this,nt).on(n(this,mt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!n(this,ji)&&!n(this,Gi)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(b.ROOM_NODE_DISCONNECTED),n(this,Pc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(s=>{s.forEach((t,e)=>{const r=n(this,H).consumers.get(e);r&&this.context.getValue("peerSessionStore").emit(b.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(n(this,H).producers.values()).find(i=>i.id===e);r&&this.context.getValue("peerSessionStore").emit(b.PRODUCER_SCORE_UPDATE,{id:e,kind:r.kind,appData:r.appData,score:t.score,scoreStats:t})})})}handlePeerCapabilities(s,t){var e,r,i,a;for(let o=0;o<=At.length;o+=1){const c=At[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===At.length-1){n(this,Ki).get(c).add(s);break}}for(let o=0;o<=At.length;o+=1){const c=At[o];if(((a=(i=t==null?void 0:t.sender)==null?void 0:i.video)==null?void 0:a.codecs.findIndex(d=>d.mimeType===c))>=0||o===At.length-1){n(this,Ji).get(c).add(s);break}}}handlePeerLeaving(s){this.context.getValue("flagsmith").hasFeature(Q.FORCE_VIDEO_CODEC)||(n(this,Ji).forEach(t=>t.delete(s)),n(this,Ki).forEach((t,e)=>{t.delete(s),!(t.size!==0||e===At[0])&&this.disableWebcam(e)}))}},Sc=new WeakMap,Ec=new WeakMap,nt=new WeakMap,H=new WeakMap,Ia=new WeakMap,mt=new WeakMap,ji=new WeakMap,Gi=new WeakMap,Wi=new WeakMap,Pc=new WeakMap,ts=new WeakMap,cr=new WeakMap,_c=new WeakMap,Ji=new WeakMap,Ki=new WeakMap,ft=new WeakMap,Ct=new WeakMap,Wr=new WeakSet,yn=function(){return this.context.getValue("connectionHandler")},hl=new WeakSet,uT=async function(s,t,e,r){m(this,Ec,s);try{return n(this,ts)?await n(this,ts):await V(this,Cc,zu).call(this,s,t,e,r),V(this,gl,pT).call(this,t),{roomJoined:await V(this,pl,hT).call(this)}}catch(i){return this.logger.error("Failed to complete room join",{error:i}),{roomJoined:!1}}finally{m(this,ts,null)}},pl=new WeakSet,hT=async function(){try{this.mediaJoined=!0;const{roomState:s}=await n(this,H).socketHandler.notifySelfJoinComplete();return m(this,Sc,s.roomUuid),m(this,Gi,!0),m(this,ji,!1),!0}catch(s){return this.logger.error("Error completing room join",{error:s}),this.mediaJoined=!1,!1}},gl=new WeakSet,pT=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)},Cc=new WeakSet,zu=async function(s,t,e,r){var i,a;try{(a=n(this,_c))!=null||m(this,_c,V(i=lT,ml,gT).call(i));const o=V(this,fl,mT).call(this);await V(this,Tl,fT).call(this,s,t,e,o),await n(this,H).setupTransports({send:!0,recv:!0}),await V(this,vl,TT).call(this,r)}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}},ml=new WeakSet,gT=function(){const{ipInfo:s}=at();if(!(s!=null&&s.loc))return;const[t,e]=s.loc.split(",").map(parseFloat);return{latitude:t,longitude:e}},fl=new WeakSet,mT=function(){var e;const s=(e=this.context.getValue("flagsmith").getValue(Q.FORCE_VIDEO_CODEC))==null?void 0:e.toString(),t=ID(s);return m(this,Ia,t),t},Tl=new WeakSet,fT=async function(s,t,e,r){await qf(async(i,a)=>{if(!n(this,nt).isConnected){a(new Error("Socket is not connected"));return}i>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${i}`});try{await n(this,H).socketHandler.joinRoom(t,s,r,e,n(this,_c))}catch(o){throw this.logger.error("Failed to send joinRoom message after retries",{error:o}),o}},{delayTime:1e3,strategy:"exponential",maxRetryCount:1/0})},vl=new WeakSet,TT=async function(s){if(!(!this.context.getValue("flagsmith").hasFeature(Q.PRECREATE_PRODUCERS)||!s))try{const e=[];if(s.canProduceVideo===B.Allowed&&e.push(this.shareWebcam(WD(!1))),s.canProduceAudio===B.Allowed){const r=GD(!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})}},Ye=new WeakSet,lt=function(s){return n(this,ft).get(s)},zi=new WeakSet,po=function(s,t){return n(this,ft).set(s,t)},yl=new WeakSet,vT=function(s){return n(this,ft).delete(s)},Sl=new WeakSet,yT=function(s){return{track:s,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},El=new WeakSet,ST=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}},g(du,ml),du);let re=lT;ae([S.trace("MediaNodeClient.reset",{country:S.location.country})],re.prototype,"reset",1);ae([S.trace("MediaNodeClient.joinRoom")],re.prototype,"joinRoom",1);ae([S.trace("MediaNodeClient.leaveRoom")],re.prototype,"leaveRoom",1);ae([S.trace("MediaNodeClient.activatePeers")],re.prototype,"activatePeers",1);ae([S.trace("MediaNodeClient.createConsumers")],re.prototype,"createConsumers",1);ae([S.trace("MediaNodeClient.closeConsumers")],re.prototype,"closeConsumers",1);ae([S.trace("MediaNodeClient._shareWebcam")],re.prototype,"_shareWebcam",1);ae([S.trace("MediaNodeClient.shareWebcam")],re.prototype,"shareWebcam",1);ae([S.trace("MediaNodeClient.shareScreen")],re.prototype,"shareScreen",1);ae([S.trace("MediaNodeClient.shareMic")],re.prototype,"shareMic",1);ae([S.trace("MediaNodeClient.pauseMic")],re.prototype,"pauseMic",1);ae([S.trace("MediaNodeClient.pauseWebcam")],re.prototype,"pauseWebcam",1);ae([S.trace("MediaNodeClient.resumeMic")],re.prototype,"resumeMic",1);ae([S.trace("MediaNodeClient.resumeWebcam")],re.prototype,"resumeWebcam",1);ae([S.trace("MediaNodeClient.disableWebcam")],re.prototype,"disableWebcam",1);ae([S.trace("MediaNodeClient.disableMic")],re.prototype,"disableMic",1);ae([S.trace("MediaNodeClient.disableScreenShare")],re.prototype,"disableScreenShare",1);ae([S.trace("MediaNodeClient.muteSelf")],re.prototype,"muteSelf",1);ae([S.trace("MediaNodeClient.resetVideoProducers")],re.prototype,"resetVideoProducers",1);ae([S.trace("MediaNodeClient.changeDisplayName")],re.prototype,"changeDisplayName",1);ae([S.trace("MediaNodeClient.kickPeer")],re.prototype,"kick",1);ae([S.trace("MediaNodeClient.kickAllPeers")],re.prototype,"kickAll",1);ae([S.trace("MediaNodeClient.muteAll")],re.prototype,"muteAll",1);ae([S.trace("MediaNodeClient.muteAllVideo")],re.prototype,"muteAllVideo",1);ae([S.trace("MediaNodeClient.disableAudio")],re.prototype,"disableAudio",1);ae([S.trace("MediaNodeClient.disableVideo")],re.prototype,"disableVideo",1);ae([S.trace("MediaNodeClient.pinPeer")],re.prototype,"pinPeer",1);ae([S.trace("MediaNodeClient.validateScreenShare")],re.prototype,"validateScreenShare",1);function ET(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 PT(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 zD=Object.defineProperty,YD=Object.getOwnPropertyDescriptor,gn=(s,t,e,r)=>{for(var i=r>1?void 0:r?YD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&zD(t,e,i),i},Yi,vs,X,Tt,Dt,Dg;const _T=(Dg=class{constructor(s,t,e,r){g(this,Tt);u(this,"self");u(this,"authToken");g(this,Yi,void 0);u(this,"viewType");g(this,vs,void 0);g(this,X,void 0);const{socket:i}=e,a=s.getValue("authToken");this.self=t,m(this,X,s),this.viewType=r,this.authToken=a,m(this,Yi,i),m(this,vs,e),t.config.viewType!==bt.Chat&&this.setupEvents()}get peerId(){return n(this,X).getValue("peerId")}get telemetry(){return n(this,X).getValue("telemetry")}get logger(){return n(this,X).getValue("logger")}get mediaJoined(){return n(this,X).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const a=at(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=await Je.__init__(s,e,r,i,i.name,c);s.setValue("self",d);const l=s.getValue("logger");if(navigator.product!=="ReactNative"){const h=!s.getValue("flagsmith").hasFeature(Q.PRECALL_BANDWIDTH_TEST);setTimeout(async()=>{const p=await d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(p)}),s.getValue("callstats").devices("AUDIO",p==null?void 0:p.filter(f=>f.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",p==null?void 0:p.filter(f=>f.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",p==null?void 0:p.filter(f=>f.kind==="audiooutput")),l.info("Callstats:: initializing");try{await s.getValue("callstats").initialize({peerId:o,engineName:Te.getDeviceInfo().engineName,env:s.getValue("env"),iceServers:await a.getICEServers(),apiBase:s.getValue("apiBase"),flags:s.getValue("flagsmith").getAllFlags(),logger:l,apiHostnames:Xm(s),skipConnectivityChecks:h}),l.info("Callstats:: initialized")}catch(f){l.error("Callstats:: initialization failed",{error:f})}},0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new _T(s,d,t,i.viewType)}async shareMediaTracks(){var c;const{audioTrack:s,videoTrack:t,permissions:e,audioEnabled:r,videoEnabled:i,screenShareEnabled:a,screenShareTracks:o}=this.self;if(e.canProduceAudio===B.Allowed&&r)try{await n(this,Tt,Dt).shareMic(s),this.self.audioEnabled||n(this,Tt,Dt).pauseMic()}catch(d){this.self.disableAudio()}if(e.canProduceVideo===B.Allowed&&i)try{const d=await n(this,Tt,Dt).shareWebcam(t);d&&d.id!==t.id&&n(this,X).getValue("flagsmith").hasFeature(Q.EXP_RESHARE)&&await n(this,Tt,Dt).shareWebcam(d),this.self.videoEnabled||n(this,Tt,Dt).pauseWebcam()}catch(d){this.self.disableVideo()}if(e.canProduceScreenshare===B.Allowed&&a)try{await((c=n(this,Tt,Dt))==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){n(this,X).getValue("callstats").callEnded(),n(this,Tt,Dt).reset(),s&&await this.joinRoom(s)}setupEvents(){n(this,X).getValue("peerSessionStore").on(b.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&this.shareMediaTracks()}),n(this,X).getValue("peerSessionStore").on(b.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),n(this,X).getValue("peerSessionStore").on(b.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),n(this,X).getValue("peerSessionStore").on(b.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),n(this,X).getValue("peerSessionStore").on(b.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),n(this,X).getValue("peerSessionStore").on(b.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;let{peerId:t}=this;s&&n(this,X).getValue("flagsmith").hasFeature(Q.REFRESH_ID_ON_DISCONNECTION)&&(t=gr.v4()),n(this,Yi).updateURL(t),n(this,X).getValue("telemetry").resetPeerId(t),at().setHeader("tracing-id",t),hr.remapContext(t,n(this,X)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),n(this,X).getValue("peerSessionStore").on(b.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),n(this,vs).on(x.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),n(this,vs).on(id.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&n(this,X).getValue("peerSessionStore").emit(b.UPDATE_PERMISSIONS,t.patch)})}),n(this,vs).on(x.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),n(this,vs).on(x.kick,()=>{this.kickHandler({kickType:"kick"})}),n(this,vs).on(x.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),n(this,X).getValue("peerSessionStore").onAsync(b.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),n(this,X).getValue("peerSessionStore").on(b.PRODUCER_SCORE_UPDATE,({score:s,kind:t,appData:e,scoreStats:r})=>{var a;const i=(a=e==null?void 0:e.screenShare)!=null?a:!1;this.self.emit("mediaScoreUpdate",{kind:t,isScreenshare:i,score:s,participantId:this.self.id,scoreStats:r})}),n(this,X).getValue("peerSessionStore").on(b.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),n(this,X).getValue("callstats").audioOff())}),n(this,X).getValue("peerSessionStore").on(b.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),n(this,X).getValue("callstats").videoOff())}),n(this,X).getValue("peerSessionStore").onAsync(b.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),n(this,X).getValue("peerSessionStore").on(b.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{const{peer:t}=await n(this,vs).joinRoom(this.self);n(this,vs).socket.flush();const e=Rh(t.stageType);if(n(this,X).setValue("stageStatus",e,!1),t.waitlisted){this.waitlistedHandler();return}await this.joinMediaRoom(s),n(this,X).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=n(this,X).getValue("roomSocketHandler"))==null||t.cleanup(),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),n(this,X).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),n(this,X).notify("stageStatus");try{(e=n(this,Yi))==null||e.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}PT(n(this,X)),this.self.roomState=s,this.self.emit("roomLeft",{state:s}),this.logger.info(`roomLeft event emitted with state: ${s}`)}async joinMediaRoom(s=!1){var a,o;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=n(this,X).getAllValues();try{if(e===bt.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}ET(n(this,X),{socket:n(this,Yi),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:h}=(o=await((a=n(this,Tt,Dt))==null?void 0:a.joinRoom(this.self.name,r,s,s,{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l})))!=null?o:{};if(!h)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 R("Error: could not join media room","0002")}}async leaveMediaRoom(s){const t=n(this,X).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===bt.Webinar)&&n(this,Tt,Dt)&&(n(this,Tt,Dt).mediaJoined&&s!=="disconnected"&&await n(this,Tt,Dt).leaveRoom(),!(s==="stageLeft"&&t===bt.Livestream)&&(n(this,Tt,Dt).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()}},Yi=new WeakMap,vs=new WeakMap,X=new WeakMap,Tt=new WeakSet,Dt=function(){return n(this,X).getValue("roomNodeClient")},Dg);let ti=_T;gn([S.trace("SelfController.resetSelf")],ti.prototype,"resetSelf",1);gn([S.trace("SelfController.setupEvents")],ti.prototype,"setupEvents",1);gn([S.trace("SelfController.joinRoom")],ti.prototype,"joinRoom",1);gn([S.trace("SelfController.leaveRoom")],ti.prototype,"leaveRoom",1);gn([S.trace("SelfController.joinMediaRoom")],ti.prototype,"joinMediaRoom",1);gn([S.trace("SelfController.leaveMediaRoom")],ti.prototype,"leaveMediaRoom",1);gn([S.trace("SelfController.init")],ti,"init",1);var wc;class QD{constructor(t){g(this,wc,void 0);m(this,wc,t)}on(t,e){let r;t===x.roomPeerCount?r=Up.fromBinary.bind(Up):r=zp.fromBinary.bind(zp),n(this,wc).on(t,({payload:i})=>{if(t===x.roomPeerCount&&!i)return;const a=r(i);e(a)})}}wc=new WeakMap;var Rc,bc;class XD{constructor(t,e){g(this,Rc,void 0);g(this,bc,void 0);m(this,Rc,e),m(this,bc,t)}get logger(){return n(this,bc).getValue("logger")}on(t,e){let r,i;switch(t){case x.transcript:{r=Zl.fromBinary.bind(Zl),i=Zl.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}n(this,Rc).on(t,({payload:a})=>{let o=i;try{o=r(a)}catch(c){this.logger.error("aiSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}Rc=new WeakMap,bc=new WeakMap;var ZD=Object.defineProperty,eO=Object.getOwnPropertyDescriptor,Uh=(s,t,e,r)=>{for(var i=r>1?void 0:r?eO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&ZD(t,e,i),i},dr,Aa;class Bl{constructor(t,e){g(this,dr,void 0);g(this,Aa,void 0);m(this,dr,e),m(this,Aa,t)}get logger(){return n(this,Aa).getValue("logger")}get telemetry(){return n(this,Aa).getValue("telemetry")}getPolls(){return n(this,dr).sendMessagePromise(qs.getPolls)}createPoll(t,e,r=!1,i=!1){const a={anonymous:r,hideVotes:i,question:t,options:e};return n(this,dr).sendMessage(qs.createPoll,rM.toBinary(a))}votePoll(t,e){const r={index:e,pollId:t};return n(this,dr).sendMessage(qs.votePoll,nM.toBinary(r))}on(t,e){let r,i;switch(t){case qs.updatePoll:case qs.createPoll:case qs.votePoll:{r=nu.fromBinary.bind(nu),i=nu.create();break}}n(this,dr).on(t,({payload:a})=>{let o=i;try{o=r(a)}catch(c){this.logger.error("pollSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}removeListeners(t){n(this,dr).removeListeners(t)}}dr=new WeakMap,Aa=new WeakMap;Uh([S.trace("PollSocketHandler.getPolls")],Bl.prototype,"getPolls",1);Uh([S.trace("PollSocketHandler.createPoll")],Bl.prototype,"createPoll",1);Uh([S.trace("PollSocketHandler.votePoll")],Bl.prototype,"votePoll",1);var tO=Object.defineProperty,sO=Object.getOwnPropertyDescriptor,rO=(s,t,e,r)=>{for(var i=r>1?void 0:r?sO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&tO(t,e,i),i},xt;class CT{constructor(t,e){u(this,"socket");g(this,xt,void 0);m(this,xt,t),this.socket=e,this.handleSocketEvents(),n(this,xt).setValue("roomSocketHandler",this)}get telemetry(){return n(this,xt).getValue("telemetry")}get logger(){return n(this,xt).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(x.joinRoom,jb.toBinary(e));try{const{peer:a}=fn.fromBinary((await r).payload);n(this,xt).getValue("connectionHandler").socketJoined=!0,n(this,xt).getValue("peerSessionStore").emit(b.SOCKET_SERVICE_ROOM_JOINED,{peer:a});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=await Promise.all([o,c]);return n(this,xt).getValue("peerSessionStore").emit(b.ROOM_STATE,d),n(this,xt).getValue("peerSessionStore").emit(b.SOCKET_PEERS,l),{peer:a}}catch(a){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:a}),new R("Error: RoomSocketHandler.joinRoom failed.","0002",this.logger,a)}}async getAllAddedParticipants(){try{return kk.fromBinary((await this.socket.sendMessagePromise(x.getAllAddedParticipants)).payload).participants.map(({id:e,...r})=>({...r,userId:e}))}catch(t){return[]}}async getRoomPeers(t,e,r){let i;try{const a={seachQuery:t,limit:e,offset:r},o=await this.socket.sendMessagePromise(x.getRoomPeersInfo,Nb.toBinary(a));i=eu.fromBinary(o.payload)}catch(a){this.logger.error("getRoomPeers::binary_decode_error",{error:a})}return i}async getRoomPeersNonPaginated(){let t;try{const e=await this.socket.sendMessagePromise(x.getRoomPeersInfo);t=eu.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(x.getRoomPeersInfo);t=eu.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(x.getPeerInfo,df.toBinary({peerId:t}));e=fn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=$p.create();try{const e=await this.socket.sendMessagePromise(x.getRoomInfo);t=$p.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=qp.create();try{const e=await this.socket.sendMessagePromise(x.getRoomStageState);t=qp.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(x.broadcastMessage,ro.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(x.broadcastToEntity,ro.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(x.broadcastToEntity,ro.toBinary(i))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(x.leaveRoom,Wb.toBinary({}))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(x.kick,uf.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(x.kickAll,af.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(x.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(x.acceptWaitingRoomRequests,Nk.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(x.denyWaitingRoomRequests,Vk.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(id.updateUserPreset,uI.toBinary(r))}handleSocketEvents(){this.socket.on(x.broadcastMessage,({payload:t})=>{try{const e=ro.fromBinary(t);n(this,xt).getValue("peerSessionStore").emit(b.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(x.broadcastToEntity,({payload:t})=>{try{const e=ro.fromBinary(t);n(this,xt).getValue("peerSessionStore").emit(b.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 x.joinRoom:case x.leaveRoom:case x.kick:case x.kickAll:{r=fn.fromBinary.bind(fn),i=fn.create();break}case x.getWaitingRoomRequests:{r=(a,o)=>a?Hp.fromBinary(a,o):{requests:[]},i=Hp.create();break}case x.recordingPaused:case x.recordingStarted:case x.recordingStopped:{r=Xp.fromBinary.bind(Xp);break}case id.updateUserPreset:{r=jp.fromBinary.bind(jp);break}case Es.peerJoinedBroadcast:case kr.peerJoinedBroadcast:{r=Op.fromBinary.bind(Op);break}case Es.selfJoinComplete:case kr.selfJoinComplete:{r=yu.fromBinary.bind(yu);break}case Es.globalPeerPinBroadcast:case kr.globalPeerPinBroadcast:{r=Vp.fromBinary.bind(Vp);break}case Es.selectedPeer:case kr.selectedPeer:{r=vu.fromBinary.bind(vu);break}case Es.selectedPeerDiff:case kr.selectedPeerDiff:{r=Dp.fromBinary.bind(Dp);break}case Es.leaveRoom:case kr.leaveRoom:{r=Su.fromBinary.bind(Su);break}}this.socket.on(t,({payload:a})=>{let o=i;if(!r)return e(void 0);try{o=r(a)}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(id.getUserPresets,iI.toBinary(e)),i=cI.fromBinary(r.payload).peerPresets[0],a=new TextDecoder().decode(i.preset),o=JSON.parse(a).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}}}xt=new WeakMap;rO([S.trace("RoomSocketHandler.joinRoom")],CT.prototype,"joinRoom",1);var wt;class iO{constructor(t){g(this,wt,void 0);m(this,wt,t)}async getStageRequests(){const{payload:t}=await n(this,wt).sendMessagePromise(x.getStageRequests);return t?iu.fromBinary(t):{stageRequests:[]}}requestAccess(){n(this,wt).sendMessage(x.requestStageAccess)}cancelRequestAccess(){n(this,wt).sendMessage(x.cancelStageRequest)}async grantAccess(t){const e={userIds:t};n(this,wt).sendMessage(x.grantStageAccess,JA.toBinary(e))}async denyAccess(t){const e={userIds:t};n(this,wt).sendMessage(x.denyStageAccess,zA.toBinary(e))}joinStage(){return n(this,wt).sendMessagePromise(x.joinStage,void 0,void 0,x.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return n(this,wt).sendMessagePromise(x.leaveStage,Qp.toBinary(e),void 0,x.peerStageStatusUpdate)}kick(t){const e={userIds:t};return n(this,wt).sendMessagePromise(x.leaveStage,Qp.toBinary(e))}on(t,e){let r;switch(t){case x.grantStageAccess:case x.denyStageAccess:{r=void 0;break}case x.getStagePeers:{r=Yp.fromBinary.bind(Yp);break}case x.getStageRequests:case x.requestStageAccess:case x.cancelStageRequest:{r=iu.fromBinary.bind(iu);break}case x.peerStageStatusUpdate:{r=xp.fromBinary.bind(xp);break}}n(this,wt).on(t,({payload:i,id:a})=>{if(!i||!r)return e(void 0,a);const o=r(i);return e(o,a)})}async getPeerInfo(t){const e=await n(this,wt).sendMessagePromise(x.getPeerInfo,df.toBinary({peerId:t}));return fn.fromBinary(e.payload)}}wt=new WeakMap;var Be,kc;class nO{constructor(t,e){g(this,Be,void 0);g(this,kc,void 0);m(this,Be,e),m(this,kc,t)}get logger(){return n(this,kc).getValue("logger")}addPlugin(t,e){n(this,Be).sendMessage(q.addPlugin,lA.toBinary({pluginId:t,staggered:e}))}removePlugin(t){n(this,Be).sendMessage(q.removePlugin,hA.toBinary({pluginId:t,staggered:!1}))}async getActivePlugins(){const{payload:t}=await n(this,Be).sendMessagePromise(q.getPlugins);return t?LA.fromBinary(t):{plugins:[]}}customPluginEventToRoom(t,e,r){const i={pluginId:t,pluginData:new TextEncoder().encode(JSON.stringify(e))};n(this,Be).sendMessage(q.customPluginEventToRoom,PA.toBinary(i),r)}customPluginEventToPeers(t,e,r,i){const a={pluginId:t,peerIds:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};n(this,Be).sendMessage(q.customPluginEventToPeers,CA.toBinary(a),i)}enablePluginForRoom(t,e){n(this,Be).sendMessage(q.enablePluginForRoom,gA.toBinary({pluginId:t}),e)}enablePluginForPeers(t,e,r){n(this,Be).sendMessage(q.enablePluginForPeers,vA.toBinary({pluginId:t,peerIds:e}),r)}disablePluginForRoom(t,e){n(this,Be).sendMessage(q.disablePluginForRoom,fA.toBinary({pluginId:t}),e)}disablePluginForPeers(t,e,r){n(this,Be).sendMessage(q.disablePluginForPeers,SA.toBinary({pluginId:t,peerIds:e}),r)}storeInsertKeys(t,e,r,i){const a={pluginId:t,storeName:e,insertKeys:r.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};n(this,Be).sendMessage(q.storeInsertKeys,Gp.toBinary(a),i)}storeGetKeys(t,e,r,i){const a={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};n(this,Be).sendMessage(q.storeGetKeys,kA.toBinary(a),i)}storeDeleteKeys(t,e,r,i){const a={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};n(this,Be).sendMessage(q.storeDeleteKeys,AA.toBinary(a),i)}storeDelete(t,e,r){n(this,Be).sendMessage(q.storeDelete,DA.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))}]};n(this,Be).sendMessage(q.storeInsertKeys,Gp.toBinary(i))}on(t,e){let r;switch(t){case q.addPlugin:case q.enablePluginForPeers:case q.enablePluginForRoom:{r=Cu.fromBinary.bind(Cu);break}case q.removePlugin:case q.disablePluginForPeers:case q.disablePluginForRoom:{r=Wp.fromBinary.bind(Wp);break}case q.customPluginEventToPeers:case q.customPluginEventToRoom:{r=Kp.fromBinary.bind(Kp);break}case q.storeInsertKeys:case q.storeGetKeys:case q.storeDeleteKeys:case q.storeDelete:{r=Jp.fromBinary.bind(Jp);break}}n(this,Be).on(t,({payload:i,id:a})=>{const o=r(i);return e(o,a)})}}Be=new WeakMap,kc=new WeakMap;var aO=Object.defineProperty,oO=(s,t,e)=>t in s?aO(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,cO=(s,t,e)=>(oO(s,typeof t!="symbol"?t+"":t,e),e),$h=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},A=(s,t,e)=>($h(s,t,"read from private field"),e?e.call(s):t.get(s)),ge=(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)},se=(s,t,e,r)=>($h(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),Se=(s,t,e)=>($h(s,t,"access private method"),e),Rd={},dO={get exports(){return Rd},set exports(s){Rd=s}},An=typeof Reflect=="object"?Reflect:null,dg=An&&typeof An.apply=="function"?An.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},ud;An&&typeof An.ownKeys=="function"?ud=An.ownKeys:Object.getOwnPropertySymbols?ud=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:ud=function(s){return Object.getOwnPropertyNames(s)};function lO(s){console&&console.warn&&console.warn(s)}var wT=Number.isNaN||function(s){return s!==s};function ne(){ne.init.call(this)}dO.exports=ne;Rd.once=gO;ne.EventEmitter=ne;ne.prototype._events=void 0;ne.prototype._eventsCount=0;ne.prototype._maxListeners=void 0;var lg=10;function Hl(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(ne,"defaultMaxListeners",{enumerable:!0,get:function(){return lg},set:function(s){if(typeof s!="number"||s<0||wT(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");lg=s}});ne.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};ne.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||wT(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 RT(s){return s._maxListeners===void 0?ne.defaultMaxListeners:s._maxListeners}ne.prototype.getMaxListeners=function(){return RT(this)};ne.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 a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var c=i[s];if(c===void 0)return!1;if(typeof c=="function")dg(c,this,t);else for(var d=c.length,l=MT(c,d),e=0;e<d;++e)dg(l[e],this,t);return!0};function bT(s,t,e,r){var i,a,o;if(Hl(e),a=s._events,a===void 0?(a=s._events=Object.create(null),s._eventsCount=0):(a.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),a=s._events),o=a[t]),o===void 0)o=a[t]=e,++s._eventsCount;else if(typeof o=="function"?o=a[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=RT(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,lO(c)}return s}ne.prototype.addListener=function(s,t){return bT(this,s,t,!1)};ne.prototype.on=ne.prototype.addListener;ne.prototype.prependListener=function(s,t){return bT(this,s,t,!0)};function uO(){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 kT(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=uO.bind(r);return i.listener=e,r.wrapFn=i,i}ne.prototype.once=function(s,t){return Hl(t),this.on(s,kT(this,s,t)),this};ne.prototype.prependOnceListener=function(s,t){return Hl(t),this.prependListener(s,kT(this,s,t)),this};ne.prototype.removeListener=function(s,t){var e,r,i,a,o;if(Hl(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,a=e.length-1;a>=0;a--)if(e[a]===t||e[a].listener===t){o=e[a].listener,i=a;break}if(i<0)return this;i===0?e.shift():hO(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this};ne.prototype.off=ne.prototype.removeListener;ne.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),a;for(r=0;r<i.length;++r)a=i[r],a!=="removeListener"&&this.removeAllListeners(a);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 IT(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?pO(i):MT(i,i.length)}ne.prototype.listeners=function(s){return IT(this,s,!0)};ne.prototype.rawListeners=function(s){return IT(this,s,!1)};ne.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):AT.call(s,t)};ne.prototype.listenerCount=AT;function AT(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}ne.prototype.eventNames=function(){return this._eventsCount>0?ud(this._events):[]};function MT(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function hO(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function pO(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function gO(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,a),r(o)}function a(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}DT(s,t,a,{once:!0}),t!=="error"&&mO(s,i,{once:!0})})}function mO(s,t,e){typeof s.on=="function"&&DT(s,"error",t,e)}function DT(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(a){r.once&&s.removeEventListener(t,i),e(a)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}class fO extends v.MessageType{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 ug=new fO;class OT{static encode(t){return ug.toBinary(t)}static decode(t){return ug.fromBinary(new Uint8Array(t))}}function TO(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Rr;class vO{constructor(t={}){cO(this,"opts"),ge(this,Rr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},se(this,Rr,0)}async wait(){se(this,Rr,A(this,Rr)+1);const t=TO(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**A(this,Rr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return A(this,Rr)}reset(){se(this,Rr,0)}}Rr=new WeakMap;const _r={debug:0,info:1,warn:2,error:3};var oi,ci;class yO{constructor(t){ge(this,oi,void 0),ge(this,ci,void 0),se(this,oi,console),se(this,ci,t)}debug(...t){_r[A(this,ci)]>_r.debug||A(this,oi).debug("[Sockrates]:",...t)}info(...t){_r[A(this,ci)]>_r.info||A(this,oi).info("[Sockrates]:",...t)}warn(...t){_r[A(this,ci)]>_r.warn||A(this,oi).warn("[Sockrates]:",...t)}error(...t){_r[A(this,ci)]>_r.error||A(this,oi).error("[Sockrates]:",...t)}}oi=new WeakMap,ci=new WeakMap;var NT=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(NT||{});const SO="2",EO="3";var be,Sn,ye,Oe,br,Ge,ur,Yr,Ss,En,Hs,Yu,LT,go,hd,Qu,VT,Xu,hg,bd,Zu,eh,xT,To,pd,vo,kd,Id,th,Mn,yo,So,Ad;class PO{constructor(t,e){var f,T,E,P,C,_,N,U,D,$;ge(this,Yu),ge(this,go),ge(this,Qu),ge(this,Xu),ge(this,bd),ge(this,eh),ge(this,To),ge(this,vo),ge(this,Id),ge(this,Mn),ge(this,So),ge(this,be,void 0),ge(this,Sn,void 0),ge(this,ye,void 0),ge(this,Oe,void 0),ge(this,br,void 0),ge(this,Ge,void 0),ge(this,ur,void 0),ge(this,Yr,void 0),ge(this,Ss,void 0),ge(this,En,void 0),ge(this,Hs,void 0);var r,i,a,o,c,d,l,h,p;se(this,Sn,t),se(this,br,[]),se(this,Ge,new Rd),se(this,ur,!0),se(this,Ss,!1),se(this,ye,e!=null?e:{}),(f=(r=A(this,ye)).autoReconnect)!=null||(r.autoReconnect=!0),(T=(i=A(this,ye)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(E=(a=A(this,ye)).pingTimeout)!=null||(a.pingTimeout=3e4),(P=(o=A(this,ye)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(C=(c=A(this,ye)).debug)!=null||(c.debug=!0),(_=(d=A(this,ye)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(N=(l=A(this,ye)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(U=(h=A(this,ye)).queueOnDisconnect)!=null||(h.queueOnDisconnect=!1),(D=(p=A(this,ye)).flushOnReconnect)!=null||(p.flushOnReconnect=!1),se(this,Yr,{code:void 0,reason:void 0}),se(this,Oe,($=A(this,ye).logger)!=null?$:new yO(A(this,ye).debug?"debug":"info")),se(this,Hs,new vO)}get readyState(){var t;return(t=A(this,be))==null?void 0:t.readyState}get url(){return A(this,Sn)}updateURL(t){se(this,Sn,t),Se(this,eh,xT).call(this)}get config(){return A(this,ye)}get sendQueue(){return A(this,br)}flush(){if(!A(this,ye).queueOnDisconnect)return!1;const t=[];return A(this,br).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),se(this,br,t),A(this,br)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){A(this,Oe).debug("Websocket was already connecting or connected.");return}if(A(this,ur)!==!1)return new Promise((e,r)=>{Se(this,Mn,yo).call(this),Se(this,So,Ad).call(this);try{se(this,be,new WebSocket(Se(this,Yu,LT).call(this,A(this,Sn)))),A(this,be).binaryType="arraybuffer",A(this,Oe).debug("Connecting");const i=setTimeout(()=>{A(this,Oe).debug("Connection timeout. Closing socket"),se(this,ur,!0),Se(this,So,Ad).call(this),A(this,be).close(3001,"Connection Timeout"),A(this,ye).autoReconnect&&!A(this,Ss)&&(A(this,Ge).emit("reconnecting"),Se(this,To,pd).call(this)),r(new Error("Connection timed out!"))},A(this,ye).connectionTimeout);A(this,be).onopen=()=>{A(this,Oe).debug(`Ready State: ${NT[A(this,be).readyState]}`),i&&clearTimeout(i),Se(this,Id,th).call(this),se(this,Yr,{code:void 0,reason:void 0}),A(this,Ge).emit("connected"),A(this,ye).flushOnReconnect&&this.flush(),e()},A(this,be).onclose=a=>{try{i&&clearTimeout(i);const{code:o,reason:c}=a;r(c),A(this,Oe).debug("Socket closed. Close event:",{event:a}),A(this,Oe).debug(`Connection closed code: ${o}`),A(this,Oe).debug(`Connection closed reason: ${c}`),A(this,Ss)||Se(this,bd,Zu).call(this,o,c)}catch(o){Se(this,go,hd).call(this,o)}},A(this,be).onerror=a=>{Se(this,go,hd).call(this,a)},A(this,be).onmessage=a=>Se(this,Qu,VT).call(this,a)}catch(i){Se(this,go,hd).call(this,i,r)}})}send(t,e,r,i){const a={event:t,id:e,payload:r,metadata:i};if(A(this,ye).queueOnDisconnect&&(!A(this,be)||A(this,be).readyState!==1))return A(this,Oe).debug("Queuing message since socket is not connected!",a),A(this,br).push(a),!1;const o=OT.encode(a);return Se(this,vo,kd).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return Se(this,vo,kd).call(this,t)}receive(t,e){return A(this,Ge).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")){A(this,Ge).on(t,e);return}this.receive(t,e)}removeAllListeners(){A(this,Ge).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){A(this,Ge).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){A(this,Ge).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){se(this,ur,!1),Se(this,Mn,yo).call(this),this.removeAllListeners(),se(this,Yr,{code:1e3,reason:"Sockrates disconnect method called"}),A(this,be).close(1e3,"Sockrates disconnect method called.")}}be=new WeakMap,Sn=new WeakMap,ye=new WeakMap,Oe=new WeakMap,br=new WeakMap,Ge=new WeakMap,ur=new WeakMap,Yr=new WeakMap,Ss=new WeakMap,En=new WeakMap,Hs=new WeakMap,Yu=new WeakSet,LT=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)://.")},go=new WeakSet,hd=function(s,t){A(this,Oe).error("Error:",{error:s}),A(this,Ge).emit("errored",{error:s}),t==null||t(s)},Qu=new WeakSet,VT=function(s){if(Se(this,Id,th).call(this),s.data===SO){A(this,Oe).debug("Received ping from server"),Se(this,vo,kd).call(this,EO);return}const t=OT.decode(s.data),{id:e,payload:r}=t;A(this,Oe).debug("Received message",{event:t.event,messageID:e}),A(this,Ge).emit(t.event.toString(),{id:e,payload:r})},Xu=new WeakSet,hg=function(){return A(this,be).readyState===1},bd=new WeakSet,Zu=function(s,t){se(this,Yr,{reason:t,code:s}),A(this,Ge).emit("disconnected",{code:s,reason:t})},eh=new WeakSet,xT=function(){const{reason:s,code:t}=A(this,Yr);t&&t!==1e3&&A(this,ur)&&A(this,ye).autoReconnect&&!A(this,Ss)&&(A(this,Oe).debug(`Triggering reconnection due to ${s}.`),A(this,Ge).emit("reconnecting"),Se(this,To,pd).call(this))},To=new WeakSet,pd=async function(s=!0){if(s&&A(this,Ss)){A(this,Oe).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(A(this,Ss)||A(this,Hs).reset(),A(this,ye).maxReconnectionAttempts!==null&&A(this,Hs).getAttempts()>=A(this,ye).maxReconnectionAttempts){A(this,Ge).emit("failed"),se(this,Ss,!1);return}se(this,Ss,!0),Se(this,So,Ad).call(this),Se(this,Mn,yo).call(this);try{if(await A(this,Hs).wait(),A(this,ur)===!1)return;if(A(this,Oe).debug(`Reconnection attempt ${A(this,Hs).getAttempts()}`),A(this,Ge).emit("reconnectAttempt",{attempt:A(this,Hs).getAttempts()}),await this.connect(),!Se(this,Xu,hg).call(this))throw Error("Reconnect Failed");se(this,Ss,!1),se(this,Yr,{code:void 0,reason:void 0}),A(this,Ge).emit("reconnected")}catch(t){A(this,Oe).debug("Failed to reconnect."),A(this,Ge).emit("reconnectFailure",{attempt:A(this,Hs).getAttempts()}),Se(this,To,pd).call(this,!1)}},vo=new WeakSet,kd=function(s){try{return A(this,be).send(s),!0}catch(t){return A(this,Oe).error(t.message),!1}},Id=new WeakSet,th=function(){this.config.disconnectOnPingTimeout&&(A(this,Oe).debug("Resetting ping timeout"),Se(this,Mn,yo).call(this),se(this,En,setTimeout(()=>{var s;A(this,Oe).debug("Disconnecting the socket due to ping timeout"),se(this,ur,!0);const t=3002,e="Ping timeout";(s=A(this,be))==null||s.close(t,e),Se(this,bd,Zu).call(this,t,e)},A(this,ye).pingTimeout)))},Mn=new WeakSet,yo=function(){A(this,En)&&(clearTimeout(A(this,En)),se(this,En,void 0))},So=new WeakSet,Ad=function(){A(this,be)&&(A(this,be).onopen=void 0,A(this,be).onerror=void 0,A(this,be).onmessage=void 0,A(this,be).onclose=void 0)};var _O=Object.defineProperty,CO=Object.getOwnPropertyDescriptor,ql=(s,t,e,r)=>{for(var i=r>1?void 0:r?CO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&_O(t,e,i),i};const pg=65535,wO=3e3;var Jr,Ee,Pe,ke,ss,Qe,Ic,sh,Ac,rh,Og;const UT=(Og=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){g(this,Pe);g(this,Ic);g(this,Ac);g(this,Jr,void 0);g(this,Ee,void 0);u(this,"roomName");u(this,"authToken");u(this,"capabilities");g(this,ss,void 0);g(this,Qe,void 0);var a;if(!t||!e||!r)throw new R("peerId, meetingId, or authToken can not be empty","0404");m(this,ss,void 0),m(this,Qe,s),this.capabilities=i,this.roomName=e,this.authToken=r,m(this,Jr,V(this,Ic,sh).call(this,t)),m(this,Ee,new PO(n(this,Jr),{autoReconnect:!0,disconnectOnPingTimeout:(a=i.includes("PING"))!=null?a:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return n(this,Pe,ke).socketJoinAttempted}set joinAttempted(s){n(this,Pe,ke).socketJoinAttempted=s}get telemetry(){return n(this,Qe).getValue("telemetry")}get logger(){return n(this,Qe).getValue("logger")}get peerId(){return n(this,Qe).getValue("peerId")}updateURL(s){s!==this.peerId&&(m(this,Jr,V(this,Ic,sh).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),n(this,Ee).updateURL(n(this,Jr))}static getSocketEdgeDomain(s){return tn({servicePrefix:"socket-edge",baseURI:s})}get url(){return n(this,Jr)}async connect(){n(this,Pe,ke).socketJoinAttempted=!0,await n(this,Ee).connect(),n(this,Pe,ke).socketJoinAttempted=!0,n(this,Pe,ke).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}disconnect(){n(this,Pe,ke).socketJoinAttempted=!1,n(this,Ee).disconnect(),n(this,Pe,ke).socketJoinAttempted=!0,n(this,Pe,ke).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return n(this,Ee).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return n(this,Qe).getValue("telemetry").injectContext(r),n(this,Ee).send(s,e!=null?e:V(this,Ac,rh).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 a=i!=null?i:s;return new Promise((o,c)=>{const d=(E,P)=>{n(this,Ee).removeListener(a,E),n(this,Ee).removeListener(pg,P),n(this,Ee).removeListener(kr.errorResponse,P),n(this,Ee).removeListener(Es.errorResponse,P)},l=r!=null?r:V(this,Ac,rh).call(this),h={};n(this,Qe).getValue("telemetry").injectContext(h);const f=({id:E,payload:P})=>{if(l===E){let C;try{const _=RR.fromBinary(P);C=new Error(_.errorMessage)}catch(_){C=new Error("failed to parse error message",{cause:_});try{const N=bb.fromBinary(P);C=new Error(N.message)}catch(N){C=new Error("failed to parse error message",{cause:N})}}c(C),d(T,f)}},T=({id:E,payload:P})=>{l===E&&(o({id:E,payload:P}),d(T,f))};n(this,Ee).on(a,T),n(this,Ee).on(pg,f),n(this,Ee).on(kr.errorResponse,f),n(this,Ee).on(Es.errorResponse,f),setTimeout(()=>{d(T,f),c(new Error(`request timeout for callback eventId:${s}`))},t),n(this,Ee).send(s,l,e,new TextEncoder().encode(JSON.stringify(h)))})}on(s,t){n(this,Ee).on(s,t)}onStateEvent(s,t){n(this,Ee).on(s,t)}removeListener(s,t){n(this,Ee).removeListener(s,t)}removeListeners(s){n(this,Ee).removeListeners(s)}flush(){return n(this,Ee).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{this.logger.info("SocketService::Connected to socket-edge"),n(this,ss)&&(clearTimeout(n(this,ss)),m(this,ss,void 0)),n(this,Pe,ke).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:S.location.country});const{recv:e,send:r}=(i=n(this,Pe,ke).mediaState)!=null?i:{};e!=null&&e.state&&(e==null?void 0:e.state)!==In.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==In.CONNECTED?n(this,Qe).getValue("peerSessionStore").emit(b.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:n(this,Pe,ke).joinAttempted}):m(this,ss,setTimeout(()=>{n(this,Qe).getValue("peerSessionStore").emit(b.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:n(this,Pe,ke).joinAttempted}),m(this,ss,void 0)},wO)),n(this,Pe,ke).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",async()=>{this.logger.info("SocketService::Reconnecting to socket-edge",{country:S.location.country}),n(this,Pe,ke).updateSocketConnectionState("reconnecting")}),this.onStateEvent("reconnectAttempt",async({attempt:s})=>{this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),n(this,Pe,ke).updateSocketConnectionState("reconnectAttempt",s)}),this.onStateEvent("reconnectFailure",({attempt:s})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),n(this,Pe,ke).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",async()=>{this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:n(this,Pe,ke).mediaJoinAttempted}}),n(this,ss)&&(clearTimeout(n(this,ss)),m(this,ss,void 0)),n(this,Qe).getValue("peerSessionStore").emit(b.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:n(this,Pe,ke).mediaJoinAttempted}),n(this,Pe,ke).updateSocketConnectionState("reconnected")}),this.onStateEvent("failed",async()=>{this.logger.info("SocketService::Failed to connect to socket-edge",{country:S.location.country}),n(this,Qe).getValue("peerSessionStore").emit(b.SOCKET_SERVICE_FAILED),n(this,Pe,ke).updateSocketConnectionState("failed")})}},Jr=new WeakMap,Ee=new WeakMap,Pe=new WeakSet,ke=function(){return n(this,Qe).getValue("connectionHandler")},ss=new WeakMap,Qe=new WeakMap,Ic=new WeakSet,sh=function(s){let t=UT.getSocketEdgeDomain(n(this,Qe).getValue("baseURI"));typeof Na(n(this,Qe),"socket_server_base")=="string"&&(t=Na(n(this,Qe),"socket_server_base"));const e=`wss://${t}`,r=new URL(`${e}/ws`),i=this.peerId,a={roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0,...i!==s&&{oldPeerID:i},ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(o=>Sd[o]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0};return Object.entries(a).forEach(([o,c])=>{r.searchParams.append(o,c.toString())}),r.href},Ac=new WeakSet,rh=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},Og);let Bc=UT;ql([S.trace("SocketService.connect")],Bc.prototype,"connect",1);ql([S.trace("SocketService.disconnect")],Bc.prototype,"disconnect",1);ql([S.trace("SocketService.sendMessagePromise")],Bc.prototype,"sendMessagePromise",1);ql([S.trace("SocketService.sendMessagePromiseWithTimeout")],Bc.prototype,"sendMessagePromiseWithTimeout",1);class RO{constructor(t){u(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var a;const e=ek.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:(a=e.parentMeeting.participants)!=null?a:[]},meetings:r}}handleTransferPeerRaw({payload:t}){const e=Rk.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=lf.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return Bp.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return fk.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise(x.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const{payload:e}=await this.socketService.sendMessagePromise(x.createConnectedRooms,ik.toBinary({payloads:t}));return Bp.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(x.deleteConnectedRooms,gk.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(x.movePeers,Pk.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 bO=Object.defineProperty,kO=Object.getOwnPropertyDescriptor,IO=(s,t,e,r)=>{for(var i=r>1?void 0:r?kO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&bO(t,e,i),i},ys;class $T extends Ft{constructor(e){const r=e.getValue("logger");super(r);u(this,"meetings",[]);u(this,"parentMeeting",null);g(this,ys,void 0);m(this,ys,e)}get supportsConnectedMeetings(){return n(this,ys).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.
13
- Please connect with our support team to enable connected meetings.`)}async getConnectedMeetings(){return this.validateConnectedMeetingsAction(),await n(this,ys).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump()}async createMeetings(e){return this.validateConnectedMeetingsAction(),(await n(this,ys).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e)).map(i=>({id:i.id,title:i.title}))}async updateMeetings(e){this.validateConnectedMeetingsAction(),await n(this,ys).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title})))}async deleteMeetings(e){this.validateConnectedMeetingsAction();const r=this.meetings.map(a=>e.includes(a.id)&&a.participants.length!==0?this.moveParticipants(a.id,this.parentMeeting.id,a.participants.map(o=>o.id)):Promise.resolve());return await Promise.all(r),await n(this,ys).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e)}async moveParticipants(e,r,i){this.validateConnectedMeetingsAction();const a=await n(this,ys).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(o=>({id:o}))});return a.success&&this.moveSuccessHandler(e,r,i),a}async moveParticipantsWithCustomPreset(e,r,i){this.validateConnectedMeetingsAction();const a=await n(this,ys).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return a.success&&this.moveSuccessHandler(e,r,i.map(o=>o.id)),a}moveSuccessHandler(e,r,i){const a=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(o=>o.participants)].forEach(o=>a.set(o.id,o)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(o=>a.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=>a.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})}}ys=new WeakMap;IO([kt({maxInvocations:60,period:60})],$T.prototype,"getConnectedMeetings",1);var AO=Object.defineProperty,MO=Object.getOwnPropertyDescriptor,Fh=(s,t,e,r)=>{for(var i=r>1?void 0:r?MO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&AO(t,e,i),i},ue,Ng;const FT=(Ng=class{constructor(s){u(this,"connectedMeetings");g(this,ue,void 0);m(this,ue,s),this.connectedMeetings=new $T(s)}get telemetry(){return n(this,ue).getValue("telemetry")}get logger(){return n(this,ue).getValue("logger")}static init(s){const t=new FT(s);return t.connectedMeetings.supportsConnectedMeetings&&(t.setupEvents(),s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings())),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){n(this,ue).getValue("connectedMeetingsSocketHandler").socketService.on(x.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),n(this,ue).getValue("connectedMeetingsSocketHandler").socketService.on(x.transferPeer,this.handleTransferPeer.bind(this)),n(this,ue).getValue("connectedMeetingsSocketHandler").socketService.on(x.movedPeer,this.handleMovedPeer.bind(this)),n(this,ue).getValue("connectedMeetingsSocketHandler").socketService.on(x.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),n(this,ue).getValue("connectedMeetingsSocketHandler").socketService.on(x.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){const t=n(this,ue).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(s);return this.switchMeeting(t)}async switchMeeting({authToken:s,meetingId:t}){var i,a,o,c;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
13
+ Please connect with our support team to enable connected meetings.`)}async getConnectedMeetings(){this.validateConnectedMeetingsAction(),this.logger.info("Getting connected meetings dump");const e=await n(this,ys).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump();return this.logger.info("Got connected meetings dump"),e}async createMeetings(e){this.validateConnectedMeetingsAction(),this.logger.info(`Creating connected meetings ${JSON.stringify(e)}`);const r=await n(this,ys).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e);return this.logger.info(`Created connected meetings ${JSON.stringify(r)}`),r.map(i=>({id:i.id,title:i.title}))}async updateMeetings(e){this.validateConnectedMeetingsAction(),this.logger.info(`Updating connected meetings ${JSON.stringify(e)}`),await n(this,ys).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title}))),this.logger.info(`Updated connected meetings ${JSON.stringify(e)}`)}async deleteMeetings(e){this.validateConnectedMeetingsAction(),this.logger.info(`Moving participants before deleting connected meetings ${JSON.stringify(e)}`);const r=this.meetings.map(a=>e.includes(a.id)&&a.participants.length!==0?this.moveParticipants(a.id,this.parentMeeting.id,a.participants.map(o=>o.id)):Promise.resolve());this.logger.info(`Moved participants before deleting connected meetings ${JSON.stringify(e)}. Deleting now.`),await Promise.all(r);const i=await n(this,ys).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e);return this.logger.info(`Deleted connected meetings ${JSON.stringify(e)}`),i}async moveParticipants(e,r,i){this.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`);const a=await n(this,ys).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(o=>({id:o}))});return a.success?(this.logger.info(`Moved connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i)):this.logger.error(`Failed to move connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),a}async moveParticipantsWithCustomPreset(e,r,i){this.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`);const a=await n(this,ys).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return a.success?(this.logger.info(`Moved connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i.map(o=>o.id))):this.logger.error(`Failed to move connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),a}moveSuccessHandler(e,r,i){const a=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(o=>o.participants)].forEach(o=>a.set(o.id,o)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(o=>a.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=>a.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})}}ys=new WeakMap;IO([kt({maxInvocations:60,period:60})],$T.prototype,"getConnectedMeetings",1);var AO=Object.defineProperty,MO=Object.getOwnPropertyDescriptor,Fh=(s,t,e,r)=>{for(var i=r>1?void 0:r?MO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&AO(t,e,i),i},ue,Ng;const FT=(Ng=class{constructor(s){u(this,"connectedMeetings");g(this,ue,void 0);m(this,ue,s),this.connectedMeetings=new $T(s)}get telemetry(){return n(this,ue).getValue("telemetry")}get logger(){return n(this,ue).getValue("logger")}static init(s){const t=new FT(s);return t.connectedMeetings.supportsConnectedMeetings&&(t.setupEvents(),s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings())),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){n(this,ue).getValue("connectedMeetingsSocketHandler").socketService.on(x.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),n(this,ue).getValue("connectedMeetingsSocketHandler").socketService.on(x.transferPeer,this.handleTransferPeer.bind(this)),n(this,ue).getValue("connectedMeetingsSocketHandler").socketService.on(x.movedPeer,this.handleMovedPeer.bind(this)),n(this,ue).getValue("connectedMeetingsSocketHandler").socketService.on(x.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),n(this,ue).getValue("connectedMeetingsSocketHandler").socketService.on(x.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){this.logger.info("Received backend request to switch connected meetings");const t=n(this,ue).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(s);return this.logger.info(`Honoring request to switch connected meetings. Going to ${t==null?void 0:t.meetingId}`),this.switchMeeting(t)}async switchMeeting({authToken:s,meetingId:t}){var i,a,o,c;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
14
14
  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:n(this,ue).getValue("self").videoEnabled,audio:n(this,ue).getValue("self").audioEnabled};try{n(this,ue).getValue("self").cleanupEvents(),await n(this,ue).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(a=(i=n(this,ue).getValue("meeting"))==null?void 0:i.meta)==null?void 0:a.meetingId}`,{error:d})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${t}`);const r=await HT.init({...n(this,ue).getValue("options"),cachedUserDetails:null,defaults:{...n(this,ue).getValue("options").defaults,...e,mediaHandler:n(this,ue).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}=n(this,ue).getValue("self");r.self.setName(n(this,ue).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=n(this,ue).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 n(this,ue).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=n(this,ue).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=n(this,ue).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})}},ue=new WeakMap,Ng);let jl=FT;Fh([S.trace("ConnectedMeetingsController.getConnectedMeetings")],jl.prototype,"getConnectedMeetings",1);Fh([S.trace("ConnectedMeetingsController.setupEvents")],jl.prototype,"setupEvents",1);Fh([S.trace("ConnectedMeetingsController.switchMeeting")],jl.prototype,"switchMeeting",1);var DO=Object.defineProperty,OO=Object.getOwnPropertyDescriptor,Gl=(s,t,e,r)=>{for(var i=r>1?void 0:r?OO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&DO(t,e,i),i};const Pn=class{constructor(s,t,e){u(this,"apiBase");u(this,"selfController");u(this,"pollController");u(this,"chatController");u(this,"metaController");u(this,"storesManager");u(this,"stageController");u(this,"pluginController");u(this,"internalsController");u(this,"recordingController");u(this,"livestreamController");u(this,"participantController");u(this,"connectedMeetingsController");u(this,"telemetry");u(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 D,$;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:a,cachedUserDetails:o,logger:c}=s.getAllValues();if(PT(s),Te.isSupported()===!1)throw new R("Browser not supported","0010",c,!0);const d=UM(s,{authToken:r,baseURL:e,cachedUserDetails:o});d.setRoomName(i),d.setRoomUUID(i),d.setOrganizationId(a),d.setHeader("tracing-id",t),s.setValue("apiClient",d);const l=new S0(s);s.setValue("connectionHandler",l);const h=Pn.createSocketService(s),p=h.connect(),f=d.getUserDetails(),T=d.getPlugins();let E,P="";try{await Pn.setupFlagsmith(s)}catch(G){c.error("Failed to setup flagsmith",{error:G})}try{await p}catch(G){c.error("[Controller]: Failed to connect to socket server:",{error:G})}try{({meetingTitle:P}=await d.getRoomNodeData()),E=await f,c.info("CF SFU is being used."),s.setValue("presetName",E.preset.name)}catch(G){c.error("Failed to get room metadata",{error:G})}const C=Nu.init(E.preset,!s.getValue("modules").theme),_=Uu.init(s,C.viewType,E.preset.permissions),N=Pn.setupControllers(h,s,E,T,P,C,_);d0(C)&&((D=Pn.createRoomNodeClient(s,h).initializeConnection(E.participant.name,i,!1,_))==null||D.catch(ee=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:ee})})),S.location.country=($=d.ipInfo)==null?void 0:$.country;const{controllers:U}=await N;return ow(),new Pn(e,U,s)}static async setupFlagsmith(s){var l;const{peerId:t,baseURI:e,overrides:r,meetingId:i,organizationId:a,logger:o}=s.getAllValues(),c=aw(i),d={entity:fu.PEER,clientId:a,isAnonUser:!a,sdkVersion:s.getValue("sdkVersion"),presetName:s.getValue("presetName"),meetingHash:c,roomName:i,...Te.getDeviceInfo(),isReactNative:navigator.isReactNative};try{const h=(l=r==null?void 0:r.whitelabelled_flags_endpoint)==null||l?tn({servicePrefix:"flags",baseURI:e}):"edge.api.flagsmith.com";await s.getValue("flagsmith").identify(`${fu.PEER}_${t}`,JSON.parse(JSON.stringify(d)),!1,5e3,h,o),o.info("flagsmith::allFlags",{flags:JSON.stringify(s.getValue("flagsmith").getAllFlags())},!0)}catch(h){o.error("Failed to fetch flagsmith flags")}}static async setupControllers(s,t,e,r,i,a,o){var k,Le,Pr;const c=t.getValue("modules"),{participant:d}=e,l=t.getValue("defaults"),h=t.getValue("logger"),{viewType:p,mediaConstraints:{audio:f}}=a;t.setValue("viewType",p),t.setValue("defaults",{mediaConfiguration:{audio:{enableHighBitrate:(k=f.enableHighBitrate)!=null?k:!1,enableStereo:(Le=f.enableStereo)!=null?Le:!1}},...l}),t.setValue("maxPreferredStreams",Te.isMobile()?a.maxVideoStreams.mobile:a.maxVideoStreams.desktop);let T,E,P,C,_,N,U,D,$;const G=new XD(t,s),ee=new RO(s);t.setValue("connectedMeetingsSocketHandler",ee);const Xe=new Bl(t,s),as=new is(t,s),si=new iO(s),os=new CT(t,s),I=new nO(t,s),y=new QD(s),w=new an(t,s),L=await ti.init(t,os,d,o,a);t.setValue("selfController",L);const pe=await wf.init(t,L.self,os,G,i);if(c.participant&&(D=new Er(t,L.self,os)),(Pr=c.e2ee)!=null&&Pr.enabled&&c.e2ee.manager.init(h,t.getValue("peerSessionStore")),c.chat&&(E=await Ps.init(t,as,w,L.self,D.participants)),c.internals&&(_=await kh.init(t)),c.livestream&&a.viewType===bt.Livestream&&t.getValue("flagsmith").hasFeature(Q.LIVESTREAM)&&(U=new Nf(t,L.self,y)),a.viewType!==bt.Chat){if(c.poll&&(T=await Ef.init(t,L.self,Xe)),c.recording&&(N=new If(t,L.self,os)),c.stage&&(P=new Rf(t,si,os,L.self,D.participants)),c.plugin){if(!D)throw new R("The plugin module cannot be initialized without the `participant` module","0102");const Fs=await r;C=await xc.init(t,Fs,I,as,E==null?void 0:E.chat,L.self,D.participants,i)}if(c.connectedMeetings&&($=await jl.init(t)),c.pip){const Fs=await Tu._init(t,L.self);t.setValue("pip",Fs)}}const O={storesManager:new uD(t,I),pollController:T,selfController:L,metaController:pe,chatController:E,stageController:P,pluginController:C,recordingController:N,internalsController:_,livestreamController:U,participantController:D,connectedMeetingsController:$};return{theme:a,permissions:o,controllers:O}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return ET(s,{socket:t,peerId:e})}static createSocketService(s){const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),i=["PING"];return new Bc(s,{peerId:t,meetingId:e,authToken:r,capabilities:i})}};let Hc=Pn;Gl([S.trace("Controller.init")],Hc,"init",1);Gl([S.trace("setupFlagsmith")],Hc,"setupFlagsmith",1);Gl([S.trace("Controller.createRoomNodeClient")],Hc,"createRoomNodeClient",1);Gl([S.trace("Controller.createSocketService")],Hc,"createSocketService",1);class NO{constructor(){u(this,"battery");u(this,"logger");u(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)}});u(this,"updateChargeInfo",()=>{var t;this.logger.log(`Battery charging? ${(t=this.battery)!=null&&t.charging?"Yes":"No"}`)});u(this,"updateLevelInfo",()=>{if(!this.battery){this.logger.log("Battery level: Not known");return}this.logger.log(`Battery level: ${this.battery.level*100}%`)});u(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 gg=new NO;function LO(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 a=hi.baseURI.prod;t&&(a=t);const o=`https://${tn({servicePrefix:"api",baseURI:a})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:a,apiBase:o}}catch(e){throw new R("Invalid auth token","0004")}}var Kr,Qi,Xi,Mc,Pl,BT;class VO{constructor(){g(this,Pl);g(this,Kr,new Audio);g(this,Qi,new MediaStream);g(this,Xi,new Map);g(this,Mc,void 0);n(this,Kr).srcObject=n(this,Qi),n(this,Kr).autoplay=!0}async playTracks(t){return t.forEach(e=>{n(this,Xi).has(e.id)||(n(this,Qi).addTrack(e),n(this,Xi).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&n(this,Kr).setSinkId(t)}removeTrack(t){const e=n(this,Xi).get(t);e&&(n(this,Qi).removeTrack(e),n(this,Xi).delete(t))}async play(){return n(this,Kr).srcObject=n(this,Qi),n(this,Kr).play().catch(t=>{V(this,Pl,BT).call(this,t)})}onError(t){m(this,Mc,t)}}Kr=new WeakMap,Qi=new WeakMap,Xi=new WeakMap,Mc=new WeakMap,Pl=new WeakSet,BT=function(t){var e;(e=n(this,Mc))==null||e.call(this,t)};var Zi;class xO extends VO{constructor(){super();g(this,Zi,void 0);m(this,Zi,new Map)}addParticipantTrack(e,r){n(this,Zi).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=n(this,Zi).get(e);r&&this.removeTrack(r),n(this,Zi).delete(e)}}Zi=new WeakMap;var UO=Object.defineProperty,$O=Object.getOwnPropertyDescriptor,Wl=(s,t,e,r)=>{for(var i=r>1?void 0:r?$O(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&UO(t,e,i),i},He,en,Lg;let Zr=(Lg=class{constructor(t,e){g(this,He,void 0);g(this,en,void 0);m(this,en,t),m(this,He,e)}get peerId(){return n(this,en).getValue("peerId")}static initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:gr.v4(),a=hr.createContext(i,{peerId:i}),o=a.getValue("logger");o.init(a);const c=new Hf(o);return c.init(t,e,a),a.setValue("defaults",{mediaHandler:c}),c}static async init(t){var T,E,P,C,_,N,U;Te.init();const{mediaHandler:e}=(T=t.defaults)!=null?T:{},r=(e==null?void 0:e.peerId)||((P=(E=t==null?void 0:t.cachedUserDetails)==null?void 0:E.peerId)!=null?P:gr.v4()),{authToken:i,baseURI:a}=t,{meetingId:o,...c}=LO(i,a);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const d=Zr.setupContext(r,t,o,c),l=d.getValue("telemetry"),h=d.getValue("logger");zT(h),gg.init(h),l.init(d,{roomName:o,userId:c.participantId,organizationId:c.orgId,peerId:r},(_=(C=t.modules)==null?void 0:C.tracing)!=null?_:!0),h.init(d),h.info("Client::init::options",{clientInitOptions:{...t,authToken:`${(N=t.authToken)==null?void 0:N.slice(0,10)}...
15
- ${(U=t.authToken)==null?void 0:U.slice(-10)}`}});const p=await Hc.init(d),f=new Zr(d,p);return d.setValue("meeting",f),f}static setupContext(t,e,r,i){var d,l;const a=hr.createContext(t,e),o={...YC,...e==null?void 0:e.modules},c=e.defaults||{audio:!0,video:!0};return a.setValue("options",e),a.setValue("peerId",t),a.setValue("modules",o),a.setValue("sdkName","web-core"),a.setValue("meetingId",r),a.setValue("apiBase",i.apiBase),a.setValue("baseURI",i.baseURI),a.setValue("userId",i.participantId),a.setValue("organizationId",i.orgId),a.setValue("authToken",e.authToken),a.setValue("overrides",(d=e.overrides)!=null?d:{}),a.setValue("env",QC({baseURI:i.baseURI})),a.setValue("defaults",c),a.setValue("onError",e.onError||(()=>{})),a.setValue("cachedUserDetails",_s(e.cachedUserDetails)),a.setValue("sdkVersion","1.2.2-staging.3"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&a.setValue("audioPlayback",new xO),a}async join(){const{selfController:t}=n(this,He);return t.self.roomJoined?null:t.joinRoom()}async leave(t){gg.cleanup(),n(this,en).getValue("peerSessionStore").reset();const{selfController:e}=n(this,He);return e.leaveRoom(t)}get participants(){var t;return(t=n(this,He).participantController)==null?void 0:t.participants}get self(){var t;return(t=n(this,He).selfController)==null?void 0:t.self}get meta(){var t;return(t=n(this,He).metaController)==null?void 0:t.meta}get ai(){var t;return(t=n(this,He).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=n(this,He).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=n(this,He).chatController)==null?void 0:t.chat}get polls(){var t;return(t=n(this,He).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=n(this,He).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=n(this,He).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=n(this,He).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=n(this,He).stageController)==null?void 0:t.stage}get stores(){return n(this,He).storesManager}get audio(){return n(this,en).getValue("audioPlayback")}get __internals__(){var t;return(t=n(this,He).internalsController)==null?void 0:t.internals}async joinRoom(){return this.join()}async leaveRoom(t){return this.leave(t)}},He=new WeakMap,en=new WeakMap,Lg);Wl([ct("0002"),Sr.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],Zr.prototype,"join",1);Wl([ct("0003")],Zr.prototype,"leave",1);Wl([ct("0001"),Sr.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],Zr,"init",1);Zr=Wl([ct("0000")],Zr);const HT=Zr;module.exports=HT;
15
+ ${(U=t.authToken)==null?void 0:U.slice(-10)}`}});const p=await Hc.init(d),f=new Zr(d,p);return d.setValue("meeting",f),f}static setupContext(t,e,r,i){var d,l;const a=hr.createContext(t,e),o={...YC,...e==null?void 0:e.modules},c=e.defaults||{audio:!0,video:!0};return a.setValue("options",e),a.setValue("peerId",t),a.setValue("modules",o),a.setValue("sdkName","web-core"),a.setValue("meetingId",r),a.setValue("apiBase",i.apiBase),a.setValue("baseURI",i.baseURI),a.setValue("userId",i.participantId),a.setValue("organizationId",i.orgId),a.setValue("authToken",e.authToken),a.setValue("overrides",(d=e.overrides)!=null?d:{}),a.setValue("env",QC({baseURI:i.baseURI})),a.setValue("defaults",c),a.setValue("onError",e.onError||(()=>{})),a.setValue("cachedUserDetails",_s(e.cachedUserDetails)),a.setValue("sdkVersion","1.2.2-staging.4"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&a.setValue("audioPlayback",new xO),a}async join(){const{selfController:t}=n(this,He);return t.self.roomJoined?null:t.joinRoom()}async leave(t){gg.cleanup(),n(this,en).getValue("peerSessionStore").reset();const{selfController:e}=n(this,He);return e.leaveRoom(t)}get participants(){var t;return(t=n(this,He).participantController)==null?void 0:t.participants}get self(){var t;return(t=n(this,He).selfController)==null?void 0:t.self}get meta(){var t;return(t=n(this,He).metaController)==null?void 0:t.meta}get ai(){var t;return(t=n(this,He).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=n(this,He).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=n(this,He).chatController)==null?void 0:t.chat}get polls(){var t;return(t=n(this,He).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=n(this,He).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=n(this,He).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=n(this,He).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=n(this,He).stageController)==null?void 0:t.stage}get stores(){return n(this,He).storesManager}get audio(){return n(this,en).getValue("audioPlayback")}get __internals__(){var t;return(t=n(this,He).internalsController)==null?void 0:t.internals}async joinRoom(){return this.join()}async leaveRoom(t){return this.leave(t)}},He=new WeakMap,en=new WeakMap,Lg);Wl([ct("0002"),Sr.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],Zr.prototype,"join",1);Wl([ct("0003")],Zr.prototype,"leave",1);Wl([ct("0001"),Sr.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],Zr,"init",1);Zr=Wl([ct("0000")],Zr);const HT=Zr;module.exports=HT;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudflare/realtimekit",
3
- "version": "1.2.2-staging.3",
3
+ "version": "1.2.2-staging.4",
4
4
  "description": "A real-time video and audio SDK for building custom, collaborative communication experiences.",
5
5
  "main": "./dist/index.cjs.js",
6
6
  "module": "./dist/index.es.js",