sip-connector 26.2.1 → 26.2.2

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/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2021 - 2025 Krivega
3
+ Copyright (c) 2021 - 2026 Krivega
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -7,7 +7,7 @@
7
7
 
8
8
  ## 📖 Описание
9
9
 
10
- **sip-connector** — это TypeScript SDK для интеграции WebRTC-приложений с платформой Vinteo через SIP-протокол. Библиотека построена на базе `@krivega/jssip` и предоставляет высокоуровневый API для создания полнофункциональных видеоконференций.
10
+ **sip-connector** — это TypeScript SDK для интеграции WebRTC-приложений с платформой Vinteo через SIP-протокол. Предоставляет высокоуровневый API для создания полнофункциональных видеоконференций.
11
11
 
12
12
  ### 🎯 Основные возможности
13
13
 
@@ -36,17 +36,8 @@ SDK предоставляет комплексное решение для:
36
36
 
37
37
  ## 🚀 Установка
38
38
 
39
- ### Команды установки
40
-
41
39
  ```bash
42
- # npm
43
40
  npm install sip-connector
44
-
45
- # yarn
46
- yarn add sip-connector
47
-
48
- # pnpm
49
- pnpm add sip-connector
50
41
  ```
51
42
 
52
43
  ---
@@ -427,10 +427,10 @@ class Mt {
427
427
  this.events.trigger(g.PARTICIPANT_MOVE_REQUEST_TO_STREAM, t);
428
428
  };
429
429
  triggerAccountChangedNotify = () => {
430
- this.events.trigger(g.ACCOUNT_CHANGED, {});
430
+ this.events.trigger(g.ACCOUNT_CHANGED);
431
431
  };
432
432
  triggerAccountDeletedNotify = () => {
433
- this.events.trigger(g.ACCOUNT_DELETED, {});
433
+ this.events.trigger(g.ACCOUNT_DELETED);
434
434
  };
435
435
  triggerConferenceParticipantTokenIssued = ({
436
436
  body: { conference: e, participant: t, jwt: s }
@@ -474,11 +474,11 @@ class Mt {
474
474
  break;
475
475
  }
476
476
  case V.NOT_AVAILABLE_CONTENTED_STREAM: {
477
- this.events.trigger(g.CONTENTED_STREAM_NOT_AVAILABLE, {});
477
+ this.events.trigger(g.CONTENTED_STREAM_NOT_AVAILABLE);
478
478
  break;
479
479
  }
480
480
  case V.MUST_STOP_PRESENTATION: {
481
- this.events.trigger(g.PRESENTATION_MUST_STOP, {});
481
+ this.events.trigger(g.PRESENTATION_MUST_STOP);
482
482
  break;
483
483
  }
484
484
  }
@@ -501,7 +501,7 @@ class Mt {
501
501
  audioId: s
502
502
  }));
503
503
  }
504
- t === z.PARTICIPANT && this.events.trigger(g.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS, {});
504
+ t === z.PARTICIPANT && this.events.trigger(g.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS);
505
505
  };
506
506
  triggerMainCamControl = (e) => {
507
507
  const t = A(e, h.MAIN_CAM), s = A(e, h.MEDIA_SYNC), i = s === j.ADMIN_SYNC_FORCED;
@@ -0,0 +1 @@
1
+ "use strict";const Re=require("@krivega/jssip"),de=require("debug"),M=require("events-constructor"),H=require("@krivega/cancelable-promise"),B=require("@krivega/timeout-requester"),te=require("repeated-calls"),I=require("xstate"),he=require("stack-promises");require("ua-parser-js");require("sequent-promises");const Et=require("lodash"),le="sip-connector",d=de(le),Ne=(n,e)=>{d(`${n}:`,e)},Ct=()=>{de.enable(le)},mt=()=>{de.enable(`-${le}`)},pt="Error decline with 603",Rt=1006,Nt=n=>typeof n=="object"&&n!==null&&"code"in n&&n.code===Rt,At=n=>n.message===pt;var J=(n=>(n.SPECTATOR="SPECTATOR",n.PARTICIPANT="PARTICIPANT",n))(J||{}),P=(n=>(n.SHARE_STATE="application/vinteo.webrtc.sharedesktop",n.MAIN_CAM="application/vinteo.webrtc.maincam",n.ENTER_ROOM="application/vinteo.webrtc.roomname",n.MIC="application/vinteo.webrtc.mic",n.USE_LICENSE="application/vinteo.webrtc.uselic",n.PARTICIPANT_STATE="application/vinteo.webrtc.partstate",n.NOTIFY="application/vinteo.webrtc.notify",n))(P||{}),O=(n=>(n.SHARE_STATE="application/vinteo.webrtc.sharedesktop",n.MAIN_CAM="application/vinteo.webrtc.maincam",n.CHANNELS="application/vinteo.webrtc.channels",n.MEDIA_STATE="application/vinteo.webrtc.mediastate",n.REFUSAL="application/vinteo.webrtc.refusal",n.STATS="application/vinteo.webrtc.stats",n))(O||{}),b=(n=>(n.PAUSE_MAIN_CAM="PAUSEMAINCAM",n.RESUME_MAIN_CAM="RESUMEMAINCAM",n.MAX_MAIN_CAM_RESOLUTION="MAXMAINCAMRESOLUTION",n.ADMIN_STOP_MAIN_CAM="ADMINSTOPMAINCAM",n.ADMIN_START_MAIN_CAM="ADMINSTARTMAINCAM",n))(b||{}),j=(n=>(n.ADMIN_STOP_MIC="ADMINSTOPMIC",n.ADMIN_START_MIC="ADMINSTARTMIC",n))(j||{}),ye=(n=>(n.H264="H264",n.VP8="VP8",n.VP9="VP9",n.AV1="AV1",n))(ye||{}),h=(n=>(n.CONTENT_TYPE="content-type",n.CONTENT_ENTER_ROOM="x-webrtc-enter-room",n.CONTENT_USE_LICENSE="x-webrtc-use-license",n.PARTICIPANT_NAME="x-webrtc-participant-name",n.INPUT_CHANNELS="x-webrtc-input-channels",n.OUTPUT_CHANNELS="x-webrtc-output-channels",n.MAIN_CAM="x-webrtc-maincam",n.MIC="x-webrtc-mic",n.MEDIA_SYNC="x-webrtc-sync",n.MAIN_CAM_RESOLUTION="x-webrtc-maincam-resolution",n.MEDIA_STATE="x-webrtc-media-state",n.MEDIA_TYPE="x-vinteo-media-type",n.MAIN_CAM_STATE="x-vinteo-maincam-state",n.MIC_STATE="x-vinteo-mic-state",n.CONTENT_PARTICIPANT_STATE="x-webrtc-partstate",n.AUDIO_ID="x-webrtc-audioid",n.SPECTATOR_MODE="x-webrtc-spectator-mode",n.NOTIFY="x-vinteo-notify",n.CONTENT_ENABLE_MEDIA_DEVICE="x-webrtc-request-enable-media-device",n.CONTENTED_STREAM_STATE="x-webrtc-share-state",n.CONTENTED_STREAM_CODEC="x-webrtc-share-codec",n.AVAILABLE_INCOMING_BITRATE="x-webrtc-available-incoming-bitrate",n.AUDIO_TRACK_COUNT="x-webrtc-audio-track-count",n.VIDEO_TRACK_COUNT="x-webrtc-video-track-count",n.TRACKS_DIRECTION="x-webrtc-tracks-direction",n.BEARER_TOKEN="x-bearer-token",n.IS_DIRECT_PEER_TO_PEER="x-webrtc-is-direct-p2p",n))(h||{}),V=(n=>(n.AVAILABLE_CONTENTED_STREAM="YOUCANRECEIVECONTENT",n.NOT_AVAILABLE_CONTENTED_STREAM="CONTENTEND",n.MUST_STOP_PRESENTATION="YOUMUSTSTOPSENDCONTENT",n))(V||{}),k=(n=>(n.AVAILABLE_CONTENTED_STREAM="x-webrtc-share-state: YOUCANRECEIVECONTENT",n.NOT_AVAILABLE_CONTENTED_STREAM="x-webrtc-share-state: CONTENTEND",n.ACK_PERMISSION_TO_START_PRESENTATION="x-webrtc-share-state: LETMESTARTPRESENTATION",n.STOPPED_CLIENT_PRESENTATION="x-webrtc-share-state: STOPPRESENTATION",n.ENABLE_MAIN_CAM="x-webrtc-request-enable-media-device: LETMESTARTMAINCAM",n))(k||{}),X=(n=>(n.ADMIN_SYNC_FORCED="1",n.ADMIN_SYNC_NOT_FORCED="0",n))(X||{}),ue=(n=>(n.SPECTATOR_MANUAL="0",n.BY_STATE_CAM="1",n.SPECTATOR_FORCED="2",n))(ue||{}),ge=(n=>(n.AUDIO="AUDIO",n.VIDEO="VIDEO",n.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION",n))(ge||{}),g=(n=>(n.ENTER_ROOM="enter-room",n.MAIN_CAM_CONTROL="main-cam-control",n.USE_LICENSE="use-license",n.NEW_DTMF="new-dtmf",n.CONFERENCE_PARTICIPANT_TOKEN_ISSUED="conference:participant-token-issued",n.CONTENTED_STREAM_AVAILABLE="contented-stream:available",n.CONTENTED_STREAM_NOT_AVAILABLE="contented-stream:not-available",n.PRESENTATION_MUST_STOP="presentation:must-stop",n.CHANNELS_ALL="channels:all",n.CHANNELS_NOTIFY="channels:notify",n.PARTICIPANT_ADDED_TO_LIST_MODERATORS="participant:added-to-list-moderators",n.PARTICIPANT_REMOVED_FROM_LIST_MODERATORS="participant:removed-from-list-moderators",n.PARTICIPANT_MOVE_REQUEST_TO_STREAM="participant:move-request-to-stream",n.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS="participant:move-request-to-spectators",n.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS_SYNTHETIC="participant:move-request-to-spectators-synthetic",n.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS_WITH_AUDIO_ID="participant:move-request-to-spectators-with-audio-id",n.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS="participant:move-request-to-participants",n.PARTICIPATION_ACCEPTING_WORD_REQUEST="participation:accepting-word-request",n.PARTICIPATION_CANCELLING_WORD_REQUEST="participation:cancelling-word-request",n.WEBCAST_STARTED="webcast:started",n.WEBCAST_STOPPED="webcast:stopped",n.ACCOUNT_CHANGED="account:changed",n.ACCOUNT_DELETED="account:deleted",n.ADMIN_START_MAIN_CAM="admin:start-main-cam",n.ADMIN_STOP_MAIN_CAM="admin:stop-main-cam",n.ADMIN_START_MIC="admin:start-mic",n.ADMIN_STOP_MIC="admin:stop-mic",n.ADMIN_FORCE_SYNC_MEDIA_STATE="admin:force-sync-media-state",n.FAILED_SEND_ROOM_DIRECT_P2P="failed-send-room-direct-p2p",n))(g||{});const Le=["enter-room","main-cam-control","use-license","new-dtmf","conference:participant-token-issued","contented-stream:available","contented-stream:not-available","presentation:must-stop","channels:all","channels:notify","participant:added-to-list-moderators","participant:removed-from-list-moderators","participant:move-request-to-stream","participant:move-request-to-spectators","participant:move-request-to-spectators-synthetic","participant:move-request-to-spectators-with-audio-id","participant:move-request-to-participants","participation:accepting-word-request","participation:cancelling-word-request","webcast:started","webcast:stopped","account:changed","account:deleted","admin:start-main-cam","admin:stop-main-cam","admin:start-mic","admin:stop-mic","admin:force-sync-media-state","failed-send-room-direct-p2p"],It=()=>new M.TypedEvents(Le),vt=n=>typeof n=="string"&&n.trim().length>0,L=(n,e)=>{const t=e.toLowerCase(),s=Object.entries(n).find(([,i])=>typeof i=="string"&&i.toLowerCase()===t);return s?s[1]:void 0},ft=n=>typeof n=="string"&&!Number.isNaN(Number(n))&&Number.isFinite(Number(n)),Mt=n=>{if(ft(n))return Number(n)},_t=n=>{const e=n.toLowerCase();if(e==="true"||e==="1")return!0;if(e==="false"||e==="0")return!1},A=(n,e)=>{const t=n.getHeader(e.toLowerCase());if(!vt(t))return;const s=t.toLowerCase();switch(e){case h.BEARER_TOKEN:return t;case h.CONTENT_ENTER_ROOM:case h.PARTICIPANT_NAME:case h.INPUT_CHANNELS:case h.OUTPUT_CHANNELS:case h.TRACKS_DIRECTION:case h.AUDIO_ID:case h.MAIN_CAM_RESOLUTION:case h.MEDIA_STATE:case h.NOTIFY:case h.CONTENT_ENABLE_MEDIA_DEVICE:return s;case h.MEDIA_TYPE:case h.MAIN_CAM_STATE:case h.MIC_STATE:case h.AVAILABLE_INCOMING_BITRATE:case h.AUDIO_TRACK_COUNT:case h.VIDEO_TRACK_COUNT:return Mt(s);case h.CONTENTED_STREAM_CODEC:return L(ye,s);case h.CONTENT_TYPE:return L(P,s);case h.CONTENT_USE_LICENSE:return L(ge,s);case h.MAIN_CAM:return L(b,s);case h.MIC:return L(j,s);case h.MEDIA_SYNC:return L(X,s);case h.CONTENT_PARTICIPANT_STATE:return L(J,s);case h.SPECTATOR_MODE:return L(ue,s);case h.CONTENTED_STREAM_STATE:return L(V,s);case h.IS_DIRECT_PEER_TO_PEER:return _t(s);default:return}};var f=(n=>(n.CHANNELS="channels",n.WEBCAST_STARTED="WebcastStarted",n.WEBCAST_STOPPED="WebcastStopped",n.ACCOUNT_CHANGED="accountChanged",n.ACCOUNT_DELETED="accountDeleted",n.ADDED_TO_LIST_MODERATORS="addedToListModerators",n.REMOVED_FROM_LIST_MODERATORS="removedFromListModerators",n.ACCEPTING_WORD_REQUEST="ParticipationRequestAccepted",n.CANCELLING_WORD_REQUEST="ParticipationRequestRejected",n.MOVE_REQUEST_TO_STREAM="ParticipantMovedToWebcast",n.CONFERENCE_PARTICIPANT_TOKEN_ISSUED="ConferenceParticipantTokenIssued",n))(f||{});class bt{events;callManager;constructor(){this.events=It()}subscribe({connectionManager:e,callManager:t}){this.callManager=t,e.on("sipEvent",this.handleSipEvent),t.on("newInfo",this.handleNewInfo),t.on("newDTMF",({originator:s})=>{this.events.trigger(g.NEW_DTMF,{originator:s})})}async waitChannels(){return this.wait(g.CHANNELS_ALL)}async waitSyncMediaState(){return this.wait(g.ADMIN_FORCE_SYNC_MEDIA_STATE)}async sendDTMF(e){return new Promise((t,s)=>{let i;try{i=this.getEstablishedRTCSessionProtected()}catch(r){s(r)}i&&(this.callManager?.once("newDTMF",({originator:r})=>{r==="local"&&t()}),i.sendDTMF(e,{duration:120,interToneGap:600}))})}async sendChannels({inputChannels:e,outputChannels:t}){const s=this.getEstablishedRTCSessionProtected(),i=`${h.INPUT_CHANNELS}: ${e}`,r=`${h.OUTPUT_CHANNELS}: ${t}`,a=[i,r];return s.sendInfo(O.CHANNELS,void 0,{extraHeaders:a})}sendEnterRoom(e){this.sendEnterRoomProtected(e).catch(t=>{this.events.trigger(g.FAILED_SEND_ROOM_DIRECT_P2P,{error:t})})}async sendMediaState({cam:e,mic:t},s={}){const i=this.getEstablishedRTCSessionProtected(),r=`${h.MEDIA_STATE}: currentstate`,a=`${h.MAIN_CAM_STATE}: ${Number(e)}`,o=`${h.MIC_STATE}: ${Number(t)}`,c=[r,a,o];return i.sendInfo(O.MEDIA_STATE,void 0,{noTerminateWhenError:!0,...s,extraHeaders:c})}async sendStats({availableIncomingBitrate:e}){const t=this.getEstablishedRTCSessionProtected(),i=[`${h.AVAILABLE_INCOMING_BITRATE}: ${e}`];return t.sendInfo(O.STATS,void 0,{noTerminateWhenError:!0,extraHeaders:i})}async sendRefusalToTurnOn(e,t={}){const s=this.getEstablishedRTCSessionProtected(),a=e==="mic"?0:1,c=[`${h.MEDIA_TYPE}: ${a}`];return s.sendInfo(O.REFUSAL,void 0,{noTerminateWhenError:!0,...t,extraHeaders:c})}async sendRefusalToTurnOnMic(e={}){return this.sendRefusalToTurnOn("mic",{noTerminateWhenError:!0,...e})}async sendRefusalToTurnOnCam(e={}){return this.sendRefusalToTurnOn("cam",{noTerminateWhenError:!0,...e})}async sendAvailableContentedStream(){await this.getEstablishedRTCSessionProtected().sendInfo(O.SHARE_STATE,void 0,{extraHeaders:[k.AVAILABLE_CONTENTED_STREAM]})}async askPermissionToStartPresentation(){await this.getEstablishedRTCSessionProtected().sendInfo(O.SHARE_STATE,void 0,{extraHeaders:[k.ACK_PERMISSION_TO_START_PRESENTATION]})}async sendStoppedPresentation(){await this.getEstablishedRTCSessionProtected().sendInfo(O.SHARE_STATE,void 0,{extraHeaders:[k.STOPPED_CLIENT_PRESENTATION]})}async sendNotAvailableContentedStream(){await this.getEstablishedRTCSessionProtected().sendInfo(O.SHARE_STATE,void 0,{extraHeaders:[k.NOT_AVAILABLE_CONTENTED_STREAM]})}async askPermissionToEnableCam(e={}){const t=this.getEstablishedRTCSessionProtected(),s=[k.ENABLE_MAIN_CAM];return t.sendInfo(O.MAIN_CAM,void 0,{noTerminateWhenError:!0,...e,extraHeaders:s}).catch(i=>{if(At(i))throw i})}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}getEstablishedRTCSessionProtected=()=>{const e=this.callManager?.getEstablishedRTCSession();if(!e)throw new Error("No rtcSession established");return e};handleSipEvent=({request:e})=>{this.maybeHandleNotify(e)};maybeHandleNotify=e=>{try{const t=e.getHeader(h.NOTIFY);if(t){const s=JSON.parse(t);this.handleNotify(s)}}catch(t){d("error parse notify",t)}};handleNotify=e=>{switch(e.cmd){case f.CHANNELS:{const t=e;this.triggerChannelsNotify(t);break}case f.WEBCAST_STARTED:{const t=e;this.triggerWebcastStartedNotify(t);break}case f.WEBCAST_STOPPED:{const t=e;this.triggerWebcastStoppedNotify(t);break}case f.ADDED_TO_LIST_MODERATORS:{const t=e;this.triggerAddedToListModeratorsNotify(t);break}case f.REMOVED_FROM_LIST_MODERATORS:{const t=e;this.triggerRemovedFromListModeratorsNotify(t);break}case f.ACCEPTING_WORD_REQUEST:{const t=e;this.triggerParticipationAcceptingWordRequest(t);break}case f.CANCELLING_WORD_REQUEST:{const t=e;this.triggerParticipationCancellingWordRequest(t);break}case f.MOVE_REQUEST_TO_STREAM:{const t=e;this.triggerParticipantMoveRequestToStream(t);break}case f.ACCOUNT_CHANGED:{this.triggerAccountChangedNotify();break}case f.ACCOUNT_DELETED:{this.triggerAccountDeletedNotify();break}case f.CONFERENCE_PARTICIPANT_TOKEN_ISSUED:{const t=e;this.triggerConferenceParticipantTokenIssued(t);break}default:d("unknown cmd",e)}};handleNewInfo=e=>{const{originator:t}=e;if(t!=="remote")return;const{request:s}=e,i=s,r=A(i,h.CONTENT_TYPE);if(r!==void 0)switch(r){case P.ENTER_ROOM:{this.triggerEnterRoom(i),this.maybeTriggerChannels(i);break}case P.NOTIFY:{this.maybeHandleNotify(i);break}case P.SHARE_STATE:{this.triggerContentedStreamState(i);break}case P.MAIN_CAM:{this.triggerMainCamControl(i);break}case P.MIC:{this.triggerMicControl(i);break}case P.USE_LICENSE:{this.triggerUseLicense(i);break}case P.PARTICIPANT_STATE:{this.maybeTriggerParticipantMoveRequest(i);break}}};triggerChannelsNotify=e=>{const t=e.input,s=e.output,i={inputChannels:t,outputChannels:s};this.events.trigger(g.CHANNELS_NOTIFY,i)};triggerWebcastStartedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this.events.trigger(g.WEBCAST_STARTED,s)};triggerWebcastStoppedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this.events.trigger(g.WEBCAST_STOPPED,s)};triggerAddedToListModeratorsNotify=({conference:e})=>{const t={conference:e};this.events.trigger(g.PARTICIPANT_ADDED_TO_LIST_MODERATORS,t)};triggerRemovedFromListModeratorsNotify=({conference:e})=>{const t={conference:e};this.events.trigger(g.PARTICIPANT_REMOVED_FROM_LIST_MODERATORS,t)};triggerParticipationAcceptingWordRequest=({body:{conference:e}})=>{const t={conference:e};this.events.trigger(g.PARTICIPATION_ACCEPTING_WORD_REQUEST,t)};triggerParticipationCancellingWordRequest=({body:{conference:e}})=>{const t={conference:e};this.events.trigger(g.PARTICIPATION_CANCELLING_WORD_REQUEST,t)};triggerParticipantMoveRequestToStream=({body:{conference:e}})=>{const t={conference:e};this.events.trigger(g.PARTICIPANT_MOVE_REQUEST_TO_STREAM,t)};triggerAccountChangedNotify=()=>{this.events.trigger(g.ACCOUNT_CHANGED)};triggerAccountDeletedNotify=()=>{this.events.trigger(g.ACCOUNT_DELETED)};triggerConferenceParticipantTokenIssued=({body:{conference:e,participant:t,jwt:s}})=>{const i={conference:e,participant:t,jwt:s};this.events.trigger(g.CONFERENCE_PARTICIPANT_TOKEN_ISSUED,i)};maybeTriggerChannels=e=>{const t=A(e,h.INPUT_CHANNELS),s=A(e,h.OUTPUT_CHANNELS);if(t!==void 0&&s!==void 0){const i={inputChannels:t,outputChannels:s};this.events.trigger(g.CHANNELS_ALL,i)}};triggerEnterRoom=e=>{const t=A(e,h.CONTENT_ENTER_ROOM),s=A(e,h.PARTICIPANT_NAME),i=A(e,h.BEARER_TOKEN),r=A(e,h.IS_DIRECT_PEER_TO_PEER);t!==void 0&&s!==void 0&&this.events.trigger(g.ENTER_ROOM,{room:t,participantName:s,bearerToken:i,isDirectPeerToPeer:r})};triggerContentedStreamState=e=>{const t=A(e,h.CONTENTED_STREAM_STATE);if(t!==void 0)switch(t){case V.AVAILABLE_CONTENTED_STREAM:{const s=A(e,h.CONTENTED_STREAM_CODEC);this.events.trigger(g.CONTENTED_STREAM_AVAILABLE,{codec:s});break}case V.NOT_AVAILABLE_CONTENTED_STREAM:{this.events.trigger(g.CONTENTED_STREAM_NOT_AVAILABLE);break}case V.MUST_STOP_PRESENTATION:{this.events.trigger(g.PRESENTATION_MUST_STOP);break}}};maybeTriggerParticipantMoveRequest=e=>{const t=A(e,h.CONTENT_PARTICIPANT_STATE),s=A(e,h.AUDIO_ID),i=A(e,h.SPECTATOR_MODE);if(t===J.SPECTATOR){const r=i===ue.BY_STATE_CAM;s===void 0?(this.events.trigger(g.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS_SYNTHETIC,{isAvailableSendingMedia:r}),this.events.trigger(g.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS,{isAvailableSendingMedia:r,isSynthetic:!0})):(this.events.trigger(g.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS_WITH_AUDIO_ID,{isAvailableSendingMedia:r,audioId:s}),this.events.trigger(g.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS,{isAvailableSendingMedia:r,isSynthetic:!1,audioId:s}))}t===J.PARTICIPANT&&this.events.trigger(g.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS)};triggerMainCamControl=e=>{const t=A(e,h.MAIN_CAM),s=A(e,h.MEDIA_SYNC),i=s===X.ADMIN_SYNC_FORCED;if(t===b.ADMIN_START_MAIN_CAM){this.events.trigger(g.ADMIN_START_MAIN_CAM,{isSyncForced:i});return}if(t===b.ADMIN_STOP_MAIN_CAM){this.events.trigger(g.ADMIN_STOP_MAIN_CAM,{isSyncForced:i});return}(t===b.RESUME_MAIN_CAM||t===b.PAUSE_MAIN_CAM)&&s!==void 0&&this.events.trigger(g.ADMIN_FORCE_SYNC_MEDIA_STATE,{isSyncForced:i});const r=A(e,h.MAIN_CAM_RESOLUTION);this.events.trigger(g.MAIN_CAM_CONTROL,{mainCam:t,resolutionMainCam:r})};triggerMicControl=e=>{const t=A(e,h.MIC),i=A(e,h.MEDIA_SYNC)===X.ADMIN_SYNC_FORCED;t===j.ADMIN_START_MIC?this.events.trigger(g.ADMIN_START_MIC,{isSyncForced:i}):t===j.ADMIN_STOP_MIC&&this.events.trigger(g.ADMIN_STOP_MIC,{isSyncForced:i})};triggerUseLicense=e=>{const t=A(e,h.CONTENT_USE_LICENSE);t!==void 0&&this.events.trigger(g.USE_LICENSE,t)};async sendEnterRoomProtected(e){return this.getEstablishedRTCSessionProtected().sendInfo(P.ENTER_ROOM,void 0,{extraHeaders:e})}}const Ot=/^p2p.+to.+$/i,Te=n=>n!==void 0&&n.length>0&&Ot.test(n),we="purgatory",Se=n=>n===we,Pt=(n,e)=>{n.getVideoTracks().forEach(s=>{"contentHint"in s&&s.contentHint!==e&&(s.contentHint=e)})},x=(n,{directionVideo:e,directionAudio:t,contentHint:s}={})=>{if(!n||e==="recvonly"&&t==="recvonly")return;const i=t==="recvonly"?[]:n.getAudioTracks(),r=e==="recvonly"?[]:n.getVideoTracks(),a=[...i,...r],o=new MediaStream(a);return o.getTracks=()=>[...o.getAudioTracks(),...o.getVideoTracks()],s&&s!=="none"&&Pt(o,s),o},Dt="api/v2/rtp2webrtc/offer",Ue=async({serverUrl:n,conferenceNumber:e,quality:t,audio:s,offer:i,token:r})=>{const a=new URL(`https://${n.replace(/\/$/,"")}/${Dt}/${encodeURIComponent(e)}`);a.searchParams.set("quality",t),a.searchParams.set("audio",String(s));const o={"Content-Type":"application/json",Authorization:`Bearer ${r}`},c=await fetch(a.toString(),{method:"POST",headers:o,credentials:"same-origin",body:JSON.stringify(i)});if(!c.ok)throw new Error(`sendOffer failed with status ${c.status}`);const l=await c.json();return{type:l.type,sdp:l.sdp,toJSON(){return l}}},yt=(n,e)=>(n.degradationPreference=e.degradationPreference,n),Lt=(n,e)=>{n.encodings??=[];for(let t=n.encodings.length;t<e;t+=1)n.encodings.push({});return n},ke=n=>(e,t)=>t!==void 0&&e!==t||t===void 0&&e!==n,wt=ke(),Ut=(n,e)=>{if(wt(n,e))return n},kt=(n,e,{isResetAllowed:t=!1}={})=>{const s=n.maxBitrate,i=Ut(e,s);return(i!==void 0||t)&&(n.maxBitrate=i),n},Fe=1,Ft=ke(Fe),Bt=(n,e)=>{const t=n===void 0?void 0:Math.max(n,Fe);if(t!==void 0&&Ft(t,e))return t},$t=(n,e)=>{const t=n.scaleResolutionDownBy,s=Bt(e,t);return s!==void 0&&(n.scaleResolutionDownBy=s),n},Gt=(n,e,{isResetAllowed:t}={})=>{const s=e.encodings?.length??0;return Lt(n,s),n.encodings.forEach((i,r)=>{const a=(e?.encodings??[])[r],o=a?.maxBitrate,c=a?.scaleResolutionDownBy;kt(i,o,{isResetAllowed:t}),$t(i,c)}),n},qt=(n,e)=>{if(n.codecs?.length!==e.codecs?.length)return!0;for(let t=0;t<(n.codecs?.length??0);t++)if(JSON.stringify(n.codecs[t])!==JSON.stringify(e.codecs[t]))return!0;if(n.headerExtensions?.length!==e.headerExtensions?.length)return!0;for(let t=0;t<(n.headerExtensions?.length??0);t++)if(JSON.stringify(n.headerExtensions[t])!==JSON.stringify(e.headerExtensions[t]))return!0;if(n.encodings?.length!==e.encodings?.length)return!0;for(let t=0;t<(n.encodings?.length??0);t++)if(JSON.stringify(n.encodings[t])!==JSON.stringify(e.encodings[t]))return!0;return n.rtcp?.cname!==e.rtcp?.cname||n.rtcp?.reducedSize!==e.rtcp?.reducedSize||n.degradationPreference!==e.degradationPreference},K=async(n,e,{isResetAllowed:t}={})=>{const s=n.getParameters(),i=JSON.parse(JSON.stringify(s));Gt(s,e,{isResetAllowed:t}),yt(s,e);const r=qt(i,s);return r&&await n.setParameters(s),{parameters:s,isChanged:r}},Ee=async(n,e,t)=>{const{isChanged:s,parameters:i}=await K(n,{encodings:[{scaleResolutionDownBy:e.scaleResolutionDownBy,maxBitrate:e.maxBitrate}]});return s&&t&&t(i),{isChanged:s,parameters:i}},Vt=(n,e)=>n.find(t=>t.track!==null&&e.getTracks().includes(t.track)),xt=async(n,e,t)=>{const s=Vt(n,e);if(s)return Ee(s,{maxBitrate:t})};class Be{command=void 0;unsubscribe;options;constructor(e){this.options=e}set(e){this.cancel(),this.command=e,this.unsubscribe=this.options.subscribe(t=>{this.options.isReady(t)?(this.command!==void 0&&this.options.onExecute(this.command),this.cancel()):this.options.isCancelled(t)&&this.cancel()})}cancel(){this.unsubscribe?.(),this.unsubscribe=void 0,this.command=void 0}}class W{actor;subscriptions=[];stateChangeListeners=new Set;constructor(e){this.actor=I.createActor(e),this.actor.start(),this.addSubscription(this.subscribe(t=>{const s=t.value;this.stateChangeListeners.forEach(i=>{i(s)})}))}get state(){return this.getSnapshot().value}get context(){return this.getSnapshot().context}send(e){this.actor.send(e)}getSnapshot(){return this.actor.getSnapshot()}subscribe(e){const t=this.actor.subscribe(e);return this.addSubscription(t),t}onStateChange(e){return this.stateChangeListeners.add(e),()=>{this.stateChangeListeners.delete(e)}}stop(){this.stateChangeListeners.clear(),this.subscriptions.forEach(e=>{e()}),this.subscriptions.length=0,this.actor.stop()}addSubscription(e){const t=typeof e=="function"?e:()=>{e.unsubscribe()};return this.subscriptions.push(t),t}}var Z=(n=>(n.IDLE="call:idle",n.CONNECTING="call:connecting",n.PURGATORY="call:purgatory",n.P2P_ROOM="call:p2pRoom",n.DIRECT_P2P_ROOM="call:directP2pRoom",n.IN_ROOM="call:inRoom",n.DISCONNECTING="call:disconnecting",n))(Z||{});const m="evaluate",ee=n=>typeof n=="string"&&n.length>0,Q=n=>"number"in n&&ee(n.number)&&typeof n.answer=="boolean",ne=n=>"room"in n&&ee(n.room)&&ee(n.participantName),se=n=>"token"in n&&ee(n.token),$e=({isDirectPeerToPeer:n})=>n===!0,Ht=n=>Se(n.room)||Te(n.room)||$e(n),Wt=n=>Q(n)&&ne(n)&&!se(n)&&"room"in n&&Se(n.room),Qt=n=>Q(n)&&ne(n)&&!se(n)&&"room"in n&&Te(n.room),Yt=n=>"isDirectPeerToPeer"in n&&$e(n),zt=n=>Q(n)&&ne(n)&&!se(n)&&"room"in n&&Yt(n),Ge=n=>Q(n)&&ne(n)&&se(n),Jt={},ie=()=>({number:void 0,answer:void 0,room:void 0,participantName:void 0,token:void 0,isDirectPeerToPeer:void 0,pendingDisconnect:void 0}),jt=I.setup({types:{context:Jt,events:{}},actions:{setConnecting:I.assign(({event:n,context:e})=>n.type!=="CALL.CONNECTING"?e:{...ie(),number:n.number,answer:n.answer}),setRoomInfo:I.assign(({event:n,context:e})=>{if(n.type!=="CALL.ENTER_ROOM")return e;const t={room:n.room,participantName:n.participantName};return n.token!==void 0?t.token=n.token:Ht(n)&&(t.token=void 0),n.isDirectPeerToPeer!==void 0&&(t.isDirectPeerToPeer=n.isDirectPeerToPeer),t}),setTokenInfo:I.assign(({event:n,context:e})=>n.type!=="CALL.TOKEN_ISSUED"?e:{token:n.token}),reset:I.assign(ie()),prepareDisconnect:I.assign(()=>({...ie(),pendingDisconnect:!0}))}}).createMachine({id:"call",initial:"call:idle",context:{},states:{"call:idle":{on:{"CALL.CONNECTING":{target:m,actions:"setConnecting"}}},"call:connecting":{on:{"CALL.ENTER_ROOM":{target:m,actions:"setRoomInfo"},"CALL.TOKEN_ISSUED":{target:m,actions:"setTokenInfo"},"CALL.START_DISCONNECT":{target:m,actions:"prepareDisconnect"},"CALL.RESET":{target:m,actions:"reset"}}},"call:inRoom":{on:{"CALL.ENTER_ROOM":{target:m,actions:"setRoomInfo"},"CALL.TOKEN_ISSUED":{target:m,actions:"setTokenInfo"},"CALL.START_DISCONNECT":{target:m,actions:"prepareDisconnect"},"CALL.RESET":{target:m,actions:"reset"}}},[m]:{always:[{target:"call:disconnecting",guard:({context:n})=>n.pendingDisconnect===!0,actions:"reset"},{target:"call:inRoom",guard:({context:n})=>Ge(n)},{target:"call:directP2pRoom",guard:({context:n})=>zt(n)},{target:"call:p2pRoom",guard:({context:n})=>Qt(n)},{target:"call:purgatory",guard:({context:n})=>Wt(n)},{target:"call:connecting",guard:({context:n})=>Q(n)},{target:"call:idle"}]},"call:purgatory":{on:{"CALL.ENTER_ROOM":{target:m,actions:"setRoomInfo"},"CALL.TOKEN_ISSUED":{target:m,actions:"setTokenInfo"},"CALL.START_DISCONNECT":{target:m,actions:"prepareDisconnect"},"CALL.RESET":{target:m,actions:"reset"}}},"call:p2pRoom":{on:{"CALL.ENTER_ROOM":{target:m,actions:"setRoomInfo"},"CALL.TOKEN_ISSUED":{target:m,actions:"setTokenInfo"},"CALL.START_DISCONNECT":{target:m,actions:"prepareDisconnect"},"CALL.RESET":{target:m,actions:"reset"}}},"call:directP2pRoom":{on:{"CALL.ENTER_ROOM":{target:m,actions:"setRoomInfo"},"CALL.TOKEN_ISSUED":{target:m,actions:"setTokenInfo"},"CALL.START_DISCONNECT":{target:m,actions:"prepareDisconnect"},"CALL.RESET":{target:m,actions:"reset"}}},"call:disconnecting":{on:{"CALL.RESET":{target:m,actions:"reset"}}}}});class Xt extends W{constructor(e){super(jt),this.subscribeToEvents(e)}get isIdle(){return this.state==="call:idle"}get isConnecting(){return this.state==="call:connecting"}get isInPurgatory(){return this.state==="call:purgatory"}get isP2PRoom(){return this.state==="call:p2pRoom"}get isDirectP2PRoom(){return this.state==="call:directP2pRoom"}get isInRoom(){return this.state==="call:inRoom"}get isDisconnecting(){return this.state==="call:disconnecting"}get inRoomContext(){const{context:e}=this;return Ge(e)?e:void 0}get isActive(){return this.isInRoom||this.isInPurgatory||this.isP2PRoom||this.isDirectP2PRoom}get number(){const{context:e}=this;if("number"in e)return e.number}get token(){const{context:e}=this;if("token"in e)return e.token}get isCallInitiator(){return!this.isCallAnswerer}get isCallAnswerer(){const{context:e}=this;return"answer"in e?e.answer:!1}reset(){this.send({type:"CALL.RESET"})}send(e){if(!this.actor.getSnapshot().can(e)){console.warn(`[CallStateMachine] Invalid transition: ${e.type} from ${this.state}. Event cannot be processed in current state.`);return}super.send(e)}subscribeToApiEvents(e){this.addSubscription(e.on("enter-room",({room:t,participantName:s,bearerToken:i,isDirectPeerToPeer:r})=>{this.send({type:"CALL.ENTER_ROOM",room:t,participantName:s,token:i,isDirectPeerToPeer:r})})),this.addSubscription(e.on("conference:participant-token-issued",({jwt:t})=>{this.send({type:"CALL.TOKEN_ISSUED",token:t})}))}subscribeToEvents(e){this.addSubscription(e.on("start-call",({number:t,answer:s})=>{this.send({type:"CALL.CONNECTING",number:t,answer:s})})),this.addSubscription(e.on("end-call",()=>{this.send({type:"CALL.START_DISCONNECT"})})),this.addSubscription(e.on("ended",()=>{this.send({type:"CALL.RESET"})})),this.addSubscription(e.on("failed",()=>{this.send({type:"CALL.RESET"})}))}}var S=(n=>(n.PEER_CONNECTION="peerconnection",n.CONNECTING="connecting",n.SENDING="sending",n.PROGRESS="progress",n.ACCEPTED="accepted",n.CONFIRMED="confirmed",n.ENDED="ended",n.FAILED="failed",n.NEW_DTMF="newDTMF",n.NEW_INFO="newInfo",n.HOLD="hold",n.UNHOLD="unhold",n.MUTED="muted",n.UNMUTED="unmuted",n.REINVITE="reinvite",n.UPDATE="update",n.REFER="refer",n.REPLACES="replaces",n.SDP="sdp",n.ICE_CANDIDATE="icecandidate",n.GET_USER_MEDIA_FAILED="getusermediafailed",n.PEER_CONNECTION_CREATE_OFFER_FAILED="peerconnection:createofferfailed",n.PEER_CONNECTION_CREATE_ANSWER_FAILED="peerconnection:createanswerfailed",n.PEER_CONNECTION_SET_LOCAL_DESCRIPTION_FAILED="peerconnection:setlocaldescriptionfailed",n.PEER_CONNECTION_SET_REMOTE_DESCRIPTION_FAILED="peerconnection:setremotedescriptionfailed",n.START_PRESENTATION="presentation:start",n.STARTED_PRESENTATION="presentation:started",n.END_PRESENTATION="presentation:end",n.ENDED_PRESENTATION="presentation:ended",n.FAILED_PRESENTATION="presentation:failed",n.START_CALL="start-call",n.END_CALL="end-call",n.PEER_CONNECTION_CONFIRMED="peerconnection:confirmed",n.PEER_CONNECTION_ONTRACK="peerconnection:ontrack",n.ENDED_FROM_SERVER="ended:fromserver",n.CALL_STATUS_CHANGED="call-status-changed",n.REMOTE_TRACKS_CHANGED="remote-tracks-changed",n.REMOTE_STREAMS_CHANGED="remote-streams-changed",n.RECV_SESSION_STARTED="recv-session-started",n.RECV_SESSION_ENDED="recv-session-ended",n.RECV_QUALITY_CHANGED="recv-quality-changed",n))(S||{}),qe=(n=>(n.LOCAL="local",n.REMOTE="remote",n.SYSTEM="system",n))(qe||{});const Ve=["peerconnection","connecting","sending","progress","accepted","confirmed","ended","failed","hold","unhold","muted","unmuted","newInfo","newDTMF","presentation:start","presentation:started","presentation:end","presentation:ended","presentation:failed","reinvite","update","refer","replaces","sdp","icecandidate","getusermediafailed","peerconnection:createofferfailed","peerconnection:createanswerfailed","peerconnection:setlocaldescriptionfailed","peerconnection:setremotedescriptionfailed"],Kt=["start-call","end-call","peerconnection:confirmed","peerconnection:ontrack","ended:fromserver","call-status-changed","remote-tracks-changed","remote-streams-changed","recv-session-started","recv-session-ended","recv-quality-changed"],xe=[...Ve,...Kt],Zt=()=>new M.TypedEvents(xe),en=6e3,tn=1e3,z=(n,e)=>n.getSenders().filter(t=>t.track?.kind===e),nn=n=>n==="audio"?en:tn,sn=n=>n.track!==null;class rn{previousBitrates=new Map;async setMinBitrateForSenders(e,t="all"){const s=[];if(!e)return;(t==="audio"||t==="all")&&s.push(...z(e,"audio")),(t==="video"||t==="all")&&s.push(...z(e,"video"));const i=s.filter(sn).map(async r=>{const a=r.getParameters();this.saveCurrentBitrate(r,a);const o={...a,encodings:a.encodings.map(c=>({...c,maxBitrate:nn(r.track.kind)}))};await K(r,o)});await Promise.all(i)}async restoreBitrateForSenders(e,t="all"){const s=[];if(!e)return;(t==="audio"||t==="all")&&s.push(...z(e,"audio")),(t==="video"||t==="all")&&s.push(...z(e,"video"));const i=s.map(async r=>{const a=this.getSavedBitrate(r);if(a){const c={...r.getParameters(),encodings:a};await K(r,c,{isResetAllowed:!0}),this.clearSavedBitrate(r)}});await Promise.all(i)}getSavedBitrate(e){return this.previousBitrates.get(e)}clearSavedBitrate(e){this.previousBitrates.delete(e)}clearAll(){this.previousBitrates.clear()}hasSavedBitrate(e){return this.previousBitrates.has(e)}getSavedCount(){return this.previousBitrates.size}saveCurrentBitrate(e,t){const s=t.encodings.map(i=>({...i}));this.previousBitrates.set(e,s)}}var Ce=(n=>(n.BYE="Terminated",n.WEBRTC_ERROR="WebRTC Error",n.CANCELED="Canceled",n.REQUEST_TIMEOUT="Request Timeout",n.REJECTED="Rejected",n.REDIRECTED="Redirected",n.UNAVAILABLE="Unavailable",n.NOT_FOUND="Not Found",n.ADDRESS_INCOMPLETE="Address Incomplete",n.INCOMPATIBLE_SDP="Incompatible SDP",n.BAD_MEDIA_DESCRIPTION="Bad Media Description",n))(Ce||{});class an{events;rtcSession;disposers=new Set;onReset;bitrateStateManager=new rn;constructor(e,{onReset:t}){this.events=e,this.onReset=t,e.on(S.FAILED,this.handleEnded),e.on(S.ENDED,this.handleEnded)}get connection(){return this.rtcSession?.connection}get isCallActive(){return this.rtcSession?.isEstablished()===!0}getEstablishedRTCSession=()=>this.rtcSession?.isEstablished()===!0?this.rtcSession:void 0;async renegotiate(){if(this.rtcSession===void 0)throw new Error("No rtcSession established");return this.rtcSession.renegotiate()}startCall=async(e,t,{number:s,mediaStream:i,extraHeaders:r=[],iceServers:a,directionVideo:o,directionAudio:c,contentHint:l,offerToReceiveAudio:u=!0,offerToReceiveVideo:T=!0,degradationPreference:E,sendEncodings:N,onAddedTransceiver:y})=>new Promise((v,U)=>{this.handleCall().then(v).catch($=>{U($)}),this.rtcSession=e.call(t(s),{mediaStream:x(i,{directionVideo:o,directionAudio:c,contentHint:l}),pcConfig:{iceServers:a},rtcOfferConstraints:{offerToReceiveAudio:u,offerToReceiveVideo:T},eventHandlers:this.events.triggers,extraHeaders:r,directionVideo:o,directionAudio:c,degradationPreference:E,sendEncodings:N,onAddedTransceiver:y})});async endCall(){const{rtcSession:e}=this;if(e&&!e.isEnded())return e.terminateAsync({cause:Ce.CANCELED}).finally(()=>{this.reset()});this.reset()}answerToIncomingCall=async(e,{mediaStream:t,extraHeaders:s=[],iceServers:i,directionVideo:r,directionAudio:a,offerToReceiveAudio:o,offerToReceiveVideo:c,contentHint:l,degradationPreference:u,sendEncodings:T,onAddedTransceiver:E})=>new Promise((N,y)=>{try{this.rtcSession=e,this.subscribeToSessionEvents(e),this.handleCall().then(N).catch(v=>{y(v)}),e.answer({pcConfig:{iceServers:i},rtcOfferConstraints:{offerToReceiveAudio:o,offerToReceiveVideo:c},mediaStream:x(t,{directionVideo:r,directionAudio:a,contentHint:l}),extraHeaders:s,directionVideo:r,directionAudio:a,degradationPreference:u,sendEncodings:T,onAddedTransceiver:E})}catch(v){y(v)}});async replaceMediaStream(e,t){if(!this.rtcSession)throw new Error("No rtcSession established");const{contentHint:s}=t??{},i=x(e,{contentHint:s});if(i===void 0)throw new Error("No preparedMediaStream");return this.rtcSession.replaceMediaStream(i,t)}async restartIce(e){if(!this.rtcSession)throw new Error("No rtcSession established");return this.rtcSession.restartIce(e)}setMinBitrateForSenders(e="all"){this.bitrateStateManager.setMinBitrateForSenders(this.connection,e).catch(t=>{Ne("MCUSession.setMinBitrateForSenders",t)})}restoreBitrateForSenders(e="all"){this.bitrateStateManager.restoreBitrateForSenders(this.connection,e).catch(t=>{Ne("MCUSession.restoreBitrateForSenders",t)})}handleCall=async()=>new Promise((e,t)=>{const s=()=>{this.events.on(S.PEER_CONNECTION,l),this.events.on(S.CONFIRMED,u)},i=()=>{this.events.off(S.PEER_CONNECTION,l),this.events.off(S.CONFIRMED,u)},r=()=>{this.events.on(S.FAILED,o),this.events.on(S.ENDED,o)},a=()=>{this.events.off(S.FAILED,o),this.events.off(S.ENDED,o)},o=T=>{i(),a(),t(T)};let c;const l=({peerconnection:T})=>{c=T;const E=N=>{this.events.trigger(S.PEER_CONNECTION_ONTRACK,N)};T.addEventListener("track",E),this.disposers.add(()=>{T.removeEventListener("track",E)})},u=()=>{c!==void 0&&this.events.trigger(S.PEER_CONNECTION_CONFIRMED,c),i(),a(),e(c)};s(),r()});subscribeToSessionEvents(e){this.events.eachTriggers((t,s)=>{const i=Ve.find(r=>r===s);i&&(e.on(i,t),this.disposers.add(()=>{e.off(i,t)}))})}unsubscribeFromSessionEvents(){this.disposers.forEach(e=>{e()}),this.disposers.clear()}handleEnded=e=>{const{originator:t}=e;t==="remote"&&this.events.trigger(S.ENDED_FROM_SERVER,e),this.reset()};reset=()=>{delete this.rtcSession,this.unsubscribeFromSessionEvents(),this.bitrateStateManager.clearAll(),this.onReset()}}const Ae=n=>n==="auto"?"high":n,on=10,cn=500,dn=5e3;class hn{cancelableSendOfferWithRepeatedCalls;currentRenegotiation;config;tools;connection;lastCallParams;constructor(e,t){const s=e.quality??"auto";this.config={...e,quality:s,effectiveQuality:Ae(s)},this.tools=t,this.connection=new RTCPeerConnection(e.pcConfig),this.addTransceivers()}get settings(){return this.config}get peerConnection(){return this.connection}getQuality(){return this.config.quality}getEffectiveQuality(){return this.config.effectiveQuality}async setQuality(e){if(!this.lastCallParams)return!1;const t=this.config.effectiveQuality,s=this.config.quality,i=Ae(e);return e===s&&i===t?!1:(this.config.quality=e,this.config.effectiveQuality=i,i!==t&&await this.renegotiate(this.lastCallParams),!0)}async applyQuality(e){const t=await this.setQuality(e),s=this.getEffectiveQuality();return{applied:t,effectiveQuality:s}}close(){this.cancelSendOfferWithRepeatedCalls(),this.connection.close()}async call({conferenceNumber:e,token:t}){const s=this.waitForTracks();await this.renegotiate({conferenceNumber:e,token:t}),await s}async renegotiate({conferenceNumber:e,token:t}){this.lastCallParams={conferenceNumber:e,token:t},this.cancelSendOfferWithRepeatedCalls();const s=this.currentRenegotiation;s&&await s.catch(()=>{});const i=this.performRenegotiate({conferenceNumber:e,token:t});this.currentRenegotiation=i;try{return await i}finally{this.currentRenegotiation===i&&(this.currentRenegotiation=void 0)}}async performRenegotiate({conferenceNumber:e,token:t}){this.hasHaveLocalOfferSignalingState()&&await this.connection.setLocalDescription({type:"rollback"}),await this.waitForPeerConnectionReady();const s=await this.createOffer(),i=async()=>this.tools.sendOffer({conferenceNumber:e,token:t,quality:this.config.effectiveQuality,audioChannel:this.config.audioChannel},s),r=o=>!(o instanceof Error);this.cancelableSendOfferWithRepeatedCalls=te.repeatedCallsAsync({targetFunction:i,isComplete:r,callLimit:on,delay:cn,isRejectAsValid:!0,isCheckBeforeCall:!1});const a=await this.cancelableSendOfferWithRepeatedCalls.then(o=>o).finally(()=>{this.cancelableSendOfferWithRepeatedCalls=void 0});return await this.setRemoteDescription(a),await this.waitForPeerConnectionReady(),!0}async createOffer(){const e=await this.connection.createOffer();return await this.connection.setLocalDescription(e),e}async setRemoteDescription(e){return this.connection.setRemoteDescription(e)}hasStableSignalingState(){return this.connection.signalingState==="stable"}hasReadyConnectionState(){const e=this.connection.connectionState;return e==="connected"||e==="new"}hasTerminalConnectionState(){const e=this.connection.connectionState;return e==="failed"||e==="closed"}isStableAndReady(){return this.hasStableSignalingState()&&this.hasReadyConnectionState()}hasHaveLocalOfferSignalingState(){return this.connection.signalingState==="have-local-offer"}async waitForPeerConnectionReady(){if(this.isStableAndReady())return;const e=()=>{const s=this.connection.connectionState;return new Error(`Peer connection in terminal state: ${s}. Recovery is not possible.`)},t=()=>this.hasTerminalConnectionState()?"error":this.isStableAndReady()?"success":"loading";if(t()==="error")throw e();return new Promise((s,i)=>{let r,a=!1;const o=()=>{a||(a=!0,clearTimeout(r),this.connection.removeEventListener("signalingstatechange",l),this.connection.removeEventListener("connectionstatechange",l),s())},c=u=>{a||(a=!0,clearTimeout(r),this.connection.removeEventListener("signalingstatechange",l),this.connection.removeEventListener("connectionstatechange",l),i(u))};function l(){const u=t();if(u==="error"){c(e());return}u==="success"&&o()}r=setTimeout(()=>{c(new Error("Timed out waiting for stable signaling state and ready connection state"))},dn),this.connection.addEventListener("signalingstatechange",l),this.connection.addEventListener("connectionstatechange",l),l()})}async waitForTracks(){return new Promise(e=>{const t=new Set,s=i=>{const{track:r}=i;t.add(r.kind),t.has("audio")&&t.has("video")&&(this.connection.removeEventListener("track",s),e())};this.connection.addEventListener("track",s)})}addTransceivers(){this.addRecvOnlyTransceiver("audio"),this.addRecvOnlyTransceiver("video"),this.addRecvOnlyTransceiver("video"),this.addRecvOnlyTransceiver("video"),this.addRecvOnlyTransceiver("video")}addRecvOnlyTransceiver(e){const t={direction:"recvonly"};return this.connection.addTransceiver(e,t)}cancelSendOfferWithRepeatedCalls(){this.cancelableSendOfferWithRepeatedCalls?.cancel()}}const He=n=>n.getSettings(),ln=(n,e)=>{const t=He(n);let s=e;s??=n.label;let i=t?.msid;return i??=s,i??=n.id,i},un=(n,e)=>{const t=He(n);let s=e;return s??=t?.msid,s??=n.label,(s&&s.length>0?s:void 0)??n.id};class Ie{participantGroups=new Map;trackToGroup=new Map;trackDisposers=new Map;get mainStream(){const e=this.getStreams(),[t]=e;return t}reset(){this.participantGroups.clear(),this.trackToGroup.clear(),this.trackDisposers.forEach(e=>{e()}),this.trackDisposers.clear()}addTrack(e,{onRemoved:t,streamHint:s}={}){const i=un(e,s),r=ln(e,s);if(this.trackToGroup.has(e.id))return{isAddedTrack:!1,isAddedStream:!1};const a=this.getParticipantGroups(i),o=a.get(r),c=!o;let l=o;l||(l={participantId:i,groupId:r,stream:new MediaStream,trackIds:new Set},a.set(r,l)),l.stream.addTrack(e),l.trackIds.add(e.id),this.trackToGroup.set(e.id,{participantId:i,groupId:r});const u=()=>{this.disposeTrackListener(e.id);const T=this.removeTrack(e.id);T.isRemovedTrack&&t?.({participantId:i,trackId:e.id,isRemovedStream:T.isRemovedStream})};return e.addEventListener("ended",u),this.trackDisposers.set(e.id,()=>{e.removeEventListener("ended",u)}),{isAddedTrack:!0,isAddedStream:c,participantId:i}}removeTrack(e){this.disposeTrackListener(e);const t=this.trackToGroup.get(e);if(!t)return{isRemovedTrack:!1,isRemovedStream:!1};const{participantId:s,groupId:i}=t,r=this.participantGroups.get(s),a=r?.get(i);if(!a)return this.trackToGroup.delete(e),{isRemovedTrack:!1,isRemovedStream:!1};const o=a.stream.getTracks().find(l=>l.id===e);o&&a.stream.removeTrack(o),a.trackIds.delete(e),this.trackToGroup.delete(e);const c=a.trackIds.size===0;return c&&(r?.delete(i),r?.size===0&&this.participantGroups.delete(s)),{isRemovedTrack:!0,isRemovedStream:c}}removeStaleTracks(e,t){const s=this.participantGroups.get(e);if(!s)return!1;let i=!1;return[...s.values()].forEach(a=>{[...a.trackIds].filter(c=>!t.includes(c)).forEach(c=>{const l=this.removeTrack(c);i||=l.isRemovedTrack})}),i}getStreams(e){if(e!==void 0){const t=this.participantGroups.get(e);return t?[...t.values()].map(s=>s.stream):[]}return[...this.participantGroups.values()].flatMap(t=>[...t.values()]).map(t=>t.stream)}disposeTrackListener(e){const t=this.trackDisposers.get(e);t&&(t(),this.trackDisposers.delete(e))}getParticipantGroups(e){const t=this.participantGroups.get(e);if(t)return t;const s=new Map;return this.participantGroups.set(e,s),s}}const re={type:"participant"},gn={type:"spectator_synthetic"},Tn=n=>({type:"spectator",recvParams:n});class p{role=re;onRoleChanged;constructor(e){this.onRoleChanged=e}static hasParticipant(e){return e.type==="participant"}static hasSpectatorSynthetic(e){return e.type==="spectator_synthetic"}static hasSpectator(e){return e.type==="spectator"}static isExitingSpectatorRole(e,t){return p.hasSpectator(e)&&!p.hasSpectator(t)}static isEnteringSpectatorRole(e,t){return p.hasSpectator(t)}static isExitingAnySpectatorRole(e,t){const s=p.hasSpectator(e)||p.hasSpectatorSynthetic(e),i=p.hasSpectator(t)||p.hasSpectatorSynthetic(t);return s&&!i}static isEnteringAnySpectatorRole(e,t){const s=p.hasSpectator(e)||p.hasSpectatorSynthetic(e),i=p.hasSpectator(t)||p.hasSpectatorSynthetic(t);return!s&&i}getRole(){return this.role}setCallRoleParticipant(){this.changeRole(re)}setCallRoleSpectatorSynthetic(){this.changeRole(gn)}setCallRoleSpectator(e){this.changeRole(Tn(e))}changeRole(e){const t=this.role;if(t.type!==e.type){this.setRole(e);return}p.hasSpectator(e)&&p.hasSpectator(t)&&t.recvParams.audioId!==e.recvParams.audioId&&this.setRole(e)}reset(){this.role=re}hasParticipant(){return p.hasParticipant(this.role)}hasSpectatorSynthetic(){return p.hasSpectatorSynthetic(this.role)}hasSpectator(){return p.hasSpectator(this.role)}setRole(e){const t=this.role;this.role=e,this.onRoleChanged?.({previous:t,next:e})}}const Sn=(n,e)=>{if(!n||!e)return n===e;const t=n.mainStream?.id,s=e.mainStream?.id,i=n.contentedStream?.id,r=e.contentedStream?.id;return t===s&&i===r};class En{lastEmittedStreams;hasChanged(e){return!Sn(this.lastEmittedStreams,e)}updateLastEmittedStreams(e){this.lastEmittedStreams=e}getLastEmittedStreams(){return this.lastEmittedStreams}reset(){this.lastEmittedStreams=void 0}}const Cn="default",mn="dual",pn="content_",Rn=n=>`${pn}${n.toLowerCase()}`,Nn=n=>[...n.getTracks()].some(e=>e.label.includes(mn));class An{mainRemoteStreamsManager;recvRemoteStreamsManager;constructor(e,t){this.mainRemoteStreamsManager=e,this.recvRemoteStreamsManager=t}getActiveStreamsManagerTools({isSpectator:e,stateInfo:t}){return e?this.getRecvRemoteStreamsManagerTools({stateInfo:t}):this.getMainRemoteStreamsManagerTools({stateInfo:t})}getMainRemoteStreamsManagerTools({stateInfo:e}){const t=this.mainRemoteStreamsManager;return{manager:t,getRemoteStreams:()=>{const i=t.getStreams(),r=i.find(o=>!Nn(o)),a=e.isAvailable?i.find(o=>o!==r):void 0;return{mainStream:r,contentedStream:a}}}}getRecvRemoteStreamsManagerTools({stateInfo:e}){const t=this.recvRemoteStreamsManager;return{manager:t,getRemoteStreams:()=>{const r=t.getStreams(Cn)[0],a=this.getRecvRemoteContentedStream({stateInfo:e});return{mainStream:r,contentedStream:a}}}}getRecvRemoteContentedStream({stateInfo:e}){if(!e.isAvailable||e.codec===void 0)return;const t=Rn(e.codec);return this.recvRemoteStreamsManager.getStreams(t)[0]}}const ve=n=>n.streams[0]?.id;function In(n){const{inRoomContext:e}=n;if(e===void 0)throw new Error("[CallManager] Invariant: inRoomContext expected when deferred runner executes (state IN_ROOM)");return e.token}class vn{events;stateMachine;isPendingCall=!1;isPendingAnswer=!1;mainRemoteStreamsManager=new Ie;recvRemoteStreamsManager=new Ie;streamsManagerProvider;contentedStreamManager;roleManager=new p(e=>{this.onRoleChanged(e)});mcuSession;recvSession;disposeRecvSessionTrackListener;deferredStartRecvSessionRunner;streamsChangeTracker=new En;constructor(e){this.contentedStreamManager=e,this.events=Zt(),this.mcuSession=new an(this.events,{onReset:this.reset}),this.stateMachine=new Xt(this.events),this.streamsManagerProvider=new An(this.mainRemoteStreamsManager,this.recvRemoteStreamsManager),this.deferredStartRecvSessionRunner=new Be({subscribe:t=>this.stateMachine.onStateChange(t),isReady:t=>t===Z.IN_ROOM,isCancelled:t=>t===Z.IDLE,onExecute:t=>{const s=In(this.stateMachine);this.startRecvSession(t.audioId,{sendOffer:t.sendOffer,token:s})}}),this.subscribeCallStatusChange(),this.subscribeMcuRemoteTrackEvents(),this.subscribeContentedStreamEvents()}get requested(){return this.isPendingCall||this.isPendingAnswer}get connection(){return this.mcuSession.connection}get isCallActive(){return this.mcuSession.isCallActive}get number(){return this.stateMachine.number}get isCallInitiator(){return this.stateMachine.isCallInitiator}get isDirectP2PRoom(){return this.stateMachine.isDirectP2PRoom}get isDisconnecting(){return this.stateMachine.isDisconnecting}getStreamsManagerProvider(){return this.streamsManagerProvider}getContentedStreamManager(){return this.contentedStreamManager}getEstablishedRTCSession=()=>this.mcuSession.getEstablishedRTCSession();on(e,t){return this.events.on(e,t)}onRace(e,t){return this.events.onRace(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}subscribeToApiEvents(e){this.stateMachine.subscribeToApiEvents(e.events)}startCall=async(e,t,s)=>(this.isPendingCall=!0,this.events.emit(S.START_CALL,{number:s.number,answer:!1}),this.mcuSession.startCall(e,t,s).finally(()=>{this.isPendingCall=!1}));async endCall(){return this.events.emit(S.END_CALL),this.mcuSession.endCall()}async renegotiate(){return this.roleManager.hasSpectator()?this.renegotiateRecvSession():this.renegotiateMcuSession()}answerToIncomingCall=async(e,t)=>{this.isPendingAnswer=!0;const s=e();return this.events.emit(S.START_CALL,{answer:!0,number:s.remote_identity.uri.user}),this.mcuSession.answerToIncomingCall(s,t).finally(()=>{this.isPendingAnswer=!1})};getMainRemoteStream(){const{mainStream:e}=this.getRemoteStreams();return e}getRemoteStreams(){const{getRemoteStreams:e}=this.getActiveStreamsManagerTools();return e()}getToken(){return this.stateMachine.token}getRecvQuality(){const{recvSession:e}=this;if(e===void 0)return;const t=e.getEffectiveQuality();return{quality:e.getQuality(),effectiveQuality:t}}getActivePeerConnection=()=>this.roleManager.hasSpectator()?this.recvSession?.peerConnection:this.mcuSession.connection;setCallRoleParticipant(){this.roleManager.setCallRoleParticipant()}setCallRoleSpectatorSynthetic(){this.roleManager.setCallRoleSpectatorSynthetic()}setCallRoleSpectator(e){this.roleManager.setCallRoleSpectator(e)}async replaceMediaStream(e,t){return this.mcuSession.replaceMediaStream(e,t)}async restartIce(e){return this.mcuSession.restartIce(e)}async setRecvQuality(e){const{recvSession:t}=this;if(!this.roleManager.hasSpectator()||!t)return!1;const s=t.getQuality(),i=await t.applyQuality(e);return i.applied&&this.events.trigger(S.RECV_QUALITY_CHANGED,{previousQuality:s,quality:e,effectiveQuality:i.effectiveQuality}),i.applied}async failed(e,t){this.emitFailedCall(e,t),await this.endCall()}emitFailedCall(e,t){this.events.trigger(S.FAILED,{message:e,cause:t,originator:"local"})}reset=()=>{this.mainRemoteStreamsManager.reset(),this.roleManager.reset(),this.recvRemoteStreamsManager.reset(),this.stopRecvSession(),this.deferredStartRecvSessionRunner.cancel(),this.streamsChangeTracker.reset()};subscribeCallStatusChange(){const{ACCEPTED:e,CONFIRMED:t,ENDED:s,FAILED:i}=S,r=this.createCallStatusChangeListener();this.onRace([e,t,s,i],r)}createCallStatusChangeListener(){let e=this.isCallActive;return()=>{const t=this.isCallActive;t!==e&&this.events.trigger(S.CALL_STATUS_CHANGED,{isCallActive:t}),e=t}}subscribeMcuRemoteTrackEvents(){this.on(S.PEER_CONNECTION_ONTRACK,e=>{this.addRemoteTrack(this.mainRemoteStreamsManager,e.track,ve(e))})}addRemoteTrack(e,t,s){const i=e.addTrack(t,{streamHint:s,onRemoved:r=>{this.handleChangedRemoteTracks(e,"removed",{isRemovedStream:r.isRemovedStream,isAddedStream:!1,trackId:r.trackId,participantId:r.participantId})}});i.isAddedTrack&&this.handleChangedRemoteTracks(e,"added",{isRemovedStream:!1,isAddedStream:i.isAddedStream,trackId:t.id,participantId:i.participantId})}handleChangedRemoteTracks(e,t,{trackId:s,participantId:i,isRemovedStream:r,isAddedStream:a}){const o=this.getActiveStreamsManagerTools();if(e!==o.manager)return;const c=o.getRemoteStreams();this.emitEventChangedRemoteTracks(c,t,{trackId:s,participantId:i}),(a||r)&&this.emitEventChangedRemoteStreams(c)}emitEventChangedRemoteTracks(e,t,{trackId:s,participantId:i}){this.events.trigger(S.REMOTE_TRACKS_CHANGED,{streams:e,changeType:t,trackId:s,participantId:i})}emitEventChangedRemoteStreamsConnected=()=>{this.emitEventChangedRemoteStreams(this.getRemoteStreams())};emitEventChangedRemoteStreams(e){this.streamsChangeTracker.hasChanged(e)&&(this.streamsChangeTracker.updateLastEmittedStreams(e),this.events.trigger(S.REMOTE_STREAMS_CHANGED,{streams:e}))}getActiveStreamsManagerTools(){return this.streamsManagerProvider.getActiveStreamsManagerTools({isSpectator:this.roleManager.hasSpectator(),stateInfo:this.contentedStreamManager.getStateInfo()})}attachRecvSessionTracks(e){const{peerConnection:t}=e,s=i=>{this.addRemoteTrack(this.recvRemoteStreamsManager,i.track,ve(i))};t.addEventListener("track",s),this.disposeRecvSessionTrackListener=()=>{t.removeEventListener("track",s)}}startRecvSession(e,{sendOffer:t,token:s}){const i=this.stateMachine.number;if(i===void 0)return;this.stopRecvSession();const r={audioChannel:e},a=new hn(r,{sendOffer:t});this.recvSession=a,this.recvRemoteStreamsManager.reset(),this.attachRecvSessionTracks(a),a.call({conferenceNumber:i,token:s}).then(()=>{this.events.emit("recv-session-started")}).catch(()=>{this.stopRecvSession()})}stopRecvSession(){this.recvSession?.close(),this.recvSession=void 0,this.disposeRecvSessionTrackListener?.(),this.disposeRecvSessionTrackListener=void 0,this.recvRemoteStreamsManager.reset(),this.events.emit("recv-session-ended")}onRoleChanged=({previous:e,next:t})=>{if(p.isExitingSpectatorRole(e,t)&&(this.stopRecvSession(),this.deferredStartRecvSessionRunner.cancel(),this.emitEventChangedRemoteStreamsConnected()),p.isEnteringSpectatorRole(e,t)){const s=t.recvParams,{token:i}=this.stateMachine;i===void 0?this.deferredStartRecvSessionRunner.set({audioId:s.audioId,sendOffer:s.sendOffer}):this.startRecvSession(s.audioId,{token:i,sendOffer:s.sendOffer})}p.isExitingAnySpectatorRole(e,t)&&this.mcuSession.restoreBitrateForSenders(),p.isEnteringAnySpectatorRole(e,t)&&this.mcuSession.setMinBitrateForSenders()};subscribeContentedStreamEvents(){this.contentedStreamManager.on("available",this.emitEventChangedRemoteStreamsConnected),this.contentedStreamManager.on("not-available",this.emitEventChangedRemoteStreamsConnected)}async renegotiateRecvSession(){const e=this.stateMachine.number,{token:t}=this.stateMachine;return e===void 0||t===void 0||this.recvSession===void 0?!1:this.recvSession.renegotiate({conferenceNumber:e,token:t})}async renegotiateMcuSession(){return this.mcuSession.renegotiate()}}var w=(n=>(n.START_PRESENTATION="presentation:start",n.STARTED_PRESENTATION="presentation:started",n.END_PRESENTATION="presentation:end",n.ENDED_PRESENTATION="presentation:ended",n.FAILED_PRESENTATION="presentation:failed",n))(w||{});const We=["presentation:start","presentation:started","presentation:end","presentation:ended","presentation:failed"],fn=()=>new M.TypedEvents(We);var Qe=(n=>(n.IDLE="presentation:idle",n.STARTING="presentation:starting",n.ACTIVE="presentation:active",n.STOPPING="presentation:stopping",n.FAILED="presentation:failed",n))(Qe||{});const Mn=I.setup({types:{context:{},events:{}},actions:{logTransition:(n,e)=>{d(`State transition: ${e.from} -> ${e.to} (${e.event})`)},logStateChange:(n,e)=>{d("PresentationStateMachine state changed",e.state)},setError:I.assign(({event:n})=>"error"in n&&n.error!==void 0?{lastError:n.error instanceof Error?n.error:new Error(JSON.stringify(n.error))}:{lastError:void 0}),clearError:I.assign({lastError:void 0})}}).createMachine({id:"presentation",initial:"presentation:idle",context:{},states:{"presentation:idle":{entry:{type:"logStateChange",params:{state:"presentation:idle"}},on:{"SCREEN.STARTING":{target:"presentation:starting",actions:["clearError",{type:"logTransition",params:{from:"presentation:idle",to:"presentation:starting",event:"SCREEN.STARTING"}}]}}},"presentation:starting":{entry:{type:"logStateChange",params:{state:"presentation:starting"}},on:{"SCREEN.STARTED":{target:"presentation:active",actions:{type:"logTransition",params:{from:"presentation:starting",to:"presentation:active",event:"SCREEN.STARTED"}}},"SCREEN.FAILED":{target:"presentation:failed",actions:["setError",{type:"logTransition",params:{from:"presentation:starting",to:"presentation:failed",event:"SCREEN.FAILED"}}]},"SCREEN.ENDED":{target:"presentation:idle",actions:["clearError",{type:"logTransition",params:{from:"presentation:starting",to:"presentation:idle",event:"SCREEN.ENDED"}}]},"CALL.ENDED":{target:"presentation:idle",actions:["clearError",{type:"logTransition",params:{from:"presentation:starting",to:"presentation:idle",event:"CALL.ENDED"}}]},"CALL.FAILED":{target:"presentation:failed",actions:["setError",{type:"logTransition",params:{from:"presentation:starting",to:"presentation:failed",event:"CALL.FAILED"}}]}}},"presentation:active":{entry:{type:"logStateChange",params:{state:"presentation:active"}},on:{"SCREEN.ENDING":{target:"presentation:stopping",actions:{type:"logTransition",params:{from:"presentation:active",to:"presentation:stopping",event:"SCREEN.ENDING"}}},"SCREEN.ENDED":{target:"presentation:idle",actions:["clearError",{type:"logTransition",params:{from:"presentation:active",to:"presentation:idle",event:"SCREEN.ENDED"}}]},"SCREEN.FAILED":{target:"presentation:failed",actions:["setError",{type:"logTransition",params:{from:"presentation:active",to:"presentation:failed",event:"SCREEN.FAILED"}}]},"CALL.ENDED":{target:"presentation:idle",actions:["clearError",{type:"logTransition",params:{from:"presentation:active",to:"presentation:idle",event:"CALL.ENDED"}}]},"CALL.FAILED":{target:"presentation:failed",actions:["setError",{type:"logTransition",params:{from:"presentation:active",to:"presentation:failed",event:"CALL.FAILED"}}]}}},"presentation:stopping":{entry:{type:"logStateChange",params:{state:"presentation:stopping"}},on:{"SCREEN.ENDED":{target:"presentation:idle",actions:["clearError",{type:"logTransition",params:{from:"presentation:stopping",to:"presentation:idle",event:"SCREEN.ENDED"}}]},"SCREEN.FAILED":{target:"presentation:failed",actions:["setError",{type:"logTransition",params:{from:"presentation:stopping",to:"presentation:failed",event:"SCREEN.FAILED"}}]},"CALL.ENDED":{target:"presentation:idle",actions:["clearError",{type:"logTransition",params:{from:"presentation:stopping",to:"presentation:idle",event:"CALL.ENDED"}}]},"CALL.FAILED":{target:"presentation:failed",actions:["setError",{type:"logTransition",params:{from:"presentation:stopping",to:"presentation:failed",event:"CALL.FAILED"}}]}}},"presentation:failed":{entry:{type:"logStateChange",params:{state:"presentation:failed"}},on:{"SCREEN.STARTING":{target:"presentation:starting",actions:["clearError",{type:"logTransition",params:{from:"presentation:failed",to:"presentation:starting",event:"SCREEN.STARTING"}}]},"SCREEN.ENDED":{target:"presentation:idle",actions:["clearError",{type:"logTransition",params:{from:"presentation:failed",to:"presentation:idle",event:"SCREEN.ENDED"}}]},"PRESENTATION.RESET":{target:"presentation:idle",actions:["clearError",{type:"logTransition",params:{from:"presentation:failed",to:"presentation:idle",event:"PRESENTATION.RESET"}}]}}}}});class _n extends W{constructor(e){super(Mn),this.subscribeCallEvents(e)}get isIdle(){return this.state==="presentation:idle"}get isStarting(){return this.state==="presentation:starting"}get isActive(){return this.state==="presentation:active"}get isStopping(){return this.state==="presentation:stopping"}get isFailed(){return this.state==="presentation:failed"}get isPending(){return this.isStarting||this.isStopping}get isActiveOrPending(){return this.isActive||this.isPending}get lastError(){return this.getSnapshot().context.lastError}reset(){this.send({type:"PRESENTATION.RESET"})}send(e){if(!this.actor.getSnapshot().can(e)){console.warn(`[PresentationStateMachine] Invalid transition: ${e.type} from ${this.state}. Event cannot be processed in current state.`);return}super.send(e)}subscribeCallEvents(e){this.addSubscription(e.on(S.START_PRESENTATION,()=>{this.send({type:"SCREEN.STARTING"})})),this.addSubscription(e.on(S.STARTED_PRESENTATION,()=>{this.send({type:"SCREEN.STARTED"})})),this.addSubscription(e.on(S.END_PRESENTATION,()=>{this.send({type:"SCREEN.ENDING"})})),this.addSubscription(e.on(S.ENDED_PRESENTATION,()=>{this.send({type:"SCREEN.ENDED"})})),this.addSubscription(e.on(S.FAILED_PRESENTATION,t=>{this.send({type:"SCREEN.FAILED",error:t})})),this.addSubscription(e.on(S.ENDED,()=>{this.send({type:"CALL.ENDED"})})),this.addSubscription(e.on(S.FAILED,t=>{this.send({type:"CALL.FAILED",error:t})}))}}const bn=1,On=n=>te.hasCanceledError(n);class Pn{events;stateMachine;promisePendingStartPresentation;promisePendingStopPresentation;streamPresentationCurrent;maxBitrate;cancelableSendPresentationWithRepeatedCalls;callManager;constructor({callManager:e,maxBitrate:t}){this.callManager=e,this.maxBitrate=t,this.events=fn(),this.stateMachine=new _n(this.callManager.events),this.subscribe()}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}get isPresentationInProcess(){return!!this.streamPresentationCurrent||this.isPendingPresentation}async startPresentation(e,t,{isNeedReinvite:s,contentHint:i,sendEncodings:r,onAddedTransceiver:a}={},o){const c=this.getRtcSessionProtected();if(this.streamPresentationCurrent)throw new Error("Presentation is already started");return this.sendPresentationWithDuplicatedCalls(e,{rtcSession:c,stream:t,presentationOptions:{isNeedReinvite:s,contentHint:i,sendEncodings:r,onAddedTransceiver:a},options:o})}async stopPresentation(e){this.cancelSendPresentationWithRepeatedCalls();const t=this.streamPresentationCurrent;let s=this.promisePendingStartPresentation??Promise.resolve(void 0);this.promisePendingStartPresentation&&await this.promisePendingStartPresentation.catch(()=>{});const i=this.callManager.getEstablishedRTCSession();return i&&t?s=e().then(async()=>i.stopPresentation(t)).catch(r=>{const a=r instanceof Error?r:new Error(String(r));throw this.events.trigger(w.FAILED_PRESENTATION,a),r}):t&&this.events.trigger(w.ENDED_PRESENTATION,t),this.promisePendingStopPresentation=s,s.finally(()=>{this.resetPresentation()})}async updatePresentation(e,t,{contentHint:s,sendEncodings:i,onAddedTransceiver:r}={}){const a=this.getRtcSessionProtected();if(!this.streamPresentationCurrent)throw new Error("Presentation has not started yet");return this.promisePendingStartPresentation&&await this.promisePendingStartPresentation,this.sendPresentation(e,a,t,{contentHint:s,isNeedReinvite:!1,sendEncodings:i,onAddedTransceiver:r}).then(async o=>(await this.setMaxBitrate(),o))}cancelSendPresentationWithRepeatedCalls(){this.cancelableSendPresentationWithRepeatedCalls?.stopRepeatedCalls()}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}subscribe(){this.callManager.on("presentation:start",e=>{this.events.trigger(w.START_PRESENTATION,e)}),this.callManager.on("presentation:started",e=>{this.events.trigger(w.STARTED_PRESENTATION,e)}),this.callManager.on("presentation:end",e=>{this.events.trigger(w.END_PRESENTATION,e)}),this.callManager.on("presentation:ended",e=>{this.events.trigger(w.ENDED_PRESENTATION,e)}),this.callManager.on("presentation:failed",e=>{this.events.trigger(w.FAILED_PRESENTATION,e)}),this.callManager.on("failed",this.handleEnded),this.callManager.on("ended",this.handleEnded)}async sendPresentationWithDuplicatedCalls(e,{rtcSession:t,stream:s,presentationOptions:i,options:r={callLimit:bn}}){const a=async()=>this.sendPresentation(e,t,s,i),o=()=>!!this.streamPresentationCurrent;return this.cancelableSendPresentationWithRepeatedCalls=te.repeatedCallsAsync({targetFunction:a,isComplete:o,isRejectAsValid:!0,...r}),this.cancelableSendPresentationWithRepeatedCalls.then(c=>c)}async sendPresentation(e,t,s,{isNeedReinvite:i=!0,contentHint:r="detail",degradationPreference:a,sendEncodings:o,onAddedTransceiver:c}){const l=x(s,{contentHint:r});if(l===void 0)throw new Error("No streamPresentationTarget");this.streamPresentationCurrent=l;const u=e().then(async()=>t.startPresentation(l,i,{degradationPreference:a,sendEncodings:o,onAddedTransceiver:c})).then(this.setMaxBitrate).then(()=>s).catch(T=>{this.removeStreamPresentationCurrent();const E=T instanceof Error?T:new Error(String(T));throw this.events.trigger(w.FAILED_PRESENTATION,E),T});return this.promisePendingStartPresentation=u,u.finally(()=>{this.promisePendingStartPresentation=void 0})}setMaxBitrate=async()=>{const{connection:e}=this.callManager,{streamPresentationCurrent:t}=this,{maxBitrate:s}=this;if(!e||!t||s===void 0)return;const i=e.getSenders();await xt(i,t,s)};getRtcSessionProtected=()=>{const e=this.callManager.getEstablishedRTCSession();if(!e)throw new Error("No rtcSession established");return e};handleEnded=()=>{this.reset()};reset(){this.cancelSendPresentationWithRepeatedCalls(),this.resetPresentation()}resetPresentation(){this.removeStreamPresentationCurrent(),this.promisePendingStartPresentation=void 0,this.promisePendingStopPresentation=void 0}removeStreamPresentationCurrent(){delete this.streamPresentationCurrent}}class Dn{data;getUa;constructor(e){this.getUa=e.getUa}isConfigured(){return this.getUa()!==void 0}get(){if(this.data!==void 0)return{...this.data}}set(e){if(e===void 0){this.data=void 0;return}this.data={...e}}update(e,t){if(this.data===void 0)throw new Error("data is not exist");this.data[e]=t}clear(){this.data=void 0}isRegister(){return this.data?.register===!0}getSipServerIp(){return this.data?.sipServerIp}getSipServerUrl(){return this.data?.sipServerUrl}getDisplayName(){return this.data?.displayName}getUser(){return this.data?.user}getPassword(){return this.data?.password}isRegisterEnabled(){return this.data?.register===!0}}var C=(n=>(n.CONNECTING="connecting",n.CONNECTED="connected",n.DISCONNECTED="disconnected",n.DISCONNECTING="disconnecting",n.NEW_RTC_SESSION="newRTCSession",n.REGISTERED="registered",n.UNREGISTERED="unregistered",n.REGISTRATION_FAILED="registrationFailed",n.NEW_MESSAGE="newMessage",n.SIP_EVENT="sipEvent",n.CONNECT_STARTED="connect-started",n.CONNECT_SUCCEEDED="connect-succeeded",n.CONNECT_FAILED="connect-failed",n.CONNECT_PARAMETERS_RESOLVE_SUCCESS="connect-parameters-resolve-success",n.CONNECT_PARAMETERS_RESOLVE_FAILED="connect-parameters-resolve-failed",n.CONNECTED_WITH_CONFIGURATION="connected-with-configuration",n))(C||{});const Ye=["connecting","connected","disconnected","newRTCSession","registered","unregistered","registrationFailed","newMessage","sipEvent"],yn=["disconnecting","connect-started","connect-succeeded","connect-failed","connect-parameters-resolve-success","connect-parameters-resolve-failed","connected-with-configuration"],ze=[...Ye,...yn],Ln=()=>new M.TypedEvents(ze);function wn(n){return e=>`sip:${e}@${n}`}const Un=(n,e)=>()=>Math.floor(Math.random()*(e-n))+n,Je=n=>n.trim().replaceAll(" ","_"),kn=Un(1e5,99999999),Fn=3;class Bn{cancelableConnectWithRepeatedCalls;events;uaFactory;stateMachine;registrationManager;getUa;setUa;getConnectionConfiguration;setConnectionConfiguration;updateConnectionConfiguration;setGetUri;setSocket;constructor(e){this.events=e.events,this.uaFactory=e.uaFactory,this.stateMachine=e.stateMachine,this.registrationManager=e.registrationManager,this.getUa=e.getUa,this.setUa=e.setUa,this.getConnectionConfiguration=e.getConnectionConfiguration,this.setConnectionConfiguration=e.setConnectionConfiguration,this.updateConnectionConfiguration=e.updateConnectionConfiguration,this.setGetUri=e.setGetUri,this.setSocket=e.setSocket,this.proxyEvents()}connect=async(e,t)=>(this.cancelRequests(),this.connectWithDuplicatedCalls(e,t));set=async({displayName:e})=>new Promise((t,s)=>{const i=this.getUa();if(!i){s(new Error("this.ua is not initialized"));return}let r=!1;const a=this.getConnectionConfiguration();e!==void 0&&e!==a?.displayName&&(r=i.set("display_name",Je(e)),this.updateConnectionConfiguration("displayName",e));const o=r;o?t(o):s(new Error("nothing changed"))});disconnect=async()=>{this.events.trigger(C.DISCONNECTING,{});const e=new Promise(s=>{this.events.once(C.DISCONNECTED,()=>{s()})}),t=this.getUa();return t?t.stop():this.events.trigger(C.DISCONNECTED,{socket:{},error:!1}),e.finally(()=>{t?.removeAllListeners(),this.setUa(void 0),this.stateMachine.reset()})};cancelRequests(){this.cancelConnectWithRepeatedCalls()}connectWithDuplicatedCalls=async(e,{callLimit:t=Fn}={})=>{const s=async()=>this.connectInner(e),i=r=>{const c=this.getUa()?.isConnected()===!0&&this.hasEqualConnectionConfiguration(e),l=r!=null&&!Nt(r);return c||l};return this.stateMachine.startConnect(),this.cancelableConnectWithRepeatedCalls=te.repeatedCallsAsync({targetFunction:s,isComplete:i,callLimit:t,isRejectAsValid:!0,isCheckBeforeCall:!1}),this.cancelableConnectWithRepeatedCalls.then(r=>{if(typeof r=="object"&&r!==null&&"authorizationUser"in r)return r;throw r})};hasEqualConnectionConfiguration(e){const{configuration:t}=this.uaFactory.createConfiguration(e),i=this.getUa()?.configuration;return i?i.password===t.password&&i.register===t.register&&i.uri.toString()===t.uri&&i.display_name===t.display_name&&i.user_agent===t.user_agent&&i.sockets===t.sockets&&i.session_timers===t.session_timers&&i.register_expires===t.register_expires&&i.connection_recovery_min_interval===t.connection_recovery_min_interval&&i.connection_recovery_max_interval===t.connection_recovery_max_interval:!1}connectInner=async e=>this.initUa(e).then(async()=>this.start()).then(()=>{const t=this.getConnectionConfiguration();if(t===void 0)throw new Error("connectionConfiguration has not defined");return t});initUa=async({user:e,password:t,sipServerIp:s,sipServerUrl:i,remoteAddress:r,sessionTimers:a,registerExpires:o,connectionRecoveryMinInterval:c,connectionRecoveryMaxInterval:l,userAgent:u,displayName:T="",register:E=!1,extraHeaders:N=[]})=>{this.stateMachine.startInitUa(),this.getUa()&&await this.disconnect();const{ua:v,helpers:U}=this.uaFactory.createUAWithConfiguration({user:e,password:t,sipServerIp:s,sipServerUrl:i,displayName:T,register:E,sessionTimers:a,registerExpires:o,connectionRecoveryMinInterval:c,connectionRecoveryMaxInterval:l,userAgent:u,remoteAddress:r,extraHeaders:N},this.events),$=v.configuration.uri.user;return this.setConnectionConfiguration({sipServerIp:s,sipServerUrl:i,displayName:T,authorizationUser:$,register:E,user:e,password:t}),this.setUa(v),this.setGetUri(U.getUri),this.setSocket(U.socket),v};start=async()=>new Promise((e,t)=>{const s=this.getUa();if(!s){t(new Error("this.ua is not initialized"));return}let i;i=((c,l)=>{if(this.getConnectionConfiguration()?.register===!0)return this.registrationManager.subscribeToStartEvents(c,l);const T=C.CONNECTED,E=[C.DISCONNECTED];return this.events.on(T,c),E.forEach(N=>{this.events.on(N,l)}),()=>{this.events.off(T,c),E.forEach(N=>{this.events.off(N,l)})}})(()=>{i?.(),e(s)},c=>{i?.(),t(c)}),s.start()});cancelConnectWithRepeatedCalls(){this.cancelableConnectWithRepeatedCalls?.cancel()}proxyEvents(){this.events.on(C.CONNECTED,()=>{const e=this.getConnectionConfiguration();e!==void 0&&this.events.trigger(C.CONNECTED_WITH_CONFIGURATION,e)})}}var je=(n=>(n.IDLE="connection:idle",n.PREPARING="connection:preparing",n.CONNECTING="connection:connecting",n.CONNECTED="connection:connected",n.REGISTERED="connection:registered",n.ESTABLISHED="connection:established",n.DISCONNECTING="connection:disconnecting",n.DISCONNECTED="connection:disconnected",n))(je||{}),Xe=(n=>(n.START_CONNECT="START_CONNECT",n.START_INIT_UA="START_INIT_UA",n.START_DISCONNECT="START_DISCONNECT",n.UA_CONNECTED="UA_CONNECTED",n.UA_REGISTERED="UA_REGISTERED",n.UA_UNREGISTERED="UA_UNREGISTERED",n.UA_DISCONNECTED="UA_DISCONNECTED",n.RESET="RESET",n))(Xe||{});const $n=Object.values(Xe),Gn=I.setup({types:{context:{},events:{}},actions:{logTransition:(n,e)=>{d(`State transition: ${e.from} -> ${e.to} (${e.event})`)},logStateChange:(n,e)=>{d("ConnectionStateMachine state changed",e.state)}}}).createMachine({id:"connection",initial:"connection:idle",context:{},states:{"connection:idle":{entry:{type:"logStateChange",params:{state:"connection:idle"}},on:{START_CONNECT:{target:"connection:preparing",actions:{type:"logTransition",params:{from:"connection:idle",to:"connection:preparing",event:"START_CONNECT"}}}}},"connection:preparing":{entry:{type:"logStateChange",params:{state:"connection:preparing"}},on:{START_INIT_UA:{target:"connection:connecting",actions:{type:"logTransition",params:{from:"connection:preparing",to:"connection:connecting",event:"START_INIT_UA"}}},UA_DISCONNECTED:{target:"connection:disconnected",actions:{type:"logTransition",params:{from:"connection:preparing",to:"connection:disconnected",event:"UA_DISCONNECTED"}}}}},"connection:connecting":{entry:{type:"logStateChange",params:{state:"connection:connecting"}},on:{UA_CONNECTED:{target:"connection:connected",actions:{type:"logTransition",params:{from:"connection:connecting",to:"connection:connected",event:"UA_CONNECTED"}}},UA_REGISTERED:{target:"connection:registered",actions:{type:"logTransition",params:{from:"connection:connecting",to:"connection:registered",event:"UA_REGISTERED"}}},START_DISCONNECT:{target:"connection:disconnecting",actions:{type:"logTransition",params:{from:"connection:connecting",to:"connection:disconnecting",event:"START_DISCONNECT"}}},UA_DISCONNECTED:{target:"connection:disconnected",actions:{type:"logTransition",params:{from:"connection:connecting",to:"connection:disconnected",event:"UA_DISCONNECTED"}}}}},"connection:connected":{entry:{type:"logStateChange",params:{state:"connection:connected"}},always:{target:"connection:established",actions:{type:"logTransition",params:{from:"connection:connected",to:"connection:established",event:"always"}}},on:{UA_REGISTERED:{target:"connection:registered",actions:{type:"logTransition",params:{from:"connection:connected",to:"connection:registered",event:"UA_REGISTERED"}}},START_DISCONNECT:{target:"connection:disconnecting",actions:{type:"logTransition",params:{from:"connection:connected",to:"connection:disconnecting",event:"START_DISCONNECT"}}},UA_DISCONNECTED:{target:"connection:disconnected",actions:{type:"logTransition",params:{from:"connection:connected",to:"connection:disconnected",event:"UA_DISCONNECTED"}}}}},"connection:registered":{entry:{type:"logStateChange",params:{state:"connection:registered"}},always:{target:"connection:established",actions:{type:"logTransition",params:{from:"connection:registered",to:"connection:established",event:"always"}}},on:{UA_UNREGISTERED:{target:"connection:connected",actions:{type:"logTransition",params:{from:"connection:registered",to:"connection:connected",event:"UA_UNREGISTERED"}}},START_DISCONNECT:{target:"connection:disconnecting",actions:{type:"logTransition",params:{from:"connection:registered",to:"connection:disconnecting",event:"START_DISCONNECT"}}},UA_DISCONNECTED:{target:"connection:disconnected",actions:{type:"logTransition",params:{from:"connection:registered",to:"connection:disconnected",event:"UA_DISCONNECTED"}}}}},"connection:established":{entry:{type:"logStateChange",params:{state:"connection:established"}},on:{START_DISCONNECT:{target:"connection:disconnecting",actions:{type:"logTransition",params:{from:"connection:established",to:"connection:disconnecting",event:"START_DISCONNECT"}}},UA_DISCONNECTED:{target:"connection:disconnected",actions:{type:"logTransition",params:{from:"connection:established",to:"connection:disconnected",event:"UA_DISCONNECTED"}}},RESET:{target:"connection:idle",actions:{type:"logTransition",params:{from:"connection:established",to:"connection:idle",event:"RESET"}}}}},"connection:disconnecting":{entry:{type:"logStateChange",params:{state:"connection:disconnecting"}},on:{UA_DISCONNECTED:{target:"connection:disconnected",actions:{type:"logTransition",params:{from:"connection:disconnecting",to:"connection:disconnected",event:"UA_DISCONNECTED"}}}}},"connection:disconnected":{entry:{type:"logStateChange",params:{state:"connection:disconnected"}},on:{RESET:{target:"connection:idle",actions:{type:"logTransition",params:{from:"connection:disconnected",to:"connection:idle",event:"RESET"}}},START_CONNECT:{target:"connection:preparing",actions:{type:"logTransition",params:{from:"connection:disconnected",to:"connection:preparing",event:"START_CONNECT"}}}}}}});class qn extends W{events;unsubscribeFromEvents;constructor(e){super(Gn),this.events=e,this.subscribeToEvents()}get isIdle(){return this.hasState("connection:idle")}get isPreparing(){return this.hasState("connection:preparing")}get isConnecting(){return this.hasState("connection:connecting")}get isConnected(){return this.hasState("connection:connected")}get isRegistered(){return this.hasState("connection:registered")}get isEstablished(){return this.hasState("connection:established")}get isDisconnecting(){return this.hasState("connection:disconnecting")}get isDisconnected(){return this.hasState("connection:disconnected")}get isPending(){return this.isPreparing||this.isConnecting}get isPendingConnect(){return this.isPreparing}get isPendingInitUa(){return this.isConnecting}get isActiveConnection(){return this.isEstablished||this.isConnected||this.isRegistered}startConnect(){this.toStartConnect()}startInitUa(){this.toStartInitUa()}startDisconnect(){this.toStartDisconnect()}reset(){this.toIdle()}destroy(){this.unsubscribeFromEvents?.(),this.stop()}canTransition(e){return this.actor.getSnapshot().can({type:e})}getValidEvents(){return $n.filter(e=>this.canTransition(e))}hasState(e){return this.actor.getSnapshot().matches(e)}sendEvent(e){if(!this.actor.getSnapshot().can(e)){d(`Invalid transition: ${e.type} from ${this.state}. Event cannot be processed in current state.`);return}this.send(e)}toStartConnect=()=>{this.sendEvent({type:"START_CONNECT"})};toStartInitUa=()=>{this.sendEvent({type:"START_INIT_UA"})};toStartDisconnect=()=>{this.sendEvent({type:"START_DISCONNECT"})};toConnected=()=>{this.sendEvent({type:"UA_CONNECTED"})};toRegistered=()=>{this.sendEvent({type:"UA_REGISTERED"})};toUnregistered=()=>{this.sendEvent({type:"UA_UNREGISTERED"})};toDisconnected=()=>{this.sendEvent({type:"UA_DISCONNECTED"})};toIdle=()=>{this.sendEvent({type:"RESET"})};subscribeToEvents(){this.events.on("connected",this.toConnected),this.events.on("registered",this.toRegistered),this.events.on("unregistered",this.toUnregistered),this.events.on("disconnecting",this.toStartDisconnect),this.events.on("disconnected",this.toDisconnected),this.events.on("registrationFailed",this.toDisconnected),this.events.on("connect-failed",this.toDisconnected),this.unsubscribeFromEvents=()=>{this.events.off("connected",this.toConnected),this.events.off("registered",this.toRegistered),this.events.off("unregistered",this.toUnregistered),this.events.off("disconnecting",this.toStartDisconnect),this.events.off("disconnected",this.toDisconnected),this.events.off("registrationFailed",this.toDisconnected),this.events.off("connect-failed",this.toDisconnected)}}}class Vn{events;getUaProtected;constructor(e){this.events=e.events,this.getUaProtected=e.getUaProtected}async register(){const e=this.getUaProtected();return new Promise((t,s)=>{e.on(C.REGISTERED,t),e.on(C.REGISTRATION_FAILED,s),e.register()})}async unregister(){const e=this.getUaProtected();return new Promise(t=>{e.on(C.UNREGISTERED,t),e.unregister()})}async tryRegister(){try{await this.unregister()}catch(e){d("tryRegister",e)}return this.register()}subscribeToStartEvents(e,t){const s=C.REGISTERED,i=[C.REGISTRATION_FAILED,C.DISCONNECTED];return this.events.on(s,e),i.forEach(r=>{this.events.on(r,t)}),()=>{this.events.off(s,e),i.forEach(r=>{this.events.off(r,t)})}}}class xn{uaFactory;getUaProtected;constructor(e){this.uaFactory=e.uaFactory,this.getUaProtected=e.getUaProtected}async sendOptions(e,t,s){const i=this.getUaProtected();return new Promise((r,a)=>{try{i.sendOptions(e,t,{extraHeaders:s,eventHandlers:{succeeded:()=>{r()},failed:a}})}catch(o){a(o)}})}async ping(e,t){const i=this.getUaProtected().configuration.uri;return this.sendOptions(i,e,t)}async checkTelephony({userAgent:e,displayName:t,sipServerIp:s,sipServerUrl:i,remoteAddress:r,extraHeaders:a}){return new Promise((o,c)=>{const{configuration:l}=this.uaFactory.createConfiguration({sipServerUrl:i,displayName:t,userAgent:e,sipServerIp:s}),u=this.uaFactory.createUA({...l,remoteAddress:r,extraHeaders:a}),T=()=>{const N=new Error("Telephony is not available");c(N)};u.once(C.DISCONNECTED,T);const E=()=>{u.removeAllListeners(),u.once(C.DISCONNECTED,()=>{o()}),u.stop()};u.once(C.CONNECTED,E),u.start()})}}const Hn=n=>{const e=[];return n!==void 0&&n!==""&&e.push(`X-Vinteo-Remote: ${n}`),e};class F{JsSIP;constructor(e){this.JsSIP=e}static isRegisteredUA(e){return!!e&&e.isRegistered()}static validateParametersConnection({register:e,password:t,user:s,sipServerIp:i,sipServerUrl:r}){if(!i)throw new Error("sipServerIp is required");if(!r)throw new Error("sipServerUrl is required");if(e&&(t===void 0||t===""))throw new Error("password is required for authorized connection");if(e&&(s===void 0||s===""))throw new Error("user is required for authorized connection")}static resolveAuthorizationUser(e,t){return e&&t!==void 0&&t.trim()!==""?t.trim():`${kn()}`}static buildExtraHeaders(e,t){const s=e!==void 0&&e!==""?Hn(e):[];return t===void 0?s:[...s,...t]}createConfiguration({user:e,password:t,sipServerUrl:s,displayName:i="",sipServerIp:r,register:a=!1,sessionTimers:o=!1,registerExpires:c=300,connectionRecoveryMinInterval:l=2,connectionRecoveryMaxInterval:u=6,userAgent:T}){F.validateParametersConnection({register:a,password:t,user:e,sipServerIp:r,sipServerUrl:s});const E=F.resolveAuthorizationUser(a,e),N=wn(r),y=N(E),v=new this.JsSIP.WebSocketInterface(`wss://${s}/webrtc/wss/`);return{configuration:{password:t,register:a,uri:y,display_name:Je(i),user_agent:T,sdpSemantics:"unified-plan",sockets:[v],session_timers:o,register_expires:c,connection_recovery_min_interval:l,connection_recovery_max_interval:u},helpers:{socket:v,getUri:N}}}createUA({remoteAddress:e,extraHeaders:t,...s}){const i=new this.JsSIP.UA(s),r=F.buildExtraHeaders(e,t);return r.length>0&&i.registrator().setExtraHeaders(r),i}createUAWithConfiguration(e,t){const{configuration:s,helpers:i}=this.createConfiguration(e),r=this.createUA({...s,remoteAddress:e.remoteAddress,extraHeaders:e.extraHeaders});return t.eachTriggers((a,o)=>{const c=Ye.find(l=>l===o);c&&r.on(c,a)}),{ua:r,helpers:i}}}const Ke="Not ready for connection",Ze=n=>n instanceof Error&&n.message===Ke,Wn=()=>new Error(Ke),Qn=async n=>typeof n=="function"?n():n;class Yn{events;stateMachine;ua;socket;uaFactory;registrationManager;connectionFlow;sipOperations;configurationManager;constructor({JsSIP:e}){this.events=Ln(),this.uaFactory=new F(e),this.registrationManager=new Vn({events:this.events,getUaProtected:this.getUaProtected}),this.stateMachine=new qn(this.events),this.configurationManager=new Dn({getUa:this.getUa}),this.sipOperations=new xn({uaFactory:this.uaFactory,getUaProtected:this.getUaProtected}),this.connectionFlow=new Bn({events:this.events,uaFactory:this.uaFactory,stateMachine:this.stateMachine,registrationManager:this.registrationManager,getUa:this.getUa,getConnectionConfiguration:this.getConnectionConfiguration,setConnectionConfiguration:t=>{this.configurationManager.set(t)},updateConnectionConfiguration:(t,s)=>{this.configurationManager.update(t,s)},setUa:t=>{this.ua=t},setGetUri:t=>{this.getUri=t},setSocket:t=>{this.socket=t}})}get requested(){return this.stateMachine.isPending}get isPendingConnect(){return this.stateMachine.isPendingConnect}get isPendingInitUa(){return this.stateMachine.isPendingInitUa}get isIdle(){return this.stateMachine.isIdle}get isDisconnected(){return this.stateMachine.isDisconnected}get isDisconnecting(){return this.stateMachine.isDisconnecting}get connectionState(){return this.stateMachine.state}get isRegistered(){return F.isRegisteredUA(this.ua)}get isRegisterConfig(){return this.configurationManager.isRegister()}connect=async(e,t)=>this.disconnect().catch(s=>{d("connect: disconnect error",s)}).then(async()=>this.connectWithProcessError(e,t));set=async({displayName:e})=>this.connectionFlow.set({displayName:e});disconnect=async()=>{if(this.isConfigured())return this.connectionFlow.disconnect()};async register(){return this.registrationManager.register()}async unregister(){return this.registrationManager.unregister()}tryRegister=async()=>this.registrationManager.tryRegister();sendOptions=async(e,t,s)=>this.sipOperations.sendOptions(e,t,s);ping=async(e,t)=>this.sipOperations.ping(e,t);checkTelephony=async e=>this.sipOperations.checkTelephony(e);on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}isConfigured(){return this.configurationManager.isConfigured()}getConnectionConfiguration=()=>this.configurationManager.get();destroy(){this.stateMachine.destroy()}getUri=e=>e;getUser(){try{return this.getUaProtected().configuration.uri.user}catch{return}}getUaProtected=()=>{if(!this.ua)throw new Error("UA not initialized");return this.ua};getUa=()=>this.ua;connectWithProcessError=async(e,t)=>{if(!(t?.hasReadyForConnection?.()??!0))throw Wn();return this.processConnect(e,t).catch(async i=>{const r=i;return this.disconnect().then(()=>{throw r}).catch(()=>{throw r})})};processConnect=async(e,t)=>(this.events.trigger(C.CONNECT_STARTED,{}),Qn(e).then(s=>(this.events.trigger(C.CONNECT_PARAMETERS_RESOLVE_SUCCESS,s),s)).catch(s=>{throw this.events.trigger(C.CONNECT_PARAMETERS_RESOLVE_FAILED,s),s}).then(async s=>this.connectionFlow.connect(s,t)).then(s=>(this.events.trigger(C.CONNECT_SUCCEEDED,{...s}),s)).catch(s=>{const i=s??new Error("Failed to connect to server");throw this.events.trigger(C.CONNECT_FAILED,i),i}))}class zn{connectionManager;stackPromises=he.createStackPromises({noRunIsNotActual:!0});constructor({connectionManager:e}){this.connectionManager=e}connect=async(...e)=>this.stackPromises.run(async()=>this.connectionManager.connect(...e));disconnect=async()=>this.stackPromises.run(async()=>this.connectionManager.disconnect());stop(){this.stackPromises.stop()}}const fe=0,Jn=30;class jn{countInner=fe;initialCount=fe;limitInner=Jn;isInProgress=!1;onStatusChange;constructor({onStatusChange:e}){this.onStatusChange=e}get count(){return this.countInner}get limit(){return this.limitInner}get isAttemptInProgress(){return this.isInProgress}hasLimitReached(){return this.countInner>=this.limitInner}startAttempt(){this.isInProgress||(this.isInProgress=!0,this.onStatusChange({isInProgress:this.isInProgress}))}finishAttempt(){this.isInProgress&&(this.isInProgress=!1,this.onStatusChange({isInProgress:this.isInProgress}))}increment(){this.count<this.limit&&(this.countInner+=1)}reset(){this.countInner=this.initialCount,this.finishAttempt()}}class Xn{connectionManager;interval;checkTelephonyByTimeout=void 0;cancelableBeforeRequest=void 0;constructor({connectionManager:e,interval:t}){this.connectionManager=e,this.interval=t}start({onBeforeRequest:e,onSuccessRequest:t,onFailRequest:s}){this.stop(),this.cancelableBeforeRequest=new H.CancelableRequest(e),this.checkTelephonyByTimeout=B.resolveRequesterByTimeout({isDontStopOnFail:!0,requestInterval:this.interval,request:async()=>{if(!this.cancelableBeforeRequest)throw new Error("cancelableBeforeRequest is not defined");const i=await this.cancelableBeforeRequest.request();return this.connectionManager.checkTelephony(i)}}),this.checkTelephonyByTimeout.start(void 0,{onFailRequest:s,onSuccessRequest:()=>{this.stop(),t()}})}stop(){this.checkTelephonyByTimeout?.stop(),this.checkTelephonyByTimeout=void 0,this.cancelableBeforeRequest?.cancelRequest(),this.cancelableBeforeRequest=void 0}}var _=(n=>(n.BEFORE_ATTEMPT="before-attempt",n.SUCCESS="success",n.FAILED_ALL_ATTEMPTS="failed-all-attempts",n.CANCELLED_ATTEMPTS="cancelled-attempts",n.CHANGED_ATTEMPT_STATUS="changed-attempt-status",n.STOP_ATTEMPTS_BY_ERROR="stop-attempts-by-error",n.LIMIT_REACHED_ATTEMPTS="limit-reached-attempts",n))(_||{});const et=["before-attempt","success","failed-all-attempts","cancelled-attempts","changed-attempt-status","stop-attempts-by-error","limit-reached-attempts"],Kn=()=>new M.TypedEvents(et);class me{callManager;disposers=[];constructor({callManager:e}){this.callManager=e}subscribe(e){this.unsubscribe(),this.disposers.push(this.callManager.on("call-status-changed",()=>{this.handleCallStatusChange(e)})),this.handleCallStatusChange(e)}unsubscribe(){this.disposers.forEach(e=>{e()}),this.disposers=[]}handleCallStatusChange({onActive:e,onInactive:t}){this.callManager.isCallActive?e?.():t()}}const Zn=15e3,es=2;class ts{connectionManager;pingServerByTimeoutWithFailCalls;constructor({connectionManager:e}){this.connectionManager=e,this.pingServerByTimeoutWithFailCalls=B.requesterByTimeoutsWithFailCalls(es,{whenPossibleRequest:async()=>{},requestInterval:Zn,request:async()=>(d("ping"),this.connectionManager.ping().then(()=>{d("ping success")}))})}start({onFailRequest:e}){this.pingServerByTimeoutWithFailCalls.start(void 0,{onFailRequest:e}).catch(d)}stop(){this.pingServerByTimeoutWithFailCalls.stop()}}class ns{pingServerRequester;notActiveCallSubscriber;constructor({connectionManager:e,callManager:t}){this.pingServerRequester=new ts({connectionManager:e}),this.notActiveCallSubscriber=new me({callManager:t})}start({onFailRequest:e}){d("start"),this.notActiveCallSubscriber.subscribe({onActive:()=>{this.pingServerRequester.stop()},onInactive:()=>{this.pingServerRequester.start({onFailRequest:e})}})}stop(){d("stop"),this.pingServerRequester.stop(),this.unsubscribeCallStatusChange()}unsubscribeCallStatusChange(){this.notActiveCallSubscriber.unsubscribe()}}class ss{connectionManager;isRegistrationFailed=!1;disposers=[];notActiveCallSubscriber;constructor({connectionManager:e,callManager:t}){this.connectionManager=e,this.notActiveCallSubscriber=new me({callManager:t})}subscribe(e){this.unsubscribe(),this.disposers.push(this.connectionManager.on("registrationFailed",()=>{this.setIsRegistrationFailed()})),this.notActiveCallSubscriber.subscribe({onInactive:()=>{this.isRegistrationFailed&&e()}}),this.disposers.push(()=>{this.notActiveCallSubscriber.unsubscribe()})}unsubscribe(){this.disposers.forEach(e=>{e()}),this.disposers=[],this.resetIsRegistrationFailed()}setIsRegistrationFailed(){this.isRegistrationFailed=!0}resetIsRegistrationFailed(){this.isRegistrationFailed=!1}}const is=3e3,rs=15e3,Me={LIMIT_REACHED:"Limit reached",FAILED_TO_RECONNECT:"Failed to reconnect"},as=async()=>{},os=n=>!0;class cs{events;connectionManager;connectionQueueManager;checkTelephonyRequester;pingServerIfNotActiveCallRequester;registrationFailedOutOfCallSubscriber;attemptsState;delayBetweenAttempts;cancelableRequestBeforeRetry;onBeforeRetry;canRetryOnError;networkInterfacesSubscriber;resumeFromSleepModeSubscriber;notActiveCallSubscriber;constructor({connectionQueueManager:e,connectionManager:t,callManager:s},i){const r=i?.onBeforeRetry??as,a=i?.canRetryOnError??os;this.connectionQueueManager=e,this.connectionManager=t,this.onBeforeRetry=r,this.canRetryOnError=a,this.networkInterfacesSubscriber=i?.networkInterfacesSubscriber,this.resumeFromSleepModeSubscriber=i?.resumeFromSleepModeSubscriber,this.events=Kn(),this.checkTelephonyRequester=new Xn({connectionManager:t,interval:i?.checkTelephonyRequestInterval??rs}),this.pingServerIfNotActiveCallRequester=new ns({connectionManager:t,callManager:s}),this.registrationFailedOutOfCallSubscriber=new ss({connectionManager:t,callManager:s}),this.attemptsState=new jn({onStatusChange:this.emitStatusChange}),this.cancelableRequestBeforeRetry=new H.CancelableRequest(r),this.delayBetweenAttempts=new B.DelayRequester(i?.timeoutBetweenAttempts??is),this.notActiveCallSubscriber=new me({callManager:s})}start(e){d("auto connector start"),this.restartConnectionAttempts(e),this.subscribeToNotActiveCall(e)}stop(){d("auto connector stop"),this.unsubscribeFromNotActiveCall(),this.unsubscribeFromHardwareTriggers(),this.stopConnectionFlow().catch(e=>{d("auto connector stop from stop method: error",e)})}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}restartConnectionAttempts(e){d("auto connector restart connection attempts"),this.stopConnectionFlow().then(async()=>this.attemptConnection(e)).catch(t=>{d("auto connector failed to restart connection attempts:",t)})}async stopConnectionFlow(){d("stopConnectionFlow"),this.stopAttempts(),this.stopConnectTriggers(),await this.connectionQueueManager.disconnect()}stopAttempts(){this.attemptsState.isAttemptInProgress&&this.connectionQueueManager.stop(),this.delayBetweenAttempts.cancelRequest(),this.cancelableRequestBeforeRetry.cancelRequest(),this.attemptsState.reset()}stopConnectTriggers(){d("stopConnectTriggers"),this.stopPingRequester(),this.checkTelephonyRequester.stop(),this.registrationFailedOutOfCallSubscriber.unsubscribe()}startCheckTelephony(e){d("startCheckTelephony"),this.checkTelephonyRequester.start({onBeforeRequest:async()=>(await this.onBeforeRetry(),e.getParameters()),onSuccessRequest:()=>{d("startCheckTelephony: onSuccessRequest"),this.connectIfDisconnected(e)},onFailRequest:t=>{d("startCheckTelephony: onFailRequest",t.message)}})}async attemptConnection(e){if(d("attemptConnection: attempts.count",this.attemptsState.count),this.events.trigger(_.BEFORE_ATTEMPT,{}),this.stopConnectTriggers(),this.attemptsState.hasLimitReached()){d("attemptConnection: limit reached"),this.handleLimitReached(e);return}return this.attemptsState.startAttempt(),this.attemptsState.increment(),this.executeConnectionAttempt(e)}async executeConnectionAttempt(e){try{await this.connectionQueueManager.connect(e.getParameters,e.options),d("executeConnectionAttempt: success"),this.handleSucceededAttempt(e)}catch(t){this.handleConnectionError(t,e)}}handleConnectionError(e,t){if(Ze(e)){this.attemptsState.finishAttempt(),this.events.trigger(_.STOP_ATTEMPTS_BY_ERROR,e);return}if(!this.canRetryOnError(e)){d("executeConnectionAttempt: error does not allow retry",e),this.attemptsState.finishAttempt(),this.events.trigger(_.STOP_ATTEMPTS_BY_ERROR,e);return}if(he.isPromiseIsNotActualError(e)){d("executeConnectionAttempt: not actual error",e),this.attemptsState.finishAttempt(),this.events.trigger(_.CANCELLED_ATTEMPTS,e);return}d("executeConnectionAttempt: error",e),this.scheduleReconnect(t)}handleLimitReached(e){this.attemptsState.finishAttempt(),this.events.trigger(_.LIMIT_REACHED_ATTEMPTS,new Error(Me.LIMIT_REACHED)),this.startCheckTelephony(e)}handleSucceededAttempt(e){d("handleSucceededAttempt"),this.subscribeToConnectTriggers(e),this.events.trigger(_.SUCCESS)}subscribeToConnectTriggers(e){this.startPingRequester(e),this.registrationFailedOutOfCallSubscriber.subscribe(()=>{d("registrationFailedOutOfCallListener callback"),this.restartConnectionAttempts(e)})}subscribeToNotActiveCall(e){this.notActiveCallSubscriber.subscribe({onActive:()=>{d("subscribeToNotActiveCall onActive"),this.unsubscribeFromHardwareTriggers()},onInactive:()=>{d("subscribeToNotActiveCall onInactive"),this.subscribeToHardwareTriggers(e)}})}unsubscribeFromNotActiveCall(){this.notActiveCallSubscriber.unsubscribe()}subscribeToHardwareTriggers(e){this.unsubscribeFromHardwareTriggers(),d("subscribeToHardwareTriggers"),this.networkInterfacesSubscriber?.subscribe({onChange:()=>{d("networkInterfacesSubscriber onChange"),this.restartConnectionAttempts(e)},onUnavailable:()=>{d("networkInterfacesSubscriber onUnavailable"),this.stopConnectionFlow().catch(t=>{d("auto connector stop from networkInterfacesSubscriber onUnavailable: error",t)})}}),this.resumeFromSleepModeSubscriber?.subscribe({onResume:()=>{d("resumeFromSleepModeSubscriber onResume"),this.restartConnectionAttempts(e)}})}unsubscribeFromHardwareTriggers(){d("unsubscribeFromHardwareTriggers"),this.networkInterfacesSubscriber?.unsubscribe(),this.resumeFromSleepModeSubscriber?.unsubscribe()}stopPingRequester(){this.pingServerIfNotActiveCallRequester.stop()}startPingRequester(e){this.pingServerIfNotActiveCallRequester.start({onFailRequest:()=>{d("pingRequester: onFailRequest"),this.restartConnectionAttempts(e)}})}connectIfDisconnected(e){const t=this.isConnectionUnavailable();d("connectIfDisconnected: isUnavailable",t),t?this.restartConnectionAttempts(e):(this.stopConnectTriggers(),this.events.trigger(_.SUCCESS))}scheduleReconnect(e){d("scheduleReconnect"),this.delayBetweenAttempts.request().then(async()=>(d("scheduleReconnect: delayBetweenAttempts success"),this.cancelableRequestBeforeRetry.request())).then(async()=>(d("scheduleReconnect: onBeforeRetry success"),this.attemptConnection(e))).catch(t=>{const s=t instanceof Error?t:new Error(Me.FAILED_TO_RECONNECT);this.attemptsState.finishAttempt(),H.isCanceledError(t)||B.hasCanceledError(t)?this.events.trigger(_.CANCELLED_ATTEMPTS,s):this.events.trigger(_.FAILED_ALL_ATTEMPTS,s),d("scheduleReconnect: error",t)})}isConnectionUnavailable(){const{isDisconnected:e,isIdle:t}=this.connectionManager;return e||t}emitStatusChange=({isInProgress:e})=>{this.events.trigger(_.CHANGED_ATTEMPT_STATUS,{isInProgress:e})}}const ds=I.setup({types:{context:{},events:{}},actions:{setCodec:I.assign(({event:n})=>"codec"in n?{codec:n.codec}:{}),clearCodec:I.assign({codec:void 0})}}).createMachine({id:"contented-stream",initial:"contented-stream:not-available",context:{},states:{"contented-stream:not-available":{on:{"CONTENTED_STREAM.AVAILABLE":{target:"contented-stream:available",actions:"setCodec"}}},"contented-stream:available":{on:{"CONTENTED_STREAM.NOT_AVAILABLE":{target:"contented-stream:not-available",actions:"clearCodec"},"CONTENTED_STREAM.AVAILABLE":{target:"contented-stream:available",actions:"setCodec",reenter:!0},"CONTENTED_STREAM.RESET":{target:"contented-stream:not-available",actions:"clearCodec"}}}}});class hs extends W{constructor(){super(ds)}get isAvailable(){return this.state==="contented-stream:available"}get isNotAvailable(){return this.state==="contented-stream:not-available"}get codec(){return this.getSnapshot().context.codec}getStateInfo(){return{isAvailable:this.isAvailable,codec:this.codec}}reset(){this.send({type:"CONTENTED_STREAM.RESET"})}send(e){if(!this.actor.getSnapshot().can(e)){console.warn(`[ContentedStreamStateMachine] Invalid transition: ${e.type} from ${this.state}. Event cannot be processed in current state.`);return}super.send(e)}subscribeToApiEvents(e){this.addSubscription(e.on("contented-stream:available",t=>{this.send({type:"CONTENTED_STREAM.AVAILABLE",codec:t.codec})})),this.addSubscription(e.on("contented-stream:not-available",()=>{this.send({type:"CONTENTED_STREAM.NOT_AVAILABLE"})}))}}var ce=(n=>(n.AVAILABLE="available",n.NOT_AVAILABLE="not-available",n))(ce||{});const ls=["available","not-available"],us=()=>new M.TypedEvents(ls);class gs{events;stateMachine;constructor(){this.events=us(),this.stateMachine=new hs,this.proxyEvents()}get isAvailable(){return this.stateMachine.isAvailable}get codec(){return this.stateMachine.codec}getStateInfo(){return this.stateMachine.getStateInfo()}reset(){this.stateMachine.reset()}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}off(e,t){this.events.off(e,t)}subscribeToApiEvents(e){this.stateMachine.subscribeToApiEvents(e.events)}proxyEvents(){this.stateMachine.onStateChange(()=>{const e=this.getStateInfo();e.isAvailable?this.events.trigger(ce.AVAILABLE,{codec:e.codec}):this.events.trigger(ce.NOT_AVAILABLE,{})})}}var q=(n=>(n.RINGING="ringing",n.DECLINED_INCOMING_CALL="declinedIncomingCall",n.TERMINATED_INCOMING_CALL="terminatedIncomingCall",n.FAILED_INCOMING_CALL="failedIncomingCall",n))(q||{});const tt=["ringing","declinedIncomingCall","terminatedIncomingCall","failedIncomingCall"],Ts=()=>new M.TypedEvents(tt);var nt=(n=>(n.IDLE="incoming:idle",n.RINGING="incoming:ringing",n.CONSUMED="incoming:consumed",n.DECLINED="incoming:declined",n.TERMINATED="incoming:terminated",n.FAILED="incoming:failed",n))(nt||{});const Ss=I.setup({types:{context:{},events:{}},actions:{logTransition:(n,e)=>{d(`State transition: ${e.from} -> ${e.to} (${e.event})`)},logStateChange:(n,e)=>{d("IncomingCallStateMachine state changed",e.state)},rememberIncoming:I.assign(({event:n})=>{const{data:e}=n;return{remoteCallerData:e,lastReason:void 0}}),rememberReason:I.assign(({event:n,context:e})=>n.type==="INCOMING.CONSUMED"?{remoteCallerData:e.remoteCallerData,lastReason:"incoming:consumed"}:n.type==="INCOMING.DECLINED"?{remoteCallerData:n.data,lastReason:"incoming:declined"}:n.type==="INCOMING.TERMINATED"?{remoteCallerData:n.data,lastReason:"incoming:terminated"}:{remoteCallerData:n.data,lastReason:"incoming:failed"}),clearIncoming:I.assign(()=>({remoteCallerData:void 0,lastReason:void 0}))}}).createMachine({id:"incoming",initial:"incoming:idle",context:{},states:{"incoming:idle":{entry:{type:"logStateChange",params:{state:"incoming:idle"}},on:{"INCOMING.RINGING":{target:"incoming:ringing",actions:["rememberIncoming",{type:"logTransition",params:{from:"incoming:idle",to:"incoming:ringing",event:"INCOMING.RINGING"}}]},"INCOMING.CLEAR":{target:"incoming:idle",actions:["clearIncoming",{type:"logTransition",params:{from:"incoming:idle",to:"incoming:idle",event:"INCOMING.CLEAR"}}]}}},"incoming:ringing":{entry:{type:"logStateChange",params:{state:"incoming:ringing"}},on:{"INCOMING.RINGING":{target:"incoming:ringing",actions:["rememberIncoming",{type:"logTransition",params:{from:"incoming:ringing",to:"incoming:ringing",event:"INCOMING.RINGING"}}]},"INCOMING.CONSUMED":{target:"incoming:consumed",actions:["rememberReason",{type:"logTransition",params:{from:"incoming:ringing",to:"incoming:consumed",event:"INCOMING.CONSUMED"}}]},"INCOMING.DECLINED":{target:"incoming:declined",actions:["rememberReason",{type:"logTransition",params:{from:"incoming:ringing",to:"incoming:declined",event:"INCOMING.DECLINED"}}]},"INCOMING.TERMINATED":{target:"incoming:terminated",actions:["rememberReason",{type:"logTransition",params:{from:"incoming:ringing",to:"incoming:terminated",event:"INCOMING.TERMINATED"}}]},"INCOMING.FAILED":{target:"incoming:failed",actions:["rememberReason",{type:"logTransition",params:{from:"incoming:ringing",to:"incoming:failed",event:"INCOMING.FAILED"}}]},"INCOMING.CLEAR":{target:"incoming:idle",actions:["clearIncoming",{type:"logTransition",params:{from:"incoming:ringing",to:"incoming:idle",event:"INCOMING.CLEAR"}}]}}},"incoming:consumed":{entry:{type:"logStateChange",params:{state:"incoming:consumed"}},on:{"INCOMING.CLEAR":{target:"incoming:idle",actions:["clearIncoming",{type:"logTransition",params:{from:"incoming:consumed",to:"incoming:idle",event:"INCOMING.CLEAR"}}]},"INCOMING.RINGING":{target:"incoming:ringing",actions:["rememberIncoming",{type:"logTransition",params:{from:"incoming:consumed",to:"incoming:ringing",event:"INCOMING.RINGING"}}]}}},"incoming:declined":{entry:{type:"logStateChange",params:{state:"incoming:declined"}},on:{"INCOMING.CLEAR":{target:"incoming:idle",actions:["clearIncoming",{type:"logTransition",params:{from:"incoming:declined",to:"incoming:idle",event:"INCOMING.CLEAR"}}]},"INCOMING.RINGING":{target:"incoming:ringing",actions:["rememberIncoming",{type:"logTransition",params:{from:"incoming:declined",to:"incoming:ringing",event:"INCOMING.RINGING"}}]}}},"incoming:terminated":{entry:{type:"logStateChange",params:{state:"incoming:terminated"}},on:{"INCOMING.CLEAR":{target:"incoming:idle",actions:["clearIncoming",{type:"logTransition",params:{from:"incoming:terminated",to:"incoming:idle",event:"INCOMING.CLEAR"}}]},"INCOMING.RINGING":{target:"incoming:ringing",actions:["rememberIncoming",{type:"logTransition",params:{from:"incoming:terminated",to:"incoming:ringing",event:"INCOMING.RINGING"}}]}}},"incoming:failed":{entry:{type:"logStateChange",params:{state:"incoming:failed"}},on:{"INCOMING.CLEAR":{target:"incoming:idle",actions:["clearIncoming",{type:"logTransition",params:{from:"incoming:failed",to:"incoming:idle",event:"INCOMING.CLEAR"}}]},"INCOMING.RINGING":{target:"incoming:ringing",actions:["rememberIncoming",{type:"logTransition",params:{from:"incoming:failed",to:"incoming:ringing",event:"INCOMING.RINGING"}}]}}}}});class Es extends W{constructor({incomingEvents:e,connectionEvents:t}){super(Ss),this.subscribeIncomingEvents(e),this.subscribeConnectionEvents(t)}get isIdle(){return this.state==="incoming:idle"}get isRinging(){return this.state==="incoming:ringing"}get isConsumed(){return this.state==="incoming:consumed"}get isDeclined(){return this.state==="incoming:declined"}get isTerminated(){return this.state==="incoming:terminated"}get isFailed(){return this.state==="incoming:failed"}get isActive(){return this.isRinging}get isFinished(){return this.isConsumed||this.isDeclined||this.isTerminated||this.isFailed}get remoteCallerData(){return this.getSnapshot().context.remoteCallerData}get lastReason(){return this.getSnapshot().context.lastReason}reset(){this.send({type:"INCOMING.CLEAR"})}send(e){if(!this.actor.getSnapshot().can(e)){console.warn(`[IncomingCallStateMachine] Invalid transition: ${e.type} from ${this.state}. Event cannot be processed in current state.`);return}super.send(e)}toConsumed(){this.send({type:"INCOMING.CONSUMED"})}subscribeIncomingEvents(e){this.addSubscription(e.on("ringing",t=>{this.send({type:"INCOMING.RINGING",data:t})})),this.addSubscription(e.on("declinedIncomingCall",t=>{this.send({type:"INCOMING.DECLINED",data:t})})),this.addSubscription(e.on("terminatedIncomingCall",t=>{this.send({type:"INCOMING.TERMINATED",data:t})})),this.addSubscription(e.on("failedIncomingCall",t=>{this.send({type:"INCOMING.FAILED",data:t})}))}subscribeConnectionEvents(e){this.addSubscription(e.on(C.DISCONNECTED,()=>{this.toClearIncoming()})),this.addSubscription(e.on(C.REGISTRATION_FAILED,()=>{this.toClearIncoming()})),this.addSubscription(e.on(C.CONNECT_FAILED,()=>{this.toClearIncoming()}))}toClearIncoming(){this.send({type:"INCOMING.CLEAR"})}}const Cs=486,ms=487,ae=n=>({displayName:n.remote_identity.display_name,host:n.remote_identity.uri.host,incomingNumber:n.remote_identity.uri.user,rtcSession:n});class ps{events;stateMachine;incomingRTCSession;connectionManager;constructor(e){this.connectionManager=e,this.events=Ts(),this.stateMachine=new Es({incomingEvents:this.events,connectionEvents:this.connectionManager.events}),this.start()}get remoteCallerData(){if(this.incomingRTCSession)return ae(this.incomingRTCSession)}get isAvailableIncomingCall(){return!!this.incomingRTCSession}start(){this.subscribe()}stop(){this.unsubscribe(),this.removeIncomingSession()}getIncomingRTCSession=()=>{const{incomingRTCSession:e}=this;if(!e)throw new Error("No incomingRTCSession");return e};extractIncomingRTCSession=()=>{const e=this.getIncomingRTCSession();return this.stateMachine.toConsumed(),this.removeIncomingSession(),e};async declineToIncomingCall({statusCode:e=ms}={}){return new Promise((t,s)=>{try{const i=this.getIncomingRTCSession(),r=ae(i);this.removeIncomingSession(),this.events.trigger(q.DECLINED_INCOMING_CALL,r),i.terminate({status_code:e}),t()}catch(i){s(i)}})}async busyIncomingCall(){return this.declineToIncomingCall({statusCode:Cs})}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}subscribe(){this.connectionManager.on("newRTCSession",this.handleNewRTCSession)}unsubscribe(){this.connectionManager.off("newRTCSession",this.handleNewRTCSession)}handleNewRTCSession=({originator:e,session:t})=>{e==="remote"&&this.setIncomingSession(t)};setIncomingSession(e){this.incomingRTCSession=e;const t=ae(e);e.on("failed",s=>{this.removeIncomingSession(),s.originator==="local"?this.events.trigger(q.TERMINATED_INCOMING_CALL,t):this.events.trigger(q.FAILED_INCOMING_CALL,t)}),this.events.trigger(q.RINGING,t)}removeIncomingSession(){delete this.incomingRTCSession}}class Rs{apiManager;connectionManager;callManager;get user(){return this.connectionManager?.getUser()}get number(){return this.callManager?.number}get isCallInitiator(){return!!this.callManager?.isCallInitiator}get peerToPeerRoom(){if(!(this.user===void 0||this.number===void 0))return this.isCallInitiator?`p2p${this.user}to${this.number}`:`p2p${this.number}to${this.user}`}subscribe({apiManager:e,connectionManager:t,callManager:s}){this.apiManager=e,this.connectionManager=t,this.callManager=s,s.on("confirmed",this.maybeSendDirectPeerToPeerRoom)}maybeSendDirectPeerToPeerRoom=()=>{const{peerToPeerRoom:e,number:t,apiManager:s}=this;if(e===void 0||t===void 0||s===void 0)return;const i=[`${h.CONTENT_ENTER_ROOM}: ${this.peerToPeerRoom}`,`${h.PARTICIPANT_NAME}: ${this.number}`,`${h.IS_DIRECT_PEER_TO_PEER}: true`];s.sendEnterRoom(i)}}var st=(n=>(n.SNAPSHOT_CHANGED="snapshot-changed",n))(st||{});const it=["snapshot-changed"],Ns=()=>new M.TypedEvents(it),As=(n,e)=>Object.is(n,e),_e=n=>({connection:n.connection.getSnapshot(),call:n.call.getSnapshot(),incoming:n.incoming.getSnapshot(),presentation:n.presentation.getSnapshot()});class Is{events;machines;currentSnapshot;subscribers=new Set;actorSubscriptions=[];constructor(e){this.events=Ns(),this.machines={connection:e.connectionManager.stateMachine,call:e.callManager.stateMachine,incoming:e.incomingCallManager.stateMachine,presentation:e.presentationManager.stateMachine},this.currentSnapshot=_e(this.machines),this.actorSubscriptions.push(this.machines.connection.subscribe(this.notifySubscribers),this.machines.call.subscribe(this.notifySubscribers),this.machines.incoming.subscribe(this.notifySubscribers),this.machines.presentation.subscribe(this.notifySubscribers))}getSnapshot(){return this.currentSnapshot}subscribe(e,t,s){const i=typeof t=="function",r=i?e:u=>u,a=i?t:e,o=(i?s:void 0)??As,c=r(this.currentSnapshot),l={selector:r,listener:a,equals:o,current:c};return this.subscribers.add(l),()=>{this.subscribers.delete(l)}}stop(){this.subscribers.clear(),this.actorSubscriptions.forEach(e=>{e.unsubscribe()})}on(e,t){return this.events.on(e,t)}off(e,t){this.events.off(e,t)}notifySubscribers=()=>{const e=this.currentSnapshot;this.currentSnapshot=_e(this.machines);for(const t of this.subscribers){const s=t.selector(this.currentSnapshot);t.equals(t.current,s)||(t.current=s,t.listener(s))}this.events.trigger(st.SNAPSHOT_CHANGED,{previous:e,current:this.currentSnapshot})}}const G=1e3;var R=(n=>(n.INBOUND_RTP="inbound-rtp",n.REMOTE_OUTBOUND_RTP="remote-outbound-rtp",n.MEDIA_SOURCE="media-source",n.OUTBOUND_RTP="outbound-rtp",n.REMOTE_INBOUND_RTP="remote-inbound-rtp",n.CODEC="codec",n.CANDIDATE_PAIR="candidate-pair",n.CERTIFICATE="certificate",n.TRANSPORT="transport",n.LOCAL_CANDIDATE="local-candidate",n.REMOTE_CANDIDATE="remote-candidate",n))(R||{});const rt=["collected"],vs=()=>new M.TypedEvents(rt),be=()=>"performance"in window?performance.now():Date.now(),Y=n=>[...n.keys()].reduce((e,t)=>{const s=n.get(t);return s===void 0?e:{...e,[s.type]:s}},{}),fs=n=>{if(!n)return{outboundRtp:void 0,codec:void 0,mediaSource:void 0,remoteInboundRtp:void 0};const e=Y(n);return{outboundRtp:e[R.OUTBOUND_RTP],codec:e[R.CODEC],mediaSource:e[R.MEDIA_SOURCE],remoteInboundRtp:e[R.REMOTE_INBOUND_RTP]}},Oe=n=>{if(!n)return{outboundRtp:void 0,codec:void 0,mediaSource:void 0,remoteInboundRtp:void 0};const e=Y(n);return{outboundRtp:e[R.OUTBOUND_RTP],codec:e[R.CODEC],mediaSource:e[R.MEDIA_SOURCE],remoteInboundRtp:e[R.REMOTE_INBOUND_RTP]}},Pe=({videoReceiversStats:n,synchronizationSourcesVideo:e})=>{if(!n)return{inboundRtp:void 0,codec:void 0,synchronizationSources:e};const t=Y(n);return{inboundRtp:t[R.INBOUND_RTP],codec:t[R.CODEC],synchronizationSources:e}},Ms=({audioReceiverStats:n,synchronizationSourcesAudio:e})=>{if(!n)return{inboundRtp:void 0,codec:void 0,remoteOutboundRtp:void 0,synchronizationSources:e};const t=Y(n);return{inboundRtp:t[R.INBOUND_RTP],codec:t[R.CODEC],remoteOutboundRtp:t[R.REMOTE_OUTBOUND_RTP],synchronizationSources:e}},at=n=>{if(!n)return{candidatePair:void 0,certificate:void 0,localCandidate:void 0,remoteCandidate:void 0,transport:void 0};const e=Y(n);return{candidatePair:e[R.CANDIDATE_PAIR],certificate:e[R.CERTIFICATE],localCandidate:e[R.LOCAL_CANDIDATE],remoteCandidate:e[R.REMOTE_CANDIDATE],transport:e[R.TRANSPORT]}},_s=({audioSenderStats:n,videoSenderFirstStats:e,videoSenderSecondStats:t})=>({video:Oe(e),secondVideo:Oe(t),audio:fs(n),additional:at(n??e??t)}),bs=({audioReceiverStats:n,videoReceiverFirstStats:e,videoReceiverSecondStats:t,synchronizationSources:s})=>({video:Pe({videoReceiversStats:e,synchronizationSourcesVideo:s.video}),secondVideo:Pe({videoReceiversStats:t,synchronizationSourcesVideo:s.video}),audio:Ms({audioReceiverStats:n,synchronizationSourcesAudio:s.audio}),additional:at(n??e??t)}),Os=({audioSenderStats:n,videoSenderFirstStats:e,videoSenderSecondStats:t,audioReceiverStats:s,videoReceiverFirstStats:i,videoReceiverSecondStats:r,synchronizationSources:a})=>{const o=_s({audioSenderStats:n,videoSenderFirstStats:e,videoSenderSecondStats:t}),c=bs({audioReceiverStats:s,videoReceiverFirstStats:i,videoReceiverSecondStats:r,synchronizationSources:a});return{outbound:o,inbound:c}},Ps=async n=>{const e="audio",t="video",s=n.getSenders(),i=s.find(E=>E.track?.kind===e),r=s.filter(E=>E.track?.kind===t),a=n.getReceivers(),o=a.find(E=>E.track.kind===e),c=a.filter(E=>E.track.kind===t),l={trackIdentifier:o?.track.id,item:o?.getSynchronizationSources()[0]},u={trackIdentifier:c[0]?.track.id,item:c[0]?.getSynchronizationSources()[0]},T={audio:l,video:u};return Promise.all([i?.getStats()??Promise.resolve(void 0),r[0]?.getStats()??Promise.resolve(void 0),r[1]?.getStats()??Promise.resolve(void 0),o?.getStats()??Promise.resolve(void 0),c[0]?.getStats()??Promise.resolve(void 0),c[1]?.getStats()??Promise.resolve(void 0)]).then(E=>{const[N,y,v,U,$,St]=E;return{synchronizationSources:T,audioSenderStats:N,videoSenderFirstStats:y,videoSenderSecondStats:v,audioReceiverStats:U,videoReceiverFirstStats:$,videoReceiverSecondStats:St}})},Ds=n=>{d(String(n))};class ot{events;setTimeoutRequest;requesterAllStatistics=new H.CancelableRequest(Ps);constructor(){this.events=vs(),this.setTimeoutRequest=new B.SetTimeoutRequest}get requested(){return this.setTimeoutRequest.requested}start(e,{interval:t=G,onError:s=Ds}={}){this.stop(),this.setTimeoutRequest.request(()=>{this.collectStatistics(e,{onError:s})},t)}stop(){this.setTimeoutRequest.cancelRequest(),this.requesterAllStatistics.cancelRequest()}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}collectStatistics=(e,{onError:t})=>{const s=be();this.requestAllStatistics(e).then(i=>{this.events.trigger("collected",Os(i));const a=be()-s;let o=G;a>48?o=G*4:a>32?o=G*3:a>16&&(o=G*2),this.start(e,{onError:t,interval:o})}).catch(i=>{t&&t(i)})};requestAllStatistics=async e=>{const t=e();if(t===void 0)throw new Error("failed to collect statistics: peerConnection is not defined");return this.requesterAllStatistics.request(t)}}const ys=500;class Ls{statsPeerConnection;availableStats;previousAvailableStats;callManager;apiManager;constructor({callManager:e,apiManager:t}){this.callManager=e,this.apiManager=t,this.statsPeerConnection=new ot,this.subscribe()}get events(){return this.statsPeerConnection.events}get availableIncomingBitrate(){return this.availableStats?.inbound.additional.candidatePair?.availableIncomingBitrate}get isInvalidInboundFrames(){return this.isEmptyInboundFrames&&this.isReceivingPackets}get isEmptyInboundFrames(){return!this.isFramesReceived||!this.isFramesDecoded}get previousAvailableIncomingBitrate(){return this.previousAvailableStats?.inbound.additional.candidatePair?.availableIncomingBitrate}get previousInboundRtp(){return this.previousAvailableStats?.inbound.video.inboundRtp}get previousFramesReceived(){return this.previousInboundRtp?.framesReceived}get previousFramesDecoded(){return this.previousInboundRtp?.framesDecoded}get inboundRtp(){return this.availableStats?.inbound.video.inboundRtp}get framesReceived(){return this.inboundRtp?.framesReceived}get framesDecoded(){return this.inboundRtp?.framesDecoded}get isFramesReceived(){const e=this.framesReceived!==void 0&&this.framesReceived>0,t=this.framesReceived!==this.previousFramesReceived;return e&&t}get isFramesDecoded(){const e=this.framesDecoded!==void 0&&this.framesDecoded>0,t=this.framesDecoded!==this.previousFramesDecoded;return e&&t}get packetsReceived(){return this.inboundRtp?.packetsReceived}get previousPacketsReceived(){return this.previousInboundRtp?.packetsReceived}get isReceivingPackets(){const e=this.packetsReceived!==void 0&&this.packetsReceived>=ys,t=this.packetsReceived!==this.previousPacketsReceived;return e&&t}on(e,t){return this.statsPeerConnection.on(e,t)}once(e,t){return this.statsPeerConnection.once(e,t)}onceRace(e,t){return this.statsPeerConnection.onceRace(e,t)}async wait(e){return this.statsPeerConnection.wait(e)}off(e,t){this.statsPeerConnection.off(e,t)}hasAvailableIncomingBitrateChangedQuarter(){const e=this.previousAvailableIncomingBitrate,t=this.availableIncomingBitrate;return e===void 0||t===void 0?!1:e===0?t>0:Math.abs(t-e)/e>=.25}subscribe(){this.callManager.on("peerconnection:confirmed",this.handleStarted),this.callManager.on("failed",this.handleEnded),this.callManager.on("ended",this.handleEnded),this.statsPeerConnection.on("collected",this.handleStatsCollected)}handleStatsCollected=e=>{this.previousAvailableStats=this.availableStats,this.availableStats=e,this.maybeSendStats()};handleStarted=()=>{this.statsPeerConnection.start(this.callManager.getActivePeerConnection)};handleEnded=()=>{this.statsPeerConnection.stop(),this.availableStats=void 0,this.previousAvailableStats=void 0};maybeSendStats(){this.availableIncomingBitrate!==void 0&&this.hasAvailableIncomingBitrateChangedQuarter()&&this.apiManager.sendStats({availableIncomingBitrate:this.availableIncomingBitrate}).catch(e=>{d("Failed to send stats",e)})}}const ws=(n,e)=>n.filter(s=>e.some(i=>i.clockRate===s.clockRate&&i.mimeType===s.mimeType&&i.channels===s.channels&&i.sdpFmtpLine===s.sdpFmtpLine)),Us=n=>{const e=RTCRtpSender.getCapabilities(n),t=RTCRtpReceiver.getCapabilities(n),s=e===null?[]:e.codecs,i=t===null?[]:t.codecs;return ws(s,i)},ks=(n,e)=>e===void 0||e.length===0?n:n.sort((t,s)=>{const i=e.indexOf(t.mimeType),r=e.indexOf(s.mimeType),a=i===-1?Number.MAX_VALUE:i,o=r===-1?Number.MAX_VALUE:r;return a-o}),Fs=(n,e)=>e===void 0||e.length===0?n:n.filter(t=>!e.includes(t.mimeType)),Bs=(n,{preferredMimeTypesVideoCodecs:e,excludeMimeTypesVideoCodecs:t})=>{try{if(typeof n.setCodecPreferences=="function"&&n.sender.track?.kind==="video"&&(e!==void 0&&e.length>0||t!==void 0&&t.length>0)){const s=Us("video"),i=Fs(s,t),r=ks(i,e);n.setCodecPreferences(r)}}catch(s){d("setCodecPreferences error",s)}},$s=n=>[...n.keys()].map(e=>n.get(e)),Gs=(n,e)=>$s(n).find(t=>t?.type===e),ct=async n=>n.getStats().then(e=>Gs(e,"codec")?.mimeType);class qs{async getCodecFromSender(e){return await ct(e)??""}}class Vs{stackPromises=he.createStackPromises({noRunIsNotActual:!0});async add(e){return this.stackPromises.add(e),this.run()}stop(){this.stackPromises.stop()}async run(){return this.stackPromises().catch(e=>{d("TaskQueue: error",e)})}}class xs{taskQueue;onSetParameters;constructor(e){this.onSetParameters=e,this.taskQueue=new Vs}async setEncodingsToSender(e,t){return this.taskQueue.add(async()=>Ee(e,t,this.onSetParameters))}stop(){this.taskQueue.stop()}}const dt=(n,e)=>n!==void 0&&e!==void 0&&n.toLowerCase().includes(e.toLowerCase()),Hs=1e6,D=n=>n*Hs,ht=D(.06),lt=D(4),Ws=n=>n<=64?ht:n<=128?D(.12):n<=256?D(.25):n<=384?D(.32):n<=426?D(.38):n<=640?D(.5):n<=848?D(.7):n<=1280?D(1):n<=1920?D(2):lt,Qs="av1",Ys=n=>dt(n,Qs),zs=.6,pe=(n,e)=>Ys(e)?n*zs:n,Js=n=>pe(ht,n),js=n=>pe(lt,n),De=(n,e)=>{const t=Ws(n);return pe(t,e)},oe=1,Xs=({videoTrack:n,targetSize:e})=>{const t=n.getSettings(),s=t.width,i=t.height,r=s===void 0?oe:s/e.width,a=i===void 0?oe:i/e.height;return Math.max(r,a,oe)};class Ks{ignoreForCodec;senderFinder;codecProvider;parametersSetter;resultNoChanged={isChanged:!1,parameters:{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}}};constructor({senderFinder:e,codecProvider:t,parametersSetter:s},i){this.senderFinder=e,this.codecProvider=t,this.parametersSetter=s,this.ignoreForCodec=i.ignoreForCodec}async balance(e,t){const s=e.getSenders(),i=this.senderFinder.findVideoSender(s);if(!i?.track)return{...this.resultNoChanged,sender:i};const r=await this.codecProvider.getCodecFromSender(i);if(dt(r,this.ignoreForCodec))return{...this.resultNoChanged,sender:i};const{mainCam:a,resolutionMainCam:o}=t??{};return this.processSender({mainCam:a,resolutionMainCam:o},{sender:i,codec:r,videoTrack:i.track}).then(c=>({...c,sender:i}))}async processSender(e,t){const{mainCam:s,resolutionMainCam:i}=e;switch(s){case b.PAUSE_MAIN_CAM:return this.downgradeResolutionSender(t);case b.RESUME_MAIN_CAM:return this.setBitrateByTrackResolution(t);case b.MAX_MAIN_CAM_RESOLUTION:return i!==void 0?this.setResolutionSender(i,t):this.setBitrateByTrackResolution(t);case b.ADMIN_STOP_MAIN_CAM:case b.ADMIN_START_MAIN_CAM:case void 0:return this.setBitrateByTrackResolution(t);default:return this.setBitrateByTrackResolution(t)}}async downgradeResolutionSender(e){const{sender:t,codec:s}=e,i={scaleResolutionDownBy:200,maxBitrate:Js(s)};return this.parametersSetter.setEncodingsToSender(t,i)}async setBitrateByTrackResolution(e){const{sender:t,videoTrack:s,codec:i}=e,a=s.getSettings().width,o=a===void 0?js(i):De(a,i);return this.parametersSetter.setEncodingsToSender(t,{scaleResolutionDownBy:1,maxBitrate:o})}async setResolutionSender(e,t){const[s,i]=e.split("x"),{sender:r,videoTrack:a,codec:o}=t,c={width:Number(s),height:Number(i)},l=Xs({videoTrack:a,targetSize:c}),u=De(c.width,o),T={scaleResolutionDownBy:l,maxBitrate:u};return this.parametersSetter.setEncodingsToSender(r,T)}}const Zs=n=>n.find(e=>e.track?.kind==="video");class ei{findVideoSender(e){return Zs(e)}}class ti{currentSender;originalReplaceTrack;lastWidth;lastHeight;maxPollIntervalMs;currentPollIntervalMs;pollIntervalMs;setTimeoutRequest;constructor({pollIntervalMs:e=1e3,maxPollIntervalMs:t}){this.pollIntervalMs=e,this.maxPollIntervalMs=t??e*16,this.currentPollIntervalMs=this.pollIntervalMs,this.setTimeoutRequest=new B.SetTimeoutRequest}subscribe(e,t){if(!e){this.detachSender();return}this.currentSender!==e&&(this.detachSender(),this.attachSender(e,t))}unsubscribe(){this.detachSender()}attachSender(e,t){this.currentSender=e;const s=e.replaceTrack.bind(e);this.originalReplaceTrack=s,e.replaceTrack=async i=>{await s(i),this.attachTrack(t,i??void 0),t()},this.attachTrack(t,e.track)}detachSender(){this.currentSender&&this.originalReplaceTrack&&(this.currentSender.replaceTrack=this.originalReplaceTrack),this.originalReplaceTrack=void 0,this.currentSender=void 0,this.detachTrack()}attachTrack(e,t){if(this.detachTrack(),!t)return;const{width:s,height:i}=t.getSettings();this.lastWidth=s,this.lastHeight=i,this.currentPollIntervalMs=this.pollIntervalMs,this.schedulePoll(t,e)}schedulePoll(e,t){const s=()=>{const{width:i,height:r}=e.getSettings();i!==this.lastWidth||r!==this.lastHeight?(this.lastWidth=i,this.lastHeight=r,this.currentPollIntervalMs=this.pollIntervalMs,t()):this.currentPollIntervalMs=Math.min(this.currentPollIntervalMs*2,this.maxPollIntervalMs),this.setTimeoutRequest.request(s,this.currentPollIntervalMs)};this.setTimeoutRequest.request(s,this.currentPollIntervalMs)}detachTrack(){this.setTimeoutRequest.cancelRequest(),this.lastWidth=void 0,this.lastHeight=void 0}}class ni{apiManager;currentHandler;constructor(e){this.apiManager=e}subscribe(e){this.currentHandler=e,this.apiManager.on("main-cam-control",e)}unsubscribe(){this.currentHandler&&(this.apiManager.off("main-cam-control",this.currentHandler),this.currentHandler=void 0)}}class si{eventHandler;senderBalancer;parametersSetterWithQueue;getConnection;serverHeaders;trackMonitor;constructor(e,t,{ignoreForCodec:s,onSetParameters:i,pollIntervalMs:r}={}){this.getConnection=t,this.eventHandler=new ni(e),this.parametersSetterWithQueue=new xs(i),this.senderBalancer=new Ks({senderFinder:new ei,codecProvider:new qs,parametersSetter:this.parametersSetterWithQueue},{ignoreForCodec:s}),this.trackMonitor=new ti({pollIntervalMs:r})}subscribe(){this.eventHandler.subscribe(this.handleMainCamControl)}unsubscribe(){this.eventHandler.unsubscribe(),this.parametersSetterWithQueue.stop(),this.reset()}reset(){delete this.serverHeaders,this.trackMonitor.unsubscribe()}async balance(){const e=this.getConnection();if(!e)throw new Error("connection is not exist");const t=await this.senderBalancer.balance(e,this.serverHeaders);return this.trackMonitor.subscribe(t.sender,()=>{this.balance().catch(s=>{d("balance on track change: error",s)})}),t}handleMainCamControl=e=>{this.serverHeaders=e,this.balance().catch(t=>{d("handleMainCamControl: error",t)})}}const ut=["balancing-scheduled","balancing-started","balancing-stopped","parameters-updated"],ii=()=>new M.TypedEvents(ut);class ri{isBalancingActive=!1;events;callManager;balancingStartDelay;videoSendingBalancer;startBalancingTimer;constructor(e,t,s={}){this.events=ii(),this.callManager=e,this.balancingStartDelay=s.balancingStartDelay??1e4,this.videoSendingBalancer=new si(t,()=>e.connection,{...s,onSetParameters:i=>{this.events.trigger("parameters-updated",i),s.onSetParameters?.(i)}}),this.subscribe()}get isBalancingScheduled(){return this.startBalancingTimer!==void 0}async startBalancing(){this.isBalancingActive||(this.clearStartTimer(),await this.videoSendingBalancer.balance(),this.videoSendingBalancer.subscribe(),this.isBalancingActive=!0,this.events.trigger("balancing-started",{delay:this.balancingStartDelay}))}stopBalancing(){this.clearStartTimer(),this.videoSendingBalancer.unsubscribe(),this.isBalancingActive=!1,this.events.trigger("balancing-stopped",{})}async balance(){return this.videoSendingBalancer.balance()}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}subscribe(){this.callManager.on("peerconnection:confirmed",this.handleCallStarted),this.callManager.on("ended",this.handleCallEnded),this.callManager.on("failed",this.handleCallEnded)}handleCallStarted=()=>{this.scheduleBalancingStart()};handleCallEnded=()=>{this.stopBalancing()};scheduleBalancingStart(){this.clearStartTimer(),this.startBalancingTimer=setTimeout(()=>{this.startBalancingTimer=void 0,this.startBalancing().catch(e=>{d("startBalancing: error",e)})},this.balancingStartDelay),this.events.trigger("balancing-scheduled",{delay:this.balancingStartDelay})}clearStartTimer(){this.startBalancingTimer&&(clearTimeout(this.startBalancingTimer),this.startBalancingTimer=void 0)}}const gt="no-inbound-frames",Tt=[gt],ai=()=>new M.TypedEvents(Tt);class oi{events;statsManager;callManager;constructor(e,t){this.statsManager=e,this.callManager=t,this.events=ai(),this.subscribe()}get mainVideoTrack(){return this.callManager.getMainRemoteStream()?.getVideoTracks()[0]}get isMutedMainVideoTrack(){const{mainVideoTrack:e}=this;return e===void 0?!1:e.muted}on(e,t){return this.events.on(e,t)}handleStatsCollected=()=>{this.hasNoIncomingFrames()&&this.events.trigger(gt,{})};hasNoIncomingFrames=()=>this.statsManager.isInvalidInboundFrames&&this.isMutedMainVideoTrack;subscribe(){this.statsManager.on("collected",this.handleStatsCollected)}}const ci=3e3;class di{renegotiateRequester;renegotiateThrottled;callManager;constructor(e,t=ci){this.callManager=e,this.renegotiateRequester=new H.CancelableRequest(e.renegotiate.bind(e)),this.renegotiateThrottled=Et.throttle(this.requestRenegotiate.bind(this),t),this.subscribe()}recover(){d("trying to recover main stream"),this.renegotiateThrottled()}requestRenegotiate=()=>{if(d("trying to renegotiate"),this.renegotiateRequester.requested){d("previous renegotiate is not finished yet");return}this.renegotiateRequester.request().then(()=>{d("renegotiate has successful")}).catch(e=>{d("failed to renegotiate main media stream",e)})};subscribe(){this.callManager.on("ended",()=>{this.cancel()})}cancel(){d("cancel recover main stream"),this.renegotiateThrottled.cancel(),this.renegotiateRequester.cancelRequest()}}const hi=1e6,li=et.map(n=>`auto-connect:${n}`),ui=ze.map(n=>`connection:${n}`),gi=xe.map(n=>`call:${n}`),Ti=Le.map(n=>`api:${n}`),Si=tt.map(n=>`incoming-call:${n}`),Ei=We.map(n=>`presentation:${n}`),Ci=rt.map(n=>`stats:${n}`),mi=ut.map(n=>`video-balancer:${n}`),pi=Tt.map(n=>`main-stream-health:${n}`),Ri=it.map(n=>`session:${n}`),Ni=["disconnected-from-out-of-call","connected-with-configuration-from-out-of-call","stopped-presentation-by-server-command"],Ai=[...li,...ui,...gi,...Ti,...Si,...Ei,...Ci,...mi,...pi,...Ri,...Ni],Ii=()=>new M.TypedEvents(Ai);class vi{events;connectionManager;connectionQueueManager;contentedStreamManager;callManager;autoConnectorManager;apiManager;incomingCallManager;presentationManager;statsManager;videoSendingBalancerManager;sessionManager;mainStreamHealthMonitor;peerToPeerManager;mainStreamRecovery;preferredMimeTypesVideoCodecs;excludeMimeTypesVideoCodecs;constructor({JsSIP:e},{preferredMimeTypesVideoCodecs:t,excludeMimeTypesVideoCodecs:s,videoBalancerOptions:i,autoConnectorOptions:r}={}){this.preferredMimeTypesVideoCodecs=t,this.excludeMimeTypesVideoCodecs=s,this.events=Ii(),this.apiManager=new bt,this.connectionManager=new Yn({JsSIP:e}),this.connectionQueueManager=new zn({connectionManager:this.connectionManager}),this.contentedStreamManager=new gs,this.callManager=new vn(this.contentedStreamManager),this.incomingCallManager=new ps(this.connectionManager),this.presentationManager=new Pn({callManager:this.callManager,maxBitrate:hi}),this.statsManager=new Ls({callManager:this.callManager,apiManager:this.apiManager}),this.autoConnectorManager=new cs({connectionQueueManager:this.connectionQueueManager,connectionManager:this.connectionManager,callManager:this.callManager},r),this.videoSendingBalancerManager=new ri(this.callManager,this.apiManager,i),this.mainStreamHealthMonitor=new oi(this.statsManager,this.callManager),this.mainStreamRecovery=new di(this.callManager),this.sessionManager=new Is({connectionManager:this.connectionManager,callManager:this.callManager,incomingCallManager:this.incomingCallManager,presentationManager:this.presentationManager}),this.callManager.subscribeToApiEvents(this.apiManager),this.contentedStreamManager.subscribeToApiEvents(this.apiManager),this.apiManager.subscribe({connectionManager:this.connectionManager,callManager:this.callManager}),this.peerToPeerManager=new Rs,this.peerToPeerManager.subscribe({connectionManager:this.connectionManager,callManager:this.callManager,apiManager:this.apiManager}),this.subscribe()}get requestedConnection(){return this.connectionManager.requested}get isPendingConnect(){return this.connectionManager.isPendingConnect}get isPendingInitUa(){return this.connectionManager.isPendingInitUa}get connectionState(){return this.connectionManager.connectionState}get isRegistered(){return this.connectionManager.isRegistered}get isRegisterConfig(){return this.connectionManager.isRegisterConfig}get socket(){return this.connectionManager.socket}get requestedCall(){return this.callManager.requested}get connection(){return this.callManager.connection}get isCallActive(){return this.callManager.isCallActive}get remoteCallerData(){return this.incomingCallManager.remoteCallerData}get isAvailableIncomingCall(){return this.incomingCallManager.isAvailableIncomingCall}get isDirectP2PRoom(){return this.callManager.isDirectP2PRoom}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}connect=async(...e)=>this.connectionQueueManager.connect(...e);disconnect=async()=>this.connectionQueueManager.disconnect();register=async()=>this.connectionManager.register();unregister=async()=>this.connectionManager.unregister();tryRegister=async()=>this.connectionManager.tryRegister();set=async(...e)=>this.connectionManager.set(...e);sendOptions=async(e,t,s)=>this.connectionManager.sendOptions(e,t,s);ping=async(e,t)=>this.connectionManager.ping(e,t);checkTelephony=async e=>this.connectionManager.checkTelephony(e);isConfigured=()=>this.connectionManager.isConfigured();getConnectionConfiguration=()=>this.connectionManager.getConnectionConfiguration();getUri=e=>this.connectionManager.getUri(e);startAutoConnect=(...e)=>{this.autoConnectorManager.start(...e)};stopAutoConnect=()=>{this.autoConnectorManager.stop()};call=async e=>{const{onAddedTransceiver:t,...s}=e;return this.callManager.startCall(this.connectionManager.getUaProtected(),this.getUri,{...s,onAddedTransceiver:this.resolveHandleAddTransceiver(t)})};hangUp=async()=>this.callManager.endCall();answerToIncomingCall=async e=>{const{onAddedTransceiver:t,...s}=e;return this.callManager.answerToIncomingCall(this.incomingCallManager.extractIncomingRTCSession,{...s,onAddedTransceiver:this.resolveHandleAddTransceiver(t)})};declineToIncomingCall=async(...e)=>this.incomingCallManager.declineToIncomingCall(...e);getEstablishedRTCSession=()=>this.callManager.getEstablishedRTCSession();getRemoteStreams=()=>this.callManager.getRemoteStreams();getRecvQuality=()=>this.callManager.getRecvQuality();setRecvQuality=async e=>this.callManager.setRecvQuality(e);replaceMediaStream=async(...e)=>this.callManager.replaceMediaStream(...e);async startPresentation(e,t={}){const{callLimit:s,onAddedTransceiver:i,...r}=t;return this.presentationManager.startPresentation(async()=>{await(this.isDirectP2PRoom?this.apiManager.sendAvailableContentedStream():this.apiManager.askPermissionToStartPresentation())},e,{...r,onAddedTransceiver:this.resolveHandleAddTransceiver(i)},s===void 0?void 0:{callLimit:s})}async stopPresentation(){return this.presentationManager.stopPresentation(async()=>{await(this.isDirectP2PRoom?this.apiManager.sendNotAvailableContentedStream():this.apiManager.sendStoppedPresentation())})}async updatePresentation(e,t={}){const{onAddedTransceiver:s,...i}=t;return this.presentationManager.updatePresentation(async()=>{await(this.isDirectP2PRoom?this.apiManager.sendAvailableContentedStream():this.apiManager.askPermissionToStartPresentation())},e,{...i,onAddedTransceiver:this.resolveHandleAddTransceiver(s)})}async waitChannels(...e){return this.apiManager.waitChannels(...e)}async waitSyncMediaState(...e){return this.apiManager.waitSyncMediaState(...e)}async sendDTMF(...e){return this.apiManager.sendDTMF(...e)}async sendChannels(...e){return this.apiManager.sendChannels(...e)}async sendMediaState(...e){return this.apiManager.sendMediaState(...e)}async sendRefusalToTurnOn(...e){return this.apiManager.sendRefusalToTurnOn(...e)}async sendRefusalToTurnOnMic(...e){return this.apiManager.sendRefusalToTurnOnMic(...e)}async sendRefusalToTurnOnCam(...e){return this.apiManager.sendRefusalToTurnOnCam(...e)}async askPermissionToEnableCam(...e){return this.apiManager.askPermissionToEnableCam(...e)}subscribeDisconnectedFromOutOfCall(){this.connectionManager.on("disconnected",()=>{this.isCallActive||this.events.trigger("disconnected-from-out-of-call",{})})}subscribeConnectedWithConfigurationFromOutOfCall(){this.connectionManager.on("connected-with-configuration",e=>{this.isCallActive||this.events.trigger("connected-with-configuration-from-out-of-call",e)})}mayBeStopPresentationAndNotify(){this.presentationManager.isPresentationInProcess&&(this.stopPresentation().catch(()=>{}),this.events.trigger("stopped-presentation-by-server-command",{}))}subscribeToApiEvents(){this.apiManager.on("participant:move-request-to-participants",()=>{this.callManager.setCallRoleParticipant()}),this.apiManager.on("participant:move-request-to-spectators-synthetic",()=>{this.callManager.setCallRoleSpectatorSynthetic(),this.mayBeStopPresentationAndNotify()}),this.apiManager.on("participant:move-request-to-spectators-with-audio-id",({audioId:e})=>{this.callManager.setCallRoleSpectator({audioId:e,sendOffer:this.sendOffer}),this.mayBeStopPresentationAndNotify()}),this.apiManager.on("presentation:must-stop",()=>{this.mayBeStopPresentationAndNotify()}),this.apiManager.on("failed-send-room-direct-p2p",({error:e})=>{const t=new Re.IncomingResponse;t.body=e instanceof Error?e.message:String(e);const s=Re.C.causes.INTERNAL_ERROR;this.callManager.failed(t,s).catch(i=>{d("Failed to end call after failed:",i)})})}sendOffer=async(e,t)=>{const i=this.connectionManager.getConnectionConfiguration()?.sipServerUrl;if(i===void 0)throw new Error("No sipServerUrl for sendOffer");return Ue({serverUrl:i,offer:t,token:e.token,conferenceNumber:e.conferenceNumber,quality:e.quality,audio:e.audioChannel})};setCodecPreferences(e){Bs(e,{preferredMimeTypesVideoCodecs:this.preferredMimeTypesVideoCodecs,excludeMimeTypesVideoCodecs:this.excludeMimeTypesVideoCodecs})}subscribe(){this.bridgeEvents("auto-connect",this.autoConnectorManager),this.bridgeEvents("connection",this.connectionManager),this.bridgeEvents("call",this.callManager),this.bridgeEvents("api",this.apiManager),this.bridgeEvents("incoming-call",this.incomingCallManager),this.bridgeEvents("presentation",this.presentationManager),this.bridgeEvents("stats",this.statsManager),this.bridgeEvents("video-balancer",this.videoSendingBalancerManager),this.bridgeEvents("main-stream-health",this.mainStreamHealthMonitor),this.bridgeEvents("session",this.sessionManager),this.subscribeToApiEvents(),this.subscribeDisconnectedFromOutOfCall(),this.subscribeConnectedWithConfigurationFromOutOfCall(),this.subscribeToMainStreamHealthMonitorEvents()}subscribeToMainStreamHealthMonitorEvents(){this.mainStreamHealthMonitor.on("no-inbound-frames",()=>{this.mainStreamRecovery.recover()})}bridgeEvents=(e,t)=>{t.events.eachTriggers((s,i)=>{t.on(i,r=>{this.events.trigger(`${e}:${i}`,r)})})};resolveHandleAddTransceiver=e=>async(t,s,i)=>{this.setCodecPreferences(t),await e?.(t,s,i)}}exports.DeferredCommandRunner=Be;exports.ECallCause=Ce;exports.EContentUseLicense=ge;exports.EState=Z;exports.EState$1=je;exports.EState$2=nt;exports.EState$3=Qe;exports.EStatsTypes=R;exports.Originator=qe;exports.PURGATORY_CONFERENCE_NUMBER=we;exports.SipConnector=vi;exports.StatsPeerConnection=ot;exports.disableDebug=mt;exports.enableDebug=Ct;exports.getCodecFromSender=ct;exports.hasCanceledStartPresentationError=On;exports.hasNotReadyForConnectionError=Ze;exports.hasPeerToPeer=Te;exports.hasPurgatory=Se;exports.logger=d;exports.prepareMediaStream=x;exports.sendOffer=Ue;exports.setEncodingsToSender=Ee;exports.setParametersToSender=K;
@@ -52,14 +52,14 @@ export type TEventMap = {
52
52
  'contented-stream:available': {
53
53
  codec?: EContentedStreamCodec;
54
54
  };
55
- 'contented-stream:not-available': Record<string, never>;
56
- 'presentation:must-stop': Record<string, never>;
55
+ 'contented-stream:not-available': never;
56
+ 'presentation:must-stop': never;
57
57
  'channels:all': TChannels;
58
58
  'channels:notify': TChannels;
59
59
  'participant:added-to-list-moderators': TParametersModeratorsList;
60
60
  'participant:removed-from-list-moderators': TParametersModeratorsList;
61
61
  'participant:move-request-to-stream': TParametersModeratorsList;
62
- 'participant:move-request-to-participants': Record<string, never>;
62
+ 'participant:move-request-to-participants': never;
63
63
  'participant:move-request-to-spectators': {
64
64
  isAvailableSendingMedia: boolean;
65
65
  isSynthetic: true;
@@ -79,8 +79,8 @@ export type TEventMap = {
79
79
  'participation:cancelling-word-request': TParametersModeratorsList;
80
80
  'webcast:started': TParametersWebcast;
81
81
  'webcast:stopped': TParametersWebcast;
82
- 'account:changed': Record<string, never>;
83
- 'account:deleted': Record<string, never>;
82
+ 'account:changed': never;
83
+ 'account:deleted': never;
84
84
  'admin:start-main-cam': {
85
85
  isSyncForced: boolean;
86
86
  };
@@ -161,7 +161,14 @@ declare class SipConnectorFacade implements IProxyMethods {
161
161
  getRemoteStreams: () => TRemoteStreams;
162
162
  onUseLicense: (handler: (license: EContentUseLicense) => void) => (() => void);
163
163
  onMustStopPresentation: (handler: () => void) => (() => void);
164
- onMoveToSpectators: (handler: () => void) => (() => void);
164
+ onMoveToSpectators: (handler: (event: {
165
+ isAvailableSendingMedia: boolean;
166
+ isSynthetic: true;
167
+ } | {
168
+ isAvailableSendingMedia: boolean;
169
+ isSynthetic: false;
170
+ audioId: string;
171
+ }) => void) => (() => void);
165
172
  onMoveToParticipants: (handler: () => void) => (() => void);
166
173
  onStats: (handler: (data: TStatsManagerEventMap["collected"]) => void) => (() => void);
167
174
  offStats: (handler: (data: TStatsManagerEventMap["collected"]) => void) => void;
package/dist/doMock.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const v=require("node:events"),a=require("@krivega/jssip"),_=require("webrtc-mock"),D=require("events-constructor"),y=require("./@SipConnector-Br2ML_bB.cjs");class w extends a.IncomingRequest{headers;constructor(e){super(),this.headers=new Headers(e)}getHeader(e){return this.headers.get(e)??""}}const U="incomingCall",j="declinedIncomingCall",z="failedIncomingCall",G="terminatedIncomingCall",L="connecting",H="connected",x="disconnected",q="newRTCSession",Y="registered",B="unregistered",K="registrationFailed",J="newMessage",$="sipEvent",Q="availableSecondRemoteStream",X="notAvailableSecondRemoteStream",Z="mustStopPresentation",ee="enterRoom",te="useLicense",ne="peerconnection:confirmed",re="peerconnection:ontrack",oe="channels",ie="channels:notify",se="ended:fromserver",ae="main-cam-control",ce="admin:stop-main-cam",de="admin:start-main-cam",he="admin:stop-mic",Ee="admin:start-mic",ue="admin:force-sync-media-state",me="participant:added-to-list-moderators",le="participant:removed-from-list-moderators",pe="participant:move-request-to-stream",ge="participant:move-request-to-spectators",_e="participant:move-request-to-participants",Te="participation:accepting-word-request",Ie="participation:cancelling-word-request",Se="webcast:started",we="webcast:stopped",Ne="account:changed",Ce="account:deleted",fe="conference:participant-token-issued",Re="ended",Ae="sending",Me="reinvite",Oe="replaces",Pe="refer",ve="progress",De="accepted",ye="confirmed",Le="peerconnection",be="failed",Fe="muted",ke="unmuted",We="newDTMF",Ve="newInfo",Ue="hold",je="unhold",ze="update",Ge="sdp",He="icecandidate",xe="getusermediafailed",qe="peerconnection:createofferfailed",Ye="peerconnection:createanswerfailed",Be="peerconnection:setlocaldescriptionfailed",Ke="peerconnection:setremotedescriptionfailed",Je="presentation:start",$e="presentation:started",Qe="presentation:end",Xe="presentation:ended",Ze="presentation:failed",et=[U,j,G,z,Te,Ie,pe,ie,fe,Ne,Ce,Se,we,me,le],b=[L,H,x,q,Y,B,K,J,$],tt=[Q,X,Z,ee,te,ne,re,oe,se,ae,de,ce,he,Ee,ue,ge,_e],T=[Re,L,Ae,Me,Oe,Pe,ve,De,ye,Le,be,Fe,ke,We,Ve,Ue,je,ze,Ge,He,xe,qe,Ye,Be,Ke,Je,$e,Qe,Xe,Ze];[...b,...et];[...T,...tt];class nt{originator;connection;events;remote_identity;mutedOptions={audio:!1,video:!1};addTransceiver=jest.fn(async(e,t,n)=>({}));constructor({originator:e="local",eventHandlers:t,remoteIdentity:n}){this.originator=e,this.events=new D.Events(T),this.initEvents(t),this.remote_identity=n}get contact(){throw new Error("Method not implemented.")}get direction(){throw new Error("Method not implemented.")}get local_identity(){throw new Error("Method not implemented.")}get start_time(){throw new Error("Method not implemented.")}get end_time(){throw new Error("Method not implemented.")}get status(){throw new Error("Method not implemented.")}get C(){throw new Error("Method not implemented.")}get causes(){throw new Error("Method not implemented.")}get id(){throw new Error("Method not implemented.")}get data(){throw new Error("Method not implemented.")}set data(e){throw new Error("Method not implemented.")}isInProgress(){throw new Error("Method not implemented.")}isEnded(){throw new Error("Method not implemented.")}isReadyToReOffer(){throw new Error("Method not implemented.")}answer(e){throw new Error("Method not implemented.")}terminate(e){throw new Error("Method not implemented.")}async sendInfo(e,t,n){throw new Error("Method not implemented.")}hold(e,t){throw new Error("Method not implemented.")}unhold(e,t){throw new Error("Method not implemented.")}async renegotiate(e,t){throw new Error("Method not implemented.")}isOnHold(){throw new Error("Method not implemented.")}mute(e){throw new Error("Method not implemented.")}unmute(e){throw new Error("Method not implemented.")}isMuted(){throw new Error("Method not implemented.")}refer(e,t){throw new Error("Method not implemented.")}resetLocalMedia(){throw new Error("Method not implemented.")}async replaceMediaStream(e,t){throw new Error("Method not implemented.")}addListener(e,t){throw new Error("Method not implemented.")}once(e,t){throw new Error("Method not implemented.")}removeListener(e,t){throw new Error("Method not implemented.")}off(e,t){return this.events.off(e,t),this}removeAllListeners(e){return console.warn("Method not implemented. Event:",e),this}setMaxListeners(e){throw new Error("Method not implemented.")}getMaxListeners(){throw new Error("Method not implemented.")}listeners(e){throw new Error("Method not implemented.")}rawListeners(e){throw new Error("Method not implemented.")}emit(e,...t){throw new Error("Method not implemented.")}listenerCount(e){throw new Error("Method not implemented.")}prependListener(e,t){throw new Error("Method not implemented.")}prependOnceListener(e,t){throw new Error("Method not implemented.")}eventNames(){throw new Error("Method not implemented.")}initEvents(e){e&&Object.entries(e).forEach(([t,n])=>{this.on(t,n)})}on=(e,t)=>(T.includes(e)&&this.events.on(e,t),this);trigger(e,t){this.events.trigger(e,t)}sendDTMF(){this.trigger("newDTMF",{originator:this.originator})}async startPresentation(e){return this.trigger("presentation:start",e),this.trigger("presentation:started",e),e}async stopPresentation(e){return this.trigger("presentation:end",e),this.trigger("presentation:ended",e),e}isEstablished(){return!0}}class R{stats=new Map().set("codec",{mimeType:"video/h264"});dtmf=null;track=null;transport=null;transform=null;parameters={encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}};parametersGets;constructor({track:e}={}){this.track=e??null}async getStats(){return this.stats}async replaceTrack(e){this.track=e??null}async setParameters(e){if(e!==this.parametersGets)throw new Error("Failed to execute 'setParameters' on 'RTCRtpSender': Read-only field modified in setParameters().");const{transactionId:t}=this.parameters;this.parameters={...this.parameters,...e,transactionId:`${Number(t)+1}`}}getParameters(){return this.parametersGets={...this.parameters},this.parametersGets}setStreams(){throw new Error("Method not implemented.")}}class A{currentDirection="sendrecv";direction="sendrecv";mid=null;receiver;sender;stopped=!1;constructor(e){this.sender=e}setCodecPreferences(e){}stop(){}}class rt extends EventTarget{senders=[];receivers=[];canTrickleIceCandidates;connectionState="new";currentLocalDescription;currentRemoteDescription;iceConnectionState;iceGatheringState;idpErrorInfo;idpLoginUrl;localDescription;onconnectionstatechange;ondatachannel;onicecandidate;onicecandidateerror=null;oniceconnectionstatechange;onicegatheringstatechange;onnegotiationneeded;onsignalingstatechange;ontrack;peerIdentity=void 0;pendingLocalDescription;pendingRemoteDescription;remoteDescription;sctp=null;signalingState="stable";close=jest.fn();setLocalDescription=jest.fn(async e=>{this.signalingState=e.type==="rollback"?"stable":"have-local-offer",this.dispatchEvent(new Event("signalingstatechange"))});setRemoteDescription=jest.fn(async e=>{this.signalingState="stable",this.connectionState="connected",this.dispatchEvent(new Event("signalingstatechange")),this.dispatchEvent(new Event("connectionstatechange"))});addTransceiver=jest.fn((e,t)=>({}));createOffer=jest.fn(async(e,t,n)=>({type:"offer",sdp:"offer-sdp"}));constructor(e,t){super(),this.receivers=t?.map(n=>({track:n}))??[]}getRemoteStreams(){throw new Error("Method not implemented.")}async addIceCandidate(e){throw new Error("Method not implemented.")}restartIce(){throw new Error("Method not implemented.")}async createAnswer(e,t){throw new Error("Method not implemented.")}createDataChannel(e,t){throw new Error("Method not implemented.")}getConfiguration(){throw new Error("Method not implemented.")}async getIdentityAssertion(){throw new Error("Method not implemented.")}async getStats(e){throw new Error("Method not implemented.")}getTransceivers(){throw new Error("Method not implemented.")}removeTrack(e){throw new Error("Method not implemented.")}setConfiguration(e){throw new Error("Method not implemented.")}getReceivers=()=>this.receivers;getSenders=()=>this.senders;addTrack=(e,...t)=>{const n=new R({track:e}),o=new A(n);return o.mid=e.kind==="audio"?"0":"1",this.senders.push(n),this.dispatchTrackInternal(e,...t),n};addTrackWithMid=(e,t)=>{const n=new R({track:e}),o=new A(n);return t===void 0?o.mid=e.kind==="audio"?"0":"1":o.mid=t,this.senders.push(n),this.dispatchTrackInternal(e),n};dispatchTrack(e){this.dispatchTrackInternal(new _.MediaStreamTrackMock(e))}dispatchTrackInternal(e,...t){const n=new Event("track");Object.defineProperty(n,"track",{value:e}),Object.defineProperty(n,"streams",{value:t.length===0?[new MediaStream([e])]:t}),this.dispatchEvent(n)}}function ot(r){const e=r.match(/(purgatory)|[\d.]+/g);if(!e)throw new Error("wrong sip url");return e[0]}const M=400,F="777",it=r=>r.getVideoTracks().length>0;class s extends nt{static presentationError;static startPresentationError;static countStartPresentationError=Number.POSITIVE_INFINITY;static countStartsPresentation=0;url;status_code;renegotiate=jest.fn(async()=>!0);answer=jest.fn(({mediaStream:e})=>{if(this.originator!=="remote")throw new Error("answer available only for remote sessions");this.initPeerconnection(e),setTimeout(()=>{this.trigger("connecting"),setTimeout(()=>{this.trigger("accepted")},100),setTimeout(()=>{this.trigger("confirmed")},200)},M)});replaceMediaStream=jest.fn(async e=>{});_isReadyToReOffer=jest.fn(()=>!0);restartIce=jest.fn(async e=>!0);isEndedInner=!1;delayStartPresentation=0;timeoutStartPresentation;timeoutConnect;timeoutNewInfo;timeoutAccepted;timeoutConfirmed;constructor({eventHandlers:e,originator:t,remoteIdentity:n=new a.NameAddrHeader(new a.URI("sip","caller1","test1.com",5060),"Test Caller 1"),delayStartPresentation:o=0}){super({originator:t,eventHandlers:e,remoteIdentity:n}),this.delayStartPresentation=o}static get C(){return a.SessionStatus}static setPresentationError(e){this.presentationError=e}static resetPresentationError(){this.presentationError=void 0}static setStartPresentationError(e,{count:t=Number.POSITIVE_INFINITY}={}){this.startPresentationError=e,this.countStartPresentationError=t}static resetStartPresentationError(){this.startPresentationError=void 0,this.countStartPresentationError=Number.POSITIVE_INFINITY,this.countStartsPresentation=0}startPresentation=async e=>(s.countStartsPresentation+=1,new Promise((t,n)=>{this.timeoutStartPresentation=setTimeout(()=>{if(s.presentationError){this.trigger("presentation:start",e),this.trigger("presentation:failed",e),n(s.presentationError);return}if(s.startPresentationError&&s.countStartsPresentation<s.countStartPresentationError){this.trigger("presentation:start",e),this.trigger("presentation:failed",e),n(s.startPresentationError);return}t(super.startPresentation(e))},this.delayStartPresentation)}));stopPresentation=async e=>{if(s.presentationError)throw this.trigger("presentation:end",e),this.trigger("presentation:failed",e),s.presentationError;return super.stopPresentation(e)};initPeerconnection(e){return e?(this.createPeerconnection(e),!0):!1}createPeerconnection(e){const t=_.createAudioMediaStreamTrackMock();t.id="mainaudio1";const n=[t];if(it(e)){const c=_.createVideoMediaStreamTrackMock();c.id="mainvideo1",n.push(c)}this.connection=new rt(void 0,n),this.trigger("peerconnection",{peerconnection:this.connection}),this.addStream(e)}connect(e,{mediaStream:t}={}){const n=ot(e);return this.initPeerconnection(t),this.timeoutConnect=setTimeout(()=>{e.includes(F)?this.trigger("failed",{originator:"remote",message:"IncomingResponse",cause:"Rejected"}):(this.trigger("connecting"),this.timeoutNewInfo=setTimeout(()=>{this.newInfo({originator:y.Originator.REMOTE,request:{getHeader:o=>o==="content-type"?"application/vinteo.webrtc.roomname":o==="x-webrtc-enter-room"?n:o==="x-webrtc-participant-name"?"Test Caller 1":""}})},100),this.timeoutAccepted=setTimeout(()=>{this.trigger("accepted")},200),this.timeoutConfirmed=setTimeout(()=>{this.trigger("confirmed")},300))},M),this.connection}terminate({status_code:e,cause:t}={}){return this.status_code=e,this.trigger("ended",{status_code:e,cause:t,originator:"local"}),this.isEndedInner=!1,this}async terminateAsync({status_code:e,cause:t}={}){this.terminate({status_code:e,cause:t})}terminateRemote({status_code:e}={}){return this.status_code=e,this.trigger("ended",{status_code:e,originator:"remote"}),this}addStream(e,t="getTracks"){e[t]().forEach(n=>this.connection.addTrack(n,e))}forEachSenders(e){const t=this.connection.getSenders();for(const n of t)e(n);return t}toggleMuteAudio(e){this.forEachSenders(({track:t})=>{t?.kind==="audio"&&(t.enabled=!e)})}toggleMuteVideo(e){this.forEachSenders(({track:t})=>{t?.kind==="video"&&(t.enabled=!e)})}mute(e){e.audio&&(this.mutedOptions.audio=!0,this.toggleMuteAudio(this.mutedOptions.audio)),e.video&&(this.mutedOptions.video=!0,this.toggleMuteVideo(this.mutedOptions.video)),this.onmute(e)}unmute(e){e.audio&&(this.mutedOptions.audio=!1),e.video&&(this.mutedOptions.video=!1),this.trigger("unmuted",e)}isMuted(){return this.mutedOptions}onmute({audio:e,video:t}){this.trigger("muted",{audio:e,video:t})}async sendInfo(){}isEnded(){return this.isEndedInner}newInfo(e){this.trigger("newInfo",e)}clear(){clearTimeout(this.timeoutStartPresentation),clearTimeout(this.timeoutConnect),clearTimeout(this.timeoutNewInfo),clearTimeout(this.timeoutAccepted),clearTimeout(this.timeoutConfirmed)}}class st{extraHeaders=[];setExtraHeaders(e){this.extraHeaders=e}setExtraContactParams(){}}const d="PASSWORD_CORRECT",I="PASSWORD_CORRECT_2",k="NAME_INCORRECT",u=400,g={url:"wss://sipServerUrl/webrtc/wss/",sip_uri:"sip:sipServerUrl;transport=ws",via_transport:"WSS"},O={status_code:200,reason_phrase:"OK"},P={status_code:401,reason_phrase:"Unauthorized"};class i extends v.EventEmitter{static isAvailableTelephony=!0;static startError;static countStartError=Number.POSITIVE_INFINITY;static countStarts=0;events;registratorInner;call=jest.fn((e,t)=>{const{mediaStream:n,eventHandlers:o}=t;return this.session=new s({eventHandlers:o,originator:"local"}),this.session.connect(e,{mediaStream:n}),this.session});sendOptions=jest.fn((e,t,n)=>{console.log("sendOptions",e,t,n)});start=jest.fn(()=>{if(i.countStarts+=1,i.startError&&i.countStarts<i.countStartError){this.trigger("disconnected",i.startError);return}this.register()});stop=jest.fn(()=>{this.startedTimeout&&clearTimeout(this.startedTimeout),this.stopedTimeout&&clearTimeout(this.stopedTimeout),this.unregister(),this.isStarted()?this.stopedTimeout=setTimeout(()=>{this.trigger("disconnected",{error:!0,socket:g})},u):this.trigger("disconnected",{error:!0,socket:g})});removeAllListeners=jest.fn(()=>(this.events.removeEventHandlers(),this));once=jest.fn((e,t)=>(this.events.once(e,t),this));configuration;startedTimeout;stopedTimeout;session;isRegisteredInner;isConnectedInner;constructor(e){super(),this.events=new D.Events(b);const[t,n]=e.uri.split(":"),[o,c]=n.split("@"),p={...e,uri:new a.URI(t,o,c)};this.configuration=p,this.registratorInner=new st}get C(){throw new Error("Method not implemented.")}get status(){throw new Error("Method not implemented.")}get contact(){throw new Error("Method not implemented.")}get transport(){throw new Error("Method not implemented.")}static C(){throw new Error("Method not implemented.")}static setStartError(e,{count:t=Number.POSITIVE_INFINITY}={}){i.startError=e,i.countStartError=t}static resetStartError(){i.startError=void 0,i.countStartError=Number.POSITIVE_INFINITY,i.countStarts=0}static setAvailableTelephony(){i.isAvailableTelephony=!0}static setNotAvailableTelephony(){i.isAvailableTelephony=!1}static reset(){i.resetStartError(),i.setAvailableTelephony()}on(e,t){return this.events.on(e,t),this}sendMessage(){throw new Error("Method not implemented.")}normalizeTarget(){throw new Error("Method not implemented.")}get(){throw new Error("Method not implemented.")}off(e,t){return this.events.off(e,t),this}trigger(e,t){this.events.trigger(e,t)}terminateSessions(){this.session?.terminate()}set(e,t){return this.configuration[e]=t,!0}register(){this.startedTimeout&&clearTimeout(this.startedTimeout);const{password:e,register:t,uri:n}=this.configuration;t===!0&&n.user.includes(k)?(this.isRegisteredInner=!1,this.isConnectedInner=!1,this.startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:P,cause:a.C.causes.REJECTED})},u)):!this.isRegistered()&&t===!0&&(e===d||e===I)?(this.isRegisteredInner=!0,this.startedTimeout=setTimeout(()=>{this.trigger("registered",{response:O})},u)):t===!0&&e!==d&&e!==I&&(this.isRegisteredInner=!1,this.isConnectedInner=!1,this.startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:P,cause:a.C.causes.REJECTED})},u)),i.isAvailableTelephony?(this.trigger("connected",{socket:g}),this.isConnectedInner=!0):this.stop()}unregister(){this.isRegisteredInner=!1,this.isConnectedInner=!1,this.trigger("unregistered",{response:O})}isRegistered(){return this.isRegisteredInner===!0}isConnected(){return this.isConnectedInner===!0}isStarted(){return this.configuration.register===!0&&this.isRegisteredInner===!0||this.configuration.register!==!0&&this.isConnectedInner===!0}newSipEvent(e){this.trigger("sipEvent",e)}registrator(){return this.registratorInner}}class at{url;constructor(e){this.url=e}}class ct extends v.EventEmitter{contentType;body;constructor(e,t){super(),this.contentType=e,this.body=t}}const S="remote",dt=(r,e)=>{const t=new w(e),n={originator:S,request:t,info:new ct("","")};r.newInfo(n)},ht=(r,e)=>{const n={event:"sipEvent",request:new w(e)};r.newSipEvent(n)},Et=(r,{incomingNumber:e="1234",displayName:t,host:n})=>{const o=new s({originator:S,eventHandlers:{}}),c=new a.URI("sip",e,n);o.remote_identity=new a.NameAddrHeader(c,t);const p=new w([]);r.trigger("newRTCSession",{originator:S,session:o,request:p})},ut=(r,e)=>{e?r.trigger("failed",e):r.trigger("failed",r)},N={triggerNewInfo:dt,triggerNewSipEvent:ht,triggerIncomingSession:Et,triggerFailIncomingSession:ut,WebSocketInterface:at,UA:i,C:{INVITE:"INVITE"}},h="user",E="displayName",m="SIP_SERVER_URL",C="SIP_WEB_SOCKET_SERVER_URL",mt=new N.WebSocketInterface(`wss://${C}/webrtc/wss/`),f={displayName:"DISPLAY_NAME",userAgent:"Chrome",sipServerIp:m,sipServerUrl:C},lt={...f,displayName:"DISPLAY_NAME",register:!1},W={...f,user:h,password:d,register:!0,authorizationUser:h},pt={...W,displayName:E},gt={...f,displayName:E,authorizationUser:h,register:!1},l={session_timers:!1,sockets:[mt],user_agent:"Chrome",sdpSemantics:"unified-plan",register_expires:300,connection_recovery_max_interval:6,connection_recovery_min_interval:2},_t={...l,password:d,uri:new a.URI("sip",h,m),display_name:"DISPLAY_NAME",register:!0},Tt={...l,password:d,uri:new a.URI("sip",h,m),display_name:E,register:!0},It={...l,display_name:E,register:!1},St={...l,display_name:"DISPLAY_NAME",register:!1},V="10.10.10.10",wt=[`X-Vinteo-Remote: ${V}`],Nt=()=>new y.SipConnector({JsSIP:N});exports.FAILED_CONFERENCE_NUMBER=F;exports.JsSIP=N;exports.NAME_INCORRECT=k;exports.PASSWORD_CORRECT=d;exports.PASSWORD_CORRECT_2=I;exports.SIP_SERVER_URL=m;exports.SIP_WEB_SOCKET_SERVER_URL=C;exports.dataForConnectionWithAuthorization=W;exports.dataForConnectionWithAuthorizationWithDisplayName=pt;exports.dataForConnectionWithoutAuthorization=gt;exports.dataForConnectionWithoutAuthorizationWithoutDisplayName=lt;exports.displayName=E;exports.doMockSipConnector=Nt;exports.extraHeadersRemoteAddress=wt;exports.remoteAddress=V;exports.uaConfigurationWithAuthorization=_t;exports.uaConfigurationWithAuthorizationWithDisplayName=Tt;exports.uaConfigurationWithoutAuthorization=It;exports.uaConfigurationWithoutAuthorizationWithoutDisplayName=St;exports.user=h;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const v=require("node:events"),a=require("@krivega/jssip"),_=require("webrtc-mock"),D=require("events-constructor"),y=require("./@SipConnector-w-Nwup6s.cjs");class w extends a.IncomingRequest{headers;constructor(e){super(),this.headers=new Headers(e)}getHeader(e){return this.headers.get(e)??""}}const U="incomingCall",j="declinedIncomingCall",z="failedIncomingCall",G="terminatedIncomingCall",L="connecting",H="connected",x="disconnected",q="newRTCSession",Y="registered",B="unregistered",K="registrationFailed",J="newMessage",$="sipEvent",Q="availableSecondRemoteStream",X="notAvailableSecondRemoteStream",Z="mustStopPresentation",ee="enterRoom",te="useLicense",ne="peerconnection:confirmed",re="peerconnection:ontrack",oe="channels",ie="channels:notify",se="ended:fromserver",ae="main-cam-control",ce="admin:stop-main-cam",de="admin:start-main-cam",he="admin:stop-mic",Ee="admin:start-mic",ue="admin:force-sync-media-state",me="participant:added-to-list-moderators",le="participant:removed-from-list-moderators",pe="participant:move-request-to-stream",ge="participant:move-request-to-spectators",_e="participant:move-request-to-participants",Te="participation:accepting-word-request",Ie="participation:cancelling-word-request",Se="webcast:started",we="webcast:stopped",Ne="account:changed",Ce="account:deleted",fe="conference:participant-token-issued",Re="ended",Ae="sending",Me="reinvite",Oe="replaces",Pe="refer",ve="progress",De="accepted",ye="confirmed",Le="peerconnection",be="failed",Fe="muted",ke="unmuted",We="newDTMF",Ve="newInfo",Ue="hold",je="unhold",ze="update",Ge="sdp",He="icecandidate",xe="getusermediafailed",qe="peerconnection:createofferfailed",Ye="peerconnection:createanswerfailed",Be="peerconnection:setlocaldescriptionfailed",Ke="peerconnection:setremotedescriptionfailed",Je="presentation:start",$e="presentation:started",Qe="presentation:end",Xe="presentation:ended",Ze="presentation:failed",et=[U,j,G,z,Te,Ie,pe,ie,fe,Ne,Ce,Se,we,me,le],b=[L,H,x,q,Y,B,K,J,$],tt=[Q,X,Z,ee,te,ne,re,oe,se,ae,de,ce,he,Ee,ue,ge,_e],T=[Re,L,Ae,Me,Oe,Pe,ve,De,ye,Le,be,Fe,ke,We,Ve,Ue,je,ze,Ge,He,xe,qe,Ye,Be,Ke,Je,$e,Qe,Xe,Ze];[...b,...et];[...T,...tt];class nt{originator;connection;events;remote_identity;mutedOptions={audio:!1,video:!1};addTransceiver=jest.fn(async(e,t,n)=>({}));constructor({originator:e="local",eventHandlers:t,remoteIdentity:n}){this.originator=e,this.events=new D.Events(T),this.initEvents(t),this.remote_identity=n}get contact(){throw new Error("Method not implemented.")}get direction(){throw new Error("Method not implemented.")}get local_identity(){throw new Error("Method not implemented.")}get start_time(){throw new Error("Method not implemented.")}get end_time(){throw new Error("Method not implemented.")}get status(){throw new Error("Method not implemented.")}get C(){throw new Error("Method not implemented.")}get causes(){throw new Error("Method not implemented.")}get id(){throw new Error("Method not implemented.")}get data(){throw new Error("Method not implemented.")}set data(e){throw new Error("Method not implemented.")}isInProgress(){throw new Error("Method not implemented.")}isEnded(){throw new Error("Method not implemented.")}isReadyToReOffer(){throw new Error("Method not implemented.")}answer(e){throw new Error("Method not implemented.")}terminate(e){throw new Error("Method not implemented.")}async sendInfo(e,t,n){throw new Error("Method not implemented.")}hold(e,t){throw new Error("Method not implemented.")}unhold(e,t){throw new Error("Method not implemented.")}async renegotiate(e,t){throw new Error("Method not implemented.")}isOnHold(){throw new Error("Method not implemented.")}mute(e){throw new Error("Method not implemented.")}unmute(e){throw new Error("Method not implemented.")}isMuted(){throw new Error("Method not implemented.")}refer(e,t){throw new Error("Method not implemented.")}resetLocalMedia(){throw new Error("Method not implemented.")}async replaceMediaStream(e,t){throw new Error("Method not implemented.")}addListener(e,t){throw new Error("Method not implemented.")}once(e,t){throw new Error("Method not implemented.")}removeListener(e,t){throw new Error("Method not implemented.")}off(e,t){return this.events.off(e,t),this}removeAllListeners(e){return console.warn("Method not implemented. Event:",e),this}setMaxListeners(e){throw new Error("Method not implemented.")}getMaxListeners(){throw new Error("Method not implemented.")}listeners(e){throw new Error("Method not implemented.")}rawListeners(e){throw new Error("Method not implemented.")}emit(e,...t){throw new Error("Method not implemented.")}listenerCount(e){throw new Error("Method not implemented.")}prependListener(e,t){throw new Error("Method not implemented.")}prependOnceListener(e,t){throw new Error("Method not implemented.")}eventNames(){throw new Error("Method not implemented.")}initEvents(e){e&&Object.entries(e).forEach(([t,n])=>{this.on(t,n)})}on=(e,t)=>(T.includes(e)&&this.events.on(e,t),this);trigger(e,t){this.events.trigger(e,t)}sendDTMF(){this.trigger("newDTMF",{originator:this.originator})}async startPresentation(e){return this.trigger("presentation:start",e),this.trigger("presentation:started",e),e}async stopPresentation(e){return this.trigger("presentation:end",e),this.trigger("presentation:ended",e),e}isEstablished(){return!0}}class R{stats=new Map().set("codec",{mimeType:"video/h264"});dtmf=null;track=null;transport=null;transform=null;parameters={encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}};parametersGets;constructor({track:e}={}){this.track=e??null}async getStats(){return this.stats}async replaceTrack(e){this.track=e??null}async setParameters(e){if(e!==this.parametersGets)throw new Error("Failed to execute 'setParameters' on 'RTCRtpSender': Read-only field modified in setParameters().");const{transactionId:t}=this.parameters;this.parameters={...this.parameters,...e,transactionId:`${Number(t)+1}`}}getParameters(){return this.parametersGets={...this.parameters},this.parametersGets}setStreams(){throw new Error("Method not implemented.")}}class A{currentDirection="sendrecv";direction="sendrecv";mid=null;receiver;sender;stopped=!1;constructor(e){this.sender=e}setCodecPreferences(e){}stop(){}}class rt extends EventTarget{senders=[];receivers=[];canTrickleIceCandidates;connectionState="new";currentLocalDescription;currentRemoteDescription;iceConnectionState;iceGatheringState;idpErrorInfo;idpLoginUrl;localDescription;onconnectionstatechange;ondatachannel;onicecandidate;onicecandidateerror=null;oniceconnectionstatechange;onicegatheringstatechange;onnegotiationneeded;onsignalingstatechange;ontrack;peerIdentity=void 0;pendingLocalDescription;pendingRemoteDescription;remoteDescription;sctp=null;signalingState="stable";close=jest.fn();setLocalDescription=jest.fn(async e=>{this.signalingState=e.type==="rollback"?"stable":"have-local-offer",this.dispatchEvent(new Event("signalingstatechange"))});setRemoteDescription=jest.fn(async e=>{this.signalingState="stable",this.connectionState="connected",this.dispatchEvent(new Event("signalingstatechange")),this.dispatchEvent(new Event("connectionstatechange"))});addTransceiver=jest.fn((e,t)=>({}));createOffer=jest.fn(async(e,t,n)=>({type:"offer",sdp:"offer-sdp"}));constructor(e,t){super(),this.receivers=t?.map(n=>({track:n}))??[]}getRemoteStreams(){throw new Error("Method not implemented.")}async addIceCandidate(e){throw new Error("Method not implemented.")}restartIce(){throw new Error("Method not implemented.")}async createAnswer(e,t){throw new Error("Method not implemented.")}createDataChannel(e,t){throw new Error("Method not implemented.")}getConfiguration(){throw new Error("Method not implemented.")}async getIdentityAssertion(){throw new Error("Method not implemented.")}async getStats(e){throw new Error("Method not implemented.")}getTransceivers(){throw new Error("Method not implemented.")}removeTrack(e){throw new Error("Method not implemented.")}setConfiguration(e){throw new Error("Method not implemented.")}getReceivers=()=>this.receivers;getSenders=()=>this.senders;addTrack=(e,...t)=>{const n=new R({track:e}),o=new A(n);return o.mid=e.kind==="audio"?"0":"1",this.senders.push(n),this.dispatchTrackInternal(e,...t),n};addTrackWithMid=(e,t)=>{const n=new R({track:e}),o=new A(n);return t===void 0?o.mid=e.kind==="audio"?"0":"1":o.mid=t,this.senders.push(n),this.dispatchTrackInternal(e),n};dispatchTrack(e){this.dispatchTrackInternal(new _.MediaStreamTrackMock(e))}dispatchTrackInternal(e,...t){const n=new Event("track");Object.defineProperty(n,"track",{value:e}),Object.defineProperty(n,"streams",{value:t.length===0?[new MediaStream([e])]:t}),this.dispatchEvent(n)}}function ot(r){const e=r.match(/(purgatory)|[\d.]+/g);if(!e)throw new Error("wrong sip url");return e[0]}const M=400,F="777",it=r=>r.getVideoTracks().length>0;class s extends nt{static presentationError;static startPresentationError;static countStartPresentationError=Number.POSITIVE_INFINITY;static countStartsPresentation=0;url;status_code;renegotiate=jest.fn(async()=>!0);answer=jest.fn(({mediaStream:e})=>{if(this.originator!=="remote")throw new Error("answer available only for remote sessions");this.initPeerconnection(e),setTimeout(()=>{this.trigger("connecting"),setTimeout(()=>{this.trigger("accepted")},100),setTimeout(()=>{this.trigger("confirmed")},200)},M)});replaceMediaStream=jest.fn(async e=>{});_isReadyToReOffer=jest.fn(()=>!0);restartIce=jest.fn(async e=>!0);isEndedInner=!1;delayStartPresentation=0;timeoutStartPresentation;timeoutConnect;timeoutNewInfo;timeoutAccepted;timeoutConfirmed;constructor({eventHandlers:e,originator:t,remoteIdentity:n=new a.NameAddrHeader(new a.URI("sip","caller1","test1.com",5060),"Test Caller 1"),delayStartPresentation:o=0}){super({originator:t,eventHandlers:e,remoteIdentity:n}),this.delayStartPresentation=o}static get C(){return a.SessionStatus}static setPresentationError(e){this.presentationError=e}static resetPresentationError(){this.presentationError=void 0}static setStartPresentationError(e,{count:t=Number.POSITIVE_INFINITY}={}){this.startPresentationError=e,this.countStartPresentationError=t}static resetStartPresentationError(){this.startPresentationError=void 0,this.countStartPresentationError=Number.POSITIVE_INFINITY,this.countStartsPresentation=0}startPresentation=async e=>(s.countStartsPresentation+=1,new Promise((t,n)=>{this.timeoutStartPresentation=setTimeout(()=>{if(s.presentationError){this.trigger("presentation:start",e),this.trigger("presentation:failed",e),n(s.presentationError);return}if(s.startPresentationError&&s.countStartsPresentation<s.countStartPresentationError){this.trigger("presentation:start",e),this.trigger("presentation:failed",e),n(s.startPresentationError);return}t(super.startPresentation(e))},this.delayStartPresentation)}));stopPresentation=async e=>{if(s.presentationError)throw this.trigger("presentation:end",e),this.trigger("presentation:failed",e),s.presentationError;return super.stopPresentation(e)};initPeerconnection(e){return e?(this.createPeerconnection(e),!0):!1}createPeerconnection(e){const t=_.createAudioMediaStreamTrackMock();t.id="mainaudio1";const n=[t];if(it(e)){const c=_.createVideoMediaStreamTrackMock();c.id="mainvideo1",n.push(c)}this.connection=new rt(void 0,n),this.trigger("peerconnection",{peerconnection:this.connection}),this.addStream(e)}connect(e,{mediaStream:t}={}){const n=ot(e);return this.initPeerconnection(t),this.timeoutConnect=setTimeout(()=>{e.includes(F)?this.trigger("failed",{originator:"remote",message:"IncomingResponse",cause:"Rejected"}):(this.trigger("connecting"),this.timeoutNewInfo=setTimeout(()=>{this.newInfo({originator:y.Originator.REMOTE,request:{getHeader:o=>o==="content-type"?"application/vinteo.webrtc.roomname":o==="x-webrtc-enter-room"?n:o==="x-webrtc-participant-name"?"Test Caller 1":""}})},100),this.timeoutAccepted=setTimeout(()=>{this.trigger("accepted")},200),this.timeoutConfirmed=setTimeout(()=>{this.trigger("confirmed")},300))},M),this.connection}terminate({status_code:e,cause:t}={}){return this.status_code=e,this.trigger("ended",{status_code:e,cause:t,originator:"local"}),this.isEndedInner=!1,this}async terminateAsync({status_code:e,cause:t}={}){this.terminate({status_code:e,cause:t})}terminateRemote({status_code:e}={}){return this.status_code=e,this.trigger("ended",{status_code:e,originator:"remote"}),this}addStream(e,t="getTracks"){e[t]().forEach(n=>this.connection.addTrack(n,e))}forEachSenders(e){const t=this.connection.getSenders();for(const n of t)e(n);return t}toggleMuteAudio(e){this.forEachSenders(({track:t})=>{t?.kind==="audio"&&(t.enabled=!e)})}toggleMuteVideo(e){this.forEachSenders(({track:t})=>{t?.kind==="video"&&(t.enabled=!e)})}mute(e){e.audio&&(this.mutedOptions.audio=!0,this.toggleMuteAudio(this.mutedOptions.audio)),e.video&&(this.mutedOptions.video=!0,this.toggleMuteVideo(this.mutedOptions.video)),this.onmute(e)}unmute(e){e.audio&&(this.mutedOptions.audio=!1),e.video&&(this.mutedOptions.video=!1),this.trigger("unmuted",e)}isMuted(){return this.mutedOptions}onmute({audio:e,video:t}){this.trigger("muted",{audio:e,video:t})}async sendInfo(){}isEnded(){return this.isEndedInner}newInfo(e){this.trigger("newInfo",e)}clear(){clearTimeout(this.timeoutStartPresentation),clearTimeout(this.timeoutConnect),clearTimeout(this.timeoutNewInfo),clearTimeout(this.timeoutAccepted),clearTimeout(this.timeoutConfirmed)}}class st{extraHeaders=[];setExtraHeaders(e){this.extraHeaders=e}setExtraContactParams(){}}const d="PASSWORD_CORRECT",I="PASSWORD_CORRECT_2",k="NAME_INCORRECT",u=400,g={url:"wss://sipServerUrl/webrtc/wss/",sip_uri:"sip:sipServerUrl;transport=ws",via_transport:"WSS"},O={status_code:200,reason_phrase:"OK"},P={status_code:401,reason_phrase:"Unauthorized"};class i extends v.EventEmitter{static isAvailableTelephony=!0;static startError;static countStartError=Number.POSITIVE_INFINITY;static countStarts=0;events;registratorInner;call=jest.fn((e,t)=>{const{mediaStream:n,eventHandlers:o}=t;return this.session=new s({eventHandlers:o,originator:"local"}),this.session.connect(e,{mediaStream:n}),this.session});sendOptions=jest.fn((e,t,n)=>{console.log("sendOptions",e,t,n)});start=jest.fn(()=>{if(i.countStarts+=1,i.startError&&i.countStarts<i.countStartError){this.trigger("disconnected",i.startError);return}this.register()});stop=jest.fn(()=>{this.startedTimeout&&clearTimeout(this.startedTimeout),this.stopedTimeout&&clearTimeout(this.stopedTimeout),this.unregister(),this.isStarted()?this.stopedTimeout=setTimeout(()=>{this.trigger("disconnected",{error:!0,socket:g})},u):this.trigger("disconnected",{error:!0,socket:g})});removeAllListeners=jest.fn(()=>(this.events.removeEventHandlers(),this));once=jest.fn((e,t)=>(this.events.once(e,t),this));configuration;startedTimeout;stopedTimeout;session;isRegisteredInner;isConnectedInner;constructor(e){super(),this.events=new D.Events(b);const[t,n]=e.uri.split(":"),[o,c]=n.split("@"),p={...e,uri:new a.URI(t,o,c)};this.configuration=p,this.registratorInner=new st}get C(){throw new Error("Method not implemented.")}get status(){throw new Error("Method not implemented.")}get contact(){throw new Error("Method not implemented.")}get transport(){throw new Error("Method not implemented.")}static C(){throw new Error("Method not implemented.")}static setStartError(e,{count:t=Number.POSITIVE_INFINITY}={}){i.startError=e,i.countStartError=t}static resetStartError(){i.startError=void 0,i.countStartError=Number.POSITIVE_INFINITY,i.countStarts=0}static setAvailableTelephony(){i.isAvailableTelephony=!0}static setNotAvailableTelephony(){i.isAvailableTelephony=!1}static reset(){i.resetStartError(),i.setAvailableTelephony()}on(e,t){return this.events.on(e,t),this}sendMessage(){throw new Error("Method not implemented.")}normalizeTarget(){throw new Error("Method not implemented.")}get(){throw new Error("Method not implemented.")}off(e,t){return this.events.off(e,t),this}trigger(e,t){this.events.trigger(e,t)}terminateSessions(){this.session?.terminate()}set(e,t){return this.configuration[e]=t,!0}register(){this.startedTimeout&&clearTimeout(this.startedTimeout);const{password:e,register:t,uri:n}=this.configuration;t===!0&&n.user.includes(k)?(this.isRegisteredInner=!1,this.isConnectedInner=!1,this.startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:P,cause:a.C.causes.REJECTED})},u)):!this.isRegistered()&&t===!0&&(e===d||e===I)?(this.isRegisteredInner=!0,this.startedTimeout=setTimeout(()=>{this.trigger("registered",{response:O})},u)):t===!0&&e!==d&&e!==I&&(this.isRegisteredInner=!1,this.isConnectedInner=!1,this.startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:P,cause:a.C.causes.REJECTED})},u)),i.isAvailableTelephony?(this.trigger("connected",{socket:g}),this.isConnectedInner=!0):this.stop()}unregister(){this.isRegisteredInner=!1,this.isConnectedInner=!1,this.trigger("unregistered",{response:O})}isRegistered(){return this.isRegisteredInner===!0}isConnected(){return this.isConnectedInner===!0}isStarted(){return this.configuration.register===!0&&this.isRegisteredInner===!0||this.configuration.register!==!0&&this.isConnectedInner===!0}newSipEvent(e){this.trigger("sipEvent",e)}registrator(){return this.registratorInner}}class at{url;constructor(e){this.url=e}}class ct extends v.EventEmitter{contentType;body;constructor(e,t){super(),this.contentType=e,this.body=t}}const S="remote",dt=(r,e)=>{const t=new w(e),n={originator:S,request:t,info:new ct("","")};r.newInfo(n)},ht=(r,e)=>{const n={event:"sipEvent",request:new w(e)};r.newSipEvent(n)},Et=(r,{incomingNumber:e="1234",displayName:t,host:n})=>{const o=new s({originator:S,eventHandlers:{}}),c=new a.URI("sip",e,n);o.remote_identity=new a.NameAddrHeader(c,t);const p=new w([]);r.trigger("newRTCSession",{originator:S,session:o,request:p})},ut=(r,e)=>{e?r.trigger("failed",e):r.trigger("failed",r)},N={triggerNewInfo:dt,triggerNewSipEvent:ht,triggerIncomingSession:Et,triggerFailIncomingSession:ut,WebSocketInterface:at,UA:i,C:{INVITE:"INVITE"}},h="user",E="displayName",m="SIP_SERVER_URL",C="SIP_WEB_SOCKET_SERVER_URL",mt=new N.WebSocketInterface(`wss://${C}/webrtc/wss/`),f={displayName:"DISPLAY_NAME",userAgent:"Chrome",sipServerIp:m,sipServerUrl:C},lt={...f,displayName:"DISPLAY_NAME",register:!1},W={...f,user:h,password:d,register:!0,authorizationUser:h},pt={...W,displayName:E},gt={...f,displayName:E,authorizationUser:h,register:!1},l={session_timers:!1,sockets:[mt],user_agent:"Chrome",sdpSemantics:"unified-plan",register_expires:300,connection_recovery_max_interval:6,connection_recovery_min_interval:2},_t={...l,password:d,uri:new a.URI("sip",h,m),display_name:"DISPLAY_NAME",register:!0},Tt={...l,password:d,uri:new a.URI("sip",h,m),display_name:E,register:!0},It={...l,display_name:E,register:!1},St={...l,display_name:"DISPLAY_NAME",register:!1},V="10.10.10.10",wt=[`X-Vinteo-Remote: ${V}`],Nt=()=>new y.SipConnector({JsSIP:N});exports.FAILED_CONFERENCE_NUMBER=F;exports.JsSIP=N;exports.NAME_INCORRECT=k;exports.PASSWORD_CORRECT=d;exports.PASSWORD_CORRECT_2=I;exports.SIP_SERVER_URL=m;exports.SIP_WEB_SOCKET_SERVER_URL=C;exports.dataForConnectionWithAuthorization=W;exports.dataForConnectionWithAuthorizationWithDisplayName=pt;exports.dataForConnectionWithoutAuthorization=gt;exports.dataForConnectionWithoutAuthorizationWithoutDisplayName=lt;exports.displayName=E;exports.doMockSipConnector=Nt;exports.extraHeadersRemoteAddress=wt;exports.remoteAddress=V;exports.uaConfigurationWithAuthorization=_t;exports.uaConfigurationWithAuthorizationWithDisplayName=Tt;exports.uaConfigurationWithoutAuthorization=It;exports.uaConfigurationWithoutAuthorizationWithoutDisplayName=St;exports.user=h;
package/dist/doMock.js CHANGED
@@ -2,7 +2,7 @@ import { EventEmitter as O } from "node:events";
2
2
  import { IncomingRequest as k, NameAddrHeader as P, URI as h, SessionStatus as F, C as S } from "@krivega/jssip";
3
3
  import { MediaStreamTrackMock as V, createAudioMediaStreamTrackMock as W, createVideoMediaStreamTrackMock as U } from "webrtc-mock";
4
4
  import { Events as v } from "events-constructor";
5
- import { O as j, S as G } from "./@SipConnector-CJ8rM7Da.js";
5
+ import { O as j, S as G } from "./@SipConnector--DAxFjmB.js";
6
6
  class _ extends k {
7
7
  headers;
8
8
  constructor(e) {
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("./@SipConnector-Br2ML_bB.cjs");require("events-constructor");const B=require("ua-parser-js"),q=require("sequent-promises"),W=require("repeated-calls"),$=require("@krivega/cancelable-promise"),Y=require("ts-debounce"),H=require("stack-promises"),j=()=>globalThis.process?.versions?.electron!==void 0,k=()=>{const e=new B.UAParser,{name:n}=e.getBrowser(),r=j();return{isChrome:n==="Chrome"||r}},A=e=>{const{url:n,cause:r}=e;let o=n;return(r===t.ECallCause.BAD_MEDIA_DESCRIPTION||r===t.ECallCause.NOT_FOUND)&&(o=`${e.message.to.uri.user}@${e.message.to.uri.host}`),o};var G=(e=>(e.CONNECT_SERVER_FAILED="CONNECT_SERVER_FAILED",e.WRONG_USER_OR_PASSWORD="WRONG_USER_OR_PASSWORD",e.BAD_MEDIA_ERROR="BAD_MEDIA_ERROR",e.NOT_FOUND_ERROR="NOT_FOUND_ERROR",e.WS_CONNECTION_FAILED="WS_CONNECTION_FAILED",e.CONNECT_SERVER_FAILED_BY_LINK="CONNECT_SERVER_FAILED_BY_LINK",e))(G||{});const K=new Error("Unknown error"),X=(e=K)=>{const{cause:n,socket:r}=e;let o="CONNECT_SERVER_FAILED";switch(n){case"Forbidden":{o="WRONG_USER_OR_PASSWORD";break}case t.ECallCause.BAD_MEDIA_DESCRIPTION:{o="BAD_MEDIA_ERROR";break}case t.ECallCause.NOT_FOUND:{o="NOT_FOUND_ERROR";break}default:r!==void 0&&r._ws?.readyState===3?o="WS_CONNECTION_FAILED":A(e)!==void 0&&A(e)!==""&&(o="CONNECT_SERVER_FAILED_BY_LINK")}return o},J=e=>{let n="";try{n=JSON.stringify(e)}catch(r){t.logger("failed to stringify message",r)}return n},z=new Error("Unknown error"),Q=(e=z)=>{const{code:n,cause:r,message:o}=e,a=A(e),s={code:"",cause:"",message:""};return typeof o=="object"&&o!==null?s.message=J(o):o&&(s.message=String(o)),a!==void 0&&a!==""&&(s.link=a),n!==void 0&&n!==""&&(s.code=n),r!==void 0&&r!==""&&(s.cause=r),s},Z=Object.freeze(Object.defineProperty({__proto__:null,EErrorTypes:G,getLinkError:A,getTypeFromError:X,getValuesFromError:Q},Symbol.toStringTag,{value:"Module"})),ee=({sessionId:e,remoteAddress:n,isMutedAudio:r,isMutedVideo:o,isRegistered:a,isPresentationCall:s})=>{const c=[],l=r?"0":"1",C=o?"0":"1";return c.push(`X-Vinteo-Mic-State: ${l}`,`X-Vinteo-MainCam-State: ${C}`),(a===!1||a===void 0)&&c.push("X-Vinteo-Purgatory-Call: yes"),e!==void 0&&e!==""&&c.push(`X-Vinteo-Session: ${e}`),s===!0&&c.push("X-Vinteo-Presentation-Call: yes"),n!==void 0&&n!==""&&c.push(`X-Vinteo-Remote: ${n}`),c},ne="[@*!|]",te="_",re=e=>{let n=e;return n=n.replaceAll(new RegExp(ne,"g"),te),n},oe=({appName:e,appVersion:n,browserName:r,browserVersion:o})=>{const s=`${re(e)} ${n}`;return`ChromeNew - ${r===void 0?s:`${r} ${o}, ${s}`}`},se=({isUnifiedSdpSemantic:e,appVersion:n,browserName:r,browserVersion:o,appName:a})=>e?oe({appVersion:n,browserName:r,browserVersion:o,appName:a}):"Chrome",ae=e=>n=>[...n].map(o=>async()=>e(o)),ce=async({accumulatedKeys:e,sendKey:n,canRunTask:r})=>{const a=ae(n)(e);return q.sequentPromises(a,r)},ie=e=>r=>(t.logger("onStartMainCam"),e.on("api:admin:start-main-cam",r)),le=e=>r=>(t.logger("onStartMic"),e.on("api:admin:start-mic",r)),ue=e=>r=>(t.logger("onStopMainCam"),e.on("api:admin:stop-main-cam",r)),Ce=e=>r=>(t.logger("onStopMic"),e.on("api:admin:stop-mic",r)),ge=({sipConnector:e})=>{const n=(u,g)=>({isSyncForced:d})=>{if(d===!0){u();return}g()},r=ie(e),o=ue(e),a=le(e),s=Ce(e);let c,l,C,p;const O=({onStartMainCamForced:u,onStartMainCamNotForced:g,onStopMainCamForced:d,onStopMainCamNotForced:h,onStartMicForced:N,onStartMicNotForced:_,onStopMicForced:b,onStopMicNotForced:v})=>{const E=n(u,g);c=r(E);const f=n(d,h);l=o(f);const I=n(N,_);C=a(I);const m=n(b,v);p=s(m)},T=()=>{c?.(),l?.(),C?.(),p?.()};return{start:u=>{O(u)},stop:()=>{T()}}},Se=Object.freeze(Object.defineProperty({__proto__:null,DeferredCommandRunner:t.DeferredCommandRunner,PURGATORY_CONFERENCE_NUMBER:t.PURGATORY_CONFERENCE_NUMBER,createSyncMediaState:ge,createUaParser:k,error:Z,getExtraHeaders:ee,getUserAgent:se,hasPeerToPeer:t.hasPeerToPeer,hasPurgatory:t.hasPurgatory,prepareMediaStream:t.prepareMediaStream,sendDtmfAccumulated:ce,sendOffer:t.sendOffer,setEncodingsToSender:t.setEncodingsToSender,setParametersToSender:t.setParametersToSender},Symbol.toStringTag,{value:"Module"})),de=e=>e instanceof Object&&("originator"in e||"cause"in e),Ee=e=>{if($.isCanceledError(e))return!0;if(!de(e))return!1;const{originator:n,cause:r}=e;return typeof r=="string"?r===t.ECallCause.REQUEST_TIMEOUT||r===t.ECallCause.REJECTED||n==="local"&&(r===t.ECallCause.CANCELED||r===t.ECallCause.BYE):!1};var S=(e=>(e.DISCONNECTED="system:disconnected",e.DISCONNECTING="system:disconnecting",e.CONNECTING="system:connecting",e.READY_TO_CALL="system:readyToCall",e.CALL_CONNECTING="system:callConnecting",e.CALL_DISCONNECTING="system:callDisconnecting",e.CALL_ACTIVE="system:callActive",e))(S||{});const V=e=>e.connection.value,fe=e=>e.call,F=e=>e.call.value,me=e=>e.incoming.value,pe=e=>{if(e.incoming.value!==t.EState$2.IDLE)return e.incoming.context.remoteCallerData},Re=e=>e.presentation.value,he=e=>{const n=F(e);return n===t.EState.IN_ROOM||n===t.EState.PURGATORY||n===t.EState.P2P_ROOM||n===t.EState.DIRECT_P2P_ROOM},Ne=e=>{const n=F(e);if(n===t.EState.IN_ROOM||n===t.EState.PURGATORY||n===t.EState.P2P_ROOM||n===t.EState.DIRECT_P2P_ROOM)return S.CALL_ACTIVE;const r=V(e);if(r===t.EState$1.IDLE||r===t.EState$1.DISCONNECTED)return S.DISCONNECTED;if(r===t.EState$1.DISCONNECTING)return S.DISCONNECTING;if(r===t.EState$1.PREPARING||r===t.EState$1.CONNECTING||r===t.EState$1.CONNECTED||r===t.EState$1.REGISTERED)return S.CONNECTING;switch(n){case t.EState.IDLE:return S.READY_TO_CALL;case t.EState.CONNECTING:return S.CALL_CONNECTING;case t.EState.DISCONNECTING:return S.CALL_DISCONNECTING;default:return S.READY_TO_CALL}},Oe={selectConnectionStatus:V,selectCallState:fe,selectCallStatus:F,selectIncomingStatus:me,selectIncomingRemoteCaller:pe,selectPresentationStatus:Re,selectIsInCall:he,selectSystemStatus:Ne},Te=()=>k().isChrome,Pe=e=>{if(!$.isCanceledError(e)&&!W.hasCanceledError(e)&&!t.hasNotReadyForConnectionError(e))throw e;return{configuration:void 0,isSuccessful:!1}},_e=({kind:e,readyState:n})=>e==="video"&&n==="live",L=(e,n,{onEnterPurgatory:r,onEnterConference:o})=>{t.hasPurgatory(e)?r&&r():o&&o({isSuccessProgressCall:n})},w=(e,n)=>{e(),n&&n()},U=(e,n,r)=>{throw e&&e(),n(),r},be=new Set(["on","once","onceRace","wait","off","sendDTMF","hangUp","declineToIncomingCall","sendChannels","checkTelephony","waitChannels","ping","startAutoConnect","stopAutoConnect","connection","isConfigured","isRegistered"]);class ve{on;once;onceRace;wait;off;sendDTMF;hangUp;declineToIncomingCall;sendChannels;checkTelephony;waitChannels;ping;startAutoConnect;stopAutoConnect;connection;isConfigured;isRegistered;sipConnector;constructor(n){return this.sipConnector=n,new Proxy(this,{get:(r,o,a)=>{if(typeof o=="string"&&be.has(o)&&o in this.sipConnector){const c=Reflect.get(this.sipConnector,o,this.sipConnector);return typeof c=="function"?c.bind(this.sipConnector):c}const s=Reflect.get(r,o,a);return typeof s=="function"?s.bind(r):s}})}connectToServer=async(n,r)=>this.sipConnector.connect(n,r).then(o=>(t.logger("connectToServer then"),{configuration:o,isSuccessful:!0})).catch(async o=>(t.logger("connectToServer catch: error",o),Pe(o)));callToServer=async n=>{const{conference:r,mediaStream:o,extraHeaders:a,iceServers:s,contentHint:c,degradationPreference:l,sendEncodings:C,offerToReceiveAudio:p,offerToReceiveVideo:O,directionVideo:T,directionAudio:P,onBeforeProgressCall:R,onSuccessProgressCall:u,onEnterPurgatory:g,onEnterConference:d,onFailProgressCall:h,onFinishProgressCall:N,onEndedCall:_,onAddedTransceiver:b}=n;t.logger("callToServer",n);const v=async()=>(t.logger("startCall"),this.sipConnector.call({mediaStream:o,extraHeaders:a,iceServers:s,contentHint:c,offerToReceiveAudio:p,offerToReceiveVideo:O,directionVideo:T,directionAudio:P,degradationPreference:l,onAddedTransceiver:b,sendEncodings:C,number:r}));let E=!1,f;const m=(t.logger("subscribeEnterConference: onEnterConference",d),this.sipConnector.on("api:enter-room",({room:i})=>{t.logger("enterRoom",{_room:i,isSuccessProgressCall:E}),f=i,(g??d)&&L(f,E,{onEnterPurgatory:g,onEnterConference:d})})),D=i=>(t.logger("onSuccess"),E=!0,u&&u({isPurgatory:t.hasPurgatory(f)}),this.sipConnector.onceRace(["call:ended","call:failed"],()=>{w(m,_)}),i),M=i=>(t.logger("onFail"),U(h,m,i)),y=()=>{t.logger("onFinish"),N&&N()};return t.logger("onBeforeProgressCall"),R&&R(r),v().then(D).catch(i=>M(i)).finally(y)};disconnectFromServer=async()=>this.sipConnector.disconnect().then(()=>(t.logger("disconnectFromServer: then"),{isSuccessful:!0})).catch(n=>(t.logger("disconnectFromServer: catch",n),{isSuccessful:!1}));answerToIncomingCall=async n=>{const{mediaStream:r,extraHeaders:o,iceServers:a,contentHint:s,degradationPreference:c,sendEncodings:l,offerToReceiveAudio:C,offerToReceiveVideo:p,directionVideo:O,directionAudio:T,onBeforeProgressCall:P,onSuccessProgressCall:R,onEnterPurgatory:u,onEnterConference:g,onFailProgressCall:d,onFinishProgressCall:h,onEndedCall:N,onAddedTransceiver:_}=n;t.logger("answerToIncomingCall",n);const b=async()=>this.sipConnector.answerToIncomingCall({mediaStream:r,extraHeaders:o,iceServers:a,contentHint:s,offerToReceiveAudio:C,offerToReceiveVideo:p,directionVideo:O,directionAudio:T,degradationPreference:c,onAddedTransceiver:_,sendEncodings:l}),v=()=>{const{remoteCallerData:i}=this.sipConnector;return i?.incomingNumber};let E=!1,f;const m=(t.logger("subscribeEnterConference: onEnterConference",g),this.sipConnector.on("api:enter-room",i=>{t.logger("enterRoom",{room:i.room,isSuccessProgressCall:E}),f=i.room,(u??g)&&L(f,E,{onEnterPurgatory:u,onEnterConference:g})})),D=i=>(t.logger("onSuccess"),E=!0,R&&R({isPurgatory:t.hasPurgatory(f)}),this.sipConnector.onceRace(["call:ended","call:failed"],()=>{w(m,N)}),i),M=i=>(t.logger("onFail"),U(d,m,i)),y=()=>{t.logger("onFinish"),h&&h()};if(t.logger("onBeforeProgressCall"),P){const i=v();P(i)}return b().then(D).catch(i=>M(i)).finally(y)};updatePresentation=async({mediaStream:n,contentHint:r,degradationPreference:o,sendEncodings:a,onAddedTransceiver:s})=>(t.logger("updatePresentation"),this.sipConnector.updatePresentation(n,{contentHint:r,degradationPreference:o,onAddedTransceiver:s,sendEncodings:a}));startPresentation=async({mediaStream:n,contentHint:r,degradationPreference:o,sendEncodings:a,callLimit:s,onAddedTransceiver:c})=>(t.logger("startPresentation"),this.sipConnector.startPresentation(n,{contentHint:r,callLimit:s,degradationPreference:o,onAddedTransceiver:c,sendEncodings:a}));stopPresentation=async()=>(t.logger("stopPresentation"),this.sipConnector.stopPresentation().catch(n=>{t.logger(n)}));sendRefusalToTurnOnMic=async()=>{t.logger("sendRefusalToTurnOnMic"),await this.sipConnector.sendRefusalToTurnOnMic().catch(n=>{t.logger("sendRefusalToTurnOnMic: error",n)})};sendRefusalToTurnOnCam=async()=>{t.logger("sendRefusalToTurnOnCam"),await this.sipConnector.sendRefusalToTurnOnCam().catch(n=>{t.logger("sendRefusalToTurnOnCam: error",n)})};sendMediaState=async({isEnabledCam:n,isEnabledMic:r})=>{t.logger("sendMediaState"),await this.sipConnector.sendMediaState({cam:n,mic:r})};replaceMediaStream=async(n,{deleteExisting:r,addMissing:o,forceRenegotiation:a,contentHint:s,degradationPreference:c,sendEncodings:l,onAddedTransceiver:C})=>(t.logger("replaceMediaStream"),this.sipConnector.replaceMediaStream(n,{deleteExisting:r,addMissing:o,forceRenegotiation:a,contentHint:s,degradationPreference:c,onAddedTransceiver:C,sendEncodings:l}));askPermissionToEnableCam=async()=>{t.logger("askPermissionToEnableCam"),await this.sipConnector.askPermissionToEnableCam()};resolveHandleReadyRemoteStreamsDebounced=({onReadyRemoteStreams:n})=>Y.debounce(()=>{const r=this.sipConnector.getRemoteStreams();t.logger("remoteStreams",r),n(r)},200);resolveHandleReadyRemoteStreams=({onReadyRemoteStreams:n})=>({track:r})=>{_e(r)&&n()};getRemoteStreams=()=>(t.logger("getRemoteStreams"),this.sipConnector.getRemoteStreams());onUseLicense=n=>(t.logger("onUseLicense"),this.sipConnector.on("api:use-license",n));onMustStopPresentation=n=>(t.logger("onMustStopPresentation"),this.sipConnector.on("api:presentation:must-stop",n));onMoveToSpectators=n=>(t.logger("onMoveToSpectators"),this.sipConnector.on("api:participant:move-request-to-spectators",n));onMoveToParticipants=n=>(t.logger("onMoveToParticipants"),this.sipConnector.on("api:participant:move-request-to-participants",n));onStats=n=>(t.logger("onStats"),this.sipConnector.on("stats:collected",n));offStats=n=>{t.logger("offStats"),this.sipConnector.off("stats:collected",n)}}var x=(e=>(e.VP8="video/VP8",e.VP9="video/VP9",e.H264="video/H264",e.AV1="video/AV1",e.rtx="video/rtx",e.red="video/red",e.flexfec03="video/flexfec-03",e))(x||{});exports.ECallCause=t.ECallCause;exports.ECallStatus=t.EState;exports.EConnectionStatus=t.EState$1;exports.EContentUseLicense=t.EContentUseLicense;exports.EIncomingStatus=t.EState$2;exports.EPresentationStatus=t.EState$3;exports.EStatsTypes=t.EStatsTypes;exports.SipConnector=t.SipConnector;exports.StatsPeerConnection=t.StatsPeerConnection;exports.disableDebug=t.disableDebug;exports.enableDebug=t.enableDebug;exports.getCodecFromSender=t.getCodecFromSender;exports.hasCanceledStartPresentationError=t.hasCanceledStartPresentationError;Object.defineProperty(exports,"hasConnectionPromiseIsNotActualError",{enumerable:!0,get:()=>H.isPromiseIsNotActualError});exports.EMimeTypesVideoCodecs=x;exports.ESystemStatus=S;exports.SipConnectorFacade=ve;exports.hasAvailableStats=Te;exports.hasCanceledCallError=Ee;exports.sessionSelectors=Oe;exports.tools=Se;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("./@SipConnector-w-Nwup6s.cjs");require("events-constructor");const B=require("ua-parser-js"),q=require("sequent-promises"),W=require("repeated-calls"),$=require("@krivega/cancelable-promise"),Y=require("ts-debounce"),H=require("stack-promises"),j=()=>globalThis.process?.versions?.electron!==void 0,k=()=>{const e=new B.UAParser,{name:n}=e.getBrowser(),r=j();return{isChrome:n==="Chrome"||r}},A=e=>{const{url:n,cause:r}=e;let o=n;return(r===t.ECallCause.BAD_MEDIA_DESCRIPTION||r===t.ECallCause.NOT_FOUND)&&(o=`${e.message.to.uri.user}@${e.message.to.uri.host}`),o};var G=(e=>(e.CONNECT_SERVER_FAILED="CONNECT_SERVER_FAILED",e.WRONG_USER_OR_PASSWORD="WRONG_USER_OR_PASSWORD",e.BAD_MEDIA_ERROR="BAD_MEDIA_ERROR",e.NOT_FOUND_ERROR="NOT_FOUND_ERROR",e.WS_CONNECTION_FAILED="WS_CONNECTION_FAILED",e.CONNECT_SERVER_FAILED_BY_LINK="CONNECT_SERVER_FAILED_BY_LINK",e))(G||{});const K=new Error("Unknown error"),X=(e=K)=>{const{cause:n,socket:r}=e;let o="CONNECT_SERVER_FAILED";switch(n){case"Forbidden":{o="WRONG_USER_OR_PASSWORD";break}case t.ECallCause.BAD_MEDIA_DESCRIPTION:{o="BAD_MEDIA_ERROR";break}case t.ECallCause.NOT_FOUND:{o="NOT_FOUND_ERROR";break}default:r!==void 0&&r._ws?.readyState===3?o="WS_CONNECTION_FAILED":A(e)!==void 0&&A(e)!==""&&(o="CONNECT_SERVER_FAILED_BY_LINK")}return o},J=e=>{let n="";try{n=JSON.stringify(e)}catch(r){t.logger("failed to stringify message",r)}return n},z=new Error("Unknown error"),Q=(e=z)=>{const{code:n,cause:r,message:o}=e,a=A(e),s={code:"",cause:"",message:""};return typeof o=="object"&&o!==null?s.message=J(o):o&&(s.message=String(o)),a!==void 0&&a!==""&&(s.link=a),n!==void 0&&n!==""&&(s.code=n),r!==void 0&&r!==""&&(s.cause=r),s},Z=Object.freeze(Object.defineProperty({__proto__:null,EErrorTypes:G,getLinkError:A,getTypeFromError:X,getValuesFromError:Q},Symbol.toStringTag,{value:"Module"})),ee=({sessionId:e,remoteAddress:n,isMutedAudio:r,isMutedVideo:o,isRegistered:a,isPresentationCall:s})=>{const c=[],l=r?"0":"1",C=o?"0":"1";return c.push(`X-Vinteo-Mic-State: ${l}`,`X-Vinteo-MainCam-State: ${C}`),(a===!1||a===void 0)&&c.push("X-Vinteo-Purgatory-Call: yes"),e!==void 0&&e!==""&&c.push(`X-Vinteo-Session: ${e}`),s===!0&&c.push("X-Vinteo-Presentation-Call: yes"),n!==void 0&&n!==""&&c.push(`X-Vinteo-Remote: ${n}`),c},ne="[@*!|]",te="_",re=e=>{let n=e;return n=n.replaceAll(new RegExp(ne,"g"),te),n},oe=({appName:e,appVersion:n,browserName:r,browserVersion:o})=>{const s=`${re(e)} ${n}`;return`ChromeNew - ${r===void 0?s:`${r} ${o}, ${s}`}`},se=({isUnifiedSdpSemantic:e,appVersion:n,browserName:r,browserVersion:o,appName:a})=>e?oe({appVersion:n,browserName:r,browserVersion:o,appName:a}):"Chrome",ae=e=>n=>[...n].map(o=>async()=>e(o)),ce=async({accumulatedKeys:e,sendKey:n,canRunTask:r})=>{const a=ae(n)(e);return q.sequentPromises(a,r)},ie=e=>r=>(t.logger("onStartMainCam"),e.on("api:admin:start-main-cam",r)),le=e=>r=>(t.logger("onStartMic"),e.on("api:admin:start-mic",r)),ue=e=>r=>(t.logger("onStopMainCam"),e.on("api:admin:stop-main-cam",r)),Ce=e=>r=>(t.logger("onStopMic"),e.on("api:admin:stop-mic",r)),ge=({sipConnector:e})=>{const n=(u,g)=>({isSyncForced:d})=>{if(d===!0){u();return}g()},r=ie(e),o=ue(e),a=le(e),s=Ce(e);let c,l,C,p;const O=({onStartMainCamForced:u,onStartMainCamNotForced:g,onStopMainCamForced:d,onStopMainCamNotForced:h,onStartMicForced:N,onStartMicNotForced:_,onStopMicForced:b,onStopMicNotForced:v})=>{const E=n(u,g);c=r(E);const f=n(d,h);l=o(f);const I=n(N,_);C=a(I);const m=n(b,v);p=s(m)},T=()=>{c?.(),l?.(),C?.(),p?.()};return{start:u=>{O(u)},stop:()=>{T()}}},Se=Object.freeze(Object.defineProperty({__proto__:null,DeferredCommandRunner:t.DeferredCommandRunner,PURGATORY_CONFERENCE_NUMBER:t.PURGATORY_CONFERENCE_NUMBER,createSyncMediaState:ge,createUaParser:k,error:Z,getExtraHeaders:ee,getUserAgent:se,hasPeerToPeer:t.hasPeerToPeer,hasPurgatory:t.hasPurgatory,prepareMediaStream:t.prepareMediaStream,sendDtmfAccumulated:ce,sendOffer:t.sendOffer,setEncodingsToSender:t.setEncodingsToSender,setParametersToSender:t.setParametersToSender},Symbol.toStringTag,{value:"Module"})),de=e=>e instanceof Object&&("originator"in e||"cause"in e),Ee=e=>{if($.isCanceledError(e))return!0;if(!de(e))return!1;const{originator:n,cause:r}=e;return typeof r=="string"?r===t.ECallCause.REQUEST_TIMEOUT||r===t.ECallCause.REJECTED||n==="local"&&(r===t.ECallCause.CANCELED||r===t.ECallCause.BYE):!1};var S=(e=>(e.DISCONNECTED="system:disconnected",e.DISCONNECTING="system:disconnecting",e.CONNECTING="system:connecting",e.READY_TO_CALL="system:readyToCall",e.CALL_CONNECTING="system:callConnecting",e.CALL_DISCONNECTING="system:callDisconnecting",e.CALL_ACTIVE="system:callActive",e))(S||{});const V=e=>e.connection.value,fe=e=>e.call,F=e=>e.call.value,me=e=>e.incoming.value,pe=e=>{if(e.incoming.value!==t.EState$2.IDLE)return e.incoming.context.remoteCallerData},Re=e=>e.presentation.value,he=e=>{const n=F(e);return n===t.EState.IN_ROOM||n===t.EState.PURGATORY||n===t.EState.P2P_ROOM||n===t.EState.DIRECT_P2P_ROOM},Ne=e=>{const n=F(e);if(n===t.EState.IN_ROOM||n===t.EState.PURGATORY||n===t.EState.P2P_ROOM||n===t.EState.DIRECT_P2P_ROOM)return S.CALL_ACTIVE;const r=V(e);if(r===t.EState$1.IDLE||r===t.EState$1.DISCONNECTED)return S.DISCONNECTED;if(r===t.EState$1.DISCONNECTING)return S.DISCONNECTING;if(r===t.EState$1.PREPARING||r===t.EState$1.CONNECTING||r===t.EState$1.CONNECTED||r===t.EState$1.REGISTERED)return S.CONNECTING;switch(n){case t.EState.IDLE:return S.READY_TO_CALL;case t.EState.CONNECTING:return S.CALL_CONNECTING;case t.EState.DISCONNECTING:return S.CALL_DISCONNECTING;default:return S.READY_TO_CALL}},Oe={selectConnectionStatus:V,selectCallState:fe,selectCallStatus:F,selectIncomingStatus:me,selectIncomingRemoteCaller:pe,selectPresentationStatus:Re,selectIsInCall:he,selectSystemStatus:Ne},Te=()=>k().isChrome,Pe=e=>{if(!$.isCanceledError(e)&&!W.hasCanceledError(e)&&!t.hasNotReadyForConnectionError(e))throw e;return{configuration:void 0,isSuccessful:!1}},_e=({kind:e,readyState:n})=>e==="video"&&n==="live",L=(e,n,{onEnterPurgatory:r,onEnterConference:o})=>{t.hasPurgatory(e)?r&&r():o&&o({isSuccessProgressCall:n})},w=(e,n)=>{e(),n&&n()},U=(e,n,r)=>{throw e&&e(),n(),r},be=new Set(["on","once","onceRace","wait","off","sendDTMF","hangUp","declineToIncomingCall","sendChannels","checkTelephony","waitChannels","ping","startAutoConnect","stopAutoConnect","connection","isConfigured","isRegistered"]);class ve{on;once;onceRace;wait;off;sendDTMF;hangUp;declineToIncomingCall;sendChannels;checkTelephony;waitChannels;ping;startAutoConnect;stopAutoConnect;connection;isConfigured;isRegistered;sipConnector;constructor(n){return this.sipConnector=n,new Proxy(this,{get:(r,o,a)=>{if(typeof o=="string"&&be.has(o)&&o in this.sipConnector){const c=Reflect.get(this.sipConnector,o,this.sipConnector);return typeof c=="function"?c.bind(this.sipConnector):c}const s=Reflect.get(r,o,a);return typeof s=="function"?s.bind(r):s}})}connectToServer=async(n,r)=>this.sipConnector.connect(n,r).then(o=>(t.logger("connectToServer then"),{configuration:o,isSuccessful:!0})).catch(async o=>(t.logger("connectToServer catch: error",o),Pe(o)));callToServer=async n=>{const{conference:r,mediaStream:o,extraHeaders:a,iceServers:s,contentHint:c,degradationPreference:l,sendEncodings:C,offerToReceiveAudio:p,offerToReceiveVideo:O,directionVideo:T,directionAudio:P,onBeforeProgressCall:R,onSuccessProgressCall:u,onEnterPurgatory:g,onEnterConference:d,onFailProgressCall:h,onFinishProgressCall:N,onEndedCall:_,onAddedTransceiver:b}=n;t.logger("callToServer",n);const v=async()=>(t.logger("startCall"),this.sipConnector.call({mediaStream:o,extraHeaders:a,iceServers:s,contentHint:c,offerToReceiveAudio:p,offerToReceiveVideo:O,directionVideo:T,directionAudio:P,degradationPreference:l,onAddedTransceiver:b,sendEncodings:C,number:r}));let E=!1,f;const m=(t.logger("subscribeEnterConference: onEnterConference",d),this.sipConnector.on("api:enter-room",({room:i})=>{t.logger("enterRoom",{_room:i,isSuccessProgressCall:E}),f=i,(g??d)&&L(f,E,{onEnterPurgatory:g,onEnterConference:d})})),D=i=>(t.logger("onSuccess"),E=!0,u&&u({isPurgatory:t.hasPurgatory(f)}),this.sipConnector.onceRace(["call:ended","call:failed"],()=>{w(m,_)}),i),M=i=>(t.logger("onFail"),U(h,m,i)),y=()=>{t.logger("onFinish"),N&&N()};return t.logger("onBeforeProgressCall"),R&&R(r),v().then(D).catch(i=>M(i)).finally(y)};disconnectFromServer=async()=>this.sipConnector.disconnect().then(()=>(t.logger("disconnectFromServer: then"),{isSuccessful:!0})).catch(n=>(t.logger("disconnectFromServer: catch",n),{isSuccessful:!1}));answerToIncomingCall=async n=>{const{mediaStream:r,extraHeaders:o,iceServers:a,contentHint:s,degradationPreference:c,sendEncodings:l,offerToReceiveAudio:C,offerToReceiveVideo:p,directionVideo:O,directionAudio:T,onBeforeProgressCall:P,onSuccessProgressCall:R,onEnterPurgatory:u,onEnterConference:g,onFailProgressCall:d,onFinishProgressCall:h,onEndedCall:N,onAddedTransceiver:_}=n;t.logger("answerToIncomingCall",n);const b=async()=>this.sipConnector.answerToIncomingCall({mediaStream:r,extraHeaders:o,iceServers:a,contentHint:s,offerToReceiveAudio:C,offerToReceiveVideo:p,directionVideo:O,directionAudio:T,degradationPreference:c,onAddedTransceiver:_,sendEncodings:l}),v=()=>{const{remoteCallerData:i}=this.sipConnector;return i?.incomingNumber};let E=!1,f;const m=(t.logger("subscribeEnterConference: onEnterConference",g),this.sipConnector.on("api:enter-room",i=>{t.logger("enterRoom",{room:i.room,isSuccessProgressCall:E}),f=i.room,(u??g)&&L(f,E,{onEnterPurgatory:u,onEnterConference:g})})),D=i=>(t.logger("onSuccess"),E=!0,R&&R({isPurgatory:t.hasPurgatory(f)}),this.sipConnector.onceRace(["call:ended","call:failed"],()=>{w(m,N)}),i),M=i=>(t.logger("onFail"),U(d,m,i)),y=()=>{t.logger("onFinish"),h&&h()};if(t.logger("onBeforeProgressCall"),P){const i=v();P(i)}return b().then(D).catch(i=>M(i)).finally(y)};updatePresentation=async({mediaStream:n,contentHint:r,degradationPreference:o,sendEncodings:a,onAddedTransceiver:s})=>(t.logger("updatePresentation"),this.sipConnector.updatePresentation(n,{contentHint:r,degradationPreference:o,onAddedTransceiver:s,sendEncodings:a}));startPresentation=async({mediaStream:n,contentHint:r,degradationPreference:o,sendEncodings:a,callLimit:s,onAddedTransceiver:c})=>(t.logger("startPresentation"),this.sipConnector.startPresentation(n,{contentHint:r,callLimit:s,degradationPreference:o,onAddedTransceiver:c,sendEncodings:a}));stopPresentation=async()=>(t.logger("stopPresentation"),this.sipConnector.stopPresentation().catch(n=>{t.logger(n)}));sendRefusalToTurnOnMic=async()=>{t.logger("sendRefusalToTurnOnMic"),await this.sipConnector.sendRefusalToTurnOnMic().catch(n=>{t.logger("sendRefusalToTurnOnMic: error",n)})};sendRefusalToTurnOnCam=async()=>{t.logger("sendRefusalToTurnOnCam"),await this.sipConnector.sendRefusalToTurnOnCam().catch(n=>{t.logger("sendRefusalToTurnOnCam: error",n)})};sendMediaState=async({isEnabledCam:n,isEnabledMic:r})=>{t.logger("sendMediaState"),await this.sipConnector.sendMediaState({cam:n,mic:r})};replaceMediaStream=async(n,{deleteExisting:r,addMissing:o,forceRenegotiation:a,contentHint:s,degradationPreference:c,sendEncodings:l,onAddedTransceiver:C})=>(t.logger("replaceMediaStream"),this.sipConnector.replaceMediaStream(n,{deleteExisting:r,addMissing:o,forceRenegotiation:a,contentHint:s,degradationPreference:c,onAddedTransceiver:C,sendEncodings:l}));askPermissionToEnableCam=async()=>{t.logger("askPermissionToEnableCam"),await this.sipConnector.askPermissionToEnableCam()};resolveHandleReadyRemoteStreamsDebounced=({onReadyRemoteStreams:n})=>Y.debounce(()=>{const r=this.sipConnector.getRemoteStreams();t.logger("remoteStreams",r),n(r)},200);resolveHandleReadyRemoteStreams=({onReadyRemoteStreams:n})=>({track:r})=>{_e(r)&&n()};getRemoteStreams=()=>(t.logger("getRemoteStreams"),this.sipConnector.getRemoteStreams());onUseLicense=n=>(t.logger("onUseLicense"),this.sipConnector.on("api:use-license",n));onMustStopPresentation=n=>(t.logger("onMustStopPresentation"),this.sipConnector.on("api:presentation:must-stop",n));onMoveToSpectators=n=>(t.logger("onMoveToSpectators"),this.sipConnector.on("api:participant:move-request-to-spectators",n));onMoveToParticipants=n=>(t.logger("onMoveToParticipants"),this.sipConnector.on("api:participant:move-request-to-participants",n));onStats=n=>(t.logger("onStats"),this.sipConnector.on("stats:collected",n));offStats=n=>{t.logger("offStats"),this.sipConnector.off("stats:collected",n)}}var x=(e=>(e.VP8="video/VP8",e.VP9="video/VP9",e.H264="video/H264",e.AV1="video/AV1",e.rtx="video/rtx",e.red="video/red",e.flexfec03="video/flexfec-03",e))(x||{});exports.ECallCause=t.ECallCause;exports.ECallStatus=t.EState;exports.EConnectionStatus=t.EState$1;exports.EContentUseLicense=t.EContentUseLicense;exports.EIncomingStatus=t.EState$2;exports.EPresentationStatus=t.EState$3;exports.EStatsTypes=t.EStatsTypes;exports.SipConnector=t.SipConnector;exports.StatsPeerConnection=t.StatsPeerConnection;exports.disableDebug=t.disableDebug;exports.enableDebug=t.enableDebug;exports.getCodecFromSender=t.getCodecFromSender;exports.hasCanceledStartPresentationError=t.hasCanceledStartPresentationError;Object.defineProperty(exports,"hasConnectionPromiseIsNotActualError",{enumerable:!0,get:()=>H.isPromiseIsNotActualError});exports.EMimeTypesVideoCodecs=x;exports.ESystemStatus=S;exports.SipConnectorFacade=ve;exports.hasAvailableStats=Te;exports.hasCanceledCallError=Ee;exports.sessionSelectors=Oe;exports.tools=Se;
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { E as R, l as r, D as H, P as j, h as K, a as M, p as X, s as q, b as z, c as J, d as C, e as g, f as Q, g as Z } from "./@SipConnector-CJ8rM7Da.js";
2
- import { i as qe, j as ze, k as Je, S as Qe, m as Ze, n as en, o as nn, q as tn, r as on } from "./@SipConnector-CJ8rM7Da.js";
1
+ import { E as R, l as r, D as H, P as j, h as K, a as M, p as X, s as q, b as z, c as J, d as C, e as g, f as Q, g as Z } from "./@SipConnector--DAxFjmB.js";
2
+ import { i as qe, j as ze, k as Je, S as Qe, m as Ze, n as en, o as nn, q as tn, r as on } from "./@SipConnector--DAxFjmB.js";
3
3
  import "events-constructor";
4
4
  import { UAParser as ee } from "ua-parser-js";
5
5
  import { sequentPromises as ne } from "sequent-promises";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sip-connector",
3
- "version": "26.2.1",
3
+ "version": "26.2.2",
4
4
  "description": "Module for connect to Vinteo server",
5
5
  "keywords": [
6
6
  "webrtc",
@@ -1 +0,0 @@
1
- "use strict";const Re=require("@krivega/jssip"),de=require("debug"),M=require("events-constructor"),H=require("@krivega/cancelable-promise"),B=require("@krivega/timeout-requester"),te=require("repeated-calls"),I=require("xstate"),he=require("stack-promises");require("ua-parser-js");require("sequent-promises");const Et=require("lodash"),le="sip-connector",d=de(le),Ne=(n,e)=>{d(`${n}:`,e)},Ct=()=>{de.enable(le)},mt=()=>{de.enable(`-${le}`)},pt="Error decline with 603",Rt=1006,Nt=n=>typeof n=="object"&&n!==null&&"code"in n&&n.code===Rt,At=n=>n.message===pt;var J=(n=>(n.SPECTATOR="SPECTATOR",n.PARTICIPANT="PARTICIPANT",n))(J||{}),P=(n=>(n.SHARE_STATE="application/vinteo.webrtc.sharedesktop",n.MAIN_CAM="application/vinteo.webrtc.maincam",n.ENTER_ROOM="application/vinteo.webrtc.roomname",n.MIC="application/vinteo.webrtc.mic",n.USE_LICENSE="application/vinteo.webrtc.uselic",n.PARTICIPANT_STATE="application/vinteo.webrtc.partstate",n.NOTIFY="application/vinteo.webrtc.notify",n))(P||{}),O=(n=>(n.SHARE_STATE="application/vinteo.webrtc.sharedesktop",n.MAIN_CAM="application/vinteo.webrtc.maincam",n.CHANNELS="application/vinteo.webrtc.channels",n.MEDIA_STATE="application/vinteo.webrtc.mediastate",n.REFUSAL="application/vinteo.webrtc.refusal",n.STATS="application/vinteo.webrtc.stats",n))(O||{}),b=(n=>(n.PAUSE_MAIN_CAM="PAUSEMAINCAM",n.RESUME_MAIN_CAM="RESUMEMAINCAM",n.MAX_MAIN_CAM_RESOLUTION="MAXMAINCAMRESOLUTION",n.ADMIN_STOP_MAIN_CAM="ADMINSTOPMAINCAM",n.ADMIN_START_MAIN_CAM="ADMINSTARTMAINCAM",n))(b||{}),j=(n=>(n.ADMIN_STOP_MIC="ADMINSTOPMIC",n.ADMIN_START_MIC="ADMINSTARTMIC",n))(j||{}),ye=(n=>(n.H264="H264",n.VP8="VP8",n.VP9="VP9",n.AV1="AV1",n))(ye||{}),h=(n=>(n.CONTENT_TYPE="content-type",n.CONTENT_ENTER_ROOM="x-webrtc-enter-room",n.CONTENT_USE_LICENSE="x-webrtc-use-license",n.PARTICIPANT_NAME="x-webrtc-participant-name",n.INPUT_CHANNELS="x-webrtc-input-channels",n.OUTPUT_CHANNELS="x-webrtc-output-channels",n.MAIN_CAM="x-webrtc-maincam",n.MIC="x-webrtc-mic",n.MEDIA_SYNC="x-webrtc-sync",n.MAIN_CAM_RESOLUTION="x-webrtc-maincam-resolution",n.MEDIA_STATE="x-webrtc-media-state",n.MEDIA_TYPE="x-vinteo-media-type",n.MAIN_CAM_STATE="x-vinteo-maincam-state",n.MIC_STATE="x-vinteo-mic-state",n.CONTENT_PARTICIPANT_STATE="x-webrtc-partstate",n.AUDIO_ID="x-webrtc-audioid",n.SPECTATOR_MODE="x-webrtc-spectator-mode",n.NOTIFY="x-vinteo-notify",n.CONTENT_ENABLE_MEDIA_DEVICE="x-webrtc-request-enable-media-device",n.CONTENTED_STREAM_STATE="x-webrtc-share-state",n.CONTENTED_STREAM_CODEC="x-webrtc-share-codec",n.AVAILABLE_INCOMING_BITRATE="x-webrtc-available-incoming-bitrate",n.AUDIO_TRACK_COUNT="x-webrtc-audio-track-count",n.VIDEO_TRACK_COUNT="x-webrtc-video-track-count",n.TRACKS_DIRECTION="x-webrtc-tracks-direction",n.BEARER_TOKEN="x-bearer-token",n.IS_DIRECT_PEER_TO_PEER="x-webrtc-is-direct-p2p",n))(h||{}),V=(n=>(n.AVAILABLE_CONTENTED_STREAM="YOUCANRECEIVECONTENT",n.NOT_AVAILABLE_CONTENTED_STREAM="CONTENTEND",n.MUST_STOP_PRESENTATION="YOUMUSTSTOPSENDCONTENT",n))(V||{}),k=(n=>(n.AVAILABLE_CONTENTED_STREAM="x-webrtc-share-state: YOUCANRECEIVECONTENT",n.NOT_AVAILABLE_CONTENTED_STREAM="x-webrtc-share-state: CONTENTEND",n.ACK_PERMISSION_TO_START_PRESENTATION="x-webrtc-share-state: LETMESTARTPRESENTATION",n.STOPPED_CLIENT_PRESENTATION="x-webrtc-share-state: STOPPRESENTATION",n.ENABLE_MAIN_CAM="x-webrtc-request-enable-media-device: LETMESTARTMAINCAM",n))(k||{}),X=(n=>(n.ADMIN_SYNC_FORCED="1",n.ADMIN_SYNC_NOT_FORCED="0",n))(X||{}),ue=(n=>(n.SPECTATOR_MANUAL="0",n.BY_STATE_CAM="1",n.SPECTATOR_FORCED="2",n))(ue||{}),ge=(n=>(n.AUDIO="AUDIO",n.VIDEO="VIDEO",n.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION",n))(ge||{}),g=(n=>(n.ENTER_ROOM="enter-room",n.MAIN_CAM_CONTROL="main-cam-control",n.USE_LICENSE="use-license",n.NEW_DTMF="new-dtmf",n.CONFERENCE_PARTICIPANT_TOKEN_ISSUED="conference:participant-token-issued",n.CONTENTED_STREAM_AVAILABLE="contented-stream:available",n.CONTENTED_STREAM_NOT_AVAILABLE="contented-stream:not-available",n.PRESENTATION_MUST_STOP="presentation:must-stop",n.CHANNELS_ALL="channels:all",n.CHANNELS_NOTIFY="channels:notify",n.PARTICIPANT_ADDED_TO_LIST_MODERATORS="participant:added-to-list-moderators",n.PARTICIPANT_REMOVED_FROM_LIST_MODERATORS="participant:removed-from-list-moderators",n.PARTICIPANT_MOVE_REQUEST_TO_STREAM="participant:move-request-to-stream",n.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS="participant:move-request-to-spectators",n.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS_SYNTHETIC="participant:move-request-to-spectators-synthetic",n.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS_WITH_AUDIO_ID="participant:move-request-to-spectators-with-audio-id",n.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS="participant:move-request-to-participants",n.PARTICIPATION_ACCEPTING_WORD_REQUEST="participation:accepting-word-request",n.PARTICIPATION_CANCELLING_WORD_REQUEST="participation:cancelling-word-request",n.WEBCAST_STARTED="webcast:started",n.WEBCAST_STOPPED="webcast:stopped",n.ACCOUNT_CHANGED="account:changed",n.ACCOUNT_DELETED="account:deleted",n.ADMIN_START_MAIN_CAM="admin:start-main-cam",n.ADMIN_STOP_MAIN_CAM="admin:stop-main-cam",n.ADMIN_START_MIC="admin:start-mic",n.ADMIN_STOP_MIC="admin:stop-mic",n.ADMIN_FORCE_SYNC_MEDIA_STATE="admin:force-sync-media-state",n.FAILED_SEND_ROOM_DIRECT_P2P="failed-send-room-direct-p2p",n))(g||{});const Le=["enter-room","main-cam-control","use-license","new-dtmf","conference:participant-token-issued","contented-stream:available","contented-stream:not-available","presentation:must-stop","channels:all","channels:notify","participant:added-to-list-moderators","participant:removed-from-list-moderators","participant:move-request-to-stream","participant:move-request-to-spectators","participant:move-request-to-spectators-synthetic","participant:move-request-to-spectators-with-audio-id","participant:move-request-to-participants","participation:accepting-word-request","participation:cancelling-word-request","webcast:started","webcast:stopped","account:changed","account:deleted","admin:start-main-cam","admin:stop-main-cam","admin:start-mic","admin:stop-mic","admin:force-sync-media-state","failed-send-room-direct-p2p"],It=()=>new M.TypedEvents(Le),vt=n=>typeof n=="string"&&n.trim().length>0,L=(n,e)=>{const t=e.toLowerCase(),s=Object.entries(n).find(([,i])=>typeof i=="string"&&i.toLowerCase()===t);return s?s[1]:void 0},ft=n=>typeof n=="string"&&!Number.isNaN(Number(n))&&Number.isFinite(Number(n)),Mt=n=>{if(ft(n))return Number(n)},_t=n=>{const e=n.toLowerCase();if(e==="true"||e==="1")return!0;if(e==="false"||e==="0")return!1},A=(n,e)=>{const t=n.getHeader(e.toLowerCase());if(!vt(t))return;const s=t.toLowerCase();switch(e){case h.BEARER_TOKEN:return t;case h.CONTENT_ENTER_ROOM:case h.PARTICIPANT_NAME:case h.INPUT_CHANNELS:case h.OUTPUT_CHANNELS:case h.TRACKS_DIRECTION:case h.AUDIO_ID:case h.MAIN_CAM_RESOLUTION:case h.MEDIA_STATE:case h.NOTIFY:case h.CONTENT_ENABLE_MEDIA_DEVICE:return s;case h.MEDIA_TYPE:case h.MAIN_CAM_STATE:case h.MIC_STATE:case h.AVAILABLE_INCOMING_BITRATE:case h.AUDIO_TRACK_COUNT:case h.VIDEO_TRACK_COUNT:return Mt(s);case h.CONTENTED_STREAM_CODEC:return L(ye,s);case h.CONTENT_TYPE:return L(P,s);case h.CONTENT_USE_LICENSE:return L(ge,s);case h.MAIN_CAM:return L(b,s);case h.MIC:return L(j,s);case h.MEDIA_SYNC:return L(X,s);case h.CONTENT_PARTICIPANT_STATE:return L(J,s);case h.SPECTATOR_MODE:return L(ue,s);case h.CONTENTED_STREAM_STATE:return L(V,s);case h.IS_DIRECT_PEER_TO_PEER:return _t(s);default:return}};var f=(n=>(n.CHANNELS="channels",n.WEBCAST_STARTED="WebcastStarted",n.WEBCAST_STOPPED="WebcastStopped",n.ACCOUNT_CHANGED="accountChanged",n.ACCOUNT_DELETED="accountDeleted",n.ADDED_TO_LIST_MODERATORS="addedToListModerators",n.REMOVED_FROM_LIST_MODERATORS="removedFromListModerators",n.ACCEPTING_WORD_REQUEST="ParticipationRequestAccepted",n.CANCELLING_WORD_REQUEST="ParticipationRequestRejected",n.MOVE_REQUEST_TO_STREAM="ParticipantMovedToWebcast",n.CONFERENCE_PARTICIPANT_TOKEN_ISSUED="ConferenceParticipantTokenIssued",n))(f||{});class bt{events;callManager;constructor(){this.events=It()}subscribe({connectionManager:e,callManager:t}){this.callManager=t,e.on("sipEvent",this.handleSipEvent),t.on("newInfo",this.handleNewInfo),t.on("newDTMF",({originator:s})=>{this.events.trigger(g.NEW_DTMF,{originator:s})})}async waitChannels(){return this.wait(g.CHANNELS_ALL)}async waitSyncMediaState(){return this.wait(g.ADMIN_FORCE_SYNC_MEDIA_STATE)}async sendDTMF(e){return new Promise((t,s)=>{let i;try{i=this.getEstablishedRTCSessionProtected()}catch(r){s(r)}i&&(this.callManager?.once("newDTMF",({originator:r})=>{r==="local"&&t()}),i.sendDTMF(e,{duration:120,interToneGap:600}))})}async sendChannels({inputChannels:e,outputChannels:t}){const s=this.getEstablishedRTCSessionProtected(),i=`${h.INPUT_CHANNELS}: ${e}`,r=`${h.OUTPUT_CHANNELS}: ${t}`,a=[i,r];return s.sendInfo(O.CHANNELS,void 0,{extraHeaders:a})}sendEnterRoom(e){this.sendEnterRoomProtected(e).catch(t=>{this.events.trigger(g.FAILED_SEND_ROOM_DIRECT_P2P,{error:t})})}async sendMediaState({cam:e,mic:t},s={}){const i=this.getEstablishedRTCSessionProtected(),r=`${h.MEDIA_STATE}: currentstate`,a=`${h.MAIN_CAM_STATE}: ${Number(e)}`,o=`${h.MIC_STATE}: ${Number(t)}`,c=[r,a,o];return i.sendInfo(O.MEDIA_STATE,void 0,{noTerminateWhenError:!0,...s,extraHeaders:c})}async sendStats({availableIncomingBitrate:e}){const t=this.getEstablishedRTCSessionProtected(),i=[`${h.AVAILABLE_INCOMING_BITRATE}: ${e}`];return t.sendInfo(O.STATS,void 0,{noTerminateWhenError:!0,extraHeaders:i})}async sendRefusalToTurnOn(e,t={}){const s=this.getEstablishedRTCSessionProtected(),a=e==="mic"?0:1,c=[`${h.MEDIA_TYPE}: ${a}`];return s.sendInfo(O.REFUSAL,void 0,{noTerminateWhenError:!0,...t,extraHeaders:c})}async sendRefusalToTurnOnMic(e={}){return this.sendRefusalToTurnOn("mic",{noTerminateWhenError:!0,...e})}async sendRefusalToTurnOnCam(e={}){return this.sendRefusalToTurnOn("cam",{noTerminateWhenError:!0,...e})}async sendAvailableContentedStream(){await this.getEstablishedRTCSessionProtected().sendInfo(O.SHARE_STATE,void 0,{extraHeaders:[k.AVAILABLE_CONTENTED_STREAM]})}async askPermissionToStartPresentation(){await this.getEstablishedRTCSessionProtected().sendInfo(O.SHARE_STATE,void 0,{extraHeaders:[k.ACK_PERMISSION_TO_START_PRESENTATION]})}async sendStoppedPresentation(){await this.getEstablishedRTCSessionProtected().sendInfo(O.SHARE_STATE,void 0,{extraHeaders:[k.STOPPED_CLIENT_PRESENTATION]})}async sendNotAvailableContentedStream(){await this.getEstablishedRTCSessionProtected().sendInfo(O.SHARE_STATE,void 0,{extraHeaders:[k.NOT_AVAILABLE_CONTENTED_STREAM]})}async askPermissionToEnableCam(e={}){const t=this.getEstablishedRTCSessionProtected(),s=[k.ENABLE_MAIN_CAM];return t.sendInfo(O.MAIN_CAM,void 0,{noTerminateWhenError:!0,...e,extraHeaders:s}).catch(i=>{if(At(i))throw i})}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}getEstablishedRTCSessionProtected=()=>{const e=this.callManager?.getEstablishedRTCSession();if(!e)throw new Error("No rtcSession established");return e};handleSipEvent=({request:e})=>{this.maybeHandleNotify(e)};maybeHandleNotify=e=>{try{const t=e.getHeader(h.NOTIFY);if(t){const s=JSON.parse(t);this.handleNotify(s)}}catch(t){d("error parse notify",t)}};handleNotify=e=>{switch(e.cmd){case f.CHANNELS:{const t=e;this.triggerChannelsNotify(t);break}case f.WEBCAST_STARTED:{const t=e;this.triggerWebcastStartedNotify(t);break}case f.WEBCAST_STOPPED:{const t=e;this.triggerWebcastStoppedNotify(t);break}case f.ADDED_TO_LIST_MODERATORS:{const t=e;this.triggerAddedToListModeratorsNotify(t);break}case f.REMOVED_FROM_LIST_MODERATORS:{const t=e;this.triggerRemovedFromListModeratorsNotify(t);break}case f.ACCEPTING_WORD_REQUEST:{const t=e;this.triggerParticipationAcceptingWordRequest(t);break}case f.CANCELLING_WORD_REQUEST:{const t=e;this.triggerParticipationCancellingWordRequest(t);break}case f.MOVE_REQUEST_TO_STREAM:{const t=e;this.triggerParticipantMoveRequestToStream(t);break}case f.ACCOUNT_CHANGED:{this.triggerAccountChangedNotify();break}case f.ACCOUNT_DELETED:{this.triggerAccountDeletedNotify();break}case f.CONFERENCE_PARTICIPANT_TOKEN_ISSUED:{const t=e;this.triggerConferenceParticipantTokenIssued(t);break}default:d("unknown cmd",e)}};handleNewInfo=e=>{const{originator:t}=e;if(t!=="remote")return;const{request:s}=e,i=s,r=A(i,h.CONTENT_TYPE);if(r!==void 0)switch(r){case P.ENTER_ROOM:{this.triggerEnterRoom(i),this.maybeTriggerChannels(i);break}case P.NOTIFY:{this.maybeHandleNotify(i);break}case P.SHARE_STATE:{this.triggerContentedStreamState(i);break}case P.MAIN_CAM:{this.triggerMainCamControl(i);break}case P.MIC:{this.triggerMicControl(i);break}case P.USE_LICENSE:{this.triggerUseLicense(i);break}case P.PARTICIPANT_STATE:{this.maybeTriggerParticipantMoveRequest(i);break}}};triggerChannelsNotify=e=>{const t=e.input,s=e.output,i={inputChannels:t,outputChannels:s};this.events.trigger(g.CHANNELS_NOTIFY,i)};triggerWebcastStartedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this.events.trigger(g.WEBCAST_STARTED,s)};triggerWebcastStoppedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this.events.trigger(g.WEBCAST_STOPPED,s)};triggerAddedToListModeratorsNotify=({conference:e})=>{const t={conference:e};this.events.trigger(g.PARTICIPANT_ADDED_TO_LIST_MODERATORS,t)};triggerRemovedFromListModeratorsNotify=({conference:e})=>{const t={conference:e};this.events.trigger(g.PARTICIPANT_REMOVED_FROM_LIST_MODERATORS,t)};triggerParticipationAcceptingWordRequest=({body:{conference:e}})=>{const t={conference:e};this.events.trigger(g.PARTICIPATION_ACCEPTING_WORD_REQUEST,t)};triggerParticipationCancellingWordRequest=({body:{conference:e}})=>{const t={conference:e};this.events.trigger(g.PARTICIPATION_CANCELLING_WORD_REQUEST,t)};triggerParticipantMoveRequestToStream=({body:{conference:e}})=>{const t={conference:e};this.events.trigger(g.PARTICIPANT_MOVE_REQUEST_TO_STREAM,t)};triggerAccountChangedNotify=()=>{this.events.trigger(g.ACCOUNT_CHANGED,{})};triggerAccountDeletedNotify=()=>{this.events.trigger(g.ACCOUNT_DELETED,{})};triggerConferenceParticipantTokenIssued=({body:{conference:e,participant:t,jwt:s}})=>{const i={conference:e,participant:t,jwt:s};this.events.trigger(g.CONFERENCE_PARTICIPANT_TOKEN_ISSUED,i)};maybeTriggerChannels=e=>{const t=A(e,h.INPUT_CHANNELS),s=A(e,h.OUTPUT_CHANNELS);if(t!==void 0&&s!==void 0){const i={inputChannels:t,outputChannels:s};this.events.trigger(g.CHANNELS_ALL,i)}};triggerEnterRoom=e=>{const t=A(e,h.CONTENT_ENTER_ROOM),s=A(e,h.PARTICIPANT_NAME),i=A(e,h.BEARER_TOKEN),r=A(e,h.IS_DIRECT_PEER_TO_PEER);t!==void 0&&s!==void 0&&this.events.trigger(g.ENTER_ROOM,{room:t,participantName:s,bearerToken:i,isDirectPeerToPeer:r})};triggerContentedStreamState=e=>{const t=A(e,h.CONTENTED_STREAM_STATE);if(t!==void 0)switch(t){case V.AVAILABLE_CONTENTED_STREAM:{const s=A(e,h.CONTENTED_STREAM_CODEC);this.events.trigger(g.CONTENTED_STREAM_AVAILABLE,{codec:s});break}case V.NOT_AVAILABLE_CONTENTED_STREAM:{this.events.trigger(g.CONTENTED_STREAM_NOT_AVAILABLE,{});break}case V.MUST_STOP_PRESENTATION:{this.events.trigger(g.PRESENTATION_MUST_STOP,{});break}}};maybeTriggerParticipantMoveRequest=e=>{const t=A(e,h.CONTENT_PARTICIPANT_STATE),s=A(e,h.AUDIO_ID),i=A(e,h.SPECTATOR_MODE);if(t===J.SPECTATOR){const r=i===ue.BY_STATE_CAM;s===void 0?(this.events.trigger(g.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS_SYNTHETIC,{isAvailableSendingMedia:r}),this.events.trigger(g.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS,{isAvailableSendingMedia:r,isSynthetic:!0})):(this.events.trigger(g.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS_WITH_AUDIO_ID,{isAvailableSendingMedia:r,audioId:s}),this.events.trigger(g.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS,{isAvailableSendingMedia:r,isSynthetic:!1,audioId:s}))}t===J.PARTICIPANT&&this.events.trigger(g.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS,{})};triggerMainCamControl=e=>{const t=A(e,h.MAIN_CAM),s=A(e,h.MEDIA_SYNC),i=s===X.ADMIN_SYNC_FORCED;if(t===b.ADMIN_START_MAIN_CAM){this.events.trigger(g.ADMIN_START_MAIN_CAM,{isSyncForced:i});return}if(t===b.ADMIN_STOP_MAIN_CAM){this.events.trigger(g.ADMIN_STOP_MAIN_CAM,{isSyncForced:i});return}(t===b.RESUME_MAIN_CAM||t===b.PAUSE_MAIN_CAM)&&s!==void 0&&this.events.trigger(g.ADMIN_FORCE_SYNC_MEDIA_STATE,{isSyncForced:i});const r=A(e,h.MAIN_CAM_RESOLUTION);this.events.trigger(g.MAIN_CAM_CONTROL,{mainCam:t,resolutionMainCam:r})};triggerMicControl=e=>{const t=A(e,h.MIC),i=A(e,h.MEDIA_SYNC)===X.ADMIN_SYNC_FORCED;t===j.ADMIN_START_MIC?this.events.trigger(g.ADMIN_START_MIC,{isSyncForced:i}):t===j.ADMIN_STOP_MIC&&this.events.trigger(g.ADMIN_STOP_MIC,{isSyncForced:i})};triggerUseLicense=e=>{const t=A(e,h.CONTENT_USE_LICENSE);t!==void 0&&this.events.trigger(g.USE_LICENSE,t)};async sendEnterRoomProtected(e){return this.getEstablishedRTCSessionProtected().sendInfo(P.ENTER_ROOM,void 0,{extraHeaders:e})}}const Ot=/^p2p.+to.+$/i,Te=n=>n!==void 0&&n.length>0&&Ot.test(n),we="purgatory",Se=n=>n===we,Pt=(n,e)=>{n.getVideoTracks().forEach(s=>{"contentHint"in s&&s.contentHint!==e&&(s.contentHint=e)})},x=(n,{directionVideo:e,directionAudio:t,contentHint:s}={})=>{if(!n||e==="recvonly"&&t==="recvonly")return;const i=t==="recvonly"?[]:n.getAudioTracks(),r=e==="recvonly"?[]:n.getVideoTracks(),a=[...i,...r],o=new MediaStream(a);return o.getTracks=()=>[...o.getAudioTracks(),...o.getVideoTracks()],s&&s!=="none"&&Pt(o,s),o},Dt="api/v2/rtp2webrtc/offer",Ue=async({serverUrl:n,conferenceNumber:e,quality:t,audio:s,offer:i,token:r})=>{const a=new URL(`https://${n.replace(/\/$/,"")}/${Dt}/${encodeURIComponent(e)}`);a.searchParams.set("quality",t),a.searchParams.set("audio",String(s));const o={"Content-Type":"application/json",Authorization:`Bearer ${r}`},c=await fetch(a.toString(),{method:"POST",headers:o,credentials:"same-origin",body:JSON.stringify(i)});if(!c.ok)throw new Error(`sendOffer failed with status ${c.status}`);const l=await c.json();return{type:l.type,sdp:l.sdp,toJSON(){return l}}},yt=(n,e)=>(n.degradationPreference=e.degradationPreference,n),Lt=(n,e)=>{n.encodings??=[];for(let t=n.encodings.length;t<e;t+=1)n.encodings.push({});return n},ke=n=>(e,t)=>t!==void 0&&e!==t||t===void 0&&e!==n,wt=ke(),Ut=(n,e)=>{if(wt(n,e))return n},kt=(n,e,{isResetAllowed:t=!1}={})=>{const s=n.maxBitrate,i=Ut(e,s);return(i!==void 0||t)&&(n.maxBitrate=i),n},Fe=1,Ft=ke(Fe),Bt=(n,e)=>{const t=n===void 0?void 0:Math.max(n,Fe);if(t!==void 0&&Ft(t,e))return t},$t=(n,e)=>{const t=n.scaleResolutionDownBy,s=Bt(e,t);return s!==void 0&&(n.scaleResolutionDownBy=s),n},Gt=(n,e,{isResetAllowed:t}={})=>{const s=e.encodings?.length??0;return Lt(n,s),n.encodings.forEach((i,r)=>{const a=(e?.encodings??[])[r],o=a?.maxBitrate,c=a?.scaleResolutionDownBy;kt(i,o,{isResetAllowed:t}),$t(i,c)}),n},qt=(n,e)=>{if(n.codecs?.length!==e.codecs?.length)return!0;for(let t=0;t<(n.codecs?.length??0);t++)if(JSON.stringify(n.codecs[t])!==JSON.stringify(e.codecs[t]))return!0;if(n.headerExtensions?.length!==e.headerExtensions?.length)return!0;for(let t=0;t<(n.headerExtensions?.length??0);t++)if(JSON.stringify(n.headerExtensions[t])!==JSON.stringify(e.headerExtensions[t]))return!0;if(n.encodings?.length!==e.encodings?.length)return!0;for(let t=0;t<(n.encodings?.length??0);t++)if(JSON.stringify(n.encodings[t])!==JSON.stringify(e.encodings[t]))return!0;return n.rtcp?.cname!==e.rtcp?.cname||n.rtcp?.reducedSize!==e.rtcp?.reducedSize||n.degradationPreference!==e.degradationPreference},K=async(n,e,{isResetAllowed:t}={})=>{const s=n.getParameters(),i=JSON.parse(JSON.stringify(s));Gt(s,e,{isResetAllowed:t}),yt(s,e);const r=qt(i,s);return r&&await n.setParameters(s),{parameters:s,isChanged:r}},Ee=async(n,e,t)=>{const{isChanged:s,parameters:i}=await K(n,{encodings:[{scaleResolutionDownBy:e.scaleResolutionDownBy,maxBitrate:e.maxBitrate}]});return s&&t&&t(i),{isChanged:s,parameters:i}},Vt=(n,e)=>n.find(t=>t.track!==null&&e.getTracks().includes(t.track)),xt=async(n,e,t)=>{const s=Vt(n,e);if(s)return Ee(s,{maxBitrate:t})};class Be{command=void 0;unsubscribe;options;constructor(e){this.options=e}set(e){this.cancel(),this.command=e,this.unsubscribe=this.options.subscribe(t=>{this.options.isReady(t)?(this.command!==void 0&&this.options.onExecute(this.command),this.cancel()):this.options.isCancelled(t)&&this.cancel()})}cancel(){this.unsubscribe?.(),this.unsubscribe=void 0,this.command=void 0}}class W{actor;subscriptions=[];stateChangeListeners=new Set;constructor(e){this.actor=I.createActor(e),this.actor.start(),this.addSubscription(this.subscribe(t=>{const s=t.value;this.stateChangeListeners.forEach(i=>{i(s)})}))}get state(){return this.getSnapshot().value}get context(){return this.getSnapshot().context}send(e){this.actor.send(e)}getSnapshot(){return this.actor.getSnapshot()}subscribe(e){const t=this.actor.subscribe(e);return this.addSubscription(t),t}onStateChange(e){return this.stateChangeListeners.add(e),()=>{this.stateChangeListeners.delete(e)}}stop(){this.stateChangeListeners.clear(),this.subscriptions.forEach(e=>{e()}),this.subscriptions.length=0,this.actor.stop()}addSubscription(e){const t=typeof e=="function"?e:()=>{e.unsubscribe()};return this.subscriptions.push(t),t}}var Z=(n=>(n.IDLE="call:idle",n.CONNECTING="call:connecting",n.PURGATORY="call:purgatory",n.P2P_ROOM="call:p2pRoom",n.DIRECT_P2P_ROOM="call:directP2pRoom",n.IN_ROOM="call:inRoom",n.DISCONNECTING="call:disconnecting",n))(Z||{});const m="evaluate",ee=n=>typeof n=="string"&&n.length>0,Q=n=>"number"in n&&ee(n.number)&&typeof n.answer=="boolean",ne=n=>"room"in n&&ee(n.room)&&ee(n.participantName),se=n=>"token"in n&&ee(n.token),$e=({isDirectPeerToPeer:n})=>n===!0,Ht=n=>Se(n.room)||Te(n.room)||$e(n),Wt=n=>Q(n)&&ne(n)&&!se(n)&&"room"in n&&Se(n.room),Qt=n=>Q(n)&&ne(n)&&!se(n)&&"room"in n&&Te(n.room),Yt=n=>"isDirectPeerToPeer"in n&&$e(n),zt=n=>Q(n)&&ne(n)&&!se(n)&&"room"in n&&Yt(n),Ge=n=>Q(n)&&ne(n)&&se(n),Jt={},ie=()=>({number:void 0,answer:void 0,room:void 0,participantName:void 0,token:void 0,isDirectPeerToPeer:void 0,pendingDisconnect:void 0}),jt=I.setup({types:{context:Jt,events:{}},actions:{setConnecting:I.assign(({event:n,context:e})=>n.type!=="CALL.CONNECTING"?e:{...ie(),number:n.number,answer:n.answer}),setRoomInfo:I.assign(({event:n,context:e})=>{if(n.type!=="CALL.ENTER_ROOM")return e;const t={room:n.room,participantName:n.participantName};return n.token!==void 0?t.token=n.token:Ht(n)&&(t.token=void 0),n.isDirectPeerToPeer!==void 0&&(t.isDirectPeerToPeer=n.isDirectPeerToPeer),t}),setTokenInfo:I.assign(({event:n,context:e})=>n.type!=="CALL.TOKEN_ISSUED"?e:{token:n.token}),reset:I.assign(ie()),prepareDisconnect:I.assign(()=>({...ie(),pendingDisconnect:!0}))}}).createMachine({id:"call",initial:"call:idle",context:{},states:{"call:idle":{on:{"CALL.CONNECTING":{target:m,actions:"setConnecting"}}},"call:connecting":{on:{"CALL.ENTER_ROOM":{target:m,actions:"setRoomInfo"},"CALL.TOKEN_ISSUED":{target:m,actions:"setTokenInfo"},"CALL.START_DISCONNECT":{target:m,actions:"prepareDisconnect"},"CALL.RESET":{target:m,actions:"reset"}}},"call:inRoom":{on:{"CALL.ENTER_ROOM":{target:m,actions:"setRoomInfo"},"CALL.TOKEN_ISSUED":{target:m,actions:"setTokenInfo"},"CALL.START_DISCONNECT":{target:m,actions:"prepareDisconnect"},"CALL.RESET":{target:m,actions:"reset"}}},[m]:{always:[{target:"call:disconnecting",guard:({context:n})=>n.pendingDisconnect===!0,actions:"reset"},{target:"call:inRoom",guard:({context:n})=>Ge(n)},{target:"call:directP2pRoom",guard:({context:n})=>zt(n)},{target:"call:p2pRoom",guard:({context:n})=>Qt(n)},{target:"call:purgatory",guard:({context:n})=>Wt(n)},{target:"call:connecting",guard:({context:n})=>Q(n)},{target:"call:idle"}]},"call:purgatory":{on:{"CALL.ENTER_ROOM":{target:m,actions:"setRoomInfo"},"CALL.TOKEN_ISSUED":{target:m,actions:"setTokenInfo"},"CALL.START_DISCONNECT":{target:m,actions:"prepareDisconnect"},"CALL.RESET":{target:m,actions:"reset"}}},"call:p2pRoom":{on:{"CALL.ENTER_ROOM":{target:m,actions:"setRoomInfo"},"CALL.TOKEN_ISSUED":{target:m,actions:"setTokenInfo"},"CALL.START_DISCONNECT":{target:m,actions:"prepareDisconnect"},"CALL.RESET":{target:m,actions:"reset"}}},"call:directP2pRoom":{on:{"CALL.ENTER_ROOM":{target:m,actions:"setRoomInfo"},"CALL.TOKEN_ISSUED":{target:m,actions:"setTokenInfo"},"CALL.START_DISCONNECT":{target:m,actions:"prepareDisconnect"},"CALL.RESET":{target:m,actions:"reset"}}},"call:disconnecting":{on:{"CALL.RESET":{target:m,actions:"reset"}}}}});class Xt extends W{constructor(e){super(jt),this.subscribeToEvents(e)}get isIdle(){return this.state==="call:idle"}get isConnecting(){return this.state==="call:connecting"}get isInPurgatory(){return this.state==="call:purgatory"}get isP2PRoom(){return this.state==="call:p2pRoom"}get isDirectP2PRoom(){return this.state==="call:directP2pRoom"}get isInRoom(){return this.state==="call:inRoom"}get isDisconnecting(){return this.state==="call:disconnecting"}get inRoomContext(){const{context:e}=this;return Ge(e)?e:void 0}get isActive(){return this.isInRoom||this.isInPurgatory||this.isP2PRoom||this.isDirectP2PRoom}get number(){const{context:e}=this;if("number"in e)return e.number}get token(){const{context:e}=this;if("token"in e)return e.token}get isCallInitiator(){return!this.isCallAnswerer}get isCallAnswerer(){const{context:e}=this;return"answer"in e?e.answer:!1}reset(){this.send({type:"CALL.RESET"})}send(e){if(!this.actor.getSnapshot().can(e)){console.warn(`[CallStateMachine] Invalid transition: ${e.type} from ${this.state}. Event cannot be processed in current state.`);return}super.send(e)}subscribeToApiEvents(e){this.addSubscription(e.on("enter-room",({room:t,participantName:s,bearerToken:i,isDirectPeerToPeer:r})=>{this.send({type:"CALL.ENTER_ROOM",room:t,participantName:s,token:i,isDirectPeerToPeer:r})})),this.addSubscription(e.on("conference:participant-token-issued",({jwt:t})=>{this.send({type:"CALL.TOKEN_ISSUED",token:t})}))}subscribeToEvents(e){this.addSubscription(e.on("start-call",({number:t,answer:s})=>{this.send({type:"CALL.CONNECTING",number:t,answer:s})})),this.addSubscription(e.on("end-call",()=>{this.send({type:"CALL.START_DISCONNECT"})})),this.addSubscription(e.on("ended",()=>{this.send({type:"CALL.RESET"})})),this.addSubscription(e.on("failed",()=>{this.send({type:"CALL.RESET"})}))}}var S=(n=>(n.PEER_CONNECTION="peerconnection",n.CONNECTING="connecting",n.SENDING="sending",n.PROGRESS="progress",n.ACCEPTED="accepted",n.CONFIRMED="confirmed",n.ENDED="ended",n.FAILED="failed",n.NEW_DTMF="newDTMF",n.NEW_INFO="newInfo",n.HOLD="hold",n.UNHOLD="unhold",n.MUTED="muted",n.UNMUTED="unmuted",n.REINVITE="reinvite",n.UPDATE="update",n.REFER="refer",n.REPLACES="replaces",n.SDP="sdp",n.ICE_CANDIDATE="icecandidate",n.GET_USER_MEDIA_FAILED="getusermediafailed",n.PEER_CONNECTION_CREATE_OFFER_FAILED="peerconnection:createofferfailed",n.PEER_CONNECTION_CREATE_ANSWER_FAILED="peerconnection:createanswerfailed",n.PEER_CONNECTION_SET_LOCAL_DESCRIPTION_FAILED="peerconnection:setlocaldescriptionfailed",n.PEER_CONNECTION_SET_REMOTE_DESCRIPTION_FAILED="peerconnection:setremotedescriptionfailed",n.START_PRESENTATION="presentation:start",n.STARTED_PRESENTATION="presentation:started",n.END_PRESENTATION="presentation:end",n.ENDED_PRESENTATION="presentation:ended",n.FAILED_PRESENTATION="presentation:failed",n.START_CALL="start-call",n.END_CALL="end-call",n.PEER_CONNECTION_CONFIRMED="peerconnection:confirmed",n.PEER_CONNECTION_ONTRACK="peerconnection:ontrack",n.ENDED_FROM_SERVER="ended:fromserver",n.CALL_STATUS_CHANGED="call-status-changed",n.REMOTE_TRACKS_CHANGED="remote-tracks-changed",n.REMOTE_STREAMS_CHANGED="remote-streams-changed",n.RECV_SESSION_STARTED="recv-session-started",n.RECV_SESSION_ENDED="recv-session-ended",n.RECV_QUALITY_CHANGED="recv-quality-changed",n))(S||{}),qe=(n=>(n.LOCAL="local",n.REMOTE="remote",n.SYSTEM="system",n))(qe||{});const Ve=["peerconnection","connecting","sending","progress","accepted","confirmed","ended","failed","hold","unhold","muted","unmuted","newInfo","newDTMF","presentation:start","presentation:started","presentation:end","presentation:ended","presentation:failed","reinvite","update","refer","replaces","sdp","icecandidate","getusermediafailed","peerconnection:createofferfailed","peerconnection:createanswerfailed","peerconnection:setlocaldescriptionfailed","peerconnection:setremotedescriptionfailed"],Kt=["start-call","end-call","peerconnection:confirmed","peerconnection:ontrack","ended:fromserver","call-status-changed","remote-tracks-changed","remote-streams-changed","recv-session-started","recv-session-ended","recv-quality-changed"],xe=[...Ve,...Kt],Zt=()=>new M.TypedEvents(xe),en=6e3,tn=1e3,z=(n,e)=>n.getSenders().filter(t=>t.track?.kind===e),nn=n=>n==="audio"?en:tn,sn=n=>n.track!==null;class rn{previousBitrates=new Map;async setMinBitrateForSenders(e,t="all"){const s=[];if(!e)return;(t==="audio"||t==="all")&&s.push(...z(e,"audio")),(t==="video"||t==="all")&&s.push(...z(e,"video"));const i=s.filter(sn).map(async r=>{const a=r.getParameters();this.saveCurrentBitrate(r,a);const o={...a,encodings:a.encodings.map(c=>({...c,maxBitrate:nn(r.track.kind)}))};await K(r,o)});await Promise.all(i)}async restoreBitrateForSenders(e,t="all"){const s=[];if(!e)return;(t==="audio"||t==="all")&&s.push(...z(e,"audio")),(t==="video"||t==="all")&&s.push(...z(e,"video"));const i=s.map(async r=>{const a=this.getSavedBitrate(r);if(a){const c={...r.getParameters(),encodings:a};await K(r,c,{isResetAllowed:!0}),this.clearSavedBitrate(r)}});await Promise.all(i)}getSavedBitrate(e){return this.previousBitrates.get(e)}clearSavedBitrate(e){this.previousBitrates.delete(e)}clearAll(){this.previousBitrates.clear()}hasSavedBitrate(e){return this.previousBitrates.has(e)}getSavedCount(){return this.previousBitrates.size}saveCurrentBitrate(e,t){const s=t.encodings.map(i=>({...i}));this.previousBitrates.set(e,s)}}var Ce=(n=>(n.BYE="Terminated",n.WEBRTC_ERROR="WebRTC Error",n.CANCELED="Canceled",n.REQUEST_TIMEOUT="Request Timeout",n.REJECTED="Rejected",n.REDIRECTED="Redirected",n.UNAVAILABLE="Unavailable",n.NOT_FOUND="Not Found",n.ADDRESS_INCOMPLETE="Address Incomplete",n.INCOMPATIBLE_SDP="Incompatible SDP",n.BAD_MEDIA_DESCRIPTION="Bad Media Description",n))(Ce||{});class an{events;rtcSession;disposers=new Set;onReset;bitrateStateManager=new rn;constructor(e,{onReset:t}){this.events=e,this.onReset=t,e.on(S.FAILED,this.handleEnded),e.on(S.ENDED,this.handleEnded)}get connection(){return this.rtcSession?.connection}get isCallActive(){return this.rtcSession?.isEstablished()===!0}getEstablishedRTCSession=()=>this.rtcSession?.isEstablished()===!0?this.rtcSession:void 0;async renegotiate(){if(this.rtcSession===void 0)throw new Error("No rtcSession established");return this.rtcSession.renegotiate()}startCall=async(e,t,{number:s,mediaStream:i,extraHeaders:r=[],iceServers:a,directionVideo:o,directionAudio:c,contentHint:l,offerToReceiveAudio:u=!0,offerToReceiveVideo:T=!0,degradationPreference:E,sendEncodings:N,onAddedTransceiver:y})=>new Promise((v,U)=>{this.handleCall().then(v).catch($=>{U($)}),this.rtcSession=e.call(t(s),{mediaStream:x(i,{directionVideo:o,directionAudio:c,contentHint:l}),pcConfig:{iceServers:a},rtcOfferConstraints:{offerToReceiveAudio:u,offerToReceiveVideo:T},eventHandlers:this.events.triggers,extraHeaders:r,directionVideo:o,directionAudio:c,degradationPreference:E,sendEncodings:N,onAddedTransceiver:y})});async endCall(){const{rtcSession:e}=this;if(e&&!e.isEnded())return e.terminateAsync({cause:Ce.CANCELED}).finally(()=>{this.reset()});this.reset()}answerToIncomingCall=async(e,{mediaStream:t,extraHeaders:s=[],iceServers:i,directionVideo:r,directionAudio:a,offerToReceiveAudio:o,offerToReceiveVideo:c,contentHint:l,degradationPreference:u,sendEncodings:T,onAddedTransceiver:E})=>new Promise((N,y)=>{try{this.rtcSession=e,this.subscribeToSessionEvents(e),this.handleCall().then(N).catch(v=>{y(v)}),e.answer({pcConfig:{iceServers:i},rtcOfferConstraints:{offerToReceiveAudio:o,offerToReceiveVideo:c},mediaStream:x(t,{directionVideo:r,directionAudio:a,contentHint:l}),extraHeaders:s,directionVideo:r,directionAudio:a,degradationPreference:u,sendEncodings:T,onAddedTransceiver:E})}catch(v){y(v)}});async replaceMediaStream(e,t){if(!this.rtcSession)throw new Error("No rtcSession established");const{contentHint:s}=t??{},i=x(e,{contentHint:s});if(i===void 0)throw new Error("No preparedMediaStream");return this.rtcSession.replaceMediaStream(i,t)}async restartIce(e){if(!this.rtcSession)throw new Error("No rtcSession established");return this.rtcSession.restartIce(e)}setMinBitrateForSenders(e="all"){this.bitrateStateManager.setMinBitrateForSenders(this.connection,e).catch(t=>{Ne("MCUSession.setMinBitrateForSenders",t)})}restoreBitrateForSenders(e="all"){this.bitrateStateManager.restoreBitrateForSenders(this.connection,e).catch(t=>{Ne("MCUSession.restoreBitrateForSenders",t)})}handleCall=async()=>new Promise((e,t)=>{const s=()=>{this.events.on(S.PEER_CONNECTION,l),this.events.on(S.CONFIRMED,u)},i=()=>{this.events.off(S.PEER_CONNECTION,l),this.events.off(S.CONFIRMED,u)},r=()=>{this.events.on(S.FAILED,o),this.events.on(S.ENDED,o)},a=()=>{this.events.off(S.FAILED,o),this.events.off(S.ENDED,o)},o=T=>{i(),a(),t(T)};let c;const l=({peerconnection:T})=>{c=T;const E=N=>{this.events.trigger(S.PEER_CONNECTION_ONTRACK,N)};T.addEventListener("track",E),this.disposers.add(()=>{T.removeEventListener("track",E)})},u=()=>{c!==void 0&&this.events.trigger(S.PEER_CONNECTION_CONFIRMED,c),i(),a(),e(c)};s(),r()});subscribeToSessionEvents(e){this.events.eachTriggers((t,s)=>{const i=Ve.find(r=>r===s);i&&(e.on(i,t),this.disposers.add(()=>{e.off(i,t)}))})}unsubscribeFromSessionEvents(){this.disposers.forEach(e=>{e()}),this.disposers.clear()}handleEnded=e=>{const{originator:t}=e;t==="remote"&&this.events.trigger(S.ENDED_FROM_SERVER,e),this.reset()};reset=()=>{delete this.rtcSession,this.unsubscribeFromSessionEvents(),this.bitrateStateManager.clearAll(),this.onReset()}}const Ae=n=>n==="auto"?"high":n,on=10,cn=500,dn=5e3;class hn{cancelableSendOfferWithRepeatedCalls;currentRenegotiation;config;tools;connection;lastCallParams;constructor(e,t){const s=e.quality??"auto";this.config={...e,quality:s,effectiveQuality:Ae(s)},this.tools=t,this.connection=new RTCPeerConnection(e.pcConfig),this.addTransceivers()}get settings(){return this.config}get peerConnection(){return this.connection}getQuality(){return this.config.quality}getEffectiveQuality(){return this.config.effectiveQuality}async setQuality(e){if(!this.lastCallParams)return!1;const t=this.config.effectiveQuality,s=this.config.quality,i=Ae(e);return e===s&&i===t?!1:(this.config.quality=e,this.config.effectiveQuality=i,i!==t&&await this.renegotiate(this.lastCallParams),!0)}async applyQuality(e){const t=await this.setQuality(e),s=this.getEffectiveQuality();return{applied:t,effectiveQuality:s}}close(){this.cancelSendOfferWithRepeatedCalls(),this.connection.close()}async call({conferenceNumber:e,token:t}){const s=this.waitForTracks();await this.renegotiate({conferenceNumber:e,token:t}),await s}async renegotiate({conferenceNumber:e,token:t}){this.lastCallParams={conferenceNumber:e,token:t},this.cancelSendOfferWithRepeatedCalls();const s=this.currentRenegotiation;s&&await s.catch(()=>{});const i=this.performRenegotiate({conferenceNumber:e,token:t});this.currentRenegotiation=i;try{return await i}finally{this.currentRenegotiation===i&&(this.currentRenegotiation=void 0)}}async performRenegotiate({conferenceNumber:e,token:t}){this.hasHaveLocalOfferSignalingState()&&await this.connection.setLocalDescription({type:"rollback"}),await this.waitForPeerConnectionReady();const s=await this.createOffer(),i=async()=>this.tools.sendOffer({conferenceNumber:e,token:t,quality:this.config.effectiveQuality,audioChannel:this.config.audioChannel},s),r=o=>!(o instanceof Error);this.cancelableSendOfferWithRepeatedCalls=te.repeatedCallsAsync({targetFunction:i,isComplete:r,callLimit:on,delay:cn,isRejectAsValid:!0,isCheckBeforeCall:!1});const a=await this.cancelableSendOfferWithRepeatedCalls.then(o=>o).finally(()=>{this.cancelableSendOfferWithRepeatedCalls=void 0});return await this.setRemoteDescription(a),await this.waitForPeerConnectionReady(),!0}async createOffer(){const e=await this.connection.createOffer();return await this.connection.setLocalDescription(e),e}async setRemoteDescription(e){return this.connection.setRemoteDescription(e)}hasStableSignalingState(){return this.connection.signalingState==="stable"}hasReadyConnectionState(){const e=this.connection.connectionState;return e==="connected"||e==="new"}hasTerminalConnectionState(){const e=this.connection.connectionState;return e==="failed"||e==="closed"}isStableAndReady(){return this.hasStableSignalingState()&&this.hasReadyConnectionState()}hasHaveLocalOfferSignalingState(){return this.connection.signalingState==="have-local-offer"}async waitForPeerConnectionReady(){if(this.isStableAndReady())return;const e=()=>{const s=this.connection.connectionState;return new Error(`Peer connection in terminal state: ${s}. Recovery is not possible.`)},t=()=>this.hasTerminalConnectionState()?"error":this.isStableAndReady()?"success":"loading";if(t()==="error")throw e();return new Promise((s,i)=>{let r,a=!1;const o=()=>{a||(a=!0,clearTimeout(r),this.connection.removeEventListener("signalingstatechange",l),this.connection.removeEventListener("connectionstatechange",l),s())},c=u=>{a||(a=!0,clearTimeout(r),this.connection.removeEventListener("signalingstatechange",l),this.connection.removeEventListener("connectionstatechange",l),i(u))};function l(){const u=t();if(u==="error"){c(e());return}u==="success"&&o()}r=setTimeout(()=>{c(new Error("Timed out waiting for stable signaling state and ready connection state"))},dn),this.connection.addEventListener("signalingstatechange",l),this.connection.addEventListener("connectionstatechange",l),l()})}async waitForTracks(){return new Promise(e=>{const t=new Set,s=i=>{const{track:r}=i;t.add(r.kind),t.has("audio")&&t.has("video")&&(this.connection.removeEventListener("track",s),e())};this.connection.addEventListener("track",s)})}addTransceivers(){this.addRecvOnlyTransceiver("audio"),this.addRecvOnlyTransceiver("video"),this.addRecvOnlyTransceiver("video"),this.addRecvOnlyTransceiver("video"),this.addRecvOnlyTransceiver("video")}addRecvOnlyTransceiver(e){const t={direction:"recvonly"};return this.connection.addTransceiver(e,t)}cancelSendOfferWithRepeatedCalls(){this.cancelableSendOfferWithRepeatedCalls?.cancel()}}const He=n=>n.getSettings(),ln=(n,e)=>{const t=He(n);let s=e;s??=n.label;let i=t?.msid;return i??=s,i??=n.id,i},un=(n,e)=>{const t=He(n);let s=e;return s??=t?.msid,s??=n.label,(s&&s.length>0?s:void 0)??n.id};class Ie{participantGroups=new Map;trackToGroup=new Map;trackDisposers=new Map;get mainStream(){const e=this.getStreams(),[t]=e;return t}reset(){this.participantGroups.clear(),this.trackToGroup.clear(),this.trackDisposers.forEach(e=>{e()}),this.trackDisposers.clear()}addTrack(e,{onRemoved:t,streamHint:s}={}){const i=un(e,s),r=ln(e,s);if(this.trackToGroup.has(e.id))return{isAddedTrack:!1,isAddedStream:!1};const a=this.getParticipantGroups(i),o=a.get(r),c=!o;let l=o;l||(l={participantId:i,groupId:r,stream:new MediaStream,trackIds:new Set},a.set(r,l)),l.stream.addTrack(e),l.trackIds.add(e.id),this.trackToGroup.set(e.id,{participantId:i,groupId:r});const u=()=>{this.disposeTrackListener(e.id);const T=this.removeTrack(e.id);T.isRemovedTrack&&t?.({participantId:i,trackId:e.id,isRemovedStream:T.isRemovedStream})};return e.addEventListener("ended",u),this.trackDisposers.set(e.id,()=>{e.removeEventListener("ended",u)}),{isAddedTrack:!0,isAddedStream:c,participantId:i}}removeTrack(e){this.disposeTrackListener(e);const t=this.trackToGroup.get(e);if(!t)return{isRemovedTrack:!1,isRemovedStream:!1};const{participantId:s,groupId:i}=t,r=this.participantGroups.get(s),a=r?.get(i);if(!a)return this.trackToGroup.delete(e),{isRemovedTrack:!1,isRemovedStream:!1};const o=a.stream.getTracks().find(l=>l.id===e);o&&a.stream.removeTrack(o),a.trackIds.delete(e),this.trackToGroup.delete(e);const c=a.trackIds.size===0;return c&&(r?.delete(i),r?.size===0&&this.participantGroups.delete(s)),{isRemovedTrack:!0,isRemovedStream:c}}removeStaleTracks(e,t){const s=this.participantGroups.get(e);if(!s)return!1;let i=!1;return[...s.values()].forEach(a=>{[...a.trackIds].filter(c=>!t.includes(c)).forEach(c=>{const l=this.removeTrack(c);i||=l.isRemovedTrack})}),i}getStreams(e){if(e!==void 0){const t=this.participantGroups.get(e);return t?[...t.values()].map(s=>s.stream):[]}return[...this.participantGroups.values()].flatMap(t=>[...t.values()]).map(t=>t.stream)}disposeTrackListener(e){const t=this.trackDisposers.get(e);t&&(t(),this.trackDisposers.delete(e))}getParticipantGroups(e){const t=this.participantGroups.get(e);if(t)return t;const s=new Map;return this.participantGroups.set(e,s),s}}const re={type:"participant"},gn={type:"spectator_synthetic"},Tn=n=>({type:"spectator",recvParams:n});class p{role=re;onRoleChanged;constructor(e){this.onRoleChanged=e}static hasParticipant(e){return e.type==="participant"}static hasSpectatorSynthetic(e){return e.type==="spectator_synthetic"}static hasSpectator(e){return e.type==="spectator"}static isExitingSpectatorRole(e,t){return p.hasSpectator(e)&&!p.hasSpectator(t)}static isEnteringSpectatorRole(e,t){return p.hasSpectator(t)}static isExitingAnySpectatorRole(e,t){const s=p.hasSpectator(e)||p.hasSpectatorSynthetic(e),i=p.hasSpectator(t)||p.hasSpectatorSynthetic(t);return s&&!i}static isEnteringAnySpectatorRole(e,t){const s=p.hasSpectator(e)||p.hasSpectatorSynthetic(e),i=p.hasSpectator(t)||p.hasSpectatorSynthetic(t);return!s&&i}getRole(){return this.role}setCallRoleParticipant(){this.changeRole(re)}setCallRoleSpectatorSynthetic(){this.changeRole(gn)}setCallRoleSpectator(e){this.changeRole(Tn(e))}changeRole(e){const t=this.role;if(t.type!==e.type){this.setRole(e);return}p.hasSpectator(e)&&p.hasSpectator(t)&&t.recvParams.audioId!==e.recvParams.audioId&&this.setRole(e)}reset(){this.role=re}hasParticipant(){return p.hasParticipant(this.role)}hasSpectatorSynthetic(){return p.hasSpectatorSynthetic(this.role)}hasSpectator(){return p.hasSpectator(this.role)}setRole(e){const t=this.role;this.role=e,this.onRoleChanged?.({previous:t,next:e})}}const Sn=(n,e)=>{if(!n||!e)return n===e;const t=n.mainStream?.id,s=e.mainStream?.id,i=n.contentedStream?.id,r=e.contentedStream?.id;return t===s&&i===r};class En{lastEmittedStreams;hasChanged(e){return!Sn(this.lastEmittedStreams,e)}updateLastEmittedStreams(e){this.lastEmittedStreams=e}getLastEmittedStreams(){return this.lastEmittedStreams}reset(){this.lastEmittedStreams=void 0}}const Cn="default",mn="dual",pn="content_",Rn=n=>`${pn}${n.toLowerCase()}`,Nn=n=>[...n.getTracks()].some(e=>e.label.includes(mn));class An{mainRemoteStreamsManager;recvRemoteStreamsManager;constructor(e,t){this.mainRemoteStreamsManager=e,this.recvRemoteStreamsManager=t}getActiveStreamsManagerTools({isSpectator:e,stateInfo:t}){return e?this.getRecvRemoteStreamsManagerTools({stateInfo:t}):this.getMainRemoteStreamsManagerTools({stateInfo:t})}getMainRemoteStreamsManagerTools({stateInfo:e}){const t=this.mainRemoteStreamsManager;return{manager:t,getRemoteStreams:()=>{const i=t.getStreams(),r=i.find(o=>!Nn(o)),a=e.isAvailable?i.find(o=>o!==r):void 0;return{mainStream:r,contentedStream:a}}}}getRecvRemoteStreamsManagerTools({stateInfo:e}){const t=this.recvRemoteStreamsManager;return{manager:t,getRemoteStreams:()=>{const r=t.getStreams(Cn)[0],a=this.getRecvRemoteContentedStream({stateInfo:e});return{mainStream:r,contentedStream:a}}}}getRecvRemoteContentedStream({stateInfo:e}){if(!e.isAvailable||e.codec===void 0)return;const t=Rn(e.codec);return this.recvRemoteStreamsManager.getStreams(t)[0]}}const ve=n=>n.streams[0]?.id;function In(n){const{inRoomContext:e}=n;if(e===void 0)throw new Error("[CallManager] Invariant: inRoomContext expected when deferred runner executes (state IN_ROOM)");return e.token}class vn{events;stateMachine;isPendingCall=!1;isPendingAnswer=!1;mainRemoteStreamsManager=new Ie;recvRemoteStreamsManager=new Ie;streamsManagerProvider;contentedStreamManager;roleManager=new p(e=>{this.onRoleChanged(e)});mcuSession;recvSession;disposeRecvSessionTrackListener;deferredStartRecvSessionRunner;streamsChangeTracker=new En;constructor(e){this.contentedStreamManager=e,this.events=Zt(),this.mcuSession=new an(this.events,{onReset:this.reset}),this.stateMachine=new Xt(this.events),this.streamsManagerProvider=new An(this.mainRemoteStreamsManager,this.recvRemoteStreamsManager),this.deferredStartRecvSessionRunner=new Be({subscribe:t=>this.stateMachine.onStateChange(t),isReady:t=>t===Z.IN_ROOM,isCancelled:t=>t===Z.IDLE,onExecute:t=>{const s=In(this.stateMachine);this.startRecvSession(t.audioId,{sendOffer:t.sendOffer,token:s})}}),this.subscribeCallStatusChange(),this.subscribeMcuRemoteTrackEvents(),this.subscribeContentedStreamEvents()}get requested(){return this.isPendingCall||this.isPendingAnswer}get connection(){return this.mcuSession.connection}get isCallActive(){return this.mcuSession.isCallActive}get number(){return this.stateMachine.number}get isCallInitiator(){return this.stateMachine.isCallInitiator}get isDirectP2PRoom(){return this.stateMachine.isDirectP2PRoom}get isDisconnecting(){return this.stateMachine.isDisconnecting}getStreamsManagerProvider(){return this.streamsManagerProvider}getContentedStreamManager(){return this.contentedStreamManager}getEstablishedRTCSession=()=>this.mcuSession.getEstablishedRTCSession();on(e,t){return this.events.on(e,t)}onRace(e,t){return this.events.onRace(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}subscribeToApiEvents(e){this.stateMachine.subscribeToApiEvents(e.events)}startCall=async(e,t,s)=>(this.isPendingCall=!0,this.events.emit(S.START_CALL,{number:s.number,answer:!1}),this.mcuSession.startCall(e,t,s).finally(()=>{this.isPendingCall=!1}));async endCall(){return this.events.emit(S.END_CALL),this.mcuSession.endCall()}async renegotiate(){return this.roleManager.hasSpectator()?this.renegotiateRecvSession():this.renegotiateMcuSession()}answerToIncomingCall=async(e,t)=>{this.isPendingAnswer=!0;const s=e();return this.events.emit(S.START_CALL,{answer:!0,number:s.remote_identity.uri.user}),this.mcuSession.answerToIncomingCall(s,t).finally(()=>{this.isPendingAnswer=!1})};getMainRemoteStream(){const{mainStream:e}=this.getRemoteStreams();return e}getRemoteStreams(){const{getRemoteStreams:e}=this.getActiveStreamsManagerTools();return e()}getToken(){return this.stateMachine.token}getRecvQuality(){const{recvSession:e}=this;if(e===void 0)return;const t=e.getEffectiveQuality();return{quality:e.getQuality(),effectiveQuality:t}}getActivePeerConnection=()=>this.roleManager.hasSpectator()?this.recvSession?.peerConnection:this.mcuSession.connection;setCallRoleParticipant(){this.roleManager.setCallRoleParticipant()}setCallRoleSpectatorSynthetic(){this.roleManager.setCallRoleSpectatorSynthetic()}setCallRoleSpectator(e){this.roleManager.setCallRoleSpectator(e)}async replaceMediaStream(e,t){return this.mcuSession.replaceMediaStream(e,t)}async restartIce(e){return this.mcuSession.restartIce(e)}async setRecvQuality(e){const{recvSession:t}=this;if(!this.roleManager.hasSpectator()||!t)return!1;const s=t.getQuality(),i=await t.applyQuality(e);return i.applied&&this.events.trigger(S.RECV_QUALITY_CHANGED,{previousQuality:s,quality:e,effectiveQuality:i.effectiveQuality}),i.applied}async failed(e,t){this.emitFailedCall(e,t),await this.endCall()}emitFailedCall(e,t){this.events.trigger(S.FAILED,{message:e,cause:t,originator:"local"})}reset=()=>{this.mainRemoteStreamsManager.reset(),this.roleManager.reset(),this.recvRemoteStreamsManager.reset(),this.stopRecvSession(),this.deferredStartRecvSessionRunner.cancel(),this.streamsChangeTracker.reset()};subscribeCallStatusChange(){const{ACCEPTED:e,CONFIRMED:t,ENDED:s,FAILED:i}=S,r=this.createCallStatusChangeListener();this.onRace([e,t,s,i],r)}createCallStatusChangeListener(){let e=this.isCallActive;return()=>{const t=this.isCallActive;t!==e&&this.events.trigger(S.CALL_STATUS_CHANGED,{isCallActive:t}),e=t}}subscribeMcuRemoteTrackEvents(){this.on(S.PEER_CONNECTION_ONTRACK,e=>{this.addRemoteTrack(this.mainRemoteStreamsManager,e.track,ve(e))})}addRemoteTrack(e,t,s){const i=e.addTrack(t,{streamHint:s,onRemoved:r=>{this.handleChangedRemoteTracks(e,"removed",{isRemovedStream:r.isRemovedStream,isAddedStream:!1,trackId:r.trackId,participantId:r.participantId})}});i.isAddedTrack&&this.handleChangedRemoteTracks(e,"added",{isRemovedStream:!1,isAddedStream:i.isAddedStream,trackId:t.id,participantId:i.participantId})}handleChangedRemoteTracks(e,t,{trackId:s,participantId:i,isRemovedStream:r,isAddedStream:a}){const o=this.getActiveStreamsManagerTools();if(e!==o.manager)return;const c=o.getRemoteStreams();this.emitEventChangedRemoteTracks(c,t,{trackId:s,participantId:i}),(a||r)&&this.emitEventChangedRemoteStreams(c)}emitEventChangedRemoteTracks(e,t,{trackId:s,participantId:i}){this.events.trigger(S.REMOTE_TRACKS_CHANGED,{streams:e,changeType:t,trackId:s,participantId:i})}emitEventChangedRemoteStreamsConnected=()=>{this.emitEventChangedRemoteStreams(this.getRemoteStreams())};emitEventChangedRemoteStreams(e){this.streamsChangeTracker.hasChanged(e)&&(this.streamsChangeTracker.updateLastEmittedStreams(e),this.events.trigger(S.REMOTE_STREAMS_CHANGED,{streams:e}))}getActiveStreamsManagerTools(){return this.streamsManagerProvider.getActiveStreamsManagerTools({isSpectator:this.roleManager.hasSpectator(),stateInfo:this.contentedStreamManager.getStateInfo()})}attachRecvSessionTracks(e){const{peerConnection:t}=e,s=i=>{this.addRemoteTrack(this.recvRemoteStreamsManager,i.track,ve(i))};t.addEventListener("track",s),this.disposeRecvSessionTrackListener=()=>{t.removeEventListener("track",s)}}startRecvSession(e,{sendOffer:t,token:s}){const i=this.stateMachine.number;if(i===void 0)return;this.stopRecvSession();const r={audioChannel:e},a=new hn(r,{sendOffer:t});this.recvSession=a,this.recvRemoteStreamsManager.reset(),this.attachRecvSessionTracks(a),a.call({conferenceNumber:i,token:s}).then(()=>{this.events.emit("recv-session-started")}).catch(()=>{this.stopRecvSession()})}stopRecvSession(){this.recvSession?.close(),this.recvSession=void 0,this.disposeRecvSessionTrackListener?.(),this.disposeRecvSessionTrackListener=void 0,this.recvRemoteStreamsManager.reset(),this.events.emit("recv-session-ended")}onRoleChanged=({previous:e,next:t})=>{if(p.isExitingSpectatorRole(e,t)&&(this.stopRecvSession(),this.deferredStartRecvSessionRunner.cancel(),this.emitEventChangedRemoteStreamsConnected()),p.isEnteringSpectatorRole(e,t)){const s=t.recvParams,{token:i}=this.stateMachine;i===void 0?this.deferredStartRecvSessionRunner.set({audioId:s.audioId,sendOffer:s.sendOffer}):this.startRecvSession(s.audioId,{token:i,sendOffer:s.sendOffer})}p.isExitingAnySpectatorRole(e,t)&&this.mcuSession.restoreBitrateForSenders(),p.isEnteringAnySpectatorRole(e,t)&&this.mcuSession.setMinBitrateForSenders()};subscribeContentedStreamEvents(){this.contentedStreamManager.on("available",this.emitEventChangedRemoteStreamsConnected),this.contentedStreamManager.on("not-available",this.emitEventChangedRemoteStreamsConnected)}async renegotiateRecvSession(){const e=this.stateMachine.number,{token:t}=this.stateMachine;return e===void 0||t===void 0||this.recvSession===void 0?!1:this.recvSession.renegotiate({conferenceNumber:e,token:t})}async renegotiateMcuSession(){return this.mcuSession.renegotiate()}}var w=(n=>(n.START_PRESENTATION="presentation:start",n.STARTED_PRESENTATION="presentation:started",n.END_PRESENTATION="presentation:end",n.ENDED_PRESENTATION="presentation:ended",n.FAILED_PRESENTATION="presentation:failed",n))(w||{});const We=["presentation:start","presentation:started","presentation:end","presentation:ended","presentation:failed"],fn=()=>new M.TypedEvents(We);var Qe=(n=>(n.IDLE="presentation:idle",n.STARTING="presentation:starting",n.ACTIVE="presentation:active",n.STOPPING="presentation:stopping",n.FAILED="presentation:failed",n))(Qe||{});const Mn=I.setup({types:{context:{},events:{}},actions:{logTransition:(n,e)=>{d(`State transition: ${e.from} -> ${e.to} (${e.event})`)},logStateChange:(n,e)=>{d("PresentationStateMachine state changed",e.state)},setError:I.assign(({event:n})=>"error"in n&&n.error!==void 0?{lastError:n.error instanceof Error?n.error:new Error(JSON.stringify(n.error))}:{lastError:void 0}),clearError:I.assign({lastError:void 0})}}).createMachine({id:"presentation",initial:"presentation:idle",context:{},states:{"presentation:idle":{entry:{type:"logStateChange",params:{state:"presentation:idle"}},on:{"SCREEN.STARTING":{target:"presentation:starting",actions:["clearError",{type:"logTransition",params:{from:"presentation:idle",to:"presentation:starting",event:"SCREEN.STARTING"}}]}}},"presentation:starting":{entry:{type:"logStateChange",params:{state:"presentation:starting"}},on:{"SCREEN.STARTED":{target:"presentation:active",actions:{type:"logTransition",params:{from:"presentation:starting",to:"presentation:active",event:"SCREEN.STARTED"}}},"SCREEN.FAILED":{target:"presentation:failed",actions:["setError",{type:"logTransition",params:{from:"presentation:starting",to:"presentation:failed",event:"SCREEN.FAILED"}}]},"SCREEN.ENDED":{target:"presentation:idle",actions:["clearError",{type:"logTransition",params:{from:"presentation:starting",to:"presentation:idle",event:"SCREEN.ENDED"}}]},"CALL.ENDED":{target:"presentation:idle",actions:["clearError",{type:"logTransition",params:{from:"presentation:starting",to:"presentation:idle",event:"CALL.ENDED"}}]},"CALL.FAILED":{target:"presentation:failed",actions:["setError",{type:"logTransition",params:{from:"presentation:starting",to:"presentation:failed",event:"CALL.FAILED"}}]}}},"presentation:active":{entry:{type:"logStateChange",params:{state:"presentation:active"}},on:{"SCREEN.ENDING":{target:"presentation:stopping",actions:{type:"logTransition",params:{from:"presentation:active",to:"presentation:stopping",event:"SCREEN.ENDING"}}},"SCREEN.ENDED":{target:"presentation:idle",actions:["clearError",{type:"logTransition",params:{from:"presentation:active",to:"presentation:idle",event:"SCREEN.ENDED"}}]},"SCREEN.FAILED":{target:"presentation:failed",actions:["setError",{type:"logTransition",params:{from:"presentation:active",to:"presentation:failed",event:"SCREEN.FAILED"}}]},"CALL.ENDED":{target:"presentation:idle",actions:["clearError",{type:"logTransition",params:{from:"presentation:active",to:"presentation:idle",event:"CALL.ENDED"}}]},"CALL.FAILED":{target:"presentation:failed",actions:["setError",{type:"logTransition",params:{from:"presentation:active",to:"presentation:failed",event:"CALL.FAILED"}}]}}},"presentation:stopping":{entry:{type:"logStateChange",params:{state:"presentation:stopping"}},on:{"SCREEN.ENDED":{target:"presentation:idle",actions:["clearError",{type:"logTransition",params:{from:"presentation:stopping",to:"presentation:idle",event:"SCREEN.ENDED"}}]},"SCREEN.FAILED":{target:"presentation:failed",actions:["setError",{type:"logTransition",params:{from:"presentation:stopping",to:"presentation:failed",event:"SCREEN.FAILED"}}]},"CALL.ENDED":{target:"presentation:idle",actions:["clearError",{type:"logTransition",params:{from:"presentation:stopping",to:"presentation:idle",event:"CALL.ENDED"}}]},"CALL.FAILED":{target:"presentation:failed",actions:["setError",{type:"logTransition",params:{from:"presentation:stopping",to:"presentation:failed",event:"CALL.FAILED"}}]}}},"presentation:failed":{entry:{type:"logStateChange",params:{state:"presentation:failed"}},on:{"SCREEN.STARTING":{target:"presentation:starting",actions:["clearError",{type:"logTransition",params:{from:"presentation:failed",to:"presentation:starting",event:"SCREEN.STARTING"}}]},"SCREEN.ENDED":{target:"presentation:idle",actions:["clearError",{type:"logTransition",params:{from:"presentation:failed",to:"presentation:idle",event:"SCREEN.ENDED"}}]},"PRESENTATION.RESET":{target:"presentation:idle",actions:["clearError",{type:"logTransition",params:{from:"presentation:failed",to:"presentation:idle",event:"PRESENTATION.RESET"}}]}}}}});class _n extends W{constructor(e){super(Mn),this.subscribeCallEvents(e)}get isIdle(){return this.state==="presentation:idle"}get isStarting(){return this.state==="presentation:starting"}get isActive(){return this.state==="presentation:active"}get isStopping(){return this.state==="presentation:stopping"}get isFailed(){return this.state==="presentation:failed"}get isPending(){return this.isStarting||this.isStopping}get isActiveOrPending(){return this.isActive||this.isPending}get lastError(){return this.getSnapshot().context.lastError}reset(){this.send({type:"PRESENTATION.RESET"})}send(e){if(!this.actor.getSnapshot().can(e)){console.warn(`[PresentationStateMachine] Invalid transition: ${e.type} from ${this.state}. Event cannot be processed in current state.`);return}super.send(e)}subscribeCallEvents(e){this.addSubscription(e.on(S.START_PRESENTATION,()=>{this.send({type:"SCREEN.STARTING"})})),this.addSubscription(e.on(S.STARTED_PRESENTATION,()=>{this.send({type:"SCREEN.STARTED"})})),this.addSubscription(e.on(S.END_PRESENTATION,()=>{this.send({type:"SCREEN.ENDING"})})),this.addSubscription(e.on(S.ENDED_PRESENTATION,()=>{this.send({type:"SCREEN.ENDED"})})),this.addSubscription(e.on(S.FAILED_PRESENTATION,t=>{this.send({type:"SCREEN.FAILED",error:t})})),this.addSubscription(e.on(S.ENDED,()=>{this.send({type:"CALL.ENDED"})})),this.addSubscription(e.on(S.FAILED,t=>{this.send({type:"CALL.FAILED",error:t})}))}}const bn=1,On=n=>te.hasCanceledError(n);class Pn{events;stateMachine;promisePendingStartPresentation;promisePendingStopPresentation;streamPresentationCurrent;maxBitrate;cancelableSendPresentationWithRepeatedCalls;callManager;constructor({callManager:e,maxBitrate:t}){this.callManager=e,this.maxBitrate=t,this.events=fn(),this.stateMachine=new _n(this.callManager.events),this.subscribe()}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}get isPresentationInProcess(){return!!this.streamPresentationCurrent||this.isPendingPresentation}async startPresentation(e,t,{isNeedReinvite:s,contentHint:i,sendEncodings:r,onAddedTransceiver:a}={},o){const c=this.getRtcSessionProtected();if(this.streamPresentationCurrent)throw new Error("Presentation is already started");return this.sendPresentationWithDuplicatedCalls(e,{rtcSession:c,stream:t,presentationOptions:{isNeedReinvite:s,contentHint:i,sendEncodings:r,onAddedTransceiver:a},options:o})}async stopPresentation(e){this.cancelSendPresentationWithRepeatedCalls();const t=this.streamPresentationCurrent;let s=this.promisePendingStartPresentation??Promise.resolve(void 0);this.promisePendingStartPresentation&&await this.promisePendingStartPresentation.catch(()=>{});const i=this.callManager.getEstablishedRTCSession();return i&&t?s=e().then(async()=>i.stopPresentation(t)).catch(r=>{const a=r instanceof Error?r:new Error(String(r));throw this.events.trigger(w.FAILED_PRESENTATION,a),r}):t&&this.events.trigger(w.ENDED_PRESENTATION,t),this.promisePendingStopPresentation=s,s.finally(()=>{this.resetPresentation()})}async updatePresentation(e,t,{contentHint:s,sendEncodings:i,onAddedTransceiver:r}={}){const a=this.getRtcSessionProtected();if(!this.streamPresentationCurrent)throw new Error("Presentation has not started yet");return this.promisePendingStartPresentation&&await this.promisePendingStartPresentation,this.sendPresentation(e,a,t,{contentHint:s,isNeedReinvite:!1,sendEncodings:i,onAddedTransceiver:r}).then(async o=>(await this.setMaxBitrate(),o))}cancelSendPresentationWithRepeatedCalls(){this.cancelableSendPresentationWithRepeatedCalls?.stopRepeatedCalls()}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}subscribe(){this.callManager.on("presentation:start",e=>{this.events.trigger(w.START_PRESENTATION,e)}),this.callManager.on("presentation:started",e=>{this.events.trigger(w.STARTED_PRESENTATION,e)}),this.callManager.on("presentation:end",e=>{this.events.trigger(w.END_PRESENTATION,e)}),this.callManager.on("presentation:ended",e=>{this.events.trigger(w.ENDED_PRESENTATION,e)}),this.callManager.on("presentation:failed",e=>{this.events.trigger(w.FAILED_PRESENTATION,e)}),this.callManager.on("failed",this.handleEnded),this.callManager.on("ended",this.handleEnded)}async sendPresentationWithDuplicatedCalls(e,{rtcSession:t,stream:s,presentationOptions:i,options:r={callLimit:bn}}){const a=async()=>this.sendPresentation(e,t,s,i),o=()=>!!this.streamPresentationCurrent;return this.cancelableSendPresentationWithRepeatedCalls=te.repeatedCallsAsync({targetFunction:a,isComplete:o,isRejectAsValid:!0,...r}),this.cancelableSendPresentationWithRepeatedCalls.then(c=>c)}async sendPresentation(e,t,s,{isNeedReinvite:i=!0,contentHint:r="detail",degradationPreference:a,sendEncodings:o,onAddedTransceiver:c}){const l=x(s,{contentHint:r});if(l===void 0)throw new Error("No streamPresentationTarget");this.streamPresentationCurrent=l;const u=e().then(async()=>t.startPresentation(l,i,{degradationPreference:a,sendEncodings:o,onAddedTransceiver:c})).then(this.setMaxBitrate).then(()=>s).catch(T=>{this.removeStreamPresentationCurrent();const E=T instanceof Error?T:new Error(String(T));throw this.events.trigger(w.FAILED_PRESENTATION,E),T});return this.promisePendingStartPresentation=u,u.finally(()=>{this.promisePendingStartPresentation=void 0})}setMaxBitrate=async()=>{const{connection:e}=this.callManager,{streamPresentationCurrent:t}=this,{maxBitrate:s}=this;if(!e||!t||s===void 0)return;const i=e.getSenders();await xt(i,t,s)};getRtcSessionProtected=()=>{const e=this.callManager.getEstablishedRTCSession();if(!e)throw new Error("No rtcSession established");return e};handleEnded=()=>{this.reset()};reset(){this.cancelSendPresentationWithRepeatedCalls(),this.resetPresentation()}resetPresentation(){this.removeStreamPresentationCurrent(),this.promisePendingStartPresentation=void 0,this.promisePendingStopPresentation=void 0}removeStreamPresentationCurrent(){delete this.streamPresentationCurrent}}class Dn{data;getUa;constructor(e){this.getUa=e.getUa}isConfigured(){return this.getUa()!==void 0}get(){if(this.data!==void 0)return{...this.data}}set(e){if(e===void 0){this.data=void 0;return}this.data={...e}}update(e,t){if(this.data===void 0)throw new Error("data is not exist");this.data[e]=t}clear(){this.data=void 0}isRegister(){return this.data?.register===!0}getSipServerIp(){return this.data?.sipServerIp}getSipServerUrl(){return this.data?.sipServerUrl}getDisplayName(){return this.data?.displayName}getUser(){return this.data?.user}getPassword(){return this.data?.password}isRegisterEnabled(){return this.data?.register===!0}}var C=(n=>(n.CONNECTING="connecting",n.CONNECTED="connected",n.DISCONNECTED="disconnected",n.DISCONNECTING="disconnecting",n.NEW_RTC_SESSION="newRTCSession",n.REGISTERED="registered",n.UNREGISTERED="unregistered",n.REGISTRATION_FAILED="registrationFailed",n.NEW_MESSAGE="newMessage",n.SIP_EVENT="sipEvent",n.CONNECT_STARTED="connect-started",n.CONNECT_SUCCEEDED="connect-succeeded",n.CONNECT_FAILED="connect-failed",n.CONNECT_PARAMETERS_RESOLVE_SUCCESS="connect-parameters-resolve-success",n.CONNECT_PARAMETERS_RESOLVE_FAILED="connect-parameters-resolve-failed",n.CONNECTED_WITH_CONFIGURATION="connected-with-configuration",n))(C||{});const Ye=["connecting","connected","disconnected","newRTCSession","registered","unregistered","registrationFailed","newMessage","sipEvent"],yn=["disconnecting","connect-started","connect-succeeded","connect-failed","connect-parameters-resolve-success","connect-parameters-resolve-failed","connected-with-configuration"],ze=[...Ye,...yn],Ln=()=>new M.TypedEvents(ze);function wn(n){return e=>`sip:${e}@${n}`}const Un=(n,e)=>()=>Math.floor(Math.random()*(e-n))+n,Je=n=>n.trim().replaceAll(" ","_"),kn=Un(1e5,99999999),Fn=3;class Bn{cancelableConnectWithRepeatedCalls;events;uaFactory;stateMachine;registrationManager;getUa;setUa;getConnectionConfiguration;setConnectionConfiguration;updateConnectionConfiguration;setGetUri;setSocket;constructor(e){this.events=e.events,this.uaFactory=e.uaFactory,this.stateMachine=e.stateMachine,this.registrationManager=e.registrationManager,this.getUa=e.getUa,this.setUa=e.setUa,this.getConnectionConfiguration=e.getConnectionConfiguration,this.setConnectionConfiguration=e.setConnectionConfiguration,this.updateConnectionConfiguration=e.updateConnectionConfiguration,this.setGetUri=e.setGetUri,this.setSocket=e.setSocket,this.proxyEvents()}connect=async(e,t)=>(this.cancelRequests(),this.connectWithDuplicatedCalls(e,t));set=async({displayName:e})=>new Promise((t,s)=>{const i=this.getUa();if(!i){s(new Error("this.ua is not initialized"));return}let r=!1;const a=this.getConnectionConfiguration();e!==void 0&&e!==a?.displayName&&(r=i.set("display_name",Je(e)),this.updateConnectionConfiguration("displayName",e));const o=r;o?t(o):s(new Error("nothing changed"))});disconnect=async()=>{this.events.trigger(C.DISCONNECTING,{});const e=new Promise(s=>{this.events.once(C.DISCONNECTED,()=>{s()})}),t=this.getUa();return t?t.stop():this.events.trigger(C.DISCONNECTED,{socket:{},error:!1}),e.finally(()=>{t?.removeAllListeners(),this.setUa(void 0),this.stateMachine.reset()})};cancelRequests(){this.cancelConnectWithRepeatedCalls()}connectWithDuplicatedCalls=async(e,{callLimit:t=Fn}={})=>{const s=async()=>this.connectInner(e),i=r=>{const c=this.getUa()?.isConnected()===!0&&this.hasEqualConnectionConfiguration(e),l=r!=null&&!Nt(r);return c||l};return this.stateMachine.startConnect(),this.cancelableConnectWithRepeatedCalls=te.repeatedCallsAsync({targetFunction:s,isComplete:i,callLimit:t,isRejectAsValid:!0,isCheckBeforeCall:!1}),this.cancelableConnectWithRepeatedCalls.then(r=>{if(typeof r=="object"&&r!==null&&"authorizationUser"in r)return r;throw r})};hasEqualConnectionConfiguration(e){const{configuration:t}=this.uaFactory.createConfiguration(e),i=this.getUa()?.configuration;return i?i.password===t.password&&i.register===t.register&&i.uri.toString()===t.uri&&i.display_name===t.display_name&&i.user_agent===t.user_agent&&i.sockets===t.sockets&&i.session_timers===t.session_timers&&i.register_expires===t.register_expires&&i.connection_recovery_min_interval===t.connection_recovery_min_interval&&i.connection_recovery_max_interval===t.connection_recovery_max_interval:!1}connectInner=async e=>this.initUa(e).then(async()=>this.start()).then(()=>{const t=this.getConnectionConfiguration();if(t===void 0)throw new Error("connectionConfiguration has not defined");return t});initUa=async({user:e,password:t,sipServerIp:s,sipServerUrl:i,remoteAddress:r,sessionTimers:a,registerExpires:o,connectionRecoveryMinInterval:c,connectionRecoveryMaxInterval:l,userAgent:u,displayName:T="",register:E=!1,extraHeaders:N=[]})=>{this.stateMachine.startInitUa(),this.getUa()&&await this.disconnect();const{ua:v,helpers:U}=this.uaFactory.createUAWithConfiguration({user:e,password:t,sipServerIp:s,sipServerUrl:i,displayName:T,register:E,sessionTimers:a,registerExpires:o,connectionRecoveryMinInterval:c,connectionRecoveryMaxInterval:l,userAgent:u,remoteAddress:r,extraHeaders:N},this.events),$=v.configuration.uri.user;return this.setConnectionConfiguration({sipServerIp:s,sipServerUrl:i,displayName:T,authorizationUser:$,register:E,user:e,password:t}),this.setUa(v),this.setGetUri(U.getUri),this.setSocket(U.socket),v};start=async()=>new Promise((e,t)=>{const s=this.getUa();if(!s){t(new Error("this.ua is not initialized"));return}let i;i=((c,l)=>{if(this.getConnectionConfiguration()?.register===!0)return this.registrationManager.subscribeToStartEvents(c,l);const T=C.CONNECTED,E=[C.DISCONNECTED];return this.events.on(T,c),E.forEach(N=>{this.events.on(N,l)}),()=>{this.events.off(T,c),E.forEach(N=>{this.events.off(N,l)})}})(()=>{i?.(),e(s)},c=>{i?.(),t(c)}),s.start()});cancelConnectWithRepeatedCalls(){this.cancelableConnectWithRepeatedCalls?.cancel()}proxyEvents(){this.events.on(C.CONNECTED,()=>{const e=this.getConnectionConfiguration();e!==void 0&&this.events.trigger(C.CONNECTED_WITH_CONFIGURATION,e)})}}var je=(n=>(n.IDLE="connection:idle",n.PREPARING="connection:preparing",n.CONNECTING="connection:connecting",n.CONNECTED="connection:connected",n.REGISTERED="connection:registered",n.ESTABLISHED="connection:established",n.DISCONNECTING="connection:disconnecting",n.DISCONNECTED="connection:disconnected",n))(je||{}),Xe=(n=>(n.START_CONNECT="START_CONNECT",n.START_INIT_UA="START_INIT_UA",n.START_DISCONNECT="START_DISCONNECT",n.UA_CONNECTED="UA_CONNECTED",n.UA_REGISTERED="UA_REGISTERED",n.UA_UNREGISTERED="UA_UNREGISTERED",n.UA_DISCONNECTED="UA_DISCONNECTED",n.RESET="RESET",n))(Xe||{});const $n=Object.values(Xe),Gn=I.setup({types:{context:{},events:{}},actions:{logTransition:(n,e)=>{d(`State transition: ${e.from} -> ${e.to} (${e.event})`)},logStateChange:(n,e)=>{d("ConnectionStateMachine state changed",e.state)}}}).createMachine({id:"connection",initial:"connection:idle",context:{},states:{"connection:idle":{entry:{type:"logStateChange",params:{state:"connection:idle"}},on:{START_CONNECT:{target:"connection:preparing",actions:{type:"logTransition",params:{from:"connection:idle",to:"connection:preparing",event:"START_CONNECT"}}}}},"connection:preparing":{entry:{type:"logStateChange",params:{state:"connection:preparing"}},on:{START_INIT_UA:{target:"connection:connecting",actions:{type:"logTransition",params:{from:"connection:preparing",to:"connection:connecting",event:"START_INIT_UA"}}},UA_DISCONNECTED:{target:"connection:disconnected",actions:{type:"logTransition",params:{from:"connection:preparing",to:"connection:disconnected",event:"UA_DISCONNECTED"}}}}},"connection:connecting":{entry:{type:"logStateChange",params:{state:"connection:connecting"}},on:{UA_CONNECTED:{target:"connection:connected",actions:{type:"logTransition",params:{from:"connection:connecting",to:"connection:connected",event:"UA_CONNECTED"}}},UA_REGISTERED:{target:"connection:registered",actions:{type:"logTransition",params:{from:"connection:connecting",to:"connection:registered",event:"UA_REGISTERED"}}},START_DISCONNECT:{target:"connection:disconnecting",actions:{type:"logTransition",params:{from:"connection:connecting",to:"connection:disconnecting",event:"START_DISCONNECT"}}},UA_DISCONNECTED:{target:"connection:disconnected",actions:{type:"logTransition",params:{from:"connection:connecting",to:"connection:disconnected",event:"UA_DISCONNECTED"}}}}},"connection:connected":{entry:{type:"logStateChange",params:{state:"connection:connected"}},always:{target:"connection:established",actions:{type:"logTransition",params:{from:"connection:connected",to:"connection:established",event:"always"}}},on:{UA_REGISTERED:{target:"connection:registered",actions:{type:"logTransition",params:{from:"connection:connected",to:"connection:registered",event:"UA_REGISTERED"}}},START_DISCONNECT:{target:"connection:disconnecting",actions:{type:"logTransition",params:{from:"connection:connected",to:"connection:disconnecting",event:"START_DISCONNECT"}}},UA_DISCONNECTED:{target:"connection:disconnected",actions:{type:"logTransition",params:{from:"connection:connected",to:"connection:disconnected",event:"UA_DISCONNECTED"}}}}},"connection:registered":{entry:{type:"logStateChange",params:{state:"connection:registered"}},always:{target:"connection:established",actions:{type:"logTransition",params:{from:"connection:registered",to:"connection:established",event:"always"}}},on:{UA_UNREGISTERED:{target:"connection:connected",actions:{type:"logTransition",params:{from:"connection:registered",to:"connection:connected",event:"UA_UNREGISTERED"}}},START_DISCONNECT:{target:"connection:disconnecting",actions:{type:"logTransition",params:{from:"connection:registered",to:"connection:disconnecting",event:"START_DISCONNECT"}}},UA_DISCONNECTED:{target:"connection:disconnected",actions:{type:"logTransition",params:{from:"connection:registered",to:"connection:disconnected",event:"UA_DISCONNECTED"}}}}},"connection:established":{entry:{type:"logStateChange",params:{state:"connection:established"}},on:{START_DISCONNECT:{target:"connection:disconnecting",actions:{type:"logTransition",params:{from:"connection:established",to:"connection:disconnecting",event:"START_DISCONNECT"}}},UA_DISCONNECTED:{target:"connection:disconnected",actions:{type:"logTransition",params:{from:"connection:established",to:"connection:disconnected",event:"UA_DISCONNECTED"}}},RESET:{target:"connection:idle",actions:{type:"logTransition",params:{from:"connection:established",to:"connection:idle",event:"RESET"}}}}},"connection:disconnecting":{entry:{type:"logStateChange",params:{state:"connection:disconnecting"}},on:{UA_DISCONNECTED:{target:"connection:disconnected",actions:{type:"logTransition",params:{from:"connection:disconnecting",to:"connection:disconnected",event:"UA_DISCONNECTED"}}}}},"connection:disconnected":{entry:{type:"logStateChange",params:{state:"connection:disconnected"}},on:{RESET:{target:"connection:idle",actions:{type:"logTransition",params:{from:"connection:disconnected",to:"connection:idle",event:"RESET"}}},START_CONNECT:{target:"connection:preparing",actions:{type:"logTransition",params:{from:"connection:disconnected",to:"connection:preparing",event:"START_CONNECT"}}}}}}});class qn extends W{events;unsubscribeFromEvents;constructor(e){super(Gn),this.events=e,this.subscribeToEvents()}get isIdle(){return this.hasState("connection:idle")}get isPreparing(){return this.hasState("connection:preparing")}get isConnecting(){return this.hasState("connection:connecting")}get isConnected(){return this.hasState("connection:connected")}get isRegistered(){return this.hasState("connection:registered")}get isEstablished(){return this.hasState("connection:established")}get isDisconnecting(){return this.hasState("connection:disconnecting")}get isDisconnected(){return this.hasState("connection:disconnected")}get isPending(){return this.isPreparing||this.isConnecting}get isPendingConnect(){return this.isPreparing}get isPendingInitUa(){return this.isConnecting}get isActiveConnection(){return this.isEstablished||this.isConnected||this.isRegistered}startConnect(){this.toStartConnect()}startInitUa(){this.toStartInitUa()}startDisconnect(){this.toStartDisconnect()}reset(){this.toIdle()}destroy(){this.unsubscribeFromEvents?.(),this.stop()}canTransition(e){return this.actor.getSnapshot().can({type:e})}getValidEvents(){return $n.filter(e=>this.canTransition(e))}hasState(e){return this.actor.getSnapshot().matches(e)}sendEvent(e){if(!this.actor.getSnapshot().can(e)){d(`Invalid transition: ${e.type} from ${this.state}. Event cannot be processed in current state.`);return}this.send(e)}toStartConnect=()=>{this.sendEvent({type:"START_CONNECT"})};toStartInitUa=()=>{this.sendEvent({type:"START_INIT_UA"})};toStartDisconnect=()=>{this.sendEvent({type:"START_DISCONNECT"})};toConnected=()=>{this.sendEvent({type:"UA_CONNECTED"})};toRegistered=()=>{this.sendEvent({type:"UA_REGISTERED"})};toUnregistered=()=>{this.sendEvent({type:"UA_UNREGISTERED"})};toDisconnected=()=>{this.sendEvent({type:"UA_DISCONNECTED"})};toIdle=()=>{this.sendEvent({type:"RESET"})};subscribeToEvents(){this.events.on("connected",this.toConnected),this.events.on("registered",this.toRegistered),this.events.on("unregistered",this.toUnregistered),this.events.on("disconnecting",this.toStartDisconnect),this.events.on("disconnected",this.toDisconnected),this.events.on("registrationFailed",this.toDisconnected),this.events.on("connect-failed",this.toDisconnected),this.unsubscribeFromEvents=()=>{this.events.off("connected",this.toConnected),this.events.off("registered",this.toRegistered),this.events.off("unregistered",this.toUnregistered),this.events.off("disconnecting",this.toStartDisconnect),this.events.off("disconnected",this.toDisconnected),this.events.off("registrationFailed",this.toDisconnected),this.events.off("connect-failed",this.toDisconnected)}}}class Vn{events;getUaProtected;constructor(e){this.events=e.events,this.getUaProtected=e.getUaProtected}async register(){const e=this.getUaProtected();return new Promise((t,s)=>{e.on(C.REGISTERED,t),e.on(C.REGISTRATION_FAILED,s),e.register()})}async unregister(){const e=this.getUaProtected();return new Promise(t=>{e.on(C.UNREGISTERED,t),e.unregister()})}async tryRegister(){try{await this.unregister()}catch(e){d("tryRegister",e)}return this.register()}subscribeToStartEvents(e,t){const s=C.REGISTERED,i=[C.REGISTRATION_FAILED,C.DISCONNECTED];return this.events.on(s,e),i.forEach(r=>{this.events.on(r,t)}),()=>{this.events.off(s,e),i.forEach(r=>{this.events.off(r,t)})}}}class xn{uaFactory;getUaProtected;constructor(e){this.uaFactory=e.uaFactory,this.getUaProtected=e.getUaProtected}async sendOptions(e,t,s){const i=this.getUaProtected();return new Promise((r,a)=>{try{i.sendOptions(e,t,{extraHeaders:s,eventHandlers:{succeeded:()=>{r()},failed:a}})}catch(o){a(o)}})}async ping(e,t){const i=this.getUaProtected().configuration.uri;return this.sendOptions(i,e,t)}async checkTelephony({userAgent:e,displayName:t,sipServerIp:s,sipServerUrl:i,remoteAddress:r,extraHeaders:a}){return new Promise((o,c)=>{const{configuration:l}=this.uaFactory.createConfiguration({sipServerUrl:i,displayName:t,userAgent:e,sipServerIp:s}),u=this.uaFactory.createUA({...l,remoteAddress:r,extraHeaders:a}),T=()=>{const N=new Error("Telephony is not available");c(N)};u.once(C.DISCONNECTED,T);const E=()=>{u.removeAllListeners(),u.once(C.DISCONNECTED,()=>{o()}),u.stop()};u.once(C.CONNECTED,E),u.start()})}}const Hn=n=>{const e=[];return n!==void 0&&n!==""&&e.push(`X-Vinteo-Remote: ${n}`),e};class F{JsSIP;constructor(e){this.JsSIP=e}static isRegisteredUA(e){return!!e&&e.isRegistered()}static validateParametersConnection({register:e,password:t,user:s,sipServerIp:i,sipServerUrl:r}){if(!i)throw new Error("sipServerIp is required");if(!r)throw new Error("sipServerUrl is required");if(e&&(t===void 0||t===""))throw new Error("password is required for authorized connection");if(e&&(s===void 0||s===""))throw new Error("user is required for authorized connection")}static resolveAuthorizationUser(e,t){return e&&t!==void 0&&t.trim()!==""?t.trim():`${kn()}`}static buildExtraHeaders(e,t){const s=e!==void 0&&e!==""?Hn(e):[];return t===void 0?s:[...s,...t]}createConfiguration({user:e,password:t,sipServerUrl:s,displayName:i="",sipServerIp:r,register:a=!1,sessionTimers:o=!1,registerExpires:c=300,connectionRecoveryMinInterval:l=2,connectionRecoveryMaxInterval:u=6,userAgent:T}){F.validateParametersConnection({register:a,password:t,user:e,sipServerIp:r,sipServerUrl:s});const E=F.resolveAuthorizationUser(a,e),N=wn(r),y=N(E),v=new this.JsSIP.WebSocketInterface(`wss://${s}/webrtc/wss/`);return{configuration:{password:t,register:a,uri:y,display_name:Je(i),user_agent:T,sdpSemantics:"unified-plan",sockets:[v],session_timers:o,register_expires:c,connection_recovery_min_interval:l,connection_recovery_max_interval:u},helpers:{socket:v,getUri:N}}}createUA({remoteAddress:e,extraHeaders:t,...s}){const i=new this.JsSIP.UA(s),r=F.buildExtraHeaders(e,t);return r.length>0&&i.registrator().setExtraHeaders(r),i}createUAWithConfiguration(e,t){const{configuration:s,helpers:i}=this.createConfiguration(e),r=this.createUA({...s,remoteAddress:e.remoteAddress,extraHeaders:e.extraHeaders});return t.eachTriggers((a,o)=>{const c=Ye.find(l=>l===o);c&&r.on(c,a)}),{ua:r,helpers:i}}}const Ke="Not ready for connection",Ze=n=>n instanceof Error&&n.message===Ke,Wn=()=>new Error(Ke),Qn=async n=>typeof n=="function"?n():n;class Yn{events;stateMachine;ua;socket;uaFactory;registrationManager;connectionFlow;sipOperations;configurationManager;constructor({JsSIP:e}){this.events=Ln(),this.uaFactory=new F(e),this.registrationManager=new Vn({events:this.events,getUaProtected:this.getUaProtected}),this.stateMachine=new qn(this.events),this.configurationManager=new Dn({getUa:this.getUa}),this.sipOperations=new xn({uaFactory:this.uaFactory,getUaProtected:this.getUaProtected}),this.connectionFlow=new Bn({events:this.events,uaFactory:this.uaFactory,stateMachine:this.stateMachine,registrationManager:this.registrationManager,getUa:this.getUa,getConnectionConfiguration:this.getConnectionConfiguration,setConnectionConfiguration:t=>{this.configurationManager.set(t)},updateConnectionConfiguration:(t,s)=>{this.configurationManager.update(t,s)},setUa:t=>{this.ua=t},setGetUri:t=>{this.getUri=t},setSocket:t=>{this.socket=t}})}get requested(){return this.stateMachine.isPending}get isPendingConnect(){return this.stateMachine.isPendingConnect}get isPendingInitUa(){return this.stateMachine.isPendingInitUa}get isIdle(){return this.stateMachine.isIdle}get isDisconnected(){return this.stateMachine.isDisconnected}get isDisconnecting(){return this.stateMachine.isDisconnecting}get connectionState(){return this.stateMachine.state}get isRegistered(){return F.isRegisteredUA(this.ua)}get isRegisterConfig(){return this.configurationManager.isRegister()}connect=async(e,t)=>this.disconnect().catch(s=>{d("connect: disconnect error",s)}).then(async()=>this.connectWithProcessError(e,t));set=async({displayName:e})=>this.connectionFlow.set({displayName:e});disconnect=async()=>{if(this.isConfigured())return this.connectionFlow.disconnect()};async register(){return this.registrationManager.register()}async unregister(){return this.registrationManager.unregister()}tryRegister=async()=>this.registrationManager.tryRegister();sendOptions=async(e,t,s)=>this.sipOperations.sendOptions(e,t,s);ping=async(e,t)=>this.sipOperations.ping(e,t);checkTelephony=async e=>this.sipOperations.checkTelephony(e);on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}isConfigured(){return this.configurationManager.isConfigured()}getConnectionConfiguration=()=>this.configurationManager.get();destroy(){this.stateMachine.destroy()}getUri=e=>e;getUser(){try{return this.getUaProtected().configuration.uri.user}catch{return}}getUaProtected=()=>{if(!this.ua)throw new Error("UA not initialized");return this.ua};getUa=()=>this.ua;connectWithProcessError=async(e,t)=>{if(!(t?.hasReadyForConnection?.()??!0))throw Wn();return this.processConnect(e,t).catch(async i=>{const r=i;return this.disconnect().then(()=>{throw r}).catch(()=>{throw r})})};processConnect=async(e,t)=>(this.events.trigger(C.CONNECT_STARTED,{}),Qn(e).then(s=>(this.events.trigger(C.CONNECT_PARAMETERS_RESOLVE_SUCCESS,s),s)).catch(s=>{throw this.events.trigger(C.CONNECT_PARAMETERS_RESOLVE_FAILED,s),s}).then(async s=>this.connectionFlow.connect(s,t)).then(s=>(this.events.trigger(C.CONNECT_SUCCEEDED,{...s}),s)).catch(s=>{const i=s??new Error("Failed to connect to server");throw this.events.trigger(C.CONNECT_FAILED,i),i}))}class zn{connectionManager;stackPromises=he.createStackPromises({noRunIsNotActual:!0});constructor({connectionManager:e}){this.connectionManager=e}connect=async(...e)=>this.stackPromises.run(async()=>this.connectionManager.connect(...e));disconnect=async()=>this.stackPromises.run(async()=>this.connectionManager.disconnect());stop(){this.stackPromises.stop()}}const fe=0,Jn=30;class jn{countInner=fe;initialCount=fe;limitInner=Jn;isInProgress=!1;onStatusChange;constructor({onStatusChange:e}){this.onStatusChange=e}get count(){return this.countInner}get limit(){return this.limitInner}get isAttemptInProgress(){return this.isInProgress}hasLimitReached(){return this.countInner>=this.limitInner}startAttempt(){this.isInProgress||(this.isInProgress=!0,this.onStatusChange({isInProgress:this.isInProgress}))}finishAttempt(){this.isInProgress&&(this.isInProgress=!1,this.onStatusChange({isInProgress:this.isInProgress}))}increment(){this.count<this.limit&&(this.countInner+=1)}reset(){this.countInner=this.initialCount,this.finishAttempt()}}class Xn{connectionManager;interval;checkTelephonyByTimeout=void 0;cancelableBeforeRequest=void 0;constructor({connectionManager:e,interval:t}){this.connectionManager=e,this.interval=t}start({onBeforeRequest:e,onSuccessRequest:t,onFailRequest:s}){this.stop(),this.cancelableBeforeRequest=new H.CancelableRequest(e),this.checkTelephonyByTimeout=B.resolveRequesterByTimeout({isDontStopOnFail:!0,requestInterval:this.interval,request:async()=>{if(!this.cancelableBeforeRequest)throw new Error("cancelableBeforeRequest is not defined");const i=await this.cancelableBeforeRequest.request();return this.connectionManager.checkTelephony(i)}}),this.checkTelephonyByTimeout.start(void 0,{onFailRequest:s,onSuccessRequest:()=>{this.stop(),t()}})}stop(){this.checkTelephonyByTimeout?.stop(),this.checkTelephonyByTimeout=void 0,this.cancelableBeforeRequest?.cancelRequest(),this.cancelableBeforeRequest=void 0}}var _=(n=>(n.BEFORE_ATTEMPT="before-attempt",n.SUCCESS="success",n.FAILED_ALL_ATTEMPTS="failed-all-attempts",n.CANCELLED_ATTEMPTS="cancelled-attempts",n.CHANGED_ATTEMPT_STATUS="changed-attempt-status",n.STOP_ATTEMPTS_BY_ERROR="stop-attempts-by-error",n.LIMIT_REACHED_ATTEMPTS="limit-reached-attempts",n))(_||{});const et=["before-attempt","success","failed-all-attempts","cancelled-attempts","changed-attempt-status","stop-attempts-by-error","limit-reached-attempts"],Kn=()=>new M.TypedEvents(et);class me{callManager;disposers=[];constructor({callManager:e}){this.callManager=e}subscribe(e){this.unsubscribe(),this.disposers.push(this.callManager.on("call-status-changed",()=>{this.handleCallStatusChange(e)})),this.handleCallStatusChange(e)}unsubscribe(){this.disposers.forEach(e=>{e()}),this.disposers=[]}handleCallStatusChange({onActive:e,onInactive:t}){this.callManager.isCallActive?e?.():t()}}const Zn=15e3,es=2;class ts{connectionManager;pingServerByTimeoutWithFailCalls;constructor({connectionManager:e}){this.connectionManager=e,this.pingServerByTimeoutWithFailCalls=B.requesterByTimeoutsWithFailCalls(es,{whenPossibleRequest:async()=>{},requestInterval:Zn,request:async()=>(d("ping"),this.connectionManager.ping().then(()=>{d("ping success")}))})}start({onFailRequest:e}){this.pingServerByTimeoutWithFailCalls.start(void 0,{onFailRequest:e}).catch(d)}stop(){this.pingServerByTimeoutWithFailCalls.stop()}}class ns{pingServerRequester;notActiveCallSubscriber;constructor({connectionManager:e,callManager:t}){this.pingServerRequester=new ts({connectionManager:e}),this.notActiveCallSubscriber=new me({callManager:t})}start({onFailRequest:e}){d("start"),this.notActiveCallSubscriber.subscribe({onActive:()=>{this.pingServerRequester.stop()},onInactive:()=>{this.pingServerRequester.start({onFailRequest:e})}})}stop(){d("stop"),this.pingServerRequester.stop(),this.unsubscribeCallStatusChange()}unsubscribeCallStatusChange(){this.notActiveCallSubscriber.unsubscribe()}}class ss{connectionManager;isRegistrationFailed=!1;disposers=[];notActiveCallSubscriber;constructor({connectionManager:e,callManager:t}){this.connectionManager=e,this.notActiveCallSubscriber=new me({callManager:t})}subscribe(e){this.unsubscribe(),this.disposers.push(this.connectionManager.on("registrationFailed",()=>{this.setIsRegistrationFailed()})),this.notActiveCallSubscriber.subscribe({onInactive:()=>{this.isRegistrationFailed&&e()}}),this.disposers.push(()=>{this.notActiveCallSubscriber.unsubscribe()})}unsubscribe(){this.disposers.forEach(e=>{e()}),this.disposers=[],this.resetIsRegistrationFailed()}setIsRegistrationFailed(){this.isRegistrationFailed=!0}resetIsRegistrationFailed(){this.isRegistrationFailed=!1}}const is=3e3,rs=15e3,Me={LIMIT_REACHED:"Limit reached",FAILED_TO_RECONNECT:"Failed to reconnect"},as=async()=>{},os=n=>!0;class cs{events;connectionManager;connectionQueueManager;checkTelephonyRequester;pingServerIfNotActiveCallRequester;registrationFailedOutOfCallSubscriber;attemptsState;delayBetweenAttempts;cancelableRequestBeforeRetry;onBeforeRetry;canRetryOnError;networkInterfacesSubscriber;resumeFromSleepModeSubscriber;notActiveCallSubscriber;constructor({connectionQueueManager:e,connectionManager:t,callManager:s},i){const r=i?.onBeforeRetry??as,a=i?.canRetryOnError??os;this.connectionQueueManager=e,this.connectionManager=t,this.onBeforeRetry=r,this.canRetryOnError=a,this.networkInterfacesSubscriber=i?.networkInterfacesSubscriber,this.resumeFromSleepModeSubscriber=i?.resumeFromSleepModeSubscriber,this.events=Kn(),this.checkTelephonyRequester=new Xn({connectionManager:t,interval:i?.checkTelephonyRequestInterval??rs}),this.pingServerIfNotActiveCallRequester=new ns({connectionManager:t,callManager:s}),this.registrationFailedOutOfCallSubscriber=new ss({connectionManager:t,callManager:s}),this.attemptsState=new jn({onStatusChange:this.emitStatusChange}),this.cancelableRequestBeforeRetry=new H.CancelableRequest(r),this.delayBetweenAttempts=new B.DelayRequester(i?.timeoutBetweenAttempts??is),this.notActiveCallSubscriber=new me({callManager:s})}start(e){d("auto connector start"),this.restartConnectionAttempts(e),this.subscribeToNotActiveCall(e)}stop(){d("auto connector stop"),this.unsubscribeFromNotActiveCall(),this.unsubscribeFromHardwareTriggers(),this.stopConnectionFlow().catch(e=>{d("auto connector stop from stop method: error",e)})}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}restartConnectionAttempts(e){d("auto connector restart connection attempts"),this.stopConnectionFlow().then(async()=>this.attemptConnection(e)).catch(t=>{d("auto connector failed to restart connection attempts:",t)})}async stopConnectionFlow(){d("stopConnectionFlow"),this.stopAttempts(),this.stopConnectTriggers(),await this.connectionQueueManager.disconnect()}stopAttempts(){this.attemptsState.isAttemptInProgress&&this.connectionQueueManager.stop(),this.delayBetweenAttempts.cancelRequest(),this.cancelableRequestBeforeRetry.cancelRequest(),this.attemptsState.reset()}stopConnectTriggers(){d("stopConnectTriggers"),this.stopPingRequester(),this.checkTelephonyRequester.stop(),this.registrationFailedOutOfCallSubscriber.unsubscribe()}startCheckTelephony(e){d("startCheckTelephony"),this.checkTelephonyRequester.start({onBeforeRequest:async()=>(await this.onBeforeRetry(),e.getParameters()),onSuccessRequest:()=>{d("startCheckTelephony: onSuccessRequest"),this.connectIfDisconnected(e)},onFailRequest:t=>{d("startCheckTelephony: onFailRequest",t.message)}})}async attemptConnection(e){if(d("attemptConnection: attempts.count",this.attemptsState.count),this.events.trigger(_.BEFORE_ATTEMPT,{}),this.stopConnectTriggers(),this.attemptsState.hasLimitReached()){d("attemptConnection: limit reached"),this.handleLimitReached(e);return}return this.attemptsState.startAttempt(),this.attemptsState.increment(),this.executeConnectionAttempt(e)}async executeConnectionAttempt(e){try{await this.connectionQueueManager.connect(e.getParameters,e.options),d("executeConnectionAttempt: success"),this.handleSucceededAttempt(e)}catch(t){this.handleConnectionError(t,e)}}handleConnectionError(e,t){if(Ze(e)){this.attemptsState.finishAttempt(),this.events.trigger(_.STOP_ATTEMPTS_BY_ERROR,e);return}if(!this.canRetryOnError(e)){d("executeConnectionAttempt: error does not allow retry",e),this.attemptsState.finishAttempt(),this.events.trigger(_.STOP_ATTEMPTS_BY_ERROR,e);return}if(he.isPromiseIsNotActualError(e)){d("executeConnectionAttempt: not actual error",e),this.attemptsState.finishAttempt(),this.events.trigger(_.CANCELLED_ATTEMPTS,e);return}d("executeConnectionAttempt: error",e),this.scheduleReconnect(t)}handleLimitReached(e){this.attemptsState.finishAttempt(),this.events.trigger(_.LIMIT_REACHED_ATTEMPTS,new Error(Me.LIMIT_REACHED)),this.startCheckTelephony(e)}handleSucceededAttempt(e){d("handleSucceededAttempt"),this.subscribeToConnectTriggers(e),this.events.trigger(_.SUCCESS)}subscribeToConnectTriggers(e){this.startPingRequester(e),this.registrationFailedOutOfCallSubscriber.subscribe(()=>{d("registrationFailedOutOfCallListener callback"),this.restartConnectionAttempts(e)})}subscribeToNotActiveCall(e){this.notActiveCallSubscriber.subscribe({onActive:()=>{d("subscribeToNotActiveCall onActive"),this.unsubscribeFromHardwareTriggers()},onInactive:()=>{d("subscribeToNotActiveCall onInactive"),this.subscribeToHardwareTriggers(e)}})}unsubscribeFromNotActiveCall(){this.notActiveCallSubscriber.unsubscribe()}subscribeToHardwareTriggers(e){this.unsubscribeFromHardwareTriggers(),d("subscribeToHardwareTriggers"),this.networkInterfacesSubscriber?.subscribe({onChange:()=>{d("networkInterfacesSubscriber onChange"),this.restartConnectionAttempts(e)},onUnavailable:()=>{d("networkInterfacesSubscriber onUnavailable"),this.stopConnectionFlow().catch(t=>{d("auto connector stop from networkInterfacesSubscriber onUnavailable: error",t)})}}),this.resumeFromSleepModeSubscriber?.subscribe({onResume:()=>{d("resumeFromSleepModeSubscriber onResume"),this.restartConnectionAttempts(e)}})}unsubscribeFromHardwareTriggers(){d("unsubscribeFromHardwareTriggers"),this.networkInterfacesSubscriber?.unsubscribe(),this.resumeFromSleepModeSubscriber?.unsubscribe()}stopPingRequester(){this.pingServerIfNotActiveCallRequester.stop()}startPingRequester(e){this.pingServerIfNotActiveCallRequester.start({onFailRequest:()=>{d("pingRequester: onFailRequest"),this.restartConnectionAttempts(e)}})}connectIfDisconnected(e){const t=this.isConnectionUnavailable();d("connectIfDisconnected: isUnavailable",t),t?this.restartConnectionAttempts(e):(this.stopConnectTriggers(),this.events.trigger(_.SUCCESS))}scheduleReconnect(e){d("scheduleReconnect"),this.delayBetweenAttempts.request().then(async()=>(d("scheduleReconnect: delayBetweenAttempts success"),this.cancelableRequestBeforeRetry.request())).then(async()=>(d("scheduleReconnect: onBeforeRetry success"),this.attemptConnection(e))).catch(t=>{const s=t instanceof Error?t:new Error(Me.FAILED_TO_RECONNECT);this.attemptsState.finishAttempt(),H.isCanceledError(t)||B.hasCanceledError(t)?this.events.trigger(_.CANCELLED_ATTEMPTS,s):this.events.trigger(_.FAILED_ALL_ATTEMPTS,s),d("scheduleReconnect: error",t)})}isConnectionUnavailable(){const{isDisconnected:e,isIdle:t}=this.connectionManager;return e||t}emitStatusChange=({isInProgress:e})=>{this.events.trigger(_.CHANGED_ATTEMPT_STATUS,{isInProgress:e})}}const ds=I.setup({types:{context:{},events:{}},actions:{setCodec:I.assign(({event:n})=>"codec"in n?{codec:n.codec}:{}),clearCodec:I.assign({codec:void 0})}}).createMachine({id:"contented-stream",initial:"contented-stream:not-available",context:{},states:{"contented-stream:not-available":{on:{"CONTENTED_STREAM.AVAILABLE":{target:"contented-stream:available",actions:"setCodec"}}},"contented-stream:available":{on:{"CONTENTED_STREAM.NOT_AVAILABLE":{target:"contented-stream:not-available",actions:"clearCodec"},"CONTENTED_STREAM.AVAILABLE":{target:"contented-stream:available",actions:"setCodec",reenter:!0},"CONTENTED_STREAM.RESET":{target:"contented-stream:not-available",actions:"clearCodec"}}}}});class hs extends W{constructor(){super(ds)}get isAvailable(){return this.state==="contented-stream:available"}get isNotAvailable(){return this.state==="contented-stream:not-available"}get codec(){return this.getSnapshot().context.codec}getStateInfo(){return{isAvailable:this.isAvailable,codec:this.codec}}reset(){this.send({type:"CONTENTED_STREAM.RESET"})}send(e){if(!this.actor.getSnapshot().can(e)){console.warn(`[ContentedStreamStateMachine] Invalid transition: ${e.type} from ${this.state}. Event cannot be processed in current state.`);return}super.send(e)}subscribeToApiEvents(e){this.addSubscription(e.on("contented-stream:available",t=>{this.send({type:"CONTENTED_STREAM.AVAILABLE",codec:t.codec})})),this.addSubscription(e.on("contented-stream:not-available",()=>{this.send({type:"CONTENTED_STREAM.NOT_AVAILABLE"})}))}}var ce=(n=>(n.AVAILABLE="available",n.NOT_AVAILABLE="not-available",n))(ce||{});const ls=["available","not-available"],us=()=>new M.TypedEvents(ls);class gs{events;stateMachine;constructor(){this.events=us(),this.stateMachine=new hs,this.proxyEvents()}get isAvailable(){return this.stateMachine.isAvailable}get codec(){return this.stateMachine.codec}getStateInfo(){return this.stateMachine.getStateInfo()}reset(){this.stateMachine.reset()}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}off(e,t){this.events.off(e,t)}subscribeToApiEvents(e){this.stateMachine.subscribeToApiEvents(e.events)}proxyEvents(){this.stateMachine.onStateChange(()=>{const e=this.getStateInfo();e.isAvailable?this.events.trigger(ce.AVAILABLE,{codec:e.codec}):this.events.trigger(ce.NOT_AVAILABLE,{})})}}var q=(n=>(n.RINGING="ringing",n.DECLINED_INCOMING_CALL="declinedIncomingCall",n.TERMINATED_INCOMING_CALL="terminatedIncomingCall",n.FAILED_INCOMING_CALL="failedIncomingCall",n))(q||{});const tt=["ringing","declinedIncomingCall","terminatedIncomingCall","failedIncomingCall"],Ts=()=>new M.TypedEvents(tt);var nt=(n=>(n.IDLE="incoming:idle",n.RINGING="incoming:ringing",n.CONSUMED="incoming:consumed",n.DECLINED="incoming:declined",n.TERMINATED="incoming:terminated",n.FAILED="incoming:failed",n))(nt||{});const Ss=I.setup({types:{context:{},events:{}},actions:{logTransition:(n,e)=>{d(`State transition: ${e.from} -> ${e.to} (${e.event})`)},logStateChange:(n,e)=>{d("IncomingCallStateMachine state changed",e.state)},rememberIncoming:I.assign(({event:n})=>{const{data:e}=n;return{remoteCallerData:e,lastReason:void 0}}),rememberReason:I.assign(({event:n,context:e})=>n.type==="INCOMING.CONSUMED"?{remoteCallerData:e.remoteCallerData,lastReason:"incoming:consumed"}:n.type==="INCOMING.DECLINED"?{remoteCallerData:n.data,lastReason:"incoming:declined"}:n.type==="INCOMING.TERMINATED"?{remoteCallerData:n.data,lastReason:"incoming:terminated"}:{remoteCallerData:n.data,lastReason:"incoming:failed"}),clearIncoming:I.assign(()=>({remoteCallerData:void 0,lastReason:void 0}))}}).createMachine({id:"incoming",initial:"incoming:idle",context:{},states:{"incoming:idle":{entry:{type:"logStateChange",params:{state:"incoming:idle"}},on:{"INCOMING.RINGING":{target:"incoming:ringing",actions:["rememberIncoming",{type:"logTransition",params:{from:"incoming:idle",to:"incoming:ringing",event:"INCOMING.RINGING"}}]},"INCOMING.CLEAR":{target:"incoming:idle",actions:["clearIncoming",{type:"logTransition",params:{from:"incoming:idle",to:"incoming:idle",event:"INCOMING.CLEAR"}}]}}},"incoming:ringing":{entry:{type:"logStateChange",params:{state:"incoming:ringing"}},on:{"INCOMING.RINGING":{target:"incoming:ringing",actions:["rememberIncoming",{type:"logTransition",params:{from:"incoming:ringing",to:"incoming:ringing",event:"INCOMING.RINGING"}}]},"INCOMING.CONSUMED":{target:"incoming:consumed",actions:["rememberReason",{type:"logTransition",params:{from:"incoming:ringing",to:"incoming:consumed",event:"INCOMING.CONSUMED"}}]},"INCOMING.DECLINED":{target:"incoming:declined",actions:["rememberReason",{type:"logTransition",params:{from:"incoming:ringing",to:"incoming:declined",event:"INCOMING.DECLINED"}}]},"INCOMING.TERMINATED":{target:"incoming:terminated",actions:["rememberReason",{type:"logTransition",params:{from:"incoming:ringing",to:"incoming:terminated",event:"INCOMING.TERMINATED"}}]},"INCOMING.FAILED":{target:"incoming:failed",actions:["rememberReason",{type:"logTransition",params:{from:"incoming:ringing",to:"incoming:failed",event:"INCOMING.FAILED"}}]},"INCOMING.CLEAR":{target:"incoming:idle",actions:["clearIncoming",{type:"logTransition",params:{from:"incoming:ringing",to:"incoming:idle",event:"INCOMING.CLEAR"}}]}}},"incoming:consumed":{entry:{type:"logStateChange",params:{state:"incoming:consumed"}},on:{"INCOMING.CLEAR":{target:"incoming:idle",actions:["clearIncoming",{type:"logTransition",params:{from:"incoming:consumed",to:"incoming:idle",event:"INCOMING.CLEAR"}}]},"INCOMING.RINGING":{target:"incoming:ringing",actions:["rememberIncoming",{type:"logTransition",params:{from:"incoming:consumed",to:"incoming:ringing",event:"INCOMING.RINGING"}}]}}},"incoming:declined":{entry:{type:"logStateChange",params:{state:"incoming:declined"}},on:{"INCOMING.CLEAR":{target:"incoming:idle",actions:["clearIncoming",{type:"logTransition",params:{from:"incoming:declined",to:"incoming:idle",event:"INCOMING.CLEAR"}}]},"INCOMING.RINGING":{target:"incoming:ringing",actions:["rememberIncoming",{type:"logTransition",params:{from:"incoming:declined",to:"incoming:ringing",event:"INCOMING.RINGING"}}]}}},"incoming:terminated":{entry:{type:"logStateChange",params:{state:"incoming:terminated"}},on:{"INCOMING.CLEAR":{target:"incoming:idle",actions:["clearIncoming",{type:"logTransition",params:{from:"incoming:terminated",to:"incoming:idle",event:"INCOMING.CLEAR"}}]},"INCOMING.RINGING":{target:"incoming:ringing",actions:["rememberIncoming",{type:"logTransition",params:{from:"incoming:terminated",to:"incoming:ringing",event:"INCOMING.RINGING"}}]}}},"incoming:failed":{entry:{type:"logStateChange",params:{state:"incoming:failed"}},on:{"INCOMING.CLEAR":{target:"incoming:idle",actions:["clearIncoming",{type:"logTransition",params:{from:"incoming:failed",to:"incoming:idle",event:"INCOMING.CLEAR"}}]},"INCOMING.RINGING":{target:"incoming:ringing",actions:["rememberIncoming",{type:"logTransition",params:{from:"incoming:failed",to:"incoming:ringing",event:"INCOMING.RINGING"}}]}}}}});class Es extends W{constructor({incomingEvents:e,connectionEvents:t}){super(Ss),this.subscribeIncomingEvents(e),this.subscribeConnectionEvents(t)}get isIdle(){return this.state==="incoming:idle"}get isRinging(){return this.state==="incoming:ringing"}get isConsumed(){return this.state==="incoming:consumed"}get isDeclined(){return this.state==="incoming:declined"}get isTerminated(){return this.state==="incoming:terminated"}get isFailed(){return this.state==="incoming:failed"}get isActive(){return this.isRinging}get isFinished(){return this.isConsumed||this.isDeclined||this.isTerminated||this.isFailed}get remoteCallerData(){return this.getSnapshot().context.remoteCallerData}get lastReason(){return this.getSnapshot().context.lastReason}reset(){this.send({type:"INCOMING.CLEAR"})}send(e){if(!this.actor.getSnapshot().can(e)){console.warn(`[IncomingCallStateMachine] Invalid transition: ${e.type} from ${this.state}. Event cannot be processed in current state.`);return}super.send(e)}toConsumed(){this.send({type:"INCOMING.CONSUMED"})}subscribeIncomingEvents(e){this.addSubscription(e.on("ringing",t=>{this.send({type:"INCOMING.RINGING",data:t})})),this.addSubscription(e.on("declinedIncomingCall",t=>{this.send({type:"INCOMING.DECLINED",data:t})})),this.addSubscription(e.on("terminatedIncomingCall",t=>{this.send({type:"INCOMING.TERMINATED",data:t})})),this.addSubscription(e.on("failedIncomingCall",t=>{this.send({type:"INCOMING.FAILED",data:t})}))}subscribeConnectionEvents(e){this.addSubscription(e.on(C.DISCONNECTED,()=>{this.toClearIncoming()})),this.addSubscription(e.on(C.REGISTRATION_FAILED,()=>{this.toClearIncoming()})),this.addSubscription(e.on(C.CONNECT_FAILED,()=>{this.toClearIncoming()}))}toClearIncoming(){this.send({type:"INCOMING.CLEAR"})}}const Cs=486,ms=487,ae=n=>({displayName:n.remote_identity.display_name,host:n.remote_identity.uri.host,incomingNumber:n.remote_identity.uri.user,rtcSession:n});class ps{events;stateMachine;incomingRTCSession;connectionManager;constructor(e){this.connectionManager=e,this.events=Ts(),this.stateMachine=new Es({incomingEvents:this.events,connectionEvents:this.connectionManager.events}),this.start()}get remoteCallerData(){if(this.incomingRTCSession)return ae(this.incomingRTCSession)}get isAvailableIncomingCall(){return!!this.incomingRTCSession}start(){this.subscribe()}stop(){this.unsubscribe(),this.removeIncomingSession()}getIncomingRTCSession=()=>{const{incomingRTCSession:e}=this;if(!e)throw new Error("No incomingRTCSession");return e};extractIncomingRTCSession=()=>{const e=this.getIncomingRTCSession();return this.stateMachine.toConsumed(),this.removeIncomingSession(),e};async declineToIncomingCall({statusCode:e=ms}={}){return new Promise((t,s)=>{try{const i=this.getIncomingRTCSession(),r=ae(i);this.removeIncomingSession(),this.events.trigger(q.DECLINED_INCOMING_CALL,r),i.terminate({status_code:e}),t()}catch(i){s(i)}})}async busyIncomingCall(){return this.declineToIncomingCall({statusCode:Cs})}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}subscribe(){this.connectionManager.on("newRTCSession",this.handleNewRTCSession)}unsubscribe(){this.connectionManager.off("newRTCSession",this.handleNewRTCSession)}handleNewRTCSession=({originator:e,session:t})=>{e==="remote"&&this.setIncomingSession(t)};setIncomingSession(e){this.incomingRTCSession=e;const t=ae(e);e.on("failed",s=>{this.removeIncomingSession(),s.originator==="local"?this.events.trigger(q.TERMINATED_INCOMING_CALL,t):this.events.trigger(q.FAILED_INCOMING_CALL,t)}),this.events.trigger(q.RINGING,t)}removeIncomingSession(){delete this.incomingRTCSession}}class Rs{apiManager;connectionManager;callManager;get user(){return this.connectionManager?.getUser()}get number(){return this.callManager?.number}get isCallInitiator(){return!!this.callManager?.isCallInitiator}get peerToPeerRoom(){if(!(this.user===void 0||this.number===void 0))return this.isCallInitiator?`p2p${this.user}to${this.number}`:`p2p${this.number}to${this.user}`}subscribe({apiManager:e,connectionManager:t,callManager:s}){this.apiManager=e,this.connectionManager=t,this.callManager=s,s.on("confirmed",this.maybeSendDirectPeerToPeerRoom)}maybeSendDirectPeerToPeerRoom=()=>{const{peerToPeerRoom:e,number:t,apiManager:s}=this;if(e===void 0||t===void 0||s===void 0)return;const i=[`${h.CONTENT_ENTER_ROOM}: ${this.peerToPeerRoom}`,`${h.PARTICIPANT_NAME}: ${this.number}`,`${h.IS_DIRECT_PEER_TO_PEER}: true`];s.sendEnterRoom(i)}}var st=(n=>(n.SNAPSHOT_CHANGED="snapshot-changed",n))(st||{});const it=["snapshot-changed"],Ns=()=>new M.TypedEvents(it),As=(n,e)=>Object.is(n,e),_e=n=>({connection:n.connection.getSnapshot(),call:n.call.getSnapshot(),incoming:n.incoming.getSnapshot(),presentation:n.presentation.getSnapshot()});class Is{events;machines;currentSnapshot;subscribers=new Set;actorSubscriptions=[];constructor(e){this.events=Ns(),this.machines={connection:e.connectionManager.stateMachine,call:e.callManager.stateMachine,incoming:e.incomingCallManager.stateMachine,presentation:e.presentationManager.stateMachine},this.currentSnapshot=_e(this.machines),this.actorSubscriptions.push(this.machines.connection.subscribe(this.notifySubscribers),this.machines.call.subscribe(this.notifySubscribers),this.machines.incoming.subscribe(this.notifySubscribers),this.machines.presentation.subscribe(this.notifySubscribers))}getSnapshot(){return this.currentSnapshot}subscribe(e,t,s){const i=typeof t=="function",r=i?e:u=>u,a=i?t:e,o=(i?s:void 0)??As,c=r(this.currentSnapshot),l={selector:r,listener:a,equals:o,current:c};return this.subscribers.add(l),()=>{this.subscribers.delete(l)}}stop(){this.subscribers.clear(),this.actorSubscriptions.forEach(e=>{e.unsubscribe()})}on(e,t){return this.events.on(e,t)}off(e,t){this.events.off(e,t)}notifySubscribers=()=>{const e=this.currentSnapshot;this.currentSnapshot=_e(this.machines);for(const t of this.subscribers){const s=t.selector(this.currentSnapshot);t.equals(t.current,s)||(t.current=s,t.listener(s))}this.events.trigger(st.SNAPSHOT_CHANGED,{previous:e,current:this.currentSnapshot})}}const G=1e3;var R=(n=>(n.INBOUND_RTP="inbound-rtp",n.REMOTE_OUTBOUND_RTP="remote-outbound-rtp",n.MEDIA_SOURCE="media-source",n.OUTBOUND_RTP="outbound-rtp",n.REMOTE_INBOUND_RTP="remote-inbound-rtp",n.CODEC="codec",n.CANDIDATE_PAIR="candidate-pair",n.CERTIFICATE="certificate",n.TRANSPORT="transport",n.LOCAL_CANDIDATE="local-candidate",n.REMOTE_CANDIDATE="remote-candidate",n))(R||{});const rt=["collected"],vs=()=>new M.TypedEvents(rt),be=()=>"performance"in window?performance.now():Date.now(),Y=n=>[...n.keys()].reduce((e,t)=>{const s=n.get(t);return s===void 0?e:{...e,[s.type]:s}},{}),fs=n=>{if(!n)return{outboundRtp:void 0,codec:void 0,mediaSource:void 0,remoteInboundRtp:void 0};const e=Y(n);return{outboundRtp:e[R.OUTBOUND_RTP],codec:e[R.CODEC],mediaSource:e[R.MEDIA_SOURCE],remoteInboundRtp:e[R.REMOTE_INBOUND_RTP]}},Oe=n=>{if(!n)return{outboundRtp:void 0,codec:void 0,mediaSource:void 0,remoteInboundRtp:void 0};const e=Y(n);return{outboundRtp:e[R.OUTBOUND_RTP],codec:e[R.CODEC],mediaSource:e[R.MEDIA_SOURCE],remoteInboundRtp:e[R.REMOTE_INBOUND_RTP]}},Pe=({videoReceiversStats:n,synchronizationSourcesVideo:e})=>{if(!n)return{inboundRtp:void 0,codec:void 0,synchronizationSources:e};const t=Y(n);return{inboundRtp:t[R.INBOUND_RTP],codec:t[R.CODEC],synchronizationSources:e}},Ms=({audioReceiverStats:n,synchronizationSourcesAudio:e})=>{if(!n)return{inboundRtp:void 0,codec:void 0,remoteOutboundRtp:void 0,synchronizationSources:e};const t=Y(n);return{inboundRtp:t[R.INBOUND_RTP],codec:t[R.CODEC],remoteOutboundRtp:t[R.REMOTE_OUTBOUND_RTP],synchronizationSources:e}},at=n=>{if(!n)return{candidatePair:void 0,certificate:void 0,localCandidate:void 0,remoteCandidate:void 0,transport:void 0};const e=Y(n);return{candidatePair:e[R.CANDIDATE_PAIR],certificate:e[R.CERTIFICATE],localCandidate:e[R.LOCAL_CANDIDATE],remoteCandidate:e[R.REMOTE_CANDIDATE],transport:e[R.TRANSPORT]}},_s=({audioSenderStats:n,videoSenderFirstStats:e,videoSenderSecondStats:t})=>({video:Oe(e),secondVideo:Oe(t),audio:fs(n),additional:at(n??e??t)}),bs=({audioReceiverStats:n,videoReceiverFirstStats:e,videoReceiverSecondStats:t,synchronizationSources:s})=>({video:Pe({videoReceiversStats:e,synchronizationSourcesVideo:s.video}),secondVideo:Pe({videoReceiversStats:t,synchronizationSourcesVideo:s.video}),audio:Ms({audioReceiverStats:n,synchronizationSourcesAudio:s.audio}),additional:at(n??e??t)}),Os=({audioSenderStats:n,videoSenderFirstStats:e,videoSenderSecondStats:t,audioReceiverStats:s,videoReceiverFirstStats:i,videoReceiverSecondStats:r,synchronizationSources:a})=>{const o=_s({audioSenderStats:n,videoSenderFirstStats:e,videoSenderSecondStats:t}),c=bs({audioReceiverStats:s,videoReceiverFirstStats:i,videoReceiverSecondStats:r,synchronizationSources:a});return{outbound:o,inbound:c}},Ps=async n=>{const e="audio",t="video",s=n.getSenders(),i=s.find(E=>E.track?.kind===e),r=s.filter(E=>E.track?.kind===t),a=n.getReceivers(),o=a.find(E=>E.track.kind===e),c=a.filter(E=>E.track.kind===t),l={trackIdentifier:o?.track.id,item:o?.getSynchronizationSources()[0]},u={trackIdentifier:c[0]?.track.id,item:c[0]?.getSynchronizationSources()[0]},T={audio:l,video:u};return Promise.all([i?.getStats()??Promise.resolve(void 0),r[0]?.getStats()??Promise.resolve(void 0),r[1]?.getStats()??Promise.resolve(void 0),o?.getStats()??Promise.resolve(void 0),c[0]?.getStats()??Promise.resolve(void 0),c[1]?.getStats()??Promise.resolve(void 0)]).then(E=>{const[N,y,v,U,$,St]=E;return{synchronizationSources:T,audioSenderStats:N,videoSenderFirstStats:y,videoSenderSecondStats:v,audioReceiverStats:U,videoReceiverFirstStats:$,videoReceiverSecondStats:St}})},Ds=n=>{d(String(n))};class ot{events;setTimeoutRequest;requesterAllStatistics=new H.CancelableRequest(Ps);constructor(){this.events=vs(),this.setTimeoutRequest=new B.SetTimeoutRequest}get requested(){return this.setTimeoutRequest.requested}start(e,{interval:t=G,onError:s=Ds}={}){this.stop(),this.setTimeoutRequest.request(()=>{this.collectStatistics(e,{onError:s})},t)}stop(){this.setTimeoutRequest.cancelRequest(),this.requesterAllStatistics.cancelRequest()}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}collectStatistics=(e,{onError:t})=>{const s=be();this.requestAllStatistics(e).then(i=>{this.events.trigger("collected",Os(i));const a=be()-s;let o=G;a>48?o=G*4:a>32?o=G*3:a>16&&(o=G*2),this.start(e,{onError:t,interval:o})}).catch(i=>{t&&t(i)})};requestAllStatistics=async e=>{const t=e();if(t===void 0)throw new Error("failed to collect statistics: peerConnection is not defined");return this.requesterAllStatistics.request(t)}}const ys=500;class Ls{statsPeerConnection;availableStats;previousAvailableStats;callManager;apiManager;constructor({callManager:e,apiManager:t}){this.callManager=e,this.apiManager=t,this.statsPeerConnection=new ot,this.subscribe()}get events(){return this.statsPeerConnection.events}get availableIncomingBitrate(){return this.availableStats?.inbound.additional.candidatePair?.availableIncomingBitrate}get isInvalidInboundFrames(){return this.isEmptyInboundFrames&&this.isReceivingPackets}get isEmptyInboundFrames(){return!this.isFramesReceived||!this.isFramesDecoded}get previousAvailableIncomingBitrate(){return this.previousAvailableStats?.inbound.additional.candidatePair?.availableIncomingBitrate}get previousInboundRtp(){return this.previousAvailableStats?.inbound.video.inboundRtp}get previousFramesReceived(){return this.previousInboundRtp?.framesReceived}get previousFramesDecoded(){return this.previousInboundRtp?.framesDecoded}get inboundRtp(){return this.availableStats?.inbound.video.inboundRtp}get framesReceived(){return this.inboundRtp?.framesReceived}get framesDecoded(){return this.inboundRtp?.framesDecoded}get isFramesReceived(){const e=this.framesReceived!==void 0&&this.framesReceived>0,t=this.framesReceived!==this.previousFramesReceived;return e&&t}get isFramesDecoded(){const e=this.framesDecoded!==void 0&&this.framesDecoded>0,t=this.framesDecoded!==this.previousFramesDecoded;return e&&t}get packetsReceived(){return this.inboundRtp?.packetsReceived}get previousPacketsReceived(){return this.previousInboundRtp?.packetsReceived}get isReceivingPackets(){const e=this.packetsReceived!==void 0&&this.packetsReceived>=ys,t=this.packetsReceived!==this.previousPacketsReceived;return e&&t}on(e,t){return this.statsPeerConnection.on(e,t)}once(e,t){return this.statsPeerConnection.once(e,t)}onceRace(e,t){return this.statsPeerConnection.onceRace(e,t)}async wait(e){return this.statsPeerConnection.wait(e)}off(e,t){this.statsPeerConnection.off(e,t)}hasAvailableIncomingBitrateChangedQuarter(){const e=this.previousAvailableIncomingBitrate,t=this.availableIncomingBitrate;return e===void 0||t===void 0?!1:e===0?t>0:Math.abs(t-e)/e>=.25}subscribe(){this.callManager.on("peerconnection:confirmed",this.handleStarted),this.callManager.on("failed",this.handleEnded),this.callManager.on("ended",this.handleEnded),this.statsPeerConnection.on("collected",this.handleStatsCollected)}handleStatsCollected=e=>{this.previousAvailableStats=this.availableStats,this.availableStats=e,this.maybeSendStats()};handleStarted=()=>{this.statsPeerConnection.start(this.callManager.getActivePeerConnection)};handleEnded=()=>{this.statsPeerConnection.stop(),this.availableStats=void 0,this.previousAvailableStats=void 0};maybeSendStats(){this.availableIncomingBitrate!==void 0&&this.hasAvailableIncomingBitrateChangedQuarter()&&this.apiManager.sendStats({availableIncomingBitrate:this.availableIncomingBitrate}).catch(e=>{d("Failed to send stats",e)})}}const ws=(n,e)=>n.filter(s=>e.some(i=>i.clockRate===s.clockRate&&i.mimeType===s.mimeType&&i.channels===s.channels&&i.sdpFmtpLine===s.sdpFmtpLine)),Us=n=>{const e=RTCRtpSender.getCapabilities(n),t=RTCRtpReceiver.getCapabilities(n),s=e===null?[]:e.codecs,i=t===null?[]:t.codecs;return ws(s,i)},ks=(n,e)=>e===void 0||e.length===0?n:n.sort((t,s)=>{const i=e.indexOf(t.mimeType),r=e.indexOf(s.mimeType),a=i===-1?Number.MAX_VALUE:i,o=r===-1?Number.MAX_VALUE:r;return a-o}),Fs=(n,e)=>e===void 0||e.length===0?n:n.filter(t=>!e.includes(t.mimeType)),Bs=(n,{preferredMimeTypesVideoCodecs:e,excludeMimeTypesVideoCodecs:t})=>{try{if(typeof n.setCodecPreferences=="function"&&n.sender.track?.kind==="video"&&(e!==void 0&&e.length>0||t!==void 0&&t.length>0)){const s=Us("video"),i=Fs(s,t),r=ks(i,e);n.setCodecPreferences(r)}}catch(s){d("setCodecPreferences error",s)}},$s=n=>[...n.keys()].map(e=>n.get(e)),Gs=(n,e)=>$s(n).find(t=>t?.type===e),ct=async n=>n.getStats().then(e=>Gs(e,"codec")?.mimeType);class qs{async getCodecFromSender(e){return await ct(e)??""}}class Vs{stackPromises=he.createStackPromises({noRunIsNotActual:!0});async add(e){return this.stackPromises.add(e),this.run()}stop(){this.stackPromises.stop()}async run(){return this.stackPromises().catch(e=>{d("TaskQueue: error",e)})}}class xs{taskQueue;onSetParameters;constructor(e){this.onSetParameters=e,this.taskQueue=new Vs}async setEncodingsToSender(e,t){return this.taskQueue.add(async()=>Ee(e,t,this.onSetParameters))}stop(){this.taskQueue.stop()}}const dt=(n,e)=>n!==void 0&&e!==void 0&&n.toLowerCase().includes(e.toLowerCase()),Hs=1e6,D=n=>n*Hs,ht=D(.06),lt=D(4),Ws=n=>n<=64?ht:n<=128?D(.12):n<=256?D(.25):n<=384?D(.32):n<=426?D(.38):n<=640?D(.5):n<=848?D(.7):n<=1280?D(1):n<=1920?D(2):lt,Qs="av1",Ys=n=>dt(n,Qs),zs=.6,pe=(n,e)=>Ys(e)?n*zs:n,Js=n=>pe(ht,n),js=n=>pe(lt,n),De=(n,e)=>{const t=Ws(n);return pe(t,e)},oe=1,Xs=({videoTrack:n,targetSize:e})=>{const t=n.getSettings(),s=t.width,i=t.height,r=s===void 0?oe:s/e.width,a=i===void 0?oe:i/e.height;return Math.max(r,a,oe)};class Ks{ignoreForCodec;senderFinder;codecProvider;parametersSetter;resultNoChanged={isChanged:!1,parameters:{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}}};constructor({senderFinder:e,codecProvider:t,parametersSetter:s},i){this.senderFinder=e,this.codecProvider=t,this.parametersSetter=s,this.ignoreForCodec=i.ignoreForCodec}async balance(e,t){const s=e.getSenders(),i=this.senderFinder.findVideoSender(s);if(!i?.track)return{...this.resultNoChanged,sender:i};const r=await this.codecProvider.getCodecFromSender(i);if(dt(r,this.ignoreForCodec))return{...this.resultNoChanged,sender:i};const{mainCam:a,resolutionMainCam:o}=t??{};return this.processSender({mainCam:a,resolutionMainCam:o},{sender:i,codec:r,videoTrack:i.track}).then(c=>({...c,sender:i}))}async processSender(e,t){const{mainCam:s,resolutionMainCam:i}=e;switch(s){case b.PAUSE_MAIN_CAM:return this.downgradeResolutionSender(t);case b.RESUME_MAIN_CAM:return this.setBitrateByTrackResolution(t);case b.MAX_MAIN_CAM_RESOLUTION:return i!==void 0?this.setResolutionSender(i,t):this.setBitrateByTrackResolution(t);case b.ADMIN_STOP_MAIN_CAM:case b.ADMIN_START_MAIN_CAM:case void 0:return this.setBitrateByTrackResolution(t);default:return this.setBitrateByTrackResolution(t)}}async downgradeResolutionSender(e){const{sender:t,codec:s}=e,i={scaleResolutionDownBy:200,maxBitrate:Js(s)};return this.parametersSetter.setEncodingsToSender(t,i)}async setBitrateByTrackResolution(e){const{sender:t,videoTrack:s,codec:i}=e,a=s.getSettings().width,o=a===void 0?js(i):De(a,i);return this.parametersSetter.setEncodingsToSender(t,{scaleResolutionDownBy:1,maxBitrate:o})}async setResolutionSender(e,t){const[s,i]=e.split("x"),{sender:r,videoTrack:a,codec:o}=t,c={width:Number(s),height:Number(i)},l=Xs({videoTrack:a,targetSize:c}),u=De(c.width,o),T={scaleResolutionDownBy:l,maxBitrate:u};return this.parametersSetter.setEncodingsToSender(r,T)}}const Zs=n=>n.find(e=>e.track?.kind==="video");class ei{findVideoSender(e){return Zs(e)}}class ti{currentSender;originalReplaceTrack;lastWidth;lastHeight;maxPollIntervalMs;currentPollIntervalMs;pollIntervalMs;setTimeoutRequest;constructor({pollIntervalMs:e=1e3,maxPollIntervalMs:t}){this.pollIntervalMs=e,this.maxPollIntervalMs=t??e*16,this.currentPollIntervalMs=this.pollIntervalMs,this.setTimeoutRequest=new B.SetTimeoutRequest}subscribe(e,t){if(!e){this.detachSender();return}this.currentSender!==e&&(this.detachSender(),this.attachSender(e,t))}unsubscribe(){this.detachSender()}attachSender(e,t){this.currentSender=e;const s=e.replaceTrack.bind(e);this.originalReplaceTrack=s,e.replaceTrack=async i=>{await s(i),this.attachTrack(t,i??void 0),t()},this.attachTrack(t,e.track)}detachSender(){this.currentSender&&this.originalReplaceTrack&&(this.currentSender.replaceTrack=this.originalReplaceTrack),this.originalReplaceTrack=void 0,this.currentSender=void 0,this.detachTrack()}attachTrack(e,t){if(this.detachTrack(),!t)return;const{width:s,height:i}=t.getSettings();this.lastWidth=s,this.lastHeight=i,this.currentPollIntervalMs=this.pollIntervalMs,this.schedulePoll(t,e)}schedulePoll(e,t){const s=()=>{const{width:i,height:r}=e.getSettings();i!==this.lastWidth||r!==this.lastHeight?(this.lastWidth=i,this.lastHeight=r,this.currentPollIntervalMs=this.pollIntervalMs,t()):this.currentPollIntervalMs=Math.min(this.currentPollIntervalMs*2,this.maxPollIntervalMs),this.setTimeoutRequest.request(s,this.currentPollIntervalMs)};this.setTimeoutRequest.request(s,this.currentPollIntervalMs)}detachTrack(){this.setTimeoutRequest.cancelRequest(),this.lastWidth=void 0,this.lastHeight=void 0}}class ni{apiManager;currentHandler;constructor(e){this.apiManager=e}subscribe(e){this.currentHandler=e,this.apiManager.on("main-cam-control",e)}unsubscribe(){this.currentHandler&&(this.apiManager.off("main-cam-control",this.currentHandler),this.currentHandler=void 0)}}class si{eventHandler;senderBalancer;parametersSetterWithQueue;getConnection;serverHeaders;trackMonitor;constructor(e,t,{ignoreForCodec:s,onSetParameters:i,pollIntervalMs:r}={}){this.getConnection=t,this.eventHandler=new ni(e),this.parametersSetterWithQueue=new xs(i),this.senderBalancer=new Ks({senderFinder:new ei,codecProvider:new qs,parametersSetter:this.parametersSetterWithQueue},{ignoreForCodec:s}),this.trackMonitor=new ti({pollIntervalMs:r})}subscribe(){this.eventHandler.subscribe(this.handleMainCamControl)}unsubscribe(){this.eventHandler.unsubscribe(),this.parametersSetterWithQueue.stop(),this.reset()}reset(){delete this.serverHeaders,this.trackMonitor.unsubscribe()}async balance(){const e=this.getConnection();if(!e)throw new Error("connection is not exist");const t=await this.senderBalancer.balance(e,this.serverHeaders);return this.trackMonitor.subscribe(t.sender,()=>{this.balance().catch(s=>{d("balance on track change: error",s)})}),t}handleMainCamControl=e=>{this.serverHeaders=e,this.balance().catch(t=>{d("handleMainCamControl: error",t)})}}const ut=["balancing-scheduled","balancing-started","balancing-stopped","parameters-updated"],ii=()=>new M.TypedEvents(ut);class ri{isBalancingActive=!1;events;callManager;balancingStartDelay;videoSendingBalancer;startBalancingTimer;constructor(e,t,s={}){this.events=ii(),this.callManager=e,this.balancingStartDelay=s.balancingStartDelay??1e4,this.videoSendingBalancer=new si(t,()=>e.connection,{...s,onSetParameters:i=>{this.events.trigger("parameters-updated",i),s.onSetParameters?.(i)}}),this.subscribe()}get isBalancingScheduled(){return this.startBalancingTimer!==void 0}async startBalancing(){this.isBalancingActive||(this.clearStartTimer(),await this.videoSendingBalancer.balance(),this.videoSendingBalancer.subscribe(),this.isBalancingActive=!0,this.events.trigger("balancing-started",{delay:this.balancingStartDelay}))}stopBalancing(){this.clearStartTimer(),this.videoSendingBalancer.unsubscribe(),this.isBalancingActive=!1,this.events.trigger("balancing-stopped",{})}async balance(){return this.videoSendingBalancer.balance()}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}subscribe(){this.callManager.on("peerconnection:confirmed",this.handleCallStarted),this.callManager.on("ended",this.handleCallEnded),this.callManager.on("failed",this.handleCallEnded)}handleCallStarted=()=>{this.scheduleBalancingStart()};handleCallEnded=()=>{this.stopBalancing()};scheduleBalancingStart(){this.clearStartTimer(),this.startBalancingTimer=setTimeout(()=>{this.startBalancingTimer=void 0,this.startBalancing().catch(e=>{d("startBalancing: error",e)})},this.balancingStartDelay),this.events.trigger("balancing-scheduled",{delay:this.balancingStartDelay})}clearStartTimer(){this.startBalancingTimer&&(clearTimeout(this.startBalancingTimer),this.startBalancingTimer=void 0)}}const gt="no-inbound-frames",Tt=[gt],ai=()=>new M.TypedEvents(Tt);class oi{events;statsManager;callManager;constructor(e,t){this.statsManager=e,this.callManager=t,this.events=ai(),this.subscribe()}get mainVideoTrack(){return this.callManager.getMainRemoteStream()?.getVideoTracks()[0]}get isMutedMainVideoTrack(){const{mainVideoTrack:e}=this;return e===void 0?!1:e.muted}on(e,t){return this.events.on(e,t)}handleStatsCollected=()=>{this.hasNoIncomingFrames()&&this.events.trigger(gt,{})};hasNoIncomingFrames=()=>this.statsManager.isInvalidInboundFrames&&this.isMutedMainVideoTrack;subscribe(){this.statsManager.on("collected",this.handleStatsCollected)}}const ci=3e3;class di{renegotiateRequester;renegotiateThrottled;callManager;constructor(e,t=ci){this.callManager=e,this.renegotiateRequester=new H.CancelableRequest(e.renegotiate.bind(e)),this.renegotiateThrottled=Et.throttle(this.requestRenegotiate.bind(this),t),this.subscribe()}recover(){d("trying to recover main stream"),this.renegotiateThrottled()}requestRenegotiate=()=>{if(d("trying to renegotiate"),this.renegotiateRequester.requested){d("previous renegotiate is not finished yet");return}this.renegotiateRequester.request().then(()=>{d("renegotiate has successful")}).catch(e=>{d("failed to renegotiate main media stream",e)})};subscribe(){this.callManager.on("ended",()=>{this.cancel()})}cancel(){d("cancel recover main stream"),this.renegotiateThrottled.cancel(),this.renegotiateRequester.cancelRequest()}}const hi=1e6,li=et.map(n=>`auto-connect:${n}`),ui=ze.map(n=>`connection:${n}`),gi=xe.map(n=>`call:${n}`),Ti=Le.map(n=>`api:${n}`),Si=tt.map(n=>`incoming-call:${n}`),Ei=We.map(n=>`presentation:${n}`),Ci=rt.map(n=>`stats:${n}`),mi=ut.map(n=>`video-balancer:${n}`),pi=Tt.map(n=>`main-stream-health:${n}`),Ri=it.map(n=>`session:${n}`),Ni=["disconnected-from-out-of-call","connected-with-configuration-from-out-of-call","stopped-presentation-by-server-command"],Ai=[...li,...ui,...gi,...Ti,...Si,...Ei,...Ci,...mi,...pi,...Ri,...Ni],Ii=()=>new M.TypedEvents(Ai);class vi{events;connectionManager;connectionQueueManager;contentedStreamManager;callManager;autoConnectorManager;apiManager;incomingCallManager;presentationManager;statsManager;videoSendingBalancerManager;sessionManager;mainStreamHealthMonitor;peerToPeerManager;mainStreamRecovery;preferredMimeTypesVideoCodecs;excludeMimeTypesVideoCodecs;constructor({JsSIP:e},{preferredMimeTypesVideoCodecs:t,excludeMimeTypesVideoCodecs:s,videoBalancerOptions:i,autoConnectorOptions:r}={}){this.preferredMimeTypesVideoCodecs=t,this.excludeMimeTypesVideoCodecs=s,this.events=Ii(),this.apiManager=new bt,this.connectionManager=new Yn({JsSIP:e}),this.connectionQueueManager=new zn({connectionManager:this.connectionManager}),this.contentedStreamManager=new gs,this.callManager=new vn(this.contentedStreamManager),this.incomingCallManager=new ps(this.connectionManager),this.presentationManager=new Pn({callManager:this.callManager,maxBitrate:hi}),this.statsManager=new Ls({callManager:this.callManager,apiManager:this.apiManager}),this.autoConnectorManager=new cs({connectionQueueManager:this.connectionQueueManager,connectionManager:this.connectionManager,callManager:this.callManager},r),this.videoSendingBalancerManager=new ri(this.callManager,this.apiManager,i),this.mainStreamHealthMonitor=new oi(this.statsManager,this.callManager),this.mainStreamRecovery=new di(this.callManager),this.sessionManager=new Is({connectionManager:this.connectionManager,callManager:this.callManager,incomingCallManager:this.incomingCallManager,presentationManager:this.presentationManager}),this.callManager.subscribeToApiEvents(this.apiManager),this.contentedStreamManager.subscribeToApiEvents(this.apiManager),this.apiManager.subscribe({connectionManager:this.connectionManager,callManager:this.callManager}),this.peerToPeerManager=new Rs,this.peerToPeerManager.subscribe({connectionManager:this.connectionManager,callManager:this.callManager,apiManager:this.apiManager}),this.subscribe()}get requestedConnection(){return this.connectionManager.requested}get isPendingConnect(){return this.connectionManager.isPendingConnect}get isPendingInitUa(){return this.connectionManager.isPendingInitUa}get connectionState(){return this.connectionManager.connectionState}get isRegistered(){return this.connectionManager.isRegistered}get isRegisterConfig(){return this.connectionManager.isRegisterConfig}get socket(){return this.connectionManager.socket}get requestedCall(){return this.callManager.requested}get connection(){return this.callManager.connection}get isCallActive(){return this.callManager.isCallActive}get remoteCallerData(){return this.incomingCallManager.remoteCallerData}get isAvailableIncomingCall(){return this.incomingCallManager.isAvailableIncomingCall}get isDirectP2PRoom(){return this.callManager.isDirectP2PRoom}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}connect=async(...e)=>this.connectionQueueManager.connect(...e);disconnect=async()=>this.connectionQueueManager.disconnect();register=async()=>this.connectionManager.register();unregister=async()=>this.connectionManager.unregister();tryRegister=async()=>this.connectionManager.tryRegister();set=async(...e)=>this.connectionManager.set(...e);sendOptions=async(e,t,s)=>this.connectionManager.sendOptions(e,t,s);ping=async(e,t)=>this.connectionManager.ping(e,t);checkTelephony=async e=>this.connectionManager.checkTelephony(e);isConfigured=()=>this.connectionManager.isConfigured();getConnectionConfiguration=()=>this.connectionManager.getConnectionConfiguration();getUri=e=>this.connectionManager.getUri(e);startAutoConnect=(...e)=>{this.autoConnectorManager.start(...e)};stopAutoConnect=()=>{this.autoConnectorManager.stop()};call=async e=>{const{onAddedTransceiver:t,...s}=e;return this.callManager.startCall(this.connectionManager.getUaProtected(),this.getUri,{...s,onAddedTransceiver:this.resolveHandleAddTransceiver(t)})};hangUp=async()=>this.callManager.endCall();answerToIncomingCall=async e=>{const{onAddedTransceiver:t,...s}=e;return this.callManager.answerToIncomingCall(this.incomingCallManager.extractIncomingRTCSession,{...s,onAddedTransceiver:this.resolveHandleAddTransceiver(t)})};declineToIncomingCall=async(...e)=>this.incomingCallManager.declineToIncomingCall(...e);getEstablishedRTCSession=()=>this.callManager.getEstablishedRTCSession();getRemoteStreams=()=>this.callManager.getRemoteStreams();getRecvQuality=()=>this.callManager.getRecvQuality();setRecvQuality=async e=>this.callManager.setRecvQuality(e);replaceMediaStream=async(...e)=>this.callManager.replaceMediaStream(...e);async startPresentation(e,t={}){const{callLimit:s,onAddedTransceiver:i,...r}=t;return this.presentationManager.startPresentation(async()=>{await(this.isDirectP2PRoom?this.apiManager.sendAvailableContentedStream():this.apiManager.askPermissionToStartPresentation())},e,{...r,onAddedTransceiver:this.resolveHandleAddTransceiver(i)},s===void 0?void 0:{callLimit:s})}async stopPresentation(){return this.presentationManager.stopPresentation(async()=>{await(this.isDirectP2PRoom?this.apiManager.sendNotAvailableContentedStream():this.apiManager.sendStoppedPresentation())})}async updatePresentation(e,t={}){const{onAddedTransceiver:s,...i}=t;return this.presentationManager.updatePresentation(async()=>{await(this.isDirectP2PRoom?this.apiManager.sendAvailableContentedStream():this.apiManager.askPermissionToStartPresentation())},e,{...i,onAddedTransceiver:this.resolveHandleAddTransceiver(s)})}async waitChannels(...e){return this.apiManager.waitChannels(...e)}async waitSyncMediaState(...e){return this.apiManager.waitSyncMediaState(...e)}async sendDTMF(...e){return this.apiManager.sendDTMF(...e)}async sendChannels(...e){return this.apiManager.sendChannels(...e)}async sendMediaState(...e){return this.apiManager.sendMediaState(...e)}async sendRefusalToTurnOn(...e){return this.apiManager.sendRefusalToTurnOn(...e)}async sendRefusalToTurnOnMic(...e){return this.apiManager.sendRefusalToTurnOnMic(...e)}async sendRefusalToTurnOnCam(...e){return this.apiManager.sendRefusalToTurnOnCam(...e)}async askPermissionToEnableCam(...e){return this.apiManager.askPermissionToEnableCam(...e)}subscribeDisconnectedFromOutOfCall(){this.connectionManager.on("disconnected",()=>{this.isCallActive||this.events.trigger("disconnected-from-out-of-call",{})})}subscribeConnectedWithConfigurationFromOutOfCall(){this.connectionManager.on("connected-with-configuration",e=>{this.isCallActive||this.events.trigger("connected-with-configuration-from-out-of-call",e)})}mayBeStopPresentationAndNotify(){this.presentationManager.isPresentationInProcess&&(this.stopPresentation().catch(()=>{}),this.events.trigger("stopped-presentation-by-server-command",{}))}subscribeToApiEvents(){this.apiManager.on("participant:move-request-to-participants",()=>{this.callManager.setCallRoleParticipant()}),this.apiManager.on("participant:move-request-to-spectators-synthetic",()=>{this.callManager.setCallRoleSpectatorSynthetic(),this.mayBeStopPresentationAndNotify()}),this.apiManager.on("participant:move-request-to-spectators-with-audio-id",({audioId:e})=>{this.callManager.setCallRoleSpectator({audioId:e,sendOffer:this.sendOffer}),this.mayBeStopPresentationAndNotify()}),this.apiManager.on("presentation:must-stop",()=>{this.mayBeStopPresentationAndNotify()}),this.apiManager.on("failed-send-room-direct-p2p",({error:e})=>{const t=new Re.IncomingResponse;t.body=e instanceof Error?e.message:String(e);const s=Re.C.causes.INTERNAL_ERROR;this.callManager.failed(t,s).catch(i=>{d("Failed to end call after failed:",i)})})}sendOffer=async(e,t)=>{const i=this.connectionManager.getConnectionConfiguration()?.sipServerUrl;if(i===void 0)throw new Error("No sipServerUrl for sendOffer");return Ue({serverUrl:i,offer:t,token:e.token,conferenceNumber:e.conferenceNumber,quality:e.quality,audio:e.audioChannel})};setCodecPreferences(e){Bs(e,{preferredMimeTypesVideoCodecs:this.preferredMimeTypesVideoCodecs,excludeMimeTypesVideoCodecs:this.excludeMimeTypesVideoCodecs})}subscribe(){this.bridgeEvents("auto-connect",this.autoConnectorManager),this.bridgeEvents("connection",this.connectionManager),this.bridgeEvents("call",this.callManager),this.bridgeEvents("api",this.apiManager),this.bridgeEvents("incoming-call",this.incomingCallManager),this.bridgeEvents("presentation",this.presentationManager),this.bridgeEvents("stats",this.statsManager),this.bridgeEvents("video-balancer",this.videoSendingBalancerManager),this.bridgeEvents("main-stream-health",this.mainStreamHealthMonitor),this.bridgeEvents("session",this.sessionManager),this.subscribeToApiEvents(),this.subscribeDisconnectedFromOutOfCall(),this.subscribeConnectedWithConfigurationFromOutOfCall(),this.subscribeToMainStreamHealthMonitorEvents()}subscribeToMainStreamHealthMonitorEvents(){this.mainStreamHealthMonitor.on("no-inbound-frames",()=>{this.mainStreamRecovery.recover()})}bridgeEvents=(e,t)=>{t.events.eachTriggers((s,i)=>{t.on(i,r=>{this.events.trigger(`${e}:${i}`,r)})})};resolveHandleAddTransceiver=e=>async(t,s,i)=>{this.setCodecPreferences(t),await e?.(t,s,i)}}exports.DeferredCommandRunner=Be;exports.ECallCause=Ce;exports.EContentUseLicense=ge;exports.EState=Z;exports.EState$1=je;exports.EState$2=nt;exports.EState$3=Qe;exports.EStatsTypes=R;exports.Originator=qe;exports.PURGATORY_CONFERENCE_NUMBER=we;exports.SipConnector=vi;exports.StatsPeerConnection=ot;exports.disableDebug=mt;exports.enableDebug=Ct;exports.getCodecFromSender=ct;exports.hasCanceledStartPresentationError=On;exports.hasNotReadyForConnectionError=Ze;exports.hasPeerToPeer=Te;exports.hasPurgatory=Se;exports.logger=d;exports.prepareMediaStream=x;exports.sendOffer=Ue;exports.setEncodingsToSender=Ee;exports.setParametersToSender=K;