diff --git a/build/dyte-ui-kit.esm.js b/build/dyte-ui-kit.esm.js index 905e8bd6..507ab95e 100644 --- a/build/dyte-ui-kit.esm.js +++ b/build/dyte-ui-kit.esm.js @@ -1 +1 @@ -import{p as e,b as t}from"./p-69f2ebde.js";(()=>{const t=import.meta.url,i={};return""!==t&&(i.resourcesUrl=new URL(".",t).href),e(i)})().then((e=>t(JSON.parse('[["p-95b54a27",[[1,"dyte-chat",{"meeting":[16],"config":[16],"size":[513],"iconPack":[16],"t":[16],"disablePrivateChat":[4,"disable-private-chat"],"privatePresetFilter":[16],"displayFilter":[16],"canPinMessages":[32],"unreadCountGroups":[32],"chatGroups":[32],"selectedGroup":[32],"now":[32],"dropzoneActivated":[32],"showLatestMessageButton":[32],"canSend":[32],"canSendTextMessage":[32],"canSendFiles":[32],"canPrivateMessage":[32],"canSendPrivateTexts":[32],"canSendPrivateFiles":[32],"emojiPickerEnabled":[32],"chatRecipientId":[32],"participants":[32],"selectedParticipant":[32],"channels":[32],"selectedChannelId":[32],"editingMessage":[32],"replyMessage":[32],"searchQuery":[32],"selectorState":[32],"creatingChannel":[32],"showPinnedMessages":[32]},[[8,"editMessageInit","onEditMessageInit"],[0,"switchChannel","channelSwitchListener"]]]]],["p-eab9f9ac",[[1,"dyte-settings",{"meeting":[16],"states":[16],"size":[513],"iconPack":[16],"t":[16],"activeTab":[32],"isMobileMainVisible":[32],"networkStatus":[32],"canProduceVideo":[32]}]]],["p-a8b3c968",[[1,"dyte-breakout-rooms-manager",{"meeting":[16],"states":[16],"iconPack":[16],"t":[16],"loading":[32],"roomConfig":[32],"draftState":[32],"assigningParticipants":[32],"selectedParticipants":[32],"ephemeralStatusText":[32],"isDragMode":[32]},[[0,"participantDelete","onParticipantDelete"],[0,"participantsDragging","toggleDragMode"],[0,"selectedParticipantsUpdate","updateSelectedParticipants"],[0,"allParticipantsToggleUpdate","updateAllParticipants"]]]]],["p-17c03177",[[1,"dyte-participants-viewer-list",{"meeting":[16],"config":[16],"size":[513],"hideHeader":[4,"hide-header"],"iconPack":[16],"view":[1],"search":[1],"t":[16],"stageViewers":[32]}]]],["p-6a20f8e9",[[1,"dyte-chat-composer-ui",{"canSendTextMessage":[4,"can-send-text-message"],"canSendFiles":[4,"can-send-files"],"size":[513],"iconPack":[16],"t":[16],"disableEmojiPicker":[4,"disable-emoji-picker"],"prefill":[16],"members":[16],"channelId":[1,"channel-id"],"emojiPickerActive":[32],"mentionQuery":[32],"focusedMemberIndex":[32],"filePreview":[32]}]]],["p-98d81977",[[1,"dyte-debugger",{"meeting":[16],"states":[16],"size":[513],"iconPack":[16],"t":[16],"activeTab":[32],"isMobileMainVisible":[32],"progress":[32]},[[0,"testProgress","progressUpdate"]]]]],["p-9aa229c1",[[1,"dyte-grid",{"layout":[513],"aspectRatio":[513,"aspect-ratio"],"meeting":[16],"gap":[514],"size":[513],"states":[16],"config":[16],"iconPack":[16],"t":[16],"gridSize":[16],"overrides":[8],"participants":[32],"pinnedParticipants":[32],"screenShareParticipants":[32],"plugins":[32],"emptyStage":[32],"showLiveStreamPlayer":[32],"canCurrentPeerHost":[32],"pipSupported":[32],"pipEnabled":[32],"roomState":[32]}]]],["p-5c1a5c6d",[[1,"dyte-setup-screen",{"meeting":[16],"states":[16],"size":[513],"config":[16],"iconPack":[16],"t":[16],"displayName":[32],"isJoining":[32],"canEditName":[32],"canProduceAudio":[32],"connectionState":[32]}]]],["p-2d0d680e",[[1,"dyte-mixed-grid",{"layout":[513],"participants":[16],"pinnedParticipants":[16],"screenShareParticipants":[16],"plugins":[16],"aspectRatio":[1,"aspect-ratio"],"gap":[2],"size":[513],"meeting":[16],"states":[16],"config":[16],"iconPack":[16],"t":[16],"gridSize":[16],"activeTab":[32],"initialised":[32]}]]],["p-54518b67",[[1,"dyte-participants-stage-queue",{"meeting":[16],"config":[16],"size":[513],"iconPack":[16],"view":[1],"t":[16],"stageRequestedParticipants":[32]}]]],["p-3ce728cd",[[1,"dyte-participants-waiting-list",{"meeting":[16],"config":[16],"size":[513],"iconPack":[16],"view":[1],"t":[16],"waitlistedParticipants":[32]}]]],["p-4c71c2ed",[[1,"dyte-polls",{"meeting":[16],"config":[16],"size":[513],"iconPack":[16],"t":[16],"create":[32],"polls":[32],"permissions":[32]}]]],["p-a1796033",[[1,"dyte-audio-tile",{"meeting":[16],"config":[16],"size":[513],"states":[16],"iconPack":[16],"t":[16],"participant":[16],"audioEnabled":[32],"volume":[32]}]]],["p-e5ffb262",[[1,"dyte-camera-toggle",{"variant":[513],"meeting":[16],"size":[513],"iconPack":[16],"t":[16],"videoEnabled":[32],"canProduceVideo":[32],"cameraPermission":[32],"stageStatus":[32]}]]],["p-1ba39f82",[[1,"dyte-channel-creator",{"meeting":[16],"t":[16],"iconPack":[16],"channelName":[32],"searchQuery":[32],"step":[32],"loading":[32],"selectedMemberIds":[32],"focusedMemberIndex":[32],"showAllMembersList":[32]}]]],["p-67d2cf84",[[1,"dyte-channel-selector-ui",{"channels":[16],"selectedChannelId":[1,"selected-channel-id"],"iconPack":[16],"t":[16],"showRecentMessage":[4,"show-recent-message"],"isHidden":[32],"searchQuery":[32]}]]],["p-83f74c68",[[1,"dyte-mic-toggle",{"variant":[513],"meeting":[16],"size":[513],"iconPack":[16],"t":[16],"audioEnabled":[32],"canProduceAudio":[32],"micPermission":[32],"stageStatus":[32]}]]],["p-4209571a",[[1,"dyte-mute-all-button",{"variant":[513],"meeting":[16],"size":[513],"iconPack":[16],"t":[16],"canDisable":[32]}]]],["p-fccf38b2",[[1,"dyte-screen-share-toggle",{"states":[16],"variant":[513],"meeting":[16],"size":[513],"iconPack":[16],"t":[16],"maxScreenShareCount":[32],"screenShareCount":[32],"screenShareEnabled":[32],"canScreenShare":[32],"shareScreenPermission":[32],"screenShareState":[32],"stageStatus":[32]}]]],["p-66b50bbf",[[1,"dyte-stage-toggle",{"variant":[513],"meeting":[16],"size":[513],"iconPack":[16],"t":[16],"stageStatus":[32],"state":[32]}]]],["p-2c92cba5",[[1,"dyte-ai-toggle",{"variant":[513],"states":[16],"meeting":[16],"size":[513],"iconPack":[16],"t":[16],"aiActive":[32]}]]],["p-c98e08e9",[[1,"dyte-breakout-rooms-toggle",{"variant":[513],"meeting":[16],"states":[16],"size":[513],"iconPack":[16],"t":[16],"canToggle":[32]}]]],["p-531555da",[[1,"dyte-caption-toggle",{"variant":[513],"meeting":[16],"states":[16],"config":[16],"iconPack":[16],"size":[513],"t":[16],"captionEnabled":[32]}]]],["p-9aa36e9b",[[1,"dyte-chat-toggle",{"variant":[513],"meeting":[16],"states":[16],"size":[513],"iconPack":[16],"t":[16],"unreadMessageCount":[32],"chatActive":[32],"canViewChat":[32],"hasNewMessages":[32]}]]],["p-53a489a1",[[1,"dyte-debugger-toggle",{"variant":[513],"meeting":[16],"states":[16],"t":[16],"iconPack":[16],"size":[513]}]]],["p-4ab82ecd",[[1,"dyte-fullscreen-toggle",{"states":[16],"targetElement":[16],"variant":[513],"size":[513],"iconPack":[16],"t":[16],"fullScreenActive":[32],"isFullScreenSupported":[32]}]]],["p-10abc747",[[1,"dyte-grid-pagination",{"meeting":[16],"states":[16],"size":[513],"variant":[513],"iconPack":[16],"t":[16],"page":[32],"pageCount":[32],"activeCount":[32],"activeComputedCount":[32],"showPagination":[32]}]]],["p-3a4f39fd",[[1,"dyte-idle-screen",{"meeting":[16],"config":[16],"iconPack":[16],"t":[16]}]]],["p-840cde94",[[1,"dyte-leave-button",{"variant":[513],"size":[513],"iconPack":[16],"t":[16]}]]],["p-57f8cbec",[[1,"dyte-livestream-toggle",{"variant":[513],"meeting":[16],"size":[513],"iconPack":[16],"t":[16],"livestreamState":[32]}]]],["p-b4e7929c",[[1,"dyte-more-toggle",{"states":[16],"size":[513],"iconPack":[16],"t":[16]}]]],["p-bb4a58a1",[[1,"dyte-participants",{"meeting":[16],"states":[16],"config":[16],"size":[513],"iconPack":[16],"defaultParticipantsTabId":[1,"default-participants-tab-id"],"t":[16],"currentParticipantsTabId":[32],"tabs":[32],"hasRequests":[32],"search":[32]}]]],["p-bbd97987",[[1,"dyte-participants-audio",{"meeting":[16],"iconPack":[16],"t":[16],"showPlayDialog":[32]}]]],["p-8cea527d",[[1,"dyte-participants-toggle",{"variant":[513],"meeting":[16],"states":[16],"size":[513],"iconPack":[16],"t":[16],"participantsActive":[32],"waitlistedParticipants":[32],"stageRequestedParticipants":[32],"badgeCount":[32],"canViewParticipants":[32]}]]],["p-5e472028",[[1,"dyte-pip-toggle",{"variant":[513],"meeting":[16],"states":[16],"config":[16],"iconPack":[16],"size":[513],"t":[16],"pipSupported":[32]}]]],["p-5b043c60",[[1,"dyte-plugins-toggle",{"variant":[513],"meeting":[16],"states":[16],"size":[513],"iconPack":[16],"t":[16],"pluginsActive":[32],"canViewPlugins":[32]}]]],["p-f2c6a023",[[1,"dyte-polls-toggle",{"variant":[513],"meeting":[16],"states":[16],"size":[513],"iconPack":[16],"t":[16],"pollsActive":[32],"unreadPollsCount":[32],"canViewPolls":[32]}]]],["p-408ad9b9",[[1,"dyte-recording-toggle",{"variant":[513],"meeting":[16],"t":[16],"iconPack":[16],"size":[513],"disabled":[4],"recordingState":[32],"canRecord":[32]}]]],["p-9e8290b4",[[1,"dyte-screenshare-view",{"hideFullScreenButton":[4,"hide-full-screen-button"],"nameTagPosition":[513,"name-tag-position"],"participant":[16],"meeting":[16],"variant":[513],"size":[513],"iconPack":[16],"t":[16],"videoExpanded":[32],"screenShareEnabled":[32],"isFullScreen":[32],"remoteControlInfo":[32]}]]],["p-0233867d",[[1,"dyte-settings-toggle",{"variant":[513],"states":[16],"size":[513],"iconPack":[16],"t":[16]}]]],["p-9062b1ac",[[1,"dyte-sidebar",{"enabledSections":[1040],"defaultSection":[1,"default-section"],"meeting":[16],"states":[16],"config":[16],"iconPack":[16],"t":[16],"size":[513],"view":[513],"currentTab":[32],"isFloating":[32],"enablePinning":[32]}]]],["p-194769a0",[[1,"dyte-ai",{"defaultSection":[1,"default-section"],"meeting":[16],"states":[16],"config":[16],"iconPack":[16],"t":[16],"size":[513],"view":[513],"tab":[32],"newTranscriptionAvailable":[32],"newAiMessageAvailable":[32]}]]],["p-9aed2a17",[[1,"dyte-ai-home",{"meeting":[16],"initialMessages":[16],"prompt":[32],"messages":[32]}]]],["p-fc6aa00e",[[1,"dyte-broadcast-message-modal",{"meeting":[16],"states":[16],"iconPack":[16],"t":[16],"messagePayload":[32],"successMessage":[32]}]]],["p-b89e0629",[[1,"dyte-ended-screen",{"config":[16],"size":[513],"states":[16],"t":[16],"iconPack":[16],"meeting":[16],"icon":[32],"message":[32]}]]],["p-2379bba1",[[1,"dyte-image-viewer",{"image":[16],"size":[513],"t":[16],"iconPack":[16]}]]],["p-df719c80",[[0,"dyte-message-list-view",{"messages":[16],"renderer":[16],"loadMore":[16],"visibleItemsCount":[2,"visible-items-count"],"estimateItemSize":[2,"estimate-item-size"],"iconPack":[16],"range":[32],"isFetching":[32],"autoScroll":[32],"totalHeight":[32]}]]],["p-91da494e",[[1,"dyte-permissions-message",{"meeting":[16],"t":[16],"iconPack":[16],"states":[16],"device":[32],"currentStep":[32],"svgSteps":[32]}]]],["p-1c40bf17",[[1,"dyte-plugin-main",{"meeting":[16],"plugin":[16],"iconPack":[16],"t":[16],"canClosePlugin":[32],"viewModeEnabled":[32]}]]],["p-4352d0bf",[[1,"dyte-plugins",{"meeting":[16],"config":[16],"size":[513],"iconPack":[16],"t":[16],"plugins":[32],"canStartPlugins":[32],"canClosePlugins":[32],"activatedPluginsId":[32]}]]],["p-edd38b5d",[[1,"dyte-chat-selector-ui",{"selfUserId":[1,"self-user-id"],"selectedGroupId":[1,"selected-group-id"],"unreadCounts":[16],"groups":[16],"iconPack":[16],"t":[16],"showParticipantsPanel":[32],"query":[32]}]]],["p-9f2f491c",[[1,"dyte-clock",{"meeting":[16],"iconPack":[16],"t":[16],"startedTime":[32],"timeDiff":[32]}]]],["p-87ab87bb",[[1,"dyte-confirmation-modal",{"meeting":[16],"states":[16],"iconPack":[16],"t":[16]}]]],["p-7eea5e98",[[1,"dyte-file-dropzone",{"hostEl":[16],"iconPack":[16],"t":[16],"dropzoneActivated":[32]}]]],["p-667a5e10",[[1,"dyte-information-tooltip",{"iconPack":[16]}]]],["p-13c76797",[[1,"dyte-leave-meeting",{"meeting":[16],"states":[16],"iconPack":[16],"t":[16],"canEndMeeting":[32]}]]],["p-9391fae7",[[1,"dyte-meeting-title",{"meeting":[16],"iconPack":[16],"t":[16]}]]],["p-bcb55f75",[[1,"dyte-mute-all-confirmation",{"meeting":[16],"states":[16],"iconPack":[16],"t":[16],"allowUnmute":[32]}]]],["p-17d003ce",[[1,"dyte-network-indicator",{"participant":[16],"meeting":[16],"iconPack":[16],"t":[16],"isScreenShare":[4,"is-screen-share"],"score":[32]}]]],["p-f4d16c73",[[1,"dyte-participant-count",{"meeting":[16],"iconPack":[16],"t":[16],"size":[513],"participantCount":[32],"isViewer":[32]}]]],["p-6c35e2d3",[[1,"dyte-participants-stage-list",{"meeting":[16],"config":[16],"size":[513],"hideHeader":[4,"hide-header"],"iconPack":[16],"view":[1],"t":[16],"search":[1],"participants":[32]}]]],["p-0aa60268",[[1,"dyte-recording-indicator",{"meeting":[16],"size":[513],"t":[16],"iconPack":[16],"isRecording":[32]}]]],["p-abcd39d0",[[1,"dyte-transcript",{"transcript":[16],"t":[16],"timeout":[32]}]]],["p-2b143264",[[1,"dyte-transcripts",{"meeting":[16],"states":[16],"config":[16],"t":[16],"transcripts":[32],"listenerAttached":[32]}]]],["p-efa5c489",[[1,"dyte-waiting-screen",{"meeting":[16],"config":[16],"iconPack":[16],"t":[16]}]]],["p-066abf55",[[1,"dyte-ai-chat",{"t":[16]}]]],["p-61606bc5",[[1,"dyte-ai-transcriptions",{"t":[16],"meeting":[16],"initialTranscriptions":[16],"participantQuery":[32],"isProcessing":[32],"captionViewEnabled":[32],"transcriptions":[32]}]]],["p-19d1c9ca",[[1,"dyte-audio-grid",{"meeting":[16],"config":[16],"states":[16],"iconPack":[16],"size":[513],"t":[16],"hideSelf":[4,"hide-self"],"activeParticipants":[32],"onStageParticipants":[32],"offStageParticipants":[32]}]]],["p-2710e334",[[1,"dyte-controlbar",{"variant":[513],"disableRender":[4,"disable-render"],"meeting":[16],"config":[16],"states":[16],"iconPack":[16],"t":[16],"size":[513]}]]],["p-e4a78096",[[1,"dyte-header",{"variant":[513],"disableRender":[4,"disable-render"],"meeting":[16],"config":[16],"states":[16],"iconPack":[16],"t":[16],"size":[513]}]]],["p-3844becc",[[1,"dyte-meeting",{"loadConfigFromPreset":[4,"load-config-from-preset"],"applyDesignSystem":[4,"apply-design-system"],"mode":[513],"leaveOnUnmount":[4,"leave-on-unmount"],"meeting":[16],"showSetupScreen":[1028,"show-setup-screen"],"t":[16],"config":[1040],"iconPackUrl":[513,"icon-pack-url"],"size":[1537],"gridLayout":[1,"grid-layout"],"states":[32],"iconPack":[32]},[[0,"dyteStateUpdate","listenState"]]]]],["p-97d46173",[[1,"dyte-participant-setup",{"nameTagPosition":[513,"name-tag-position"],"isPreview":[4,"is-preview"],"participant":[16],"states":[16],"config":[16],"variant":[513],"size":[513],"iconPack":[16],"t":[16],"videoState":[32],"isPinned":[32]}]]],["p-c8e30628",[[1,"dyte-simple-grid",{"participants":[16],"aspectRatio":[1,"aspect-ratio"],"gap":[2],"size":[513],"meeting":[16],"states":[16],"config":[16],"iconPack":[16],"t":[16],"dimensions":[32],"mediaConnection":[32]}]]],["p-5899d85b",[[1,"dyte-spotlight-grid",{"layout":[513],"participants":[16],"pinnedParticipants":[16],"aspectRatio":[1,"aspect-ratio"],"gap":[2],"size":[513],"meeting":[16],"states":[16],"config":[16],"iconPack":[16],"t":[16],"gridSize":[16]}]]],["p-80f2f878",[[1,"dyte-stage",{"iconPack":[16],"t":[16]}]]],["p-6a54cb64",[[1,"dyte-text-field",{"type":[1],"placeholder":[1],"disabled":[4],"iconPack":[16],"t":[16]}]]],["p-45255350",[[4,"dyte-ui-provider",{"meeting":[16],"size":[1537],"config":[1040],"t":[16],"iconPackUrl":[513,"icon-pack-url"],"loadConfigFromPreset":[4,"load-config-from-preset"],"applyDesignSystem":[4,"apply-design-system"],"joinRoom":[4,"join-room"],"isReady":[32],"iconPack":[32]}]]],["p-5343baf1",[[1,"dyte-avatar",{"participant":[16],"variant":[513],"size":[513],"iconPack":[16],"t":[16],"imageState":[32]}]]],["p-65aab370",[[1,"dyte-controlbar-button",{"variant":[513],"showWarning":[4,"show-warning"],"size":[513],"label":[1],"icon":[1],"isLoading":[4,"is-loading"],"disabled":[516],"iconPack":[16],"t":[16],"brandIcon":[516,"brand-icon"]}]]],["p-a5cd2be1",[[1,"dyte-menu",{"size":[513],"placement":[1],"offset":[2],"iconPack":[16],"t":[16]}],[1,"dyte-menu-item",{"size":[513],"iconPack":[16],"t":[16]}],[1,"dyte-menu-list",{"iconPack":[16],"t":[16]}]]],["p-f323bc7a",[[1,"dyte-button",{"size":[513],"variant":[513],"kind":[513],"reverse":[516],"disabled":[516],"iconPack":[16],"t":[16],"type":[513]}]]],["p-d9f5e252",[[1,"dyte-icon",{"icon":[1],"iconPack":[16],"variant":[513],"t":[16],"size":[513]}]]],["p-46c65a1e",[[1,"dyte-participant",{"meeting":[16],"view":[1],"participant":[16],"iconPack":[16],"t":[16],"config":[16],"audioEnabled":[32],"videoEnabled":[32],"isPinned":[32],"isOnStage":[32],"canDisableParticipantAudio":[32],"canDisableParticipantVideo":[32],"canKickParticipant":[32],"canPinParticipant":[32],"canAllowParticipantOnStage":[32],"menuOpen":[32]}]]],["p-62f5331a",[[1,"dyte-tab-bar",{"size":[513],"meeting":[16],"states":[16],"config":[16],"layout":[513],"iconPack":[16],"t":[16],"activeTab":[16],"tabs":[16]}]]],["p-e237cb50",[[1,"dyte-name-tag",{"participant":[16],"meeting":[16],"size":[513],"isScreenShare":[4,"is-screen-share"],"variant":[513],"iconPack":[16],"t":[16],"length":[32]}]]],["p-34022f5a",[[1,"dyte-settings-audio",{"meeting":[16],"states":[16],"size":[513],"iconPack":[16],"t":[16]}],[1,"dyte-settings-video",{"meeting":[16],"states":[16],"size":[513],"iconPack":[16],"t":[16],"videoEnabled":[32]}]]],["p-51ac8691",[[1,"dyte-poll-form",{"iconPack":[16],"t":[16],"options":[32],"anonymous":[32],"hideVotes":[32],"error":[32]}],[1,"dyte-poll",{"poll":[16],"self":[1],"permissions":[16],"iconPack":[16],"t":[16]}]]],["p-85f67b95",[[1,"dyte-channel-details",{"channel":[16],"t":[16],"iconPack":[16],"members":[16]}]]],["p-a9939eca",[[1,"dyte-notification",{"notification":[16],"size":[513],"iconPack":[16],"t":[16],"imageState":[32]}]]],["p-26aadbca",[[1,"dyte-sidebar-ui",{"view":[513],"tabs":[16],"hideHeader":[4,"hide-header"],"hideCloseAction":[4,"hide-close-action"],"currentTab":[1,"current-tab"],"iconPack":[16],"t":[16]}]]],["p-075608df",[[1,"dyte-spotlight-indicator",{"meeting":[16],"iconPack":[16],"t":[16],"size":[513],"canSpotlight":[32],"isSpotlighted":[32]}]]],["p-af914aac",[[0,"dyte-virtualized-participant-list",{"items":[16],"renderItem":[16],"itemHeight":[1026,"item-height"],"bufferedItemsCount":[2,"buffered-items-count"],"emptyListElement":[16],"visibleStart":[32],"visibleEnd":[32]}]]],["p-e2896ebd",[[1,"dyte-breakout-room-manager",{"meeting":[16],"assigningParticipants":[4,"assigning-participants"],"mode":[1],"states":[16],"allowDelete":[4,"allow-delete"],"iconPack":[16],"t":[16],"isDragMode":[4,"is-drag-mode"],"room":[16],"defaultExpanded":[4,"default-expanded"],"editingTitleRoomId":[32],"newTitle":[32],"showExpandedCard":[32],"glowingCard":[32]}],[1,"dyte-breakout-room-participants",{"meeting":[16],"participantIds":[16],"iconPack":[16],"t":[16],"selectedParticipantIds":[16],"search":[32],"participantsToShow":[32],"isDragging":[32]}],[1,"dyte-counter",{"size":[513],"value":[2],"minValue":[2,"min-value"],"iconPack":[16],"t":[16],"input":[32]}]]],["p-e2006c50",[[1,"dyte-livestream-player",{"meeting":[16],"size":[513],"t":[16],"iconPack":[16],"playbackUrl":[32],"isSupported":[32],"playerState":[32],"livestreamState":[32],"playerError":[32],"latency":[32],"audioPlaybackError":[32]}],[1,"dyte-livestream-indicator",{"meeting":[16],"size":[513],"t":[16],"iconPack":[16],"isLivestreaming":[32]}],[1,"dyte-viewer-count",{"meeting":[16],"variant":[513],"iconPack":[16],"t":[16],"viewerCount":[32]}]]],["p-0f01555b",[[1,"dyte-join-stage",{"meeting":[16],"config":[16],"states":[16],"size":[513],"iconPack":[16],"t":[16],"dataConfig":[16],"isLoading":[32]}],[1,"dyte-overlay-modal",{"meeting":[16],"states":[16],"iconPack":[16],"t":[16]}]]],["p-9f5ff3e1",[[1,"dyte-dialog",{"hideCloseButton":[4,"hide-close-button"],"disableEscapeKey":[4,"disable-escape-key"],"meeting":[16],"config":[16],"states":[16],"size":[513],"iconPack":[16],"t":[16],"open":[1540]}]]],["p-ef129879",[[1,"dyte-debugger-audio",{"meeting":[16],"states":[16],"size":[513],"iconPack":[16],"t":[16],"isNetworkOpen":[32],"isDevicesOpen":[32],"audioProducerFormattedStats":[32],"audioProducerScoreStats":[32],"networkBasedMediaHealth":[32],"devicesHealth":[32]}],[1,"dyte-debugger-screenshare",{"meeting":[16],"states":[16],"size":[513],"iconPack":[16],"t":[16],"isNetworkOpen":[32],"isDevicesOpen":[32],"videoProducerFormattedStats":[32],"videoProducerScoreStats":[32],"audioProducerFormattedStats":[32],"audioProducerScoreStats":[32],"networkBasedMediaHealth":[32]}],[1,"dyte-debugger-system",{"meeting":[16],"states":[16],"size":[513],"iconPack":[16],"t":[16],"isBatterySectionOpen":[32],"batterySectionHealth":[32],"battery":[32],"batteryFormattedStats":[32]}],[1,"dyte-debugger-video",{"meeting":[16],"states":[16],"size":[513],"iconPack":[16],"t":[16],"isNetworkOpen":[32],"isDevicesOpen":[32],"videoProducerFormattedStats":[32],"videoProducerScoreStats":[32],"networkBasedMediaHealth":[32],"devicesHealth":[32]}]]],["p-8793a889",[[1,"dyte-logo",{"logoUrl":[1025,"logo-url"],"config":[16],"meeting":[16],"t":[16]}]]],["p-39990800",[[1,"dyte-participant-tile",{"nameTagPosition":[513,"name-tag-position"],"isPreview":[4,"is-preview"],"participant":[16],"meeting":[16],"states":[16],"config":[16],"variant":[513],"size":[513],"iconPack":[16],"t":[16],"isPinned":[32],"mediaConnectionError":[32]}],[1,"dyte-camera-selector",{"meeting":[16],"size":[513],"iconPack":[16],"variant":[1],"t":[16],"videoDevices":[32],"currentDevice":[32],"canProduceVideo":[32]}]]],["p-c7fad504",[[1,"dyte-markdown-view",{"text":[1],"maxLength":[2,"max-length"]}]]],["p-5818108f",[[1,"dyte-spinner",{"iconPack":[16],"size":[513],"t":[16]}]]],["p-95e6b985",[[1,"dyte-draft-attachment-view",{"iconPack":[16],"t":[16],"attachment":[16],"filePreview":[32]}],[1,"dyte-emoji-picker-button",{"iconPack":[16],"t":[16],"isActive":[4,"is-active"]}],[1,"dyte-file-picker-button",{"filter":[1],"label":[1],"icon":[1],"iconPack":[16],"t":[16]}],[1,"dyte-text-composer-view",{"disabled":[4],"placeholder":[1],"value":[1],"maxLength":[2,"max-length"],"rateLimitBreached":[4,"rate-limit-breached"],"keyDownHandler":[16],"iconPack":[16],"t":[16],"maxLengthBreached":[32],"setText":[64]}],[1,"dyte-emoji-picker",{"iconPack":[16],"t":[16],"emojiList":[32],"filterVal":[32],"filteredEmojis":[32]}]]],["p-4448d3ad",[[1,"dyte-chat-message",{"message":[16],"isContinued":[4,"is-continued"],"child":[16],"isUnread":[4,"is-unread"],"size":[513],"iconPack":[16],"t":[16],"isSelf":[4,"is-self"],"canEdit":[4,"can-edit"],"canDelete":[4,"can-delete"],"canReply":[4,"can-reply"],"canPin":[4,"can-pin"],"disableControls":[4,"disable-controls"],"alignRight":[4,"align-right"],"senderDisplayPicture":[1,"sender-display-picture"],"hideAvatar":[4,"hide-avatar"],"leftAlign":[4,"left-align"],"now":[32]}],[0,"dyte-image-message",{"message":[16],"now":[16],"isContinued":[516,"is-continued"],"iconPack":[16],"t":[16],"showBubble":[4,"show-bubble"],"status":[32]}],[1,"dyte-paginated-list",{"pageSize":[2,"page-size"],"pagesAllowed":[2,"pages-allowed"],"fetchData":[16],"createNodes":[16],"selectedItemId":[1,"selected-item-id"],"autoScroll":[4,"auto-scroll"],"iconPack":[16],"t":[16],"emptyListLabel":[1,"empty-list-label"],"isLoading":[32],"rerenderBoolean":[32],"shouldRenderNewNodes":[32],"hasNewNodesToRender":[32],"showEmptyListLabel":[32],"onNewNode":[64],"onNodeDelete":[64],"onNodeUpdate":[64]}],[0,"dyte-file-message",{"message":[16],"now":[16],"isContinued":[516,"is-continued"],"iconPack":[16],"t":[16],"showBubble":[4,"show-bubble"]}],[0,"dyte-text-message",{"message":[16],"now":[16],"isContinued":[516,"is-continued"],"iconPack":[16],"t":[16],"showBubble":[4,"show-bubble"]}]]],["p-92618020",[[1,"dyte-message-view",{"actions":[16],"variant":[1],"viewType":[1,"view-type"],"avatarUrl":[1,"avatar-url"],"hideAvatar":[4,"hide-avatar"],"authorName":[1,"author-name"],"hideAuthorName":[4,"hide-author-name"],"hideMetadata":[4,"hide-metadata"],"time":[16],"iconPack":[16]}],[1,"dyte-image-message-view",{"url":[1],"iconPack":[16],"t":[16],"status":[32]}],[1,"dyte-file-message-view",{"name":[1],"size":[2],"url":[1],"iconPack":[16],"t":[16]}],[0,"dyte-text-message-view",{"text":[1],"isMarkdown":[4,"is-markdown"]}]]],["p-3ae5c7c8",[[1,"dyte-chat-messages-ui",{"selectedGroup":[1,"selected-group"],"messages":[16],"selfUserId":[1,"self-user-id"],"canPinMessages":[4,"can-pin-messages"],"size":[513],"iconPack":[16],"t":[16],"now":[32],"showLatestMessageButton":[32]}],[1,"dyte-chat-messages-ui-paginated",{"meeting":[16],"selectedChannel":[16],"selectedChannelId":[1,"selected-channel-id"],"size":[513],"iconPack":[16],"t":[16],"leftAlign":[4,"left-align"],"children":[32],"permissionsChanged":[32]}],[1,"dyte-chat-search-results",{"meeting":[16],"query":[1],"channelId":[1,"channel-id"],"iconPack":[16],"t":[16]}],[1,"dyte-chat-composer-view",{"canSendTextMessage":[4,"can-send-text-message"],"canSendFiles":[4,"can-send-files"],"message":[1],"quotedMessage":[1,"quoted-message"],"storageKey":[1,"storage-key"],"inputTextPlaceholder":[1,"input-text-placeholder"],"isEditing":[4,"is-editing"],"iconPack":[16],"t":[16],"maxLength":[2,"max-length"],"disableEmojiPicker":[4,"disable-emoji-picker"],"rateLimits":[16],"fileToUpload":[32],"isEmojiPickerOpen":[32],"disableSendButton":[32],"rateLimitsBreached":[32]}],[0,"dyte-channel-header",{"meeting":[16],"channel":[16],"iconPack":[16],"t":[16],"showBackButton":[4,"show-back-button"],"showChannelDetailsDialog":[32],"showSearchBar":[32],"members":[32]}],[1,"dyte-channel-selector-view",{"channels":[16],"selectedChannelId":[1,"selected-channel-id"],"disableSearch":[4,"disable-search"],"hideAvatar":[4,"hide-avatar"],"iconPack":[16],"t":[16],"viewAs":[1,"view-as"],"searchQuery":[32],"showDropdown":[32]}],[1,"dyte-dialog-manager",{"meeting":[16],"config":[16],"states":[16],"size":[513],"iconPack":[16],"t":[16]}],[1,"dyte-notifications",{"meeting":[16],"states":[16],"config":[16],"t":[16],"size":[513],"iconPack":[16],"notifications":[32]},[[8,"dyteAPIError","apiErrorListener"],[8,"dyteSendNotification","sendNotificationListener"]]]]],["p-0051a454",[[1,"dyte-audio-visualizer",{"variant":[513],"participant":[16],"size":[513],"iconPack":[16],"t":[16],"hideMuted":[4,"hide-muted"],"isScreenShare":[4,"is-screen-share"],"audioEnabled":[32],"volume":[32]}],[1,"dyte-speaker-selector",{"meeting":[16],"states":[16],"variant":[1],"size":[513],"iconPack":[16],"t":[16],"speakerDevices":[32],"currentDevices":[32]}],[1,"dyte-microphone-selector",{"meeting":[16],"size":[513],"iconPack":[16],"variant":[1],"t":[16],"audioinputDevices":[32],"canProduceAudio":[32],"currentDevices":[32]}],[1,"dyte-switch",{"checked":[1028],"readonly":[4],"disabled":[516],"iconPack":[16],"t":[16]}]]],["p-ff2ec150",[[1,"dyte-tooltip",{"label":[1],"variant":[513],"disabled":[516],"open":[516],"kind":[513],"size":[513],"placement":[1],"delay":[2],"iconPack":[16],"t":[16],"isInFocus":[32]}]]]]'),e))); \ No newline at end of file +import{p as e,b as t}from"./p-69f2ebde.js";(()=>{const t=import.meta.url,i={};return""!==t&&(i.resourcesUrl=new URL(".",t).href),e(i)})().then((e=>t(JSON.parse('[["p-45c45e12",[[1,"dyte-chat",{"meeting":[16],"config":[16],"size":[513],"iconPack":[16],"t":[16],"disablePrivateChat":[4,"disable-private-chat"],"privatePresetFilter":[16],"displayFilter":[16],"canPinMessages":[32],"unreadCountGroups":[32],"chatGroups":[32],"selectedGroup":[32],"now":[32],"dropzoneActivated":[32],"showLatestMessageButton":[32],"canSend":[32],"canSendTextMessage":[32],"canSendFiles":[32],"canPrivateMessage":[32],"canSendPrivateTexts":[32],"canSendPrivateFiles":[32],"emojiPickerEnabled":[32],"chatRecipientId":[32],"participants":[32],"selectedParticipant":[32],"channels":[32],"selectedChannelId":[32],"editingMessage":[32],"replyMessage":[32],"searchQuery":[32],"selectorState":[32],"creatingChannel":[32],"showPinnedMessages":[32]},[[8,"editMessageInit","onEditMessageInit"],[0,"switchChannel","channelSwitchListener"]]]]],["p-eab9f9ac",[[1,"dyte-settings",{"meeting":[16],"states":[16],"size":[513],"iconPack":[16],"t":[16],"activeTab":[32],"isMobileMainVisible":[32],"networkStatus":[32],"canProduceVideo":[32]}]]],["p-a8b3c968",[[1,"dyte-breakout-rooms-manager",{"meeting":[16],"states":[16],"iconPack":[16],"t":[16],"loading":[32],"roomConfig":[32],"draftState":[32],"assigningParticipants":[32],"selectedParticipants":[32],"ephemeralStatusText":[32],"isDragMode":[32]},[[0,"participantDelete","onParticipantDelete"],[0,"participantsDragging","toggleDragMode"],[0,"selectedParticipantsUpdate","updateSelectedParticipants"],[0,"allParticipantsToggleUpdate","updateAllParticipants"]]]]],["p-17c03177",[[1,"dyte-participants-viewer-list",{"meeting":[16],"config":[16],"size":[513],"hideHeader":[4,"hide-header"],"iconPack":[16],"view":[1],"search":[1],"t":[16],"stageViewers":[32]}]]],["p-6a20f8e9",[[1,"dyte-chat-composer-ui",{"canSendTextMessage":[4,"can-send-text-message"],"canSendFiles":[4,"can-send-files"],"size":[513],"iconPack":[16],"t":[16],"disableEmojiPicker":[4,"disable-emoji-picker"],"prefill":[16],"members":[16],"channelId":[1,"channel-id"],"emojiPickerActive":[32],"mentionQuery":[32],"focusedMemberIndex":[32],"filePreview":[32]}]]],["p-98d81977",[[1,"dyte-debugger",{"meeting":[16],"states":[16],"size":[513],"iconPack":[16],"t":[16],"activeTab":[32],"isMobileMainVisible":[32],"progress":[32]},[[0,"testProgress","progressUpdate"]]]]],["p-9aa229c1",[[1,"dyte-grid",{"layout":[513],"aspectRatio":[513,"aspect-ratio"],"meeting":[16],"gap":[514],"size":[513],"states":[16],"config":[16],"iconPack":[16],"t":[16],"gridSize":[16],"overrides":[8],"participants":[32],"pinnedParticipants":[32],"screenShareParticipants":[32],"plugins":[32],"emptyStage":[32],"showLiveStreamPlayer":[32],"canCurrentPeerHost":[32],"pipSupported":[32],"pipEnabled":[32],"roomState":[32]}]]],["p-5c1a5c6d",[[1,"dyte-setup-screen",{"meeting":[16],"states":[16],"size":[513],"config":[16],"iconPack":[16],"t":[16],"displayName":[32],"isJoining":[32],"canEditName":[32],"canProduceAudio":[32],"connectionState":[32]}]]],["p-2d0d680e",[[1,"dyte-mixed-grid",{"layout":[513],"participants":[16],"pinnedParticipants":[16],"screenShareParticipants":[16],"plugins":[16],"aspectRatio":[1,"aspect-ratio"],"gap":[2],"size":[513],"meeting":[16],"states":[16],"config":[16],"iconPack":[16],"t":[16],"gridSize":[16],"activeTab":[32],"initialised":[32]}]]],["p-54518b67",[[1,"dyte-participants-stage-queue",{"meeting":[16],"config":[16],"size":[513],"iconPack":[16],"view":[1],"t":[16],"stageRequestedParticipants":[32]}]]],["p-3ce728cd",[[1,"dyte-participants-waiting-list",{"meeting":[16],"config":[16],"size":[513],"iconPack":[16],"view":[1],"t":[16],"waitlistedParticipants":[32]}]]],["p-4c71c2ed",[[1,"dyte-polls",{"meeting":[16],"config":[16],"size":[513],"iconPack":[16],"t":[16],"create":[32],"polls":[32],"permissions":[32]}]]],["p-a1796033",[[1,"dyte-audio-tile",{"meeting":[16],"config":[16],"size":[513],"states":[16],"iconPack":[16],"t":[16],"participant":[16],"audioEnabled":[32],"volume":[32]}]]],["p-e5ffb262",[[1,"dyte-camera-toggle",{"variant":[513],"meeting":[16],"size":[513],"iconPack":[16],"t":[16],"videoEnabled":[32],"canProduceVideo":[32],"cameraPermission":[32],"stageStatus":[32]}]]],["p-1ba39f82",[[1,"dyte-channel-creator",{"meeting":[16],"t":[16],"iconPack":[16],"channelName":[32],"searchQuery":[32],"step":[32],"loading":[32],"selectedMemberIds":[32],"focusedMemberIndex":[32],"showAllMembersList":[32]}]]],["p-67d2cf84",[[1,"dyte-channel-selector-ui",{"channels":[16],"selectedChannelId":[1,"selected-channel-id"],"iconPack":[16],"t":[16],"showRecentMessage":[4,"show-recent-message"],"isHidden":[32],"searchQuery":[32]}]]],["p-83f74c68",[[1,"dyte-mic-toggle",{"variant":[513],"meeting":[16],"size":[513],"iconPack":[16],"t":[16],"audioEnabled":[32],"canProduceAudio":[32],"micPermission":[32],"stageStatus":[32]}]]],["p-4209571a",[[1,"dyte-mute-all-button",{"variant":[513],"meeting":[16],"size":[513],"iconPack":[16],"t":[16],"canDisable":[32]}]]],["p-fccf38b2",[[1,"dyte-screen-share-toggle",{"states":[16],"variant":[513],"meeting":[16],"size":[513],"iconPack":[16],"t":[16],"maxScreenShareCount":[32],"screenShareCount":[32],"screenShareEnabled":[32],"canScreenShare":[32],"shareScreenPermission":[32],"screenShareState":[32],"stageStatus":[32]}]]],["p-66b50bbf",[[1,"dyte-stage-toggle",{"variant":[513],"meeting":[16],"size":[513],"iconPack":[16],"t":[16],"stageStatus":[32],"state":[32]}]]],["p-2c92cba5",[[1,"dyte-ai-toggle",{"variant":[513],"states":[16],"meeting":[16],"size":[513],"iconPack":[16],"t":[16],"aiActive":[32]}]]],["p-c98e08e9",[[1,"dyte-breakout-rooms-toggle",{"variant":[513],"meeting":[16],"states":[16],"size":[513],"iconPack":[16],"t":[16],"canToggle":[32]}]]],["p-531555da",[[1,"dyte-caption-toggle",{"variant":[513],"meeting":[16],"states":[16],"config":[16],"iconPack":[16],"size":[513],"t":[16],"captionEnabled":[32]}]]],["p-9aa36e9b",[[1,"dyte-chat-toggle",{"variant":[513],"meeting":[16],"states":[16],"size":[513],"iconPack":[16],"t":[16],"unreadMessageCount":[32],"chatActive":[32],"canViewChat":[32],"hasNewMessages":[32]}]]],["p-53a489a1",[[1,"dyte-debugger-toggle",{"variant":[513],"meeting":[16],"states":[16],"t":[16],"iconPack":[16],"size":[513]}]]],["p-4ab82ecd",[[1,"dyte-fullscreen-toggle",{"states":[16],"targetElement":[16],"variant":[513],"size":[513],"iconPack":[16],"t":[16],"fullScreenActive":[32],"isFullScreenSupported":[32]}]]],["p-10abc747",[[1,"dyte-grid-pagination",{"meeting":[16],"states":[16],"size":[513],"variant":[513],"iconPack":[16],"t":[16],"page":[32],"pageCount":[32],"activeCount":[32],"activeComputedCount":[32],"showPagination":[32]}]]],["p-3a4f39fd",[[1,"dyte-idle-screen",{"meeting":[16],"config":[16],"iconPack":[16],"t":[16]}]]],["p-840cde94",[[1,"dyte-leave-button",{"variant":[513],"size":[513],"iconPack":[16],"t":[16]}]]],["p-57f8cbec",[[1,"dyte-livestream-toggle",{"variant":[513],"meeting":[16],"size":[513],"iconPack":[16],"t":[16],"livestreamState":[32]}]]],["p-b4e7929c",[[1,"dyte-more-toggle",{"states":[16],"size":[513],"iconPack":[16],"t":[16]}]]],["p-bb4a58a1",[[1,"dyte-participants",{"meeting":[16],"states":[16],"config":[16],"size":[513],"iconPack":[16],"defaultParticipantsTabId":[1,"default-participants-tab-id"],"t":[16],"currentParticipantsTabId":[32],"tabs":[32],"hasRequests":[32],"search":[32]}]]],["p-bbd97987",[[1,"dyte-participants-audio",{"meeting":[16],"iconPack":[16],"t":[16],"showPlayDialog":[32]}]]],["p-8cea527d",[[1,"dyte-participants-toggle",{"variant":[513],"meeting":[16],"states":[16],"size":[513],"iconPack":[16],"t":[16],"participantsActive":[32],"waitlistedParticipants":[32],"stageRequestedParticipants":[32],"badgeCount":[32],"canViewParticipants":[32]}]]],["p-5e472028",[[1,"dyte-pip-toggle",{"variant":[513],"meeting":[16],"states":[16],"config":[16],"iconPack":[16],"size":[513],"t":[16],"pipSupported":[32]}]]],["p-5b043c60",[[1,"dyte-plugins-toggle",{"variant":[513],"meeting":[16],"states":[16],"size":[513],"iconPack":[16],"t":[16],"pluginsActive":[32],"canViewPlugins":[32]}]]],["p-f2c6a023",[[1,"dyte-polls-toggle",{"variant":[513],"meeting":[16],"states":[16],"size":[513],"iconPack":[16],"t":[16],"pollsActive":[32],"unreadPollsCount":[32],"canViewPolls":[32]}]]],["p-408ad9b9",[[1,"dyte-recording-toggle",{"variant":[513],"meeting":[16],"t":[16],"iconPack":[16],"size":[513],"disabled":[4],"recordingState":[32],"canRecord":[32]}]]],["p-9e8290b4",[[1,"dyte-screenshare-view",{"hideFullScreenButton":[4,"hide-full-screen-button"],"nameTagPosition":[513,"name-tag-position"],"participant":[16],"meeting":[16],"variant":[513],"size":[513],"iconPack":[16],"t":[16],"videoExpanded":[32],"screenShareEnabled":[32],"isFullScreen":[32],"remoteControlInfo":[32]}]]],["p-0233867d",[[1,"dyte-settings-toggle",{"variant":[513],"states":[16],"size":[513],"iconPack":[16],"t":[16]}]]],["p-9062b1ac",[[1,"dyte-sidebar",{"enabledSections":[1040],"defaultSection":[1,"default-section"],"meeting":[16],"states":[16],"config":[16],"iconPack":[16],"t":[16],"size":[513],"view":[513],"currentTab":[32],"isFloating":[32],"enablePinning":[32]}]]],["p-194769a0",[[1,"dyte-ai",{"defaultSection":[1,"default-section"],"meeting":[16],"states":[16],"config":[16],"iconPack":[16],"t":[16],"size":[513],"view":[513],"tab":[32],"newTranscriptionAvailable":[32],"newAiMessageAvailable":[32]}]]],["p-9aed2a17",[[1,"dyte-ai-home",{"meeting":[16],"initialMessages":[16],"prompt":[32],"messages":[32]}]]],["p-fc6aa00e",[[1,"dyte-broadcast-message-modal",{"meeting":[16],"states":[16],"iconPack":[16],"t":[16],"messagePayload":[32],"successMessage":[32]}]]],["p-b89e0629",[[1,"dyte-ended-screen",{"config":[16],"size":[513],"states":[16],"t":[16],"iconPack":[16],"meeting":[16],"icon":[32],"message":[32]}]]],["p-2379bba1",[[1,"dyte-image-viewer",{"image":[16],"size":[513],"t":[16],"iconPack":[16]}]]],["p-df719c80",[[0,"dyte-message-list-view",{"messages":[16],"renderer":[16],"loadMore":[16],"visibleItemsCount":[2,"visible-items-count"],"estimateItemSize":[2,"estimate-item-size"],"iconPack":[16],"range":[32],"isFetching":[32],"autoScroll":[32],"totalHeight":[32]}]]],["p-91da494e",[[1,"dyte-permissions-message",{"meeting":[16],"t":[16],"iconPack":[16],"states":[16],"device":[32],"currentStep":[32],"svgSteps":[32]}]]],["p-1c40bf17",[[1,"dyte-plugin-main",{"meeting":[16],"plugin":[16],"iconPack":[16],"t":[16],"canClosePlugin":[32],"viewModeEnabled":[32]}]]],["p-4352d0bf",[[1,"dyte-plugins",{"meeting":[16],"config":[16],"size":[513],"iconPack":[16],"t":[16],"plugins":[32],"canStartPlugins":[32],"canClosePlugins":[32],"activatedPluginsId":[32]}]]],["p-edd38b5d",[[1,"dyte-chat-selector-ui",{"selfUserId":[1,"self-user-id"],"selectedGroupId":[1,"selected-group-id"],"unreadCounts":[16],"groups":[16],"iconPack":[16],"t":[16],"showParticipantsPanel":[32],"query":[32]}]]],["p-9f2f491c",[[1,"dyte-clock",{"meeting":[16],"iconPack":[16],"t":[16],"startedTime":[32],"timeDiff":[32]}]]],["p-87ab87bb",[[1,"dyte-confirmation-modal",{"meeting":[16],"states":[16],"iconPack":[16],"t":[16]}]]],["p-7eea5e98",[[1,"dyte-file-dropzone",{"hostEl":[16],"iconPack":[16],"t":[16],"dropzoneActivated":[32]}]]],["p-667a5e10",[[1,"dyte-information-tooltip",{"iconPack":[16]}]]],["p-13c76797",[[1,"dyte-leave-meeting",{"meeting":[16],"states":[16],"iconPack":[16],"t":[16],"canEndMeeting":[32]}]]],["p-9391fae7",[[1,"dyte-meeting-title",{"meeting":[16],"iconPack":[16],"t":[16]}]]],["p-bcb55f75",[[1,"dyte-mute-all-confirmation",{"meeting":[16],"states":[16],"iconPack":[16],"t":[16],"allowUnmute":[32]}]]],["p-17d003ce",[[1,"dyte-network-indicator",{"participant":[16],"meeting":[16],"iconPack":[16],"t":[16],"isScreenShare":[4,"is-screen-share"],"score":[32]}]]],["p-f4d16c73",[[1,"dyte-participant-count",{"meeting":[16],"iconPack":[16],"t":[16],"size":[513],"participantCount":[32],"isViewer":[32]}]]],["p-6c35e2d3",[[1,"dyte-participants-stage-list",{"meeting":[16],"config":[16],"size":[513],"hideHeader":[4,"hide-header"],"iconPack":[16],"view":[1],"t":[16],"search":[1],"participants":[32]}]]],["p-0aa60268",[[1,"dyte-recording-indicator",{"meeting":[16],"size":[513],"t":[16],"iconPack":[16],"isRecording":[32]}]]],["p-abcd39d0",[[1,"dyte-transcript",{"transcript":[16],"t":[16],"timeout":[32]}]]],["p-2b143264",[[1,"dyte-transcripts",{"meeting":[16],"states":[16],"config":[16],"t":[16],"transcripts":[32],"listenerAttached":[32]}]]],["p-efa5c489",[[1,"dyte-waiting-screen",{"meeting":[16],"config":[16],"iconPack":[16],"t":[16]}]]],["p-066abf55",[[1,"dyte-ai-chat",{"t":[16]}]]],["p-61606bc5",[[1,"dyte-ai-transcriptions",{"t":[16],"meeting":[16],"initialTranscriptions":[16],"participantQuery":[32],"isProcessing":[32],"captionViewEnabled":[32],"transcriptions":[32]}]]],["p-19d1c9ca",[[1,"dyte-audio-grid",{"meeting":[16],"config":[16],"states":[16],"iconPack":[16],"size":[513],"t":[16],"hideSelf":[4,"hide-self"],"activeParticipants":[32],"onStageParticipants":[32],"offStageParticipants":[32]}]]],["p-2710e334",[[1,"dyte-controlbar",{"variant":[513],"disableRender":[4,"disable-render"],"meeting":[16],"config":[16],"states":[16],"iconPack":[16],"t":[16],"size":[513]}]]],["p-e4a78096",[[1,"dyte-header",{"variant":[513],"disableRender":[4,"disable-render"],"meeting":[16],"config":[16],"states":[16],"iconPack":[16],"t":[16],"size":[513]}]]],["p-3844becc",[[1,"dyte-meeting",{"loadConfigFromPreset":[4,"load-config-from-preset"],"applyDesignSystem":[4,"apply-design-system"],"mode":[513],"leaveOnUnmount":[4,"leave-on-unmount"],"meeting":[16],"showSetupScreen":[1028,"show-setup-screen"],"t":[16],"config":[1040],"iconPackUrl":[513,"icon-pack-url"],"size":[1537],"gridLayout":[1,"grid-layout"],"states":[32],"iconPack":[32]},[[0,"dyteStateUpdate","listenState"]]]]],["p-97d46173",[[1,"dyte-participant-setup",{"nameTagPosition":[513,"name-tag-position"],"isPreview":[4,"is-preview"],"participant":[16],"states":[16],"config":[16],"variant":[513],"size":[513],"iconPack":[16],"t":[16],"videoState":[32],"isPinned":[32]}]]],["p-c8e30628",[[1,"dyte-simple-grid",{"participants":[16],"aspectRatio":[1,"aspect-ratio"],"gap":[2],"size":[513],"meeting":[16],"states":[16],"config":[16],"iconPack":[16],"t":[16],"dimensions":[32],"mediaConnection":[32]}]]],["p-5899d85b",[[1,"dyte-spotlight-grid",{"layout":[513],"participants":[16],"pinnedParticipants":[16],"aspectRatio":[1,"aspect-ratio"],"gap":[2],"size":[513],"meeting":[16],"states":[16],"config":[16],"iconPack":[16],"t":[16],"gridSize":[16]}]]],["p-80f2f878",[[1,"dyte-stage",{"iconPack":[16],"t":[16]}]]],["p-6a54cb64",[[1,"dyte-text-field",{"type":[1],"placeholder":[1],"disabled":[4],"iconPack":[16],"t":[16]}]]],["p-45255350",[[4,"dyte-ui-provider",{"meeting":[16],"size":[1537],"config":[1040],"t":[16],"iconPackUrl":[513,"icon-pack-url"],"loadConfigFromPreset":[4,"load-config-from-preset"],"applyDesignSystem":[4,"apply-design-system"],"joinRoom":[4,"join-room"],"isReady":[32],"iconPack":[32]}]]],["p-5343baf1",[[1,"dyte-avatar",{"participant":[16],"variant":[513],"size":[513],"iconPack":[16],"t":[16],"imageState":[32]}]]],["p-65aab370",[[1,"dyte-controlbar-button",{"variant":[513],"showWarning":[4,"show-warning"],"size":[513],"label":[1],"icon":[1],"isLoading":[4,"is-loading"],"disabled":[516],"iconPack":[16],"t":[16],"brandIcon":[516,"brand-icon"]}]]],["p-a5cd2be1",[[1,"dyte-menu",{"size":[513],"placement":[1],"offset":[2],"iconPack":[16],"t":[16]}],[1,"dyte-menu-item",{"size":[513],"iconPack":[16],"t":[16]}],[1,"dyte-menu-list",{"iconPack":[16],"t":[16]}]]],["p-f323bc7a",[[1,"dyte-button",{"size":[513],"variant":[513],"kind":[513],"reverse":[516],"disabled":[516],"iconPack":[16],"t":[16],"type":[513]}]]],["p-d9f5e252",[[1,"dyte-icon",{"icon":[1],"iconPack":[16],"variant":[513],"t":[16],"size":[513]}]]],["p-46c65a1e",[[1,"dyte-participant",{"meeting":[16],"view":[1],"participant":[16],"iconPack":[16],"t":[16],"config":[16],"audioEnabled":[32],"videoEnabled":[32],"isPinned":[32],"isOnStage":[32],"canDisableParticipantAudio":[32],"canDisableParticipantVideo":[32],"canKickParticipant":[32],"canPinParticipant":[32],"canAllowParticipantOnStage":[32],"menuOpen":[32]}]]],["p-62f5331a",[[1,"dyte-tab-bar",{"size":[513],"meeting":[16],"states":[16],"config":[16],"layout":[513],"iconPack":[16],"t":[16],"activeTab":[16],"tabs":[16]}]]],["p-e237cb50",[[1,"dyte-name-tag",{"participant":[16],"meeting":[16],"size":[513],"isScreenShare":[4,"is-screen-share"],"variant":[513],"iconPack":[16],"t":[16],"length":[32]}]]],["p-34022f5a",[[1,"dyte-settings-audio",{"meeting":[16],"states":[16],"size":[513],"iconPack":[16],"t":[16]}],[1,"dyte-settings-video",{"meeting":[16],"states":[16],"size":[513],"iconPack":[16],"t":[16],"videoEnabled":[32]}]]],["p-51ac8691",[[1,"dyte-poll-form",{"iconPack":[16],"t":[16],"options":[32],"anonymous":[32],"hideVotes":[32],"error":[32]}],[1,"dyte-poll",{"poll":[16],"self":[1],"permissions":[16],"iconPack":[16],"t":[16]}]]],["p-85f67b95",[[1,"dyte-channel-details",{"channel":[16],"t":[16],"iconPack":[16],"members":[16]}]]],["p-a9939eca",[[1,"dyte-notification",{"notification":[16],"size":[513],"iconPack":[16],"t":[16],"imageState":[32]}]]],["p-26aadbca",[[1,"dyte-sidebar-ui",{"view":[513],"tabs":[16],"hideHeader":[4,"hide-header"],"hideCloseAction":[4,"hide-close-action"],"currentTab":[1,"current-tab"],"iconPack":[16],"t":[16]}]]],["p-075608df",[[1,"dyte-spotlight-indicator",{"meeting":[16],"iconPack":[16],"t":[16],"size":[513],"canSpotlight":[32],"isSpotlighted":[32]}]]],["p-af914aac",[[0,"dyte-virtualized-participant-list",{"items":[16],"renderItem":[16],"itemHeight":[1026,"item-height"],"bufferedItemsCount":[2,"buffered-items-count"],"emptyListElement":[16],"visibleStart":[32],"visibleEnd":[32]}]]],["p-e2896ebd",[[1,"dyte-breakout-room-manager",{"meeting":[16],"assigningParticipants":[4,"assigning-participants"],"mode":[1],"states":[16],"allowDelete":[4,"allow-delete"],"iconPack":[16],"t":[16],"isDragMode":[4,"is-drag-mode"],"room":[16],"defaultExpanded":[4,"default-expanded"],"editingTitleRoomId":[32],"newTitle":[32],"showExpandedCard":[32],"glowingCard":[32]}],[1,"dyte-breakout-room-participants",{"meeting":[16],"participantIds":[16],"iconPack":[16],"t":[16],"selectedParticipantIds":[16],"search":[32],"participantsToShow":[32],"isDragging":[32]}],[1,"dyte-counter",{"size":[513],"value":[2],"minValue":[2,"min-value"],"iconPack":[16],"t":[16],"input":[32]}]]],["p-e2006c50",[[1,"dyte-livestream-player",{"meeting":[16],"size":[513],"t":[16],"iconPack":[16],"playbackUrl":[32],"isSupported":[32],"playerState":[32],"livestreamState":[32],"playerError":[32],"latency":[32],"audioPlaybackError":[32]}],[1,"dyte-livestream-indicator",{"meeting":[16],"size":[513],"t":[16],"iconPack":[16],"isLivestreaming":[32]}],[1,"dyte-viewer-count",{"meeting":[16],"variant":[513],"iconPack":[16],"t":[16],"viewerCount":[32]}]]],["p-0f01555b",[[1,"dyte-join-stage",{"meeting":[16],"config":[16],"states":[16],"size":[513],"iconPack":[16],"t":[16],"dataConfig":[16],"isLoading":[32]}],[1,"dyte-overlay-modal",{"meeting":[16],"states":[16],"iconPack":[16],"t":[16]}]]],["p-9f5ff3e1",[[1,"dyte-dialog",{"hideCloseButton":[4,"hide-close-button"],"disableEscapeKey":[4,"disable-escape-key"],"meeting":[16],"config":[16],"states":[16],"size":[513],"iconPack":[16],"t":[16],"open":[1540]}]]],["p-ef129879",[[1,"dyte-debugger-audio",{"meeting":[16],"states":[16],"size":[513],"iconPack":[16],"t":[16],"isNetworkOpen":[32],"isDevicesOpen":[32],"audioProducerFormattedStats":[32],"audioProducerScoreStats":[32],"networkBasedMediaHealth":[32],"devicesHealth":[32]}],[1,"dyte-debugger-screenshare",{"meeting":[16],"states":[16],"size":[513],"iconPack":[16],"t":[16],"isNetworkOpen":[32],"isDevicesOpen":[32],"videoProducerFormattedStats":[32],"videoProducerScoreStats":[32],"audioProducerFormattedStats":[32],"audioProducerScoreStats":[32],"networkBasedMediaHealth":[32]}],[1,"dyte-debugger-system",{"meeting":[16],"states":[16],"size":[513],"iconPack":[16],"t":[16],"isBatterySectionOpen":[32],"batterySectionHealth":[32],"battery":[32],"batteryFormattedStats":[32]}],[1,"dyte-debugger-video",{"meeting":[16],"states":[16],"size":[513],"iconPack":[16],"t":[16],"isNetworkOpen":[32],"isDevicesOpen":[32],"videoProducerFormattedStats":[32],"videoProducerScoreStats":[32],"networkBasedMediaHealth":[32],"devicesHealth":[32]}]]],["p-8793a889",[[1,"dyte-logo",{"logoUrl":[1025,"logo-url"],"config":[16],"meeting":[16],"t":[16]}]]],["p-39990800",[[1,"dyte-participant-tile",{"nameTagPosition":[513,"name-tag-position"],"isPreview":[4,"is-preview"],"participant":[16],"meeting":[16],"states":[16],"config":[16],"variant":[513],"size":[513],"iconPack":[16],"t":[16],"isPinned":[32],"mediaConnectionError":[32]}],[1,"dyte-camera-selector",{"meeting":[16],"size":[513],"iconPack":[16],"variant":[1],"t":[16],"videoDevices":[32],"currentDevice":[32],"canProduceVideo":[32]}]]],["p-c7fad504",[[1,"dyte-markdown-view",{"text":[1],"maxLength":[2,"max-length"]}]]],["p-5818108f",[[1,"dyte-spinner",{"iconPack":[16],"size":[513],"t":[16]}]]],["p-95e6b985",[[1,"dyte-draft-attachment-view",{"iconPack":[16],"t":[16],"attachment":[16],"filePreview":[32]}],[1,"dyte-emoji-picker-button",{"iconPack":[16],"t":[16],"isActive":[4,"is-active"]}],[1,"dyte-file-picker-button",{"filter":[1],"label":[1],"icon":[1],"iconPack":[16],"t":[16]}],[1,"dyte-text-composer-view",{"disabled":[4],"placeholder":[1],"value":[1],"maxLength":[2,"max-length"],"rateLimitBreached":[4,"rate-limit-breached"],"keyDownHandler":[16],"iconPack":[16],"t":[16],"maxLengthBreached":[32],"setText":[64]}],[1,"dyte-emoji-picker",{"iconPack":[16],"t":[16],"emojiList":[32],"filterVal":[32],"filteredEmojis":[32]}]]],["p-4448d3ad",[[1,"dyte-chat-message",{"message":[16],"isContinued":[4,"is-continued"],"child":[16],"isUnread":[4,"is-unread"],"size":[513],"iconPack":[16],"t":[16],"isSelf":[4,"is-self"],"canEdit":[4,"can-edit"],"canDelete":[4,"can-delete"],"canReply":[4,"can-reply"],"canPin":[4,"can-pin"],"disableControls":[4,"disable-controls"],"alignRight":[4,"align-right"],"senderDisplayPicture":[1,"sender-display-picture"],"hideAvatar":[4,"hide-avatar"],"leftAlign":[4,"left-align"],"now":[32]}],[0,"dyte-image-message",{"message":[16],"now":[16],"isContinued":[516,"is-continued"],"iconPack":[16],"t":[16],"showBubble":[4,"show-bubble"],"status":[32]}],[1,"dyte-paginated-list",{"pageSize":[2,"page-size"],"pagesAllowed":[2,"pages-allowed"],"fetchData":[16],"createNodes":[16],"selectedItemId":[1,"selected-item-id"],"autoScroll":[4,"auto-scroll"],"iconPack":[16],"t":[16],"emptyListLabel":[1,"empty-list-label"],"isLoading":[32],"rerenderBoolean":[32],"shouldRenderNewNodes":[32],"hasNewNodesToRender":[32],"showEmptyListLabel":[32],"onNewNode":[64],"onNodeDelete":[64],"onNodeUpdate":[64]}],[0,"dyte-file-message",{"message":[16],"now":[16],"isContinued":[516,"is-continued"],"iconPack":[16],"t":[16],"showBubble":[4,"show-bubble"]}],[0,"dyte-text-message",{"message":[16],"now":[16],"isContinued":[516,"is-continued"],"iconPack":[16],"t":[16],"showBubble":[4,"show-bubble"]}]]],["p-92618020",[[1,"dyte-message-view",{"actions":[16],"variant":[1],"viewType":[1,"view-type"],"avatarUrl":[1,"avatar-url"],"hideAvatar":[4,"hide-avatar"],"authorName":[1,"author-name"],"hideAuthorName":[4,"hide-author-name"],"hideMetadata":[4,"hide-metadata"],"time":[16],"iconPack":[16]}],[1,"dyte-image-message-view",{"url":[1],"iconPack":[16],"t":[16],"status":[32]}],[1,"dyte-file-message-view",{"name":[1],"size":[2],"url":[1],"iconPack":[16],"t":[16]}],[0,"dyte-text-message-view",{"text":[1],"isMarkdown":[4,"is-markdown"]}]]],["p-3ae5c7c8",[[1,"dyte-chat-messages-ui",{"selectedGroup":[1,"selected-group"],"messages":[16],"selfUserId":[1,"self-user-id"],"canPinMessages":[4,"can-pin-messages"],"size":[513],"iconPack":[16],"t":[16],"now":[32],"showLatestMessageButton":[32]}],[1,"dyte-chat-messages-ui-paginated",{"meeting":[16],"selectedChannel":[16],"selectedChannelId":[1,"selected-channel-id"],"size":[513],"iconPack":[16],"t":[16],"leftAlign":[4,"left-align"],"children":[32],"permissionsChanged":[32]}],[1,"dyte-chat-search-results",{"meeting":[16],"query":[1],"channelId":[1,"channel-id"],"iconPack":[16],"t":[16]}],[1,"dyte-chat-composer-view",{"canSendTextMessage":[4,"can-send-text-message"],"canSendFiles":[4,"can-send-files"],"message":[1],"quotedMessage":[1,"quoted-message"],"storageKey":[1,"storage-key"],"inputTextPlaceholder":[1,"input-text-placeholder"],"isEditing":[4,"is-editing"],"iconPack":[16],"t":[16],"maxLength":[2,"max-length"],"disableEmojiPicker":[4,"disable-emoji-picker"],"rateLimits":[16],"fileToUpload":[32],"isEmojiPickerOpen":[32],"disableSendButton":[32],"rateLimitsBreached":[32]}],[0,"dyte-channel-header",{"meeting":[16],"channel":[16],"iconPack":[16],"t":[16],"showBackButton":[4,"show-back-button"],"showChannelDetailsDialog":[32],"showSearchBar":[32],"members":[32]}],[1,"dyte-channel-selector-view",{"channels":[16],"selectedChannelId":[1,"selected-channel-id"],"disableSearch":[4,"disable-search"],"hideAvatar":[4,"hide-avatar"],"iconPack":[16],"t":[16],"viewAs":[1,"view-as"],"searchQuery":[32],"showDropdown":[32]}],[1,"dyte-dialog-manager",{"meeting":[16],"config":[16],"states":[16],"size":[513],"iconPack":[16],"t":[16]}],[1,"dyte-notifications",{"meeting":[16],"states":[16],"config":[16],"t":[16],"size":[513],"iconPack":[16],"notifications":[32]},[[8,"dyteAPIError","apiErrorListener"],[8,"dyteSendNotification","sendNotificationListener"]]]]],["p-0051a454",[[1,"dyte-audio-visualizer",{"variant":[513],"participant":[16],"size":[513],"iconPack":[16],"t":[16],"hideMuted":[4,"hide-muted"],"isScreenShare":[4,"is-screen-share"],"audioEnabled":[32],"volume":[32]}],[1,"dyte-speaker-selector",{"meeting":[16],"states":[16],"variant":[1],"size":[513],"iconPack":[16],"t":[16],"speakerDevices":[32],"currentDevices":[32]}],[1,"dyte-microphone-selector",{"meeting":[16],"size":[513],"iconPack":[16],"variant":[1],"t":[16],"audioinputDevices":[32],"canProduceAudio":[32],"currentDevices":[32]}],[1,"dyte-switch",{"checked":[1028],"readonly":[4],"disabled":[516],"iconPack":[16],"t":[16]}]]],["p-ff2ec150",[[1,"dyte-tooltip",{"label":[1],"variant":[513],"disabled":[516],"open":[516],"kind":[513],"size":[513],"placement":[1],"delay":[2],"iconPack":[16],"t":[16],"isInFocus":[32]}]]]]'),e))); \ No newline at end of file diff --git a/build/p-45c45e12.entry.js b/build/p-45c45e12.entry.js new file mode 100644 index 00000000..8d271b5a --- /dev/null +++ b/build/p-45c45e12.entry.js @@ -0,0 +1 @@ +import{r as t,c as i,h as s,F as e,H as n,a as h}from"./p-69f2ebde.js";import{d as a}from"./p-cadf534b.js";import{u as o}from"./p-54de5543.js";import{h as r,g as c,T as l,i as d,d as p,f as v,s as y,j as u}from"./p-d0b39589.js";import{c as g}from"./p-57e22a58.js";import{u as b,F as m}from"./p-19c79157.js";import{s as x}from"./p-1210aa77.js";import"./p-26e8d50e.js";import{d as f}from"./p-ba748e25.js";import"./p-799d72ea.js";import"./p-aafa2ac8.js";const w=class{constructor(e){t(this,e),this.stateUpdate=i(this,"dyteStateUpdate",7),this.chatUpdateListener=({message:t})=>{t.channelId||this.displayFilter&&!this.displayFilter(t)||(this.addToChatGroup(t),this.chatGroups=Object.assign({},this.chatGroups))},this.chatPermissionUpdateListener=()=>{this.canSend=this.meeting.self.permissions.chatPublic.canSend,this.canSendTextMessage=this.meeting.self.permissions.chatPublic.text,this.canSendFiles=this.meeting.self.permissions.chatPublic.files},this.channelMap=new Map,this.onDragOver=t=>{t.preventDefault(),this.dropzoneActivated=!0},this.onDragLeave=()=>{this.dropzoneActivated=!1},this.onDrop=t=>{t.preventDefault(),this.dropzoneActivated=!1,r(t.dataTransfer.items,((t,i)=>{var s,e,n,h;switch(t){case"image":this.isFileMessagingAllowed()&&(null===(e=null===(s=this.meeting)||void 0===s?void 0:s.chat)||void 0===e||e.sendImageMessage(i,this.getRecipientPeerIds()));break;case"file":this.isFileMessagingAllowed()&&(null===(h=null===(n=this.meeting)||void 0===n?void 0:n.chat)||void 0===h||h.sendFileMessage(i,this.getRecipientPeerIds()))}}))},this.disconnectMeeting=t=>{var i,s,e,n,h,a;this.isPrivateChatSupported()&&(null==t||t.participants.joined.removeListener("participantJoined",this.onParticipantUpdate),null==t||t.participants.joined.removeListener("participantLeft",this.onParticipantUpdate)),null===(i=null==t?void 0:t.chat)||void 0===i||i.removeListener("chatUpdate",this.chatUpdateListener),null===(s=null==t?void 0:t.chat)||void 0===s||s.removeListener("channelCreate",this.onChannelCreateOrUpdate),null===(e=null==t?void 0:t.chat)||void 0===e||e.removeListener("channelUpdate",this.onChannelCreateOrUpdate),null===(n=null==t?void 0:t.chat)||void 0===n||n.removeListener("channelMessageUpdate",this.onChannelCreateOrUpdate),null===(a=null===(h=null==t?void 0:t.participants)||void 0===h?void 0:h.all)||void 0===a||a.removeListener("participantsUpdate",this.onChannelCreateOrUpdate),t.self.permissions.removeListener("*",this.chatPermissionUpdateListener)},this.getFilteredParticipants=()=>0===this.privatePresetFilter.length?this.participants:this.participants.filter((t=>this.privatePresetFilter.includes(t.presetName))),this.onParticipantUpdate=()=>{this.participants=this.meeting.participants.joined.toArray().filter((t=>0===this.privatePresetFilter.length||this.privatePresetFilter.includes(t.presetName))),this.selectedParticipant&&!this.participants.includes(this.selectedParticipant)&&(this.selectedParticipant=null,this.chatRecipientId=this.selectedGroup="everyone")},this.usePaginatedChat=()=>(!this.isGroupCall||!this.showPinnedMessages)&&"everyone"===this.selectedGroup&&b(this.meeting),this.updateUnreadCountGroups=t=>{this.unreadCountGroups=Object.assign(Object.assign({},this.unreadCountGroups),t)},this.isPrivateChatSupported=()=>this.canPrivateMessage&&!this.disablePrivateChat,this.updateRecipients=t=>{const{id:i}=t.detail;if(this.chatRecipientId=i,this.selectedParticipant=this.participants.find((t=>t.userId===i)),"everyone"!==this.chatRecipientId){const t=c([this.chatRecipientId,this.meeting.self.userId]);this.selectedGroup=t}else this.selectedGroup="everyone";this.updateUnreadCountGroups({[this.selectedGroup]:0})},this.isTextMessagingAllowed=()=>"everyone"===this.chatRecipientId?this.canSend&&this.canSendTextMessage:this.canPrivateMessage&&this.canSendPrivateTexts,this.isFileMessagingAllowed=()=>"everyone"===this.chatRecipientId?this.canSend&&this.canSendFiles:this.canPrivateMessage&&this.canSendPrivateFiles,this.onChannelChanged=t=>{const i=t.detail;i.id.includes(l)?this.createDMChannel(i.id.replace(l,"")):this.selectedChannelId=i.id,this.cleanup(),"desktop"!==this.selectorState&&(this.selectorState="hide")},this.createDMChannel=async t=>{this.creatingChannel=!0;const i=await this.meeting.chat.createChannel("Direct Message",[t],{visibility:"private",isDirectMessage:!0});this.creatingChannel=!1,this.selectedChannelId=i.id},this.cleanup=()=>{this.editingMessage=null,this.replyMessage=null,this.searchQuery=""},this.onQuotedMessageDismiss=()=>{this.replyMessage=null},this.onChannelCreateOrUpdate=t=>{t?this.channelMap.set(t.id,t):this.meeting.chat.channels.forEach((t=>this.channelMap.set(t.id,t)));const i=Array.from(this.channelMap.values()),s=i.filter((t=>!d(t))).sort(((t,i)=>p(t.displayName,i.displayName))),e=i.filter(d).map((t=>Object.assign(Object.assign({},t),{displayName:this.getMemberDisplayName(t)}))),n=this.meeting.participants.all.toArray().filter((t=>{if(t.userId===this.meeting.self.userId)return!1;const i=v([this.meeting.self.userId,t.userId]);return e.every((t=>v(t.memberIds)!==i))})).map((t=>({id:`${l}${t.userId}`,displayName:t.name,displayPictureUrl:t.picture,isDirectMessage:!0,unreadCount:0}))),h=[...e,...n].sort(((t,i)=>p(t.displayName,i.displayName)));this.channels=[...s,...h];const a=[...s,...e];this.selectedChannelId||0===a.length||(this.selectedChannelId=a[0].id)},this.getMemberDisplayName=t=>{var i;let s;s=1===t.memberIds.length?t.memberIds[0]:t.memberIds[0]===this.meeting.self.userId?t.memberIds[1]:t.memberIds[0];const e=this.meeting.participants.all.toArray().find((t=>t.userId===s));return null!==(i=null==e?void 0:e.name)&&void 0!==i?i:s},this.onNewMessageHandler=async t=>{const i=t.detail;this.isChatViewType?(await this.meeting.chat.sendMessageToChannel(i,this.selectedChannelId,this.replyMessage?{replyTo:this.replyMessage}:{}),this.replyMessage=null):this.meeting.chat.sendMessage(i,this.getRecipientPeerIds())},this.onEditMessageHandler=async t=>{var i,s;await(null===(s=null===(i=this.meeting)||void 0===i?void 0:i.chat)||void 0===s?void 0:s.editTextMessage(this.editingMessage.id,t.detail,this.editingMessage.channelId)),this.editingMessage=null},this.onEditCancel=()=>{this.editingMessage=null},this.onSearchHandler=async t=>{this.searchQuery=t.detail},this.onSearchDismissed=()=>{this.searchQuery=""},this.onChannelCreateClicked=()=>{this.stateUpdate.emit({activeChannelCreator:!0}),x.activeChannelCreator=!0},this.onPinMessage=t=>{const i=t.detail;i.pinned?this.meeting.chat.unpin(i.id):this.meeting.chat.pin(i.id)},this.onDeleteMessage=t=>{this.meeting.chat.deleteMessage(t.detail.id)},this.getChannelItems=()=>this.channels.map((t=>{const i={id:t.id,name:t.displayName,avatarUrl:t.displayPictureUrl};return t.latestMessage&&(i.latestMessage="text"===t.latestMessage.type?y(t.latestMessage.message):"",i.latestMessageTime=t.latestMessage.time),i})),this.getPrivateChatRecipients=()=>{const t=this.getFilteredParticipants().map((t=>{const i=c([t.userId,this.meeting.self.userId]);return{id:t.userId,name:t.name,avatarUrl:t.picture,unreadCount:this.unreadCountGroups[i]}}));return[{id:"everyone",name:this.t("chat.everyone"),icon:"participants",unreadCount:this.unreadCountGroups.everyone},...t]},this.onTogglePinnedMessages=()=>{this.showPinnedMessages=!this.showPinnedMessages},this.renderPinnedMessagesHeader=()=>0===this.meeting.chat.pinned.length?null:s("dyte-tooltip",{label:this.t("chat.toggle_pinned_msgs"),iconPack:this.iconPack,t:this.t},s("div",{class:{"pinned-messages-header":!0,active:this.showPinnedMessages},onClick:this.onTogglePinnedMessages},s("dyte-icon",{icon:this.iconPack.pin,iconPack:this.iconPack,t:this.t}),this.t("chat.pinned_msgs"),` (${this.meeting.chat.pinned.length})`)),this.meeting=void 0,this.config=f,this.size=void 0,this.iconPack=a,this.t=o(),this.disablePrivateChat=!1,this.canPinMessages=!1,this.privatePresetFilter=[],this.displayFilter=void 0,this.unreadCountGroups={},this.chatGroups={everyone:[]},this.selectedGroup="everyone",this.now=new Date,this.dropzoneActivated=!1,this.showLatestMessageButton=!1,this.canSend=!1,this.canSendTextMessage=!1,this.canSendFiles=!1,this.canPrivateMessage=!1,this.canSendPrivateTexts=!1,this.canSendPrivateFiles=!1,this.emojiPickerEnabled=!1,this.chatRecipientId="everyone",this.participants=[],this.selectedParticipant=void 0,this.channels=[],this.selectedChannelId=void 0,this.editingMessage=null,this.replyMessage=null,this.searchQuery="",this.selectorState="hide",this.creatingChannel=!1,this.showPinnedMessages=!1}connectedCallback(){this.meeting&&(this.meetingChanged(this.meeting),this.meeting&&!this.meeting.chat||this.isFileMessagingAllowed()&&(this.host.addEventListener("dragover",this.onDragOver),this.host.addEventListener("dragleave",this.onDragLeave),this.host.addEventListener("drop",this.onDrop)))}onEditMessageInit(t){t.detail.flags.isReply?this.replyMessage=t.detail.payload:t.detail.flags.isEdit&&(this.editingMessage=t.detail.payload)}disconnectedCallback(){var t;null===(t=this.resizeObserver)||void 0===t||t.disconnect(),this.disconnectMeeting(this.meeting),this.host.removeEventListener("dragover",this.onDragOver),this.host.removeEventListener("dragleave",this.onDragLeave),this.host.removeEventListener("drop",this.onDrop)}meetingChanged(t,i){var s,e,n,h,a,o;null!=i&&this.disconnectMeeting(i),t&&!t.chat||null==t||(this.canSend=t.self.permissions.chatPublic.canSend,this.canSendTextMessage=t.self.permissions.chatPublic.text,this.canSendFiles=t.self.permissions.chatPublic.files,this.canPrivateMessage=!(!(null===(s=t.self.permissions.chatPrivate)||void 0===s?void 0:s.canSend)&&!(null===(e=t.self.permissions.chatPrivate)||void 0===e?void 0:e.canReceive)),this.canSendPrivateTexts=!!(null===(n=t.self.permissions.chatPrivate)||void 0===n?void 0:n.text),this.canSendPrivateFiles=!!(null===(h=t.self.permissions.chatPrivate)||void 0===h?void 0:h.files),this.canPinMessages=(null===(a=null==t?void 0:t.__internals__)||void 0===a?void 0:a.features.hasFeature(m.PINNED_MESSAGES))&&t.self.permissions.pinParticipant,this.isGroupCall="GROUP_CALL"===t.meta.viewType,this.isChatViewType="CHAT"===t.meta.viewType,this.isChatViewType&&(this.onChannelCreateOrUpdate(),this.channels.filter((t=>!t.id.includes(l))).length&&(this.selectedChannelId=this.channels[0].id),this.resizeObserver&&this.resizeObserver.disconnect(),this.resizeObserver=new ResizeObserver((t=>{for(const i of t)this.selectorState=i.contentBoxSize[0].inlineSize<758?"hide":"desktop"})),this.isChatViewType&&this.resizeObserver.observe(this.host)),this.initializeChatGroups(),this.chatGroups=Object.assign({},this.chatGroups),t.self.permissions.on("*",this.chatPermissionUpdateListener),this.onParticipantUpdate(),null===(o=t.chat)||void 0===o||o.addListener("chatUpdate",this.chatUpdateListener),this.isPrivateChatSupported()&&(t.participants.joined.addListener("participantJoined",this.onParticipantUpdate),t.participants.joined.addListener("participantLeft",this.onParticipantUpdate)),this.isChatViewType&&(t.chat.addListener("channelCreate",this.onChannelCreateOrUpdate),t.chat.addListener("channelUpdate",this.onChannelCreateOrUpdate),t.chat.addListener("channelMessageUpdate",this.onChannelCreateOrUpdate),t.participants.all.addListener("participantsUpdate",this.onChannelCreateOrUpdate)))}chatGroupsChanged(t){var i,s;if(!this.isPrivateChatSupported())return;const e={};for(const n in t){const h=null!==(i=g[n])&&void 0!==i?i:0;e[n]=t[n].filter((t=>"chat"==t.type&&t.message.time>h&&t.message.userId!==this.meeting.self.userId)).length,(n===c([this.meeting.self.userId,null===(s=this.selectedParticipant)||void 0===s?void 0:s.userId])||"everyone"===n&&null===this.selectedParticipant)&&(e[n]=0,g[n]=new Date)}this.updateUnreadCountGroups(e)}initializeChatGroups(){var t;null===(t=this.meeting.chat)||void 0===t||t.messages.forEach((t=>{this.displayFilter&&!this.displayFilter(t)||this.addToChatGroup(t)}))}onDisplayFilterChanged(t,i){t!==i&&(this.chatGroups={},this.initializeChatGroups())}addToChatGroup(t){var i;const s=u(t);let e="everyone";if((null===(i=s.targetUserIds)||void 0===i?void 0:i.length)>0){const t=new Set([s.userId,...s.targetUserIds]);e=c(Array.from(t))}void 0===this.chatGroups[e]&&(this.chatGroups[e]=[]);let n=!1,h=[];this.chatGroups[e].forEach((i=>{"chat"===i.type&&i.message.id===t.id?(n=!0,h.push({type:"chat",message:s})):h.push(i)})),n||h.push({type:"chat",message:s}),this.chatGroups[e]=h}getRecipientPeerIds(){let t=[];return"everyone"!==this.chatRecipientId&&(t=[this.selectedParticipant.id]),t}channelSwitchListener(t){this.onChannelChanged(t)}renderHeadlessComponents(){return s(e,null,s("dyte-dialog-manager",{meeting:this.meeting}),s("dyte-notifications",{meeting:this.meeting}))}renderComposerUI(){var t,i,e;if(this.isChatViewType&&0===this.channels.length)return null;if(this.isChatViewType&&""!==this.searchQuery)return null;if(this.isChatViewType&&!this.selectedChannelId)return null;if("everyone"===this.chatRecipientId){if(!this.canSendTextMessage&&!this.canSendFiles)return null}else if(!this.canSendPrivateTexts&&!this.canSendPrivateFiles)return null;const n={iconPack:this.iconPack,t:this.t,size:this.size};return s("dyte-chat-composer-view",Object.assign({message:this.editingMessage?this.editingMessage.message:"",storageKey:null!==(t=this.selectedChannelId)&&void 0!==t?t:`draft-${this.selectedChannelId}`,quotedMessage:this.replyMessage?this.replyMessage.message:"",isEditing:!!this.editingMessage,canSendTextMessage:this.isTextMessagingAllowed(),canSendFiles:this.isFileMessagingAllowed(),disableEmojiPicker:!!(null===(e=null===(i=this.meeting)||void 0===i?void 0:i.__internals__)||void 0===e?void 0:e.features.hasFeature(m.DISABLE_EMOJI_PICKER)),maxLength:this.meeting.chat.maxTextLimit,rateLimits:this.meeting.chat.rateLimits,inputTextPlaceholder:this.t("chat.message_placeholder"),onNewMessage:this.onNewMessageHandler,onEditMessage:this.onEditMessageHandler,onEditCancel:this.onEditCancel,onQuotedMessageDismiss:this.onQuotedMessageDismiss},n),s("slot",{name:"chat-addon",slot:"chat-addon"}))}renderFullChat(){if(this.creatingChannel)return s("div",{class:"banner"},s("dyte-spinner",{size:"lg"}));if(0===this.channels.length||!this.selectedChannelId)return s("div",{class:"banner"},s("dyte-icon",{icon:this.iconPack.create_channel_illustration,iconPack:this.iconPack,t:this.t,slot:"start",class:"create-channel-illustration"}),s("dyte-button",{iconPack:this.iconPack,t:this.t,kind:"wide",variant:"primary",size:"md",onClick:this.onChannelCreateClicked,class:"welcome-new-channel"},s("dyte-icon",{icon:this.iconPack.add,iconPack:this.iconPack,t:this.t,slot:"start"}),s("span",null,this.t("chat.new_channel"))),("mobile"===this.selectorState||"hide"===this.selectorState)&&s("dyte-button",{kind:"button",variant:"secondary",size:"md",class:"view-chats-btn",onClick:()=>{this.selectorState="mobile"}},s("dyte-icon",{icon:this.iconPack.chat,slot:"start"}),s("span",null,this.t("chat.view_chats"))));const t=this.channels.find((t=>t.id===this.selectedChannelId));return s("div",{class:"chat"},s("dyte-channel-header",{slot:"header",meeting:this.meeting,channel:t,onSearch:this.onSearchHandler,onSearchDismissed:this.onSearchDismissed,showBackButton:"mobile"===this.selectorState||"hide"===this.selectorState,onBack:()=>{this.selectorState="mobile"}}),""!==this.searchQuery&&s("dyte-chat-search-results",{meeting:this.meeting,query:this.searchQuery,channelId:this.selectedChannelId}),""===this.searchQuery&&s("dyte-chat-messages-ui-paginated",{meeting:this.meeting,size:this.size,iconPack:this.iconPack,t:this.t,selectedChannelId:this.selectedChannelId,selectedChannel:t}))}render(){var t,i;if(!this.meeting)return null;const e={iconPack:this.iconPack,t:this.t,size:this.size},h=null===(t=this.meeting)||void 0===t?void 0:t.self.userId;let a=this.chatGroups[this.selectedGroup]||[];return this.showPinnedMessages&&0!==this.meeting.chat.pinned.length&&(a=a.filter((t=>"chat"===t.type&&t.message.pinned))),s(n,null,this.isChatViewType&&this.renderHeadlessComponents(),s("div",{class:"chat-container"},this.isChatViewType&&s("div",{class:{"selector-container":!0,[this.selectorState]:!0}},s("dyte-channel-selector-view",{channels:this.getChannelItems(),selectedChannelId:this.selectedChannelId,onChannelChange:this.onChannelChanged,t:this.t},s("div",{class:"channel-selector-header",slot:"header"},s("dyte-logo",{meeting:this.meeting,config:this.config,t:this.t}),s("dyte-tooltip",{label:this.t("chat.new_channel"),iconPack:this.iconPack,t:this.t},s("dyte-button",{iconPack:this.iconPack,t:this.t,kind:"button",variant:"ghost",size:"md",onClick:this.onChannelCreateClicked,class:"channel-create-btn"},s("dyte-icon",{icon:this.iconPack.add,iconPack:this.iconPack,t:this.t}))))),s("dyte-button",{kind:"icon",variant:"ghost",class:"mobile-close-btn",onClick:()=>this.selectorState="hide"},s("dyte-icon",{icon:this.iconPack.dismiss}))),s("div",{class:"chat"},this.isFileMessagingAllowed()&&s("div",{id:"dropzone",class:{active:this.dropzoneActivated},part:"dropzone"},s("dyte-icon",{icon:this.iconPack.attach,iconPack:this.iconPack,t:this.t}),s("p",null,this.t("chat.send_attachment"))),this.renderPinnedMessagesHeader(),this.isPrivateChatSupported()&&s("dyte-channel-selector-view",{channels:this.getPrivateChatRecipients(),selectedChannelId:(null===(i=this.selectedParticipant)||void 0===i?void 0:i.userId)||"everyone",onChannelChange:this.updateRecipients,t:this.t,viewAs:"dropdown"}),this.isChatViewType?this.renderFullChat():this.usePaginatedChat()?s("dyte-chat-messages-ui-paginated",{meeting:this.meeting,onPinMessage:this.onPinMessage,onDeleteMessage:this.onDeleteMessage,size:this.size,iconPack:this.iconPack,t:this.t}):s("dyte-chat-messages-ui",Object.assign({messages:a,selfUserId:h,selectedGroup:this.selectedGroup,onPinMessage:this.onPinMessage,canPinMessages:this.canPinMessages},e)),this.renderComposerUI())))}get host(){return h(this)}static get watchers(){return{meeting:["meetingChanged"],chatGroups:["chatGroupsChanged"],displayFilter:["onDisplayFilterChanged"]}}};w.style=":host {\n line-height: initial;\n font-family: var(--dyte-font-family, sans-serif);\n\n font-feature-settings: normal;\n font-variation-settings: normal;\n}\n\np {\n margin: var(--dyte-space-0, 0px);\n padding: var(--dyte-space-0, 0px);\n}\n\n.scrollbar {\n /* For Firefox */\n scrollbar-width: thin;\n scrollbar-color: var(--dyte-scrollbar-color, rgb(var(--dyte-colors-background-600, 60 60 60)))\n var(--dyte-scrollbar-background, transparent);\n}\n\n/* For WebKit */\n.scrollbar::-webkit-scrollbar {\n height: var(--dyte-space-1\\.5, 6px);\n width: var(--dyte-space-1\\.5, 6px);\n border-radius: 9999px;\n background-color: var(--dyte-scrollbar-background, transparent);\n}\n\n.scrollbar::-webkit-scrollbar-thumb {\n border-radius: 9999px;\n background-color: var(--dyte-scrollbar-color, rgb(var(--dyte-colors-background-600, 60 60 60)));\n}\n\n\n:host {\n display: flex;\n height: 100%;\n width: 100%;\n flex-direction: column;\n font-size: 14px;\n position: relative;\n color: rgb(var(--dyte-colors-text-1000, 255 255 255));\n}\n\nh3 {\n margin: var(--dyte-space-0, 0px);\n display: flex;\n height: var(--dyte-space-12, 48px);\n align-items: center;\n justify-content: center;\n font-size: 16px;\n font-weight: 400;\n color: rgb(var(--dyte-colors-text-900, 255 255 255 / 0.88));\n text-align: center;\n}\n\n#dropzone {\n position: absolute;\n top: var(--dyte-space-0, 0px);\n right: var(--dyte-space-0, 0px);\n bottom: var(--dyte-space-0, 0px);\n left: var(--dyte-space-0, 0px);\n z-index: 10;\n display: none;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n --tw-bg-opacity: 1;\n background-color: rgba(var(--dyte-colors-background-800, 30 30 30) / var(--tw-bg-opacity));\n color: rgb(var(--dyte-colors-text-700, 255 255 255 / 0.64));\n}\n\n#dropzone.active {\n display: flex;\n animation: 0.2s slide-up ease-in;\n}\n\ndyte-chat-messages-ui,\ndyte-chat-messages-ui-paginated {\n flex: 1 0 0;\n}\n\ndyte-chat-composer-view {\n margin: var(--dyte-space-2, 8px);\n}\n\n.chat-container {\n display: flex;\n height: 100%;\n width: 100%;\n flex-direction: row;\n container-type: size;\n container-name: chatcontainer;\n}\n\n@container chatcontainer (height < 360px) {\n dyte-channel-selector-view {\n height: var(--dyte-space-8, 32px);\n min-height: 24px;\n }\n}\n\n.chat {\n display: flex;\n flex: 1 1 0%;\n flex-direction: column;\n}\n\n.banner {\n height: 100%;\n width: 100%;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n}\n\n.banner .welcome-new-channel {\n width: var(--dyte-space-48, 192px);\n}\n\n.banner .create-channel-illustration {\n height: var(--dyte-space-40, 160px);\n width: var(--dyte-space-40, 160px);\n}\n\n.channel-selector-header {\n box-sizing: border-box;\n height: var(--dyte-space-16, 64px);\n padding: var(--dyte-space-4, 16px);\n display: flex;\n justify-content: space-between;\n border-bottom: var(--dyte-border-width-sm, 1px) solid rgb(var(--dyte-colors-background-700, 44 44 44));\n}\n\n.channel-selector-header .channel-create-btn {\n width: var(--dyte-space-8, 32px);\n justify-content: center;\n}\n\n.channel-selector-header .channel-create-btn:hover {\n --tw-text-opacity: 1;\n color: rgba(var(--dyte-colors-brand-300, 73 124 253) / var(--tw-text-opacity));\n}\n\n.view-chats-btn {\n margin-top: var(--dyte-space-4, 16px);\n}\n\n.selector-container {\n z-index: 50;\n width: 100%;\n max-width: var(--dyte-space-80, 320px);\n border-right: var(--dyte-border-width-sm, 1px) solid rgb(var(--dyte-colors-background-600, 60 60 60));\n}\n\n.selector-container.hide {\n display: none;\n}\n\n.mobile-close-btn {\n display: none;\n}\n\n.selector-container.mobile {\n height: 100%;\n width: 100%;\n max-width: 100%;\n position: absolute;\n top: var(--dyte-space-0, 0px);\n right: var(--dyte-space-0, 0px);\n bottom: var(--dyte-space-0, 0px);\n left: var(--dyte-space-0, 0px);\n background-color: rgba(var(--dyte-colors-background-1000, 8 8 8) / 0.6);\n display: flex;\n}\n\n.selector-container.mobile dyte-channel-selector-view {\n max-width: var(--dyte-space-96, 384px);\n animation: 0.3s swipe-in;\n}\n\n.selector-container.mobile .mobile-close-btn {\n margin-top: var(--dyte-space-4, 16px);\n margin-bottom: var(--dyte-space-4, 16px);\n margin-left: var(--dyte-space-6, 24px);\n margin-right: var(--dyte-space-6, 24px);\n display: block;\n}\n\n.pinned-messages-header {\n display: flex;\n align-items: center;\n gap: var(--dyte-space-2, 8px);\n padding: var(--dyte-space-2, 8px);\n --tw-bg-opacity: 1;\n background-color: rgba(var(--dyte-colors-background-600, 60 60 60) / var(--tw-bg-opacity));\n font-size: 12px;\n cursor: pointer;\n}\n\n.pinned-messages-header dyte-icon {\n height: var(--dyte-space-3, 12px);\n width: var(--dyte-space-3, 12px);\n}\n\n.pinned-messages-header:hover {\n --tw-bg-opacity: 1;\n background-color: rgba(var(--dyte-colors-brand-500, 33 96 253) / var(--tw-bg-opacity));\n}\n\n.pinned-messages-header.active {\n --tw-bg-opacity: 1;\n background-color: rgba(var(--dyte-colors-brand-500, 33 96 253) / var(--tw-bg-opacity));\n}\n\n@keyframes swipe-in {\n from {\n transform: translateX(-100%);\n }\n to {\n transform: translateX(0);\n }\n}\n";export{w as dyte_chat} \ No newline at end of file diff --git a/build/p-95b54a27.entry.js b/build/p-95b54a27.entry.js deleted file mode 100644 index e820bdaf..00000000 --- a/build/p-95b54a27.entry.js +++ /dev/null @@ -1 +0,0 @@ -import{r as t,c as i,h as s,F as e,H as n,a as h}from"./p-69f2ebde.js";import{d as a}from"./p-cadf534b.js";import{u as o}from"./p-54de5543.js";import{h as r,g as c,T as l,i as d,d as p,f as v,s as u,j as y}from"./p-d0b39589.js";import{c as g}from"./p-57e22a58.js";import{u as b,F as m}from"./p-19c79157.js";import{s as x}from"./p-1210aa77.js";import"./p-26e8d50e.js";import{d as f}from"./p-ba748e25.js";import"./p-799d72ea.js";import"./p-aafa2ac8.js";const w=class{constructor(e){t(this,e),this.stateUpdate=i(this,"dyteStateUpdate",7),this.chatUpdateListener=({message:t})=>{t.channelId||this.displayFilter&&!this.displayFilter(t)||(this.addToChatGroup(t),this.chatGroups=Object.assign({},this.chatGroups))},this.chatPermissionUpdateListener=()=>{this.canSend=this.meeting.self.permissions.chatPublic.canSend,this.canSendTextMessage=this.meeting.self.permissions.chatPublic.text,this.canSendFiles=this.meeting.self.permissions.chatPublic.files},this.channelMap=new Map,this.onDragOver=t=>{t.preventDefault(),this.dropzoneActivated=!0},this.onDragLeave=()=>{this.dropzoneActivated=!1},this.onDrop=t=>{t.preventDefault(),this.dropzoneActivated=!1,r(t.dataTransfer.items,((t,i)=>{var s,e,n,h;switch(t){case"image":this.isFileMessagingAllowed()&&(null===(e=null===(s=this.meeting)||void 0===s?void 0:s.chat)||void 0===e||e.sendImageMessage(i,this.getRecipientPeerIds()));break;case"file":this.isFileMessagingAllowed()&&(null===(h=null===(n=this.meeting)||void 0===n?void 0:n.chat)||void 0===h||h.sendFileMessage(i,this.getRecipientPeerIds()))}}))},this.disconnectMeeting=t=>{var i,s,e,n,h,a;this.isPrivateChatSupported()&&(null==t||t.participants.joined.removeListener("participantJoined",this.onParticipantUpdate),null==t||t.participants.joined.removeListener("participantLeft",this.onParticipantUpdate)),null===(i=null==t?void 0:t.chat)||void 0===i||i.removeListener("chatUpdate",this.chatUpdateListener),null===(s=null==t?void 0:t.chat)||void 0===s||s.removeListener("channelCreate",this.onChannelCreateOrUpdate),null===(e=null==t?void 0:t.chat)||void 0===e||e.removeListener("channelUpdate",this.onChannelCreateOrUpdate),null===(n=null==t?void 0:t.chat)||void 0===n||n.removeListener("channelMessageUpdate",this.onChannelCreateOrUpdate),null===(a=null===(h=null==t?void 0:t.participants)||void 0===h?void 0:h.all)||void 0===a||a.removeListener("participantsUpdate",this.onChannelCreateOrUpdate),t.self.permissions.removeListener("*",this.chatPermissionUpdateListener)},this.getFilteredParticipants=()=>0===this.privatePresetFilter.length?this.participants:this.participants.filter((t=>this.privatePresetFilter.includes(t.presetName))),this.onParticipantUpdate=()=>{this.participants=this.meeting.participants.joined.toArray().filter((t=>0===this.privatePresetFilter.length||this.privatePresetFilter.includes(t.presetName))),this.selectedParticipant&&!this.participants.includes(this.selectedParticipant)&&(this.selectedParticipant=null,this.chatRecipientId=this.selectedGroup="everyone")},this.usePaginatedChat=()=>(!this.isGroupCall||!this.showPinnedMessages)&&"everyone"===this.selectedGroup&&b(this.meeting),this.updateUnreadCountGroups=t=>{this.unreadCountGroups=Object.assign(Object.assign({},this.unreadCountGroups),t)},this.isPrivateChatSupported=()=>{var t,i,s;return this.canPrivateMessage&&!this.disablePrivateChat&&"socket-service"===(null===(s=null===(i=null===(t=this.meeting)||void 0===t?void 0:t.__internals__)||void 0===i?void 0:i.features)||void 0===s?void 0:s.getFeatureValue("chat_socket_server"))},this.updateRecipients=t=>{const{id:i}=t.detail;if(this.chatRecipientId=i,this.selectedParticipant=this.participants.find((t=>t.userId===i)),"everyone"!==this.chatRecipientId){const t=c([this.chatRecipientId,this.meeting.self.userId]);this.selectedGroup=t}else this.selectedGroup="everyone";this.updateUnreadCountGroups({[this.selectedGroup]:0})},this.isTextMessagingAllowed=()=>"everyone"===this.chatRecipientId?this.canSend&&this.canSendTextMessage:this.canPrivateMessage&&this.canSendPrivateTexts,this.isFileMessagingAllowed=()=>"everyone"===this.chatRecipientId?this.canSend&&this.canSendFiles:this.canPrivateMessage&&this.canSendPrivateFiles,this.onChannelChanged=t=>{const i=t.detail;i.id.includes(l)?this.createDMChannel(i.id.replace(l,"")):this.selectedChannelId=i.id,this.cleanup(),"desktop"!==this.selectorState&&(this.selectorState="hide")},this.createDMChannel=async t=>{this.creatingChannel=!0;const i=await this.meeting.chat.createChannel("Direct Message",[t],{visibility:"private",isDirectMessage:!0});this.creatingChannel=!1,this.selectedChannelId=i.id},this.cleanup=()=>{this.editingMessage=null,this.replyMessage=null,this.searchQuery=""},this.onQuotedMessageDismiss=()=>{this.replyMessage=null},this.onChannelCreateOrUpdate=t=>{t?this.channelMap.set(t.id,t):this.meeting.chat.channels.forEach((t=>this.channelMap.set(t.id,t)));const i=Array.from(this.channelMap.values()),s=i.filter((t=>!d(t))).sort(((t,i)=>p(t.displayName,i.displayName))),e=i.filter(d).map((t=>Object.assign(Object.assign({},t),{displayName:this.getMemberDisplayName(t)}))),n=this.meeting.participants.all.toArray().filter((t=>{if(t.userId===this.meeting.self.userId)return!1;const i=v([this.meeting.self.userId,t.userId]);return e.every((t=>v(t.memberIds)!==i))})).map((t=>({id:`${l}${t.userId}`,displayName:t.name,displayPictureUrl:t.picture,isDirectMessage:!0,unreadCount:0}))),h=[...e,...n].sort(((t,i)=>p(t.displayName,i.displayName)));this.channels=[...s,...h];const a=[...s,...e];this.selectedChannelId||0===a.length||(this.selectedChannelId=a[0].id)},this.getMemberDisplayName=t=>{var i;let s;s=1===t.memberIds.length?t.memberIds[0]:t.memberIds[0]===this.meeting.self.userId?t.memberIds[1]:t.memberIds[0];const e=this.meeting.participants.all.toArray().find((t=>t.userId===s));return null!==(i=null==e?void 0:e.name)&&void 0!==i?i:s},this.onNewMessageHandler=async t=>{const i=t.detail;this.isChatViewType?(await this.meeting.chat.sendMessageToChannel(i,this.selectedChannelId,this.replyMessage?{replyTo:this.replyMessage}:{}),this.replyMessage=null):this.meeting.chat.sendMessage(i,this.getRecipientPeerIds())},this.onEditMessageHandler=async t=>{var i,s;await(null===(s=null===(i=this.meeting)||void 0===i?void 0:i.chat)||void 0===s?void 0:s.editTextMessage(this.editingMessage.id,t.detail,this.editingMessage.channelId)),this.editingMessage=null},this.onEditCancel=()=>{this.editingMessage=null},this.onSearchHandler=async t=>{this.searchQuery=t.detail},this.onSearchDismissed=()=>{this.searchQuery=""},this.onChannelCreateClicked=()=>{this.stateUpdate.emit({activeChannelCreator:!0}),x.activeChannelCreator=!0},this.onPinMessage=t=>{const i=t.detail;i.pinned?this.meeting.chat.unpin(i.id):this.meeting.chat.pin(i.id)},this.onDeleteMessage=t=>{this.meeting.chat.deleteMessage(t.detail.id)},this.getChannelItems=()=>this.channels.map((t=>{const i={id:t.id,name:t.displayName,avatarUrl:t.displayPictureUrl};return t.latestMessage&&(i.latestMessage="text"===t.latestMessage.type?u(t.latestMessage.message):"",i.latestMessageTime=t.latestMessage.time),i})),this.getPrivateChatRecipients=()=>{const t=this.getFilteredParticipants().map((t=>{const i=c([t.userId,this.meeting.self.userId]);return{id:t.userId,name:t.name,avatarUrl:t.picture,unreadCount:this.unreadCountGroups[i]}}));return[{id:"everyone",name:this.t("chat.everyone"),icon:"participants",unreadCount:this.unreadCountGroups.everyone},...t]},this.onTogglePinnedMessages=()=>{this.showPinnedMessages=!this.showPinnedMessages},this.renderPinnedMessagesHeader=()=>0===this.meeting.chat.pinned.length?null:s("dyte-tooltip",{label:this.t("chat.toggle_pinned_msgs"),iconPack:this.iconPack,t:this.t},s("div",{class:{"pinned-messages-header":!0,active:this.showPinnedMessages},onClick:this.onTogglePinnedMessages},s("dyte-icon",{icon:this.iconPack.pin,iconPack:this.iconPack,t:this.t}),this.t("chat.pinned_msgs"),` (${this.meeting.chat.pinned.length})`)),this.meeting=void 0,this.config=f,this.size=void 0,this.iconPack=a,this.t=o(),this.disablePrivateChat=!1,this.canPinMessages=!1,this.privatePresetFilter=[],this.displayFilter=void 0,this.unreadCountGroups={},this.chatGroups={everyone:[]},this.selectedGroup="everyone",this.now=new Date,this.dropzoneActivated=!1,this.showLatestMessageButton=!1,this.canSend=!1,this.canSendTextMessage=!1,this.canSendFiles=!1,this.canPrivateMessage=!1,this.canSendPrivateTexts=!1,this.canSendPrivateFiles=!1,this.emojiPickerEnabled=!1,this.chatRecipientId="everyone",this.participants=[],this.selectedParticipant=void 0,this.channels=[],this.selectedChannelId=void 0,this.editingMessage=null,this.replyMessage=null,this.searchQuery="",this.selectorState="hide",this.creatingChannel=!1,this.showPinnedMessages=!1}connectedCallback(){this.meeting&&(this.meetingChanged(this.meeting),this.meeting&&!this.meeting.chat||this.isFileMessagingAllowed()&&(this.host.addEventListener("dragover",this.onDragOver),this.host.addEventListener("dragleave",this.onDragLeave),this.host.addEventListener("drop",this.onDrop)))}onEditMessageInit(t){t.detail.flags.isReply?this.replyMessage=t.detail.payload:t.detail.flags.isEdit&&(this.editingMessage=t.detail.payload)}disconnectedCallback(){var t;null===(t=this.resizeObserver)||void 0===t||t.disconnect(),this.disconnectMeeting(this.meeting),this.host.removeEventListener("dragover",this.onDragOver),this.host.removeEventListener("dragleave",this.onDragLeave),this.host.removeEventListener("drop",this.onDrop)}meetingChanged(t,i){var s,e,n,h,a,o;null!=i&&this.disconnectMeeting(i),t&&!t.chat||null==t||(this.canSend=t.self.permissions.chatPublic.canSend,this.canSendTextMessage=t.self.permissions.chatPublic.text,this.canSendFiles=t.self.permissions.chatPublic.files,this.canPrivateMessage=!(!(null===(s=t.self.permissions.chatPrivate)||void 0===s?void 0:s.canSend)&&!(null===(e=t.self.permissions.chatPrivate)||void 0===e?void 0:e.canReceive)),this.canSendPrivateTexts=!!(null===(n=t.self.permissions.chatPrivate)||void 0===n?void 0:n.text),this.canSendPrivateFiles=!!(null===(h=t.self.permissions.chatPrivate)||void 0===h?void 0:h.files),this.canPinMessages=(null===(a=null==t?void 0:t.__internals__)||void 0===a?void 0:a.features.hasFeature(m.PINNED_MESSAGES))&&t.self.permissions.pinParticipant,this.isGroupCall="GROUP_CALL"===t.meta.viewType,this.isChatViewType="CHAT"===t.meta.viewType,this.isChatViewType&&(this.onChannelCreateOrUpdate(),this.channels.filter((t=>!t.id.includes(l))).length&&(this.selectedChannelId=this.channels[0].id),this.resizeObserver&&this.resizeObserver.disconnect(),this.resizeObserver=new ResizeObserver((t=>{for(const i of t)this.selectorState=i.contentBoxSize[0].inlineSize<758?"hide":"desktop"})),this.isChatViewType&&this.resizeObserver.observe(this.host)),this.initializeChatGroups(),this.chatGroups=Object.assign({},this.chatGroups),t.self.permissions.on("*",this.chatPermissionUpdateListener),this.onParticipantUpdate(),null===(o=t.chat)||void 0===o||o.addListener("chatUpdate",this.chatUpdateListener),this.isPrivateChatSupported()&&(t.participants.joined.addListener("participantJoined",this.onParticipantUpdate),t.participants.joined.addListener("participantLeft",this.onParticipantUpdate)),this.isChatViewType&&(t.chat.addListener("channelCreate",this.onChannelCreateOrUpdate),t.chat.addListener("channelUpdate",this.onChannelCreateOrUpdate),t.chat.addListener("channelMessageUpdate",this.onChannelCreateOrUpdate),t.participants.all.addListener("participantsUpdate",this.onChannelCreateOrUpdate)))}chatGroupsChanged(t){var i,s;if(!this.isPrivateChatSupported())return;const e={};for(const n in t){const h=null!==(i=g[n])&&void 0!==i?i:0;e[n]=t[n].filter((t=>"chat"==t.type&&t.message.time>h&&t.message.userId!==this.meeting.self.userId)).length,(n===c([this.meeting.self.userId,null===(s=this.selectedParticipant)||void 0===s?void 0:s.userId])||"everyone"===n&&null===this.selectedParticipant)&&(e[n]=0,g[n]=new Date)}this.updateUnreadCountGroups(e)}initializeChatGroups(){var t;null===(t=this.meeting.chat)||void 0===t||t.messages.forEach((t=>{this.displayFilter&&!this.displayFilter(t)||this.addToChatGroup(t)}))}onDisplayFilterChanged(t,i){t!==i&&(this.chatGroups={},this.initializeChatGroups())}addToChatGroup(t){var i;const s=y(t);let e="everyone";if((null===(i=s.targetUserIds)||void 0===i?void 0:i.length)>0){const t=new Set([s.userId,...s.targetUserIds]);e=c(Array.from(t))}void 0===this.chatGroups[e]&&(this.chatGroups[e]=[]);let n=!1,h=[];this.chatGroups[e].forEach((i=>{"chat"===i.type&&i.message.id===t.id?(n=!0,h.push({type:"chat",message:s})):h.push(i)})),n||h.push({type:"chat",message:s}),this.chatGroups[e]=h}getRecipientPeerIds(){let t=[];return"everyone"!==this.chatRecipientId&&(t=[this.selectedParticipant.id]),t}channelSwitchListener(t){this.onChannelChanged(t)}renderHeadlessComponents(){return s(e,null,s("dyte-dialog-manager",{meeting:this.meeting}),s("dyte-notifications",{meeting:this.meeting}))}renderComposerUI(){var t,i,e;if(this.isChatViewType&&0===this.channels.length)return null;if(this.isChatViewType&&""!==this.searchQuery)return null;if(this.isChatViewType&&!this.selectedChannelId)return null;if("everyone"===this.chatRecipientId){if(!this.canSendTextMessage&&!this.canSendFiles)return null}else if(!this.canSendPrivateTexts&&!this.canSendPrivateFiles)return null;const n={iconPack:this.iconPack,t:this.t,size:this.size};return s("dyte-chat-composer-view",Object.assign({message:this.editingMessage?this.editingMessage.message:"",storageKey:null!==(t=this.selectedChannelId)&&void 0!==t?t:`draft-${this.selectedChannelId}`,quotedMessage:this.replyMessage?this.replyMessage.message:"",isEditing:!!this.editingMessage,canSendTextMessage:this.isTextMessagingAllowed(),canSendFiles:this.isFileMessagingAllowed(),disableEmojiPicker:!!(null===(e=null===(i=this.meeting)||void 0===i?void 0:i.__internals__)||void 0===e?void 0:e.features.hasFeature(m.DISABLE_EMOJI_PICKER)),maxLength:this.meeting.chat.maxTextLimit,rateLimits:this.meeting.chat.rateLimits,inputTextPlaceholder:this.t("chat.message_placeholder"),onNewMessage:this.onNewMessageHandler,onEditMessage:this.onEditMessageHandler,onEditCancel:this.onEditCancel,onQuotedMessageDismiss:this.onQuotedMessageDismiss},n),s("slot",{name:"chat-addon",slot:"chat-addon"}))}renderFullChat(){if(this.creatingChannel)return s("div",{class:"banner"},s("dyte-spinner",{size:"lg"}));if(0===this.channels.length||!this.selectedChannelId)return s("div",{class:"banner"},s("dyte-icon",{icon:this.iconPack.create_channel_illustration,iconPack:this.iconPack,t:this.t,slot:"start",class:"create-channel-illustration"}),s("dyte-button",{iconPack:this.iconPack,t:this.t,kind:"wide",variant:"primary",size:"md",onClick:this.onChannelCreateClicked,class:"welcome-new-channel"},s("dyte-icon",{icon:this.iconPack.add,iconPack:this.iconPack,t:this.t,slot:"start"}),s("span",null,this.t("chat.new_channel"))),("mobile"===this.selectorState||"hide"===this.selectorState)&&s("dyte-button",{kind:"button",variant:"secondary",size:"md",class:"view-chats-btn",onClick:()=>{this.selectorState="mobile"}},s("dyte-icon",{icon:this.iconPack.chat,slot:"start"}),s("span",null,this.t("chat.view_chats"))));const t=this.channels.find((t=>t.id===this.selectedChannelId));return s("div",{class:"chat"},s("dyte-channel-header",{slot:"header",meeting:this.meeting,channel:t,onSearch:this.onSearchHandler,onSearchDismissed:this.onSearchDismissed,showBackButton:"mobile"===this.selectorState||"hide"===this.selectorState,onBack:()=>{this.selectorState="mobile"}}),""!==this.searchQuery&&s("dyte-chat-search-results",{meeting:this.meeting,query:this.searchQuery,channelId:this.selectedChannelId}),""===this.searchQuery&&s("dyte-chat-messages-ui-paginated",{meeting:this.meeting,size:this.size,iconPack:this.iconPack,t:this.t,selectedChannelId:this.selectedChannelId,selectedChannel:t}))}render(){var t,i;if(!this.meeting)return null;const e={iconPack:this.iconPack,t:this.t,size:this.size},h=null===(t=this.meeting)||void 0===t?void 0:t.self.userId;let a=this.chatGroups[this.selectedGroup]||[];return this.showPinnedMessages&&0!==this.meeting.chat.pinned.length&&(a=a.filter((t=>"chat"===t.type&&t.message.pinned))),s(n,null,this.isChatViewType&&this.renderHeadlessComponents(),s("div",{class:"chat-container"},this.isChatViewType&&s("div",{class:{"selector-container":!0,[this.selectorState]:!0}},s("dyte-channel-selector-view",{channels:this.getChannelItems(),selectedChannelId:this.selectedChannelId,onChannelChange:this.onChannelChanged,t:this.t},s("div",{class:"channel-selector-header",slot:"header"},s("dyte-logo",{meeting:this.meeting,config:this.config,t:this.t}),s("dyte-tooltip",{label:this.t("chat.new_channel"),iconPack:this.iconPack,t:this.t},s("dyte-button",{iconPack:this.iconPack,t:this.t,kind:"button",variant:"ghost",size:"md",onClick:this.onChannelCreateClicked,class:"channel-create-btn"},s("dyte-icon",{icon:this.iconPack.add,iconPack:this.iconPack,t:this.t}))))),s("dyte-button",{kind:"icon",variant:"ghost",class:"mobile-close-btn",onClick:()=>this.selectorState="hide"},s("dyte-icon",{icon:this.iconPack.dismiss}))),s("div",{class:"chat"},this.isFileMessagingAllowed()&&s("div",{id:"dropzone",class:{active:this.dropzoneActivated},part:"dropzone"},s("dyte-icon",{icon:this.iconPack.attach,iconPack:this.iconPack,t:this.t}),s("p",null,this.t("chat.send_attachment"))),this.renderPinnedMessagesHeader(),this.isPrivateChatSupported()&&s("dyte-channel-selector-view",{channels:this.getPrivateChatRecipients(),selectedChannelId:(null===(i=this.selectedParticipant)||void 0===i?void 0:i.userId)||"everyone",onChannelChange:this.updateRecipients,t:this.t,viewAs:"dropdown"}),this.isChatViewType?this.renderFullChat():this.usePaginatedChat()?s("dyte-chat-messages-ui-paginated",{meeting:this.meeting,onPinMessage:this.onPinMessage,onDeleteMessage:this.onDeleteMessage,size:this.size,iconPack:this.iconPack,t:this.t}):s("dyte-chat-messages-ui",Object.assign({messages:a,selfUserId:h,selectedGroup:this.selectedGroup,onPinMessage:this.onPinMessage,canPinMessages:this.canPinMessages},e)),this.renderComposerUI())))}get host(){return h(this)}static get watchers(){return{meeting:["meetingChanged"],chatGroups:["chatGroupsChanged"],displayFilter:["onDisplayFilterChanged"]}}};w.style=":host {\n line-height: initial;\n font-family: var(--dyte-font-family, sans-serif);\n\n font-feature-settings: normal;\n font-variation-settings: normal;\n}\n\np {\n margin: var(--dyte-space-0, 0px);\n padding: var(--dyte-space-0, 0px);\n}\n\n.scrollbar {\n /* For Firefox */\n scrollbar-width: thin;\n scrollbar-color: var(--dyte-scrollbar-color, rgb(var(--dyte-colors-background-600, 60 60 60)))\n var(--dyte-scrollbar-background, transparent);\n}\n\n/* For WebKit */\n.scrollbar::-webkit-scrollbar {\n height: var(--dyte-space-1\\.5, 6px);\n width: var(--dyte-space-1\\.5, 6px);\n border-radius: 9999px;\n background-color: var(--dyte-scrollbar-background, transparent);\n}\n\n.scrollbar::-webkit-scrollbar-thumb {\n border-radius: 9999px;\n background-color: var(--dyte-scrollbar-color, rgb(var(--dyte-colors-background-600, 60 60 60)));\n}\n\n\n:host {\n display: flex;\n height: 100%;\n width: 100%;\n flex-direction: column;\n font-size: 14px;\n position: relative;\n color: rgb(var(--dyte-colors-text-1000, 255 255 255));\n}\n\nh3 {\n margin: var(--dyte-space-0, 0px);\n display: flex;\n height: var(--dyte-space-12, 48px);\n align-items: center;\n justify-content: center;\n font-size: 16px;\n font-weight: 400;\n color: rgb(var(--dyte-colors-text-900, 255 255 255 / 0.88));\n text-align: center;\n}\n\n#dropzone {\n position: absolute;\n top: var(--dyte-space-0, 0px);\n right: var(--dyte-space-0, 0px);\n bottom: var(--dyte-space-0, 0px);\n left: var(--dyte-space-0, 0px);\n z-index: 10;\n display: none;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n --tw-bg-opacity: 1;\n background-color: rgba(var(--dyte-colors-background-800, 30 30 30) / var(--tw-bg-opacity));\n color: rgb(var(--dyte-colors-text-700, 255 255 255 / 0.64));\n}\n\n#dropzone.active {\n display: flex;\n animation: 0.2s slide-up ease-in;\n}\n\ndyte-chat-messages-ui,\ndyte-chat-messages-ui-paginated {\n flex: 1 0 0;\n}\n\ndyte-chat-composer-view {\n margin: var(--dyte-space-2, 8px);\n}\n\n.chat-container {\n display: flex;\n height: 100%;\n width: 100%;\n flex-direction: row;\n container-type: size;\n container-name: chatcontainer;\n}\n\n@container chatcontainer (height < 360px) {\n dyte-channel-selector-view {\n height: var(--dyte-space-8, 32px);\n min-height: 24px;\n }\n}\n\n.chat {\n display: flex;\n flex: 1 1 0%;\n flex-direction: column;\n}\n\n.banner {\n height: 100%;\n width: 100%;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n}\n\n.banner .welcome-new-channel {\n width: var(--dyte-space-48, 192px);\n}\n\n.banner .create-channel-illustration {\n height: var(--dyte-space-40, 160px);\n width: var(--dyte-space-40, 160px);\n}\n\n.channel-selector-header {\n box-sizing: border-box;\n height: var(--dyte-space-16, 64px);\n padding: var(--dyte-space-4, 16px);\n display: flex;\n justify-content: space-between;\n border-bottom: var(--dyte-border-width-sm, 1px) solid rgb(var(--dyte-colors-background-700, 44 44 44));\n}\n\n.channel-selector-header .channel-create-btn {\n width: var(--dyte-space-8, 32px);\n justify-content: center;\n}\n\n.channel-selector-header .channel-create-btn:hover {\n --tw-text-opacity: 1;\n color: rgba(var(--dyte-colors-brand-300, 73 124 253) / var(--tw-text-opacity));\n}\n\n.view-chats-btn {\n margin-top: var(--dyte-space-4, 16px);\n}\n\n.selector-container {\n z-index: 50;\n width: 100%;\n max-width: var(--dyte-space-80, 320px);\n border-right: var(--dyte-border-width-sm, 1px) solid rgb(var(--dyte-colors-background-600, 60 60 60));\n}\n\n.selector-container.hide {\n display: none;\n}\n\n.mobile-close-btn {\n display: none;\n}\n\n.selector-container.mobile {\n height: 100%;\n width: 100%;\n max-width: 100%;\n position: absolute;\n top: var(--dyte-space-0, 0px);\n right: var(--dyte-space-0, 0px);\n bottom: var(--dyte-space-0, 0px);\n left: var(--dyte-space-0, 0px);\n background-color: rgba(var(--dyte-colors-background-1000, 8 8 8) / 0.6);\n display: flex;\n}\n\n.selector-container.mobile dyte-channel-selector-view {\n max-width: var(--dyte-space-96, 384px);\n animation: 0.3s swipe-in;\n}\n\n.selector-container.mobile .mobile-close-btn {\n margin-top: var(--dyte-space-4, 16px);\n margin-bottom: var(--dyte-space-4, 16px);\n margin-left: var(--dyte-space-6, 24px);\n margin-right: var(--dyte-space-6, 24px);\n display: block;\n}\n\n.pinned-messages-header {\n display: flex;\n align-items: center;\n gap: var(--dyte-space-2, 8px);\n padding: var(--dyte-space-2, 8px);\n --tw-bg-opacity: 1;\n background-color: rgba(var(--dyte-colors-background-600, 60 60 60) / var(--tw-bg-opacity));\n font-size: 12px;\n cursor: pointer;\n}\n\n.pinned-messages-header dyte-icon {\n height: var(--dyte-space-3, 12px);\n width: var(--dyte-space-3, 12px);\n}\n\n.pinned-messages-header:hover {\n --tw-bg-opacity: 1;\n background-color: rgba(var(--dyte-colors-brand-500, 33 96 253) / var(--tw-bg-opacity));\n}\n\n.pinned-messages-header.active {\n --tw-bg-opacity: 1;\n background-color: rgba(var(--dyte-colors-brand-500, 33 96 253) / var(--tw-bg-opacity));\n}\n\n@keyframes swipe-in {\n from {\n transform: translateX(-100%);\n }\n to {\n transform: translateX(0);\n }\n}\n";export{w as dyte_chat} \ No newline at end of file diff --git a/web-core.js b/web-core.js index 09c0e405..e34dea69 100644 --- a/web-core.js +++ b/web-core.js @@ -1,7 +1,7 @@ -var DyteClient=function(){var Ev,Yr,Qr,Xt,fi,gt,Zt,qe,mr,Xr,It,Ze,gi,vi,Zr,yi,ks,wv,vt,re,bn,et,Pn,Ma,gd,Hv,Cv,vd,bv,yd,qv,Rn,Ti,Da,Pv,_i,kn,Rv,Si,Td,jv,Oa,zu,In,Na,kv,Is,Ei,_d,Iv,er,wi,Re,La,Pr,fr,Ci,Nd,As,An,Ms,Fa,es,yt,tr,bi,Pi,ts,Ri,ki,Mn,Oo,Av,ze,Dn,rr,Ii,xa,Mv,Ai,Ua,Mi,Ld,Dv,Sd,st,ht,tt,Rr,sr,Va,Ed,On,Nn,wd,Di,kr,Cd,Ov,Oi,Ni,$a,Wt,Ln,Ba,Li,xi,Ui,Ds,Tt,Os,Ns,bd,Gv,Fn,xn,Ha,Yu,qa,Ls,Pd,Jv,Vi,$i,Bi,Fs,Zi,rs,ja,xs,Hi,Fd,ss,Rd,Ga,Qu,Nv,Us,Ja,Wa,Ka,za,Ya,Ir,Qa,Xa,gr,Un,Za,eo,to,Xu,kd,Wv,Id,Kv,Vs,_t,Vn,No,Ar,St,me,Mr,$n,Bn,$s,ro,so,no,ns,ji,Dr,Ys,Lv,Bs,vr,ds,Hs,Kt,Fv,q,Gi,Ji,Ad,At,zt,Gu,io,Ut,Ki,qs,js,ea,Ye,it,zi,Yi,ao,Zu,xv,Et,Hn,Lo,Or,wt,pe,Nr,qn,jn,Gs,oo,co,lo,is,Qi,Lr,Qs,Uv,Js,yr,Ct,Vt,ir,Vv,uo,ho,as,$t,nt,Ws,Ve,Me,$e,nr,os,po,eh,mo,th,$v,fo,Md,Xi,zs,Ju,Dd,ct,go,vo,Od,zv,Bv;"use strict";var TN=Object.defineProperty;var _N=(De,Oe,de)=>Oe in De?TN(De,Oe,{enumerable:!0,configurable:!0,writable:!0,value:de}):De[Oe]=de;var m=(De,Oe,de)=>(_N(De,typeof Oe!="symbol"?Oe+"":Oe,de),de),Ku=(De,Oe,de)=>{if(!Oe.has(De))throw TypeError("Cannot "+de)};var c=(De,Oe,de)=>(Ku(De,Oe,"read from private field"),de?de.call(De):Oe.get(De)),S=(De,Oe,de)=>{if(Oe.has(De))throw TypeError("Cannot add the same private member more than once");Oe instanceof WeakSet?Oe.add(De):Oe.set(De,de)},y=(De,Oe,de,Fo)=>(Ku(De,Oe,"write to private field"),Fo?Fo.call(De,de):Oe.set(De,de),de);var je=(De,Oe,de)=>(Ku(De,Oe,"access private method"),de);var De=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Oe(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var de={},Fo={get exports(){return de},set exports(s){de=s}},Gn=typeof Reflect=="object"?Reflect:null,rh=Gn&&typeof Gn.apply=="function"?Gn.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},xo;Gn&&typeof Gn.ownKeys=="function"?xo=Gn.ownKeys:Object.getOwnPropertySymbols?xo=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:xo=function(t){return Object.getOwnPropertyNames(t)};function Yv(s){console&&console.warn&&console.warn(s)}var sh=Number.isNaN||function(t){return t!==t};function ye(){ye.init.call(this)}Fo.exports=ye,de.once=ey,ye.EventEmitter=ye,ye.prototype._events=void 0,ye.prototype._eventsCount=0,ye.prototype._maxListeners=void 0;var nh=10;function Uo(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(ye,"defaultMaxListeners",{enumerable:!0,get:function(){return nh},set:function(s){if(typeof s!="number"||s<0||sh(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");nh=s}}),ye.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},ye.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||sh(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function ih(s){return s._maxListeners===void 0?ye.defaultMaxListeners:s._maxListeners}ye.prototype.getMaxListeners=function(){return ih(this)},ye.prototype.emit=function(t){for(var e=[],r=1;r0&&(a=e[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var d=i[t];if(d===void 0)return!1;if(typeof d=="function")rh(d,this,e);else for(var u=d.length,h=lh(d,u),r=0;r0&&a.length>n&&!a.warned){a.warned=!0;var o=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");o.name="MaxListenersExceededWarning",o.emitter=s,o.type=t,o.count=a.length,Yv(o)}return s}ye.prototype.addListener=function(t,e){return ah(this,t,e,!1)},ye.prototype.on=ye.prototype.addListener,ye.prototype.prependListener=function(t,e){return ah(this,t,e,!0)};function Qv(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function oh(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},n=Qv.bind(r);return n.listener=e,r.wrapFn=n,n}ye.prototype.once=function(t,e){return Uo(e),this.on(t,oh(this,t,e)),this},ye.prototype.prependOnceListener=function(t,e){return Uo(e),this.prependListener(t,oh(this,t,e)),this},ye.prototype.removeListener=function(t,e){var r,n,i,a,o;if(Uo(e),n=this._events,n===void 0)return this;if(r=n[t],r===void 0)return this;if(r===e||r.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete n[t],n.removeListener&&this.emit("removeListener",t,r.listener||e));else if(typeof r!="function"){for(i=-1,a=r.length-1;a>=0;a--)if(r[a]===e||r[a].listener===e){o=r[a].listener,i=a;break}if(i<0)return this;i===0?r.shift():Xv(r,i),r.length===1&&(n[t]=r[0]),n.removeListener!==void 0&&this.emit("removeListener",t,o||e)}return this},ye.prototype.off=ye.prototype.removeListener,ye.prototype.removeAllListeners=function(t){var e,r,n;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[t]),this;if(arguments.length===0){var i=Object.keys(r),a;for(n=0;n=0;n--)this.removeListener(t,e[n]);return this};function ch(s,t,e){var r=s._events;if(r===void 0)return[];var n=r[t];return n===void 0?[]:typeof n=="function"?e?[n.listener||n]:[n]:e?Zv(n):lh(n,n.length)}ye.prototype.listeners=function(t){return ch(this,t,!0)},ye.prototype.rawListeners=function(t){return ch(this,t,!1)},ye.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):dh.call(s,t)},ye.prototype.listenerCount=dh;function dh(s){var t=this._events;if(t!==void 0){var e=t[s];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}ye.prototype.eventNames=function(){return this._eventsCount>0?xo(this._events):[]};function lh(s,t){for(var e=new Array(t),r=0;r{this.eventStore.add(a)}),!1}}callEvent(e){e.timestamp=new Date,this.eventStore.add(e),this.emit(e.event,e.metaData),ry.get(e.event)===K.MAJOR_EVENT&&this.flush()}async flush(){var r;const e=this.eventStore.flush();return(r=e==null?void 0:e.entries)!=null&&r.length?(await this.sendEventsChunkToServer(e),!0):!1}}var hh;(function(s){s.CHROMIUM="chromum",s.FIREFOX="firefox",s.SAFARI="safari"})(hh||(hh={}));const ta={DEVEL:"devel",PREPROD:"preprod",PROD:"prod"};var Yt;(function(s){s.AUDIO="AUDIO",s.VIDEO="VIDEO",s.SPEAKER="SPEAKER",s.SCREENSHARE="SCREENSHARE"})(Yt||(Yt={}));var ph;(function(s){s[s.INIT=0]="INIT",s[s.ACCEPTED=1]="ACCEPTED",s[s.DENIED=2]="DENIED",s[s.SYS_DENIED=3]="SYS_DENIED",s[s.FAILED=4]="FAILED",s[s.NOTFOUND=5]="NOTFOUND",s[s.NOT_APPLICABLE=6]="NOT_APPLICABLE"})(ph||(ph={}));function Vo({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function $o({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}const mh=240,fh=720,gh=8,vh=3,Bo=10,Ho=.02,qo=.03;function Fr({stat:s,weight:t,rangeMin:e,rangeMax:r,rangeRankingDirection:n}){return s==null?t:e===r?n==="UP"?s<=e?t:0:s>=r?t:0:n==="UP"?(1-Math.max(Math.min(r,Math.abs(s))-e,0)/(r-e))*t:n==="DOWN"?Math.max(Math.min(r,Math.abs(s))-e,0)/(r-e)*t:t}function yh({isLowQualityVideo:s,isVideoStuck:t,isVideoLagging:e,jitterQuality:r,packetsLostQuality:n}){const i=.8*((s?.85:1)*(e?.7:1)*(t?.5:1))+.2*(r*n);return Math.round((i+Number.EPSILON)*100)/100}function Th({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function _h({packetsLost:s,packetsSent:t,jitter:e}){const n=Fr({stat:Th({packetsLost:s,packetsSent:t}),weight:.7,rangeMin:0,rangeMax:Bo,rangeRankingDirection:"UP"}),a=Fr({stat:e,weight:.3,rangeMin:Ho,rangeMax:qo,rangeRankingDirection:"UP"});return n+a}function iy({frameWidth:s,isScreenShare:t}){return s<(t?fh:mh)}function ay({framesPerSecond:s,isScreenShare:t}){return s<(t?vh:gh)}function oy({framesEncoded:s}){return s===0}function Sh({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsSent:r,jitter:n,isScreenShare:i,framesEncoded:a}){const o=Fr({stat:Th({packetsLost:e,packetsSent:r}),weight:1,rangeMin:0,rangeMax:Bo,rangeRankingDirection:"UP"}),d=Fr({stat:n,weight:1,rangeMin:Ho,rangeMax:qo,rangeRankingDirection:"UP"}),u=iy({frameWidth:s,isScreenShare:i}),h=ay({framesPerSecond:t,isScreenShare:i}),p=oy({framesEncoded:a,isScreenShare:i});return yh({isLowQualityVideo:u,isVideoLagging:h,isVideoStuck:p,jitterQuality:d,packetsLostQuality:o})}function Eh({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}function wh({concealmentEvents:s,packetsLost:t,packetsReceived:e,jitter:r}){const i=Fr({stat:s,weight:.2,rangeMin:0,rangeMax:3,rangeRankingDirection:"UP"}),a=.5,o=Fr({stat:Eh({packetsLost:t,packetsReceived:e}),weight:a,rangeMin:0,rangeMax:Bo,rangeRankingDirection:"UP"}),u=Fr({stat:r,weight:.3,rangeMin:Ho,rangeMax:qo,rangeRankingDirection:"UP"});return i+o+u}function cy({framesDecoded:s}){return s===0}function dy({framesPerSecond:s,isScreenShare:t}){return s<(t?vh:gh)}function ly({frameWidth:s,isScreenShare:t}){return s<(t?fh:mh)}function Ch({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsReceived:r,jitter:n,isScreenShare:i,framesDecoded:a}){const o=Fr({stat:Eh({packetsLost:e,packetsReceived:r}),weight:1,rangeMin:0,rangeMax:Bo,rangeRankingDirection:"UP"}),d=Fr({stat:n,weight:1,rangeMin:Ho,rangeMax:qo,rangeRankingDirection:"UP"}),u=ly({frameWidth:s,isScreenShare:i}),h=dy({framesPerSecond:t,isScreenShare:i}),p=cy({framesDecoded:a,isScreenShare:i});return yh({isLowQualityVideo:u,isVideoLagging:h,isVideoStuck:p,jitterQuality:d,packetsLostQuality:o})}class xr{constructor(t){m(this,"pc1");m(this,"pc2");m(this,"constrainVideoBitrateKbps");m(this,"constrainOfferToRemoveVideoFec",!1);m(this,"iceCandidateFilter");const e=new RTCPeerConnection(t),r=new RTCPeerConnection(t);this.pc1=e,this.pc2=r,this.iceCandidateFilter=xr.noFilter,this.pc1.addEventListener("icecandidate",this.onIceCandidate.bind(this,this.pc2)),this.pc2.addEventListener("icecandidate",this.onIceCandidate.bind(this,this.pc1))}static parseCandidate(t){const e="candidate:",r=t.indexOf(e)+e.length,n=t.substr(r).split(" ");return{type:n[7],protocol:n[2],address:n[4]}}static isNotHostCandidate(t){return t.type!=="host"}static isHost(t){return t.type==="host"}static isRelay(t){return t.type==="relay"}static isReflexive(t){return t.type==="srflx"}static noFilter(t){return!0}onIceCandidate(t,e){if(e.candidate){const r=xr.parseCandidate(e.candidate.candidate);this.iceCandidateFilter(r)&&t.addIceCandidate(e.candidate)}}setIceCandidateFilter(t){this.iceCandidateFilter=t}constrainVideoBitrate(t){this.constrainVideoBitrateKbps=t}disableVideoFec(){this.constrainOfferToRemoveVideoFec=!0}gotOffer(t){this.constrainOfferToRemoveVideoFec&&(t.sdp=t.sdp.replace(/(m=video 1 [^\r]+)(116 117)(\r\n)/g,`$1\r +var DyteClient=function(){var Ev,Yr,Qr,Zt,fi,gt,er,qe,mr,Xr,It,Ze,gi,vi,Zr,yi,ks,wv,vt,re,bn,et,Pn,Ma,gd,Hv,Cv,vd,bv,yd,qv,Rn,Ti,Da,Pv,_i,kn,Rv,Si,Td,jv,Oa,zu,In,Na,kv,Is,Ei,_d,Iv,tr,wi,Re,La,Pr,fr,Ci,Nd,As,An,Ms,Fa,es,yt,Wt,bi,Pi,ts,Ri,ki,Mn,Oo,Av,ze,Dn,rr,Ii,xa,Mv,Ai,Ua,Mi,Ld,Dv,Sd,st,ht,tt,Rr,sr,Va,Ed,On,Nn,wd,Di,kr,Cd,Ov,Oi,Ni,$a,Kt,Ln,Ba,Li,xi,Ui,Ds,Tt,Os,Ns,bd,Gv,Fn,xn,Ha,Yu,qa,Ls,Pd,Jv,Vi,$i,Bi,Fs,Zi,rs,ja,xs,Hi,Fd,ss,Rd,Ga,Qu,Nv,Us,Ja,Wa,Ka,za,Ya,Ir,Qa,Xa,gr,Un,Za,eo,to,Xu,kd,Wv,Id,Kv,Vs,_t,Vn,No,Ar,St,me,Mr,$n,Bn,$s,ro,so,no,ns,ji,Dr,Ys,Lv,Bs,vr,ds,Hs,zt,Fv,q,Gi,Ji,Ad,At,Yt,Gu,io,Ut,Ki,qs,js,ea,Ye,it,zi,Yi,ao,Zu,xv,Et,Hn,Lo,Or,wt,pe,Nr,qn,jn,Gs,oo,co,lo,is,Qi,Lr,Qs,Uv,Js,yr,Ct,Vt,ir,Vv,uo,ho,as,$t,nt,Ws,Ve,Me,$e,nr,os,po,eh,mo,th,$v,fo,Md,Xi,zs,Ju,Dd,ct,go,vo,Od,zv,Bv;"use strict";var TN=Object.defineProperty;var _N=(De,Oe,de)=>Oe in De?TN(De,Oe,{enumerable:!0,configurable:!0,writable:!0,value:de}):De[Oe]=de;var m=(De,Oe,de)=>(_N(De,typeof Oe!="symbol"?Oe+"":Oe,de),de),Ku=(De,Oe,de)=>{if(!Oe.has(De))throw TypeError("Cannot "+de)};var c=(De,Oe,de)=>(Ku(De,Oe,"read from private field"),de?de.call(De):Oe.get(De)),S=(De,Oe,de)=>{if(Oe.has(De))throw TypeError("Cannot add the same private member more than once");Oe instanceof WeakSet?Oe.add(De):Oe.set(De,de)},y=(De,Oe,de,Fo)=>(Ku(De,Oe,"write to private field"),Fo?Fo.call(De,de):Oe.set(De,de),de);var je=(De,Oe,de)=>(Ku(De,Oe,"access private method"),de);var De=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Oe(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var de={},Fo={get exports(){return de},set exports(s){de=s}},Gn=typeof Reflect=="object"?Reflect:null,rh=Gn&&typeof Gn.apply=="function"?Gn.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},xo;Gn&&typeof Gn.ownKeys=="function"?xo=Gn.ownKeys:Object.getOwnPropertySymbols?xo=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:xo=function(t){return Object.getOwnPropertyNames(t)};function Yv(s){console&&console.warn&&console.warn(s)}var sh=Number.isNaN||function(t){return t!==t};function ye(){ye.init.call(this)}Fo.exports=ye,de.once=ey,ye.EventEmitter=ye,ye.prototype._events=void 0,ye.prototype._eventsCount=0,ye.prototype._maxListeners=void 0;var nh=10;function Uo(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(ye,"defaultMaxListeners",{enumerable:!0,get:function(){return nh},set:function(s){if(typeof s!="number"||s<0||sh(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");nh=s}}),ye.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},ye.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||sh(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function ih(s){return s._maxListeners===void 0?ye.defaultMaxListeners:s._maxListeners}ye.prototype.getMaxListeners=function(){return ih(this)},ye.prototype.emit=function(t){for(var e=[],r=1;r0&&(a=e[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var d=i[t];if(d===void 0)return!1;if(typeof d=="function")rh(d,this,e);else for(var u=d.length,h=lh(d,u),r=0;r0&&a.length>n&&!a.warned){a.warned=!0;var o=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");o.name="MaxListenersExceededWarning",o.emitter=s,o.type=t,o.count=a.length,Yv(o)}return s}ye.prototype.addListener=function(t,e){return ah(this,t,e,!1)},ye.prototype.on=ye.prototype.addListener,ye.prototype.prependListener=function(t,e){return ah(this,t,e,!0)};function Qv(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function oh(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},n=Qv.bind(r);return n.listener=e,r.wrapFn=n,n}ye.prototype.once=function(t,e){return Uo(e),this.on(t,oh(this,t,e)),this},ye.prototype.prependOnceListener=function(t,e){return Uo(e),this.prependListener(t,oh(this,t,e)),this},ye.prototype.removeListener=function(t,e){var r,n,i,a,o;if(Uo(e),n=this._events,n===void 0)return this;if(r=n[t],r===void 0)return this;if(r===e||r.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete n[t],n.removeListener&&this.emit("removeListener",t,r.listener||e));else if(typeof r!="function"){for(i=-1,a=r.length-1;a>=0;a--)if(r[a]===e||r[a].listener===e){o=r[a].listener,i=a;break}if(i<0)return this;i===0?r.shift():Xv(r,i),r.length===1&&(n[t]=r[0]),n.removeListener!==void 0&&this.emit("removeListener",t,o||e)}return this},ye.prototype.off=ye.prototype.removeListener,ye.prototype.removeAllListeners=function(t){var e,r,n;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[t]),this;if(arguments.length===0){var i=Object.keys(r),a;for(n=0;n=0;n--)this.removeListener(t,e[n]);return this};function ch(s,t,e){var r=s._events;if(r===void 0)return[];var n=r[t];return n===void 0?[]:typeof n=="function"?e?[n.listener||n]:[n]:e?Zv(n):lh(n,n.length)}ye.prototype.listeners=function(t){return ch(this,t,!0)},ye.prototype.rawListeners=function(t){return ch(this,t,!1)},ye.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):dh.call(s,t)},ye.prototype.listenerCount=dh;function dh(s){var t=this._events;if(t!==void 0){var e=t[s];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}ye.prototype.eventNames=function(){return this._eventsCount>0?xo(this._events):[]};function lh(s,t){for(var e=new Array(t),r=0;r{this.eventStore.add(a)}),!1}}callEvent(e){e.timestamp=new Date,this.eventStore.add(e),this.emit(e.event,e.metaData),ry.get(e.event)===K.MAJOR_EVENT&&this.flush()}async flush(){var r;const e=this.eventStore.flush();return(r=e==null?void 0:e.entries)!=null&&r.length?(await this.sendEventsChunkToServer(e),!0):!1}}var hh;(function(s){s.CHROMIUM="chromum",s.FIREFOX="firefox",s.SAFARI="safari"})(hh||(hh={}));const ta={DEVEL:"devel",PREPROD:"preprod",PROD:"prod"};var Qt;(function(s){s.AUDIO="AUDIO",s.VIDEO="VIDEO",s.SPEAKER="SPEAKER",s.SCREENSHARE="SCREENSHARE"})(Qt||(Qt={}));var ph;(function(s){s[s.INIT=0]="INIT",s[s.ACCEPTED=1]="ACCEPTED",s[s.DENIED=2]="DENIED",s[s.SYS_DENIED=3]="SYS_DENIED",s[s.FAILED=4]="FAILED",s[s.NOTFOUND=5]="NOTFOUND",s[s.NOT_APPLICABLE=6]="NOT_APPLICABLE"})(ph||(ph={}));function Vo({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function $o({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}const mh=240,fh=720,gh=8,vh=3,Bo=10,Ho=.02,qo=.03;function Fr({stat:s,weight:t,rangeMin:e,rangeMax:r,rangeRankingDirection:n}){return s==null?t:e===r?n==="UP"?s<=e?t:0:s>=r?t:0:n==="UP"?(1-Math.max(Math.min(r,Math.abs(s))-e,0)/(r-e))*t:n==="DOWN"?Math.max(Math.min(r,Math.abs(s))-e,0)/(r-e)*t:t}function yh({isLowQualityVideo:s,isVideoStuck:t,isVideoLagging:e,jitterQuality:r,packetsLostQuality:n}){const i=.8*((s?.85:1)*(e?.7:1)*(t?.5:1))+.2*(r*n);return Math.round((i+Number.EPSILON)*100)/100}function Th({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function _h({packetsLost:s,packetsSent:t,jitter:e}){const n=Fr({stat:Th({packetsLost:s,packetsSent:t}),weight:.7,rangeMin:0,rangeMax:Bo,rangeRankingDirection:"UP"}),a=Fr({stat:e,weight:.3,rangeMin:Ho,rangeMax:qo,rangeRankingDirection:"UP"});return n+a}function iy({frameWidth:s,isScreenShare:t}){return s<(t?fh:mh)}function ay({framesPerSecond:s,isScreenShare:t}){return s<(t?vh:gh)}function oy({framesEncoded:s}){return s===0}function Sh({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsSent:r,jitter:n,isScreenShare:i,framesEncoded:a}){const o=Fr({stat:Th({packetsLost:e,packetsSent:r}),weight:1,rangeMin:0,rangeMax:Bo,rangeRankingDirection:"UP"}),d=Fr({stat:n,weight:1,rangeMin:Ho,rangeMax:qo,rangeRankingDirection:"UP"}),u=iy({frameWidth:s,isScreenShare:i}),h=ay({framesPerSecond:t,isScreenShare:i}),p=oy({framesEncoded:a,isScreenShare:i});return yh({isLowQualityVideo:u,isVideoLagging:h,isVideoStuck:p,jitterQuality:d,packetsLostQuality:o})}function Eh({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}function wh({concealmentEvents:s,packetsLost:t,packetsReceived:e,jitter:r}){const i=Fr({stat:s,weight:.2,rangeMin:0,rangeMax:3,rangeRankingDirection:"UP"}),a=.5,o=Fr({stat:Eh({packetsLost:t,packetsReceived:e}),weight:a,rangeMin:0,rangeMax:Bo,rangeRankingDirection:"UP"}),u=Fr({stat:r,weight:.3,rangeMin:Ho,rangeMax:qo,rangeRankingDirection:"UP"});return i+o+u}function cy({framesDecoded:s}){return s===0}function dy({framesPerSecond:s,isScreenShare:t}){return s<(t?vh:gh)}function ly({frameWidth:s,isScreenShare:t}){return s<(t?fh:mh)}function Ch({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsReceived:r,jitter:n,isScreenShare:i,framesDecoded:a}){const o=Fr({stat:Eh({packetsLost:e,packetsReceived:r}),weight:1,rangeMin:0,rangeMax:Bo,rangeRankingDirection:"UP"}),d=Fr({stat:n,weight:1,rangeMin:Ho,rangeMax:qo,rangeRankingDirection:"UP"}),u=ly({frameWidth:s,isScreenShare:i}),h=dy({framesPerSecond:t,isScreenShare:i}),p=cy({framesDecoded:a,isScreenShare:i});return yh({isLowQualityVideo:u,isVideoLagging:h,isVideoStuck:p,jitterQuality:d,packetsLostQuality:o})}class xr{constructor(t){m(this,"pc1");m(this,"pc2");m(this,"constrainVideoBitrateKbps");m(this,"constrainOfferToRemoveVideoFec",!1);m(this,"iceCandidateFilter");const e=new RTCPeerConnection(t),r=new RTCPeerConnection(t);this.pc1=e,this.pc2=r,this.iceCandidateFilter=xr.noFilter,this.pc1.addEventListener("icecandidate",this.onIceCandidate.bind(this,this.pc2)),this.pc2.addEventListener("icecandidate",this.onIceCandidate.bind(this,this.pc1))}static parseCandidate(t){const e="candidate:",r=t.indexOf(e)+e.length,n=t.substr(r).split(" ");return{type:n[7],protocol:n[2],address:n[4]}}static isNotHostCandidate(t){return t.type!=="host"}static isHost(t){return t.type==="host"}static isRelay(t){return t.type==="relay"}static isReflexive(t){return t.type==="srflx"}static noFilter(t){return!0}onIceCandidate(t,e){if(e.candidate){const r=xr.parseCandidate(e.candidate.candidate);this.iceCandidateFilter(r)&&t.addIceCandidate(e.candidate)}}setIceCandidateFilter(t){this.iceCandidateFilter=t}constrainVideoBitrate(t){this.constrainVideoBitrateKbps=t}disableVideoFec(){this.constrainOfferToRemoveVideoFec=!0}gotOffer(t){this.constrainOfferToRemoveVideoFec&&(t.sdp=t.sdp.replace(/(m=video 1 [^\r]+)(116 117)(\r\n)/g,`$1\r `),t.sdp=t.sdp.replace(/a=rtpmap:116 red\/90000\r\n/g,""),t.sdp=t.sdp.replace(/a=rtpmap:117 ulpfec\/90000\r\n/g,""),t.sdp=t.sdp.replace(/a=rtpmap:98 rtx\/90000\r\n/g,""),t.sdp=t.sdp.replace(/a=fmtp:98 apt=116\r\n/g,"")),this.pc1.setLocalDescription(t),this.pc2.setRemoteDescription(t),this.pc2.createAnswer().then(this.gotAnswer.bind(this),this.reportFatal.bind(this))}gotAnswer(t){this.constrainVideoBitrateKbps&&(t.sdp=t.sdp.replace(/a=mid:video\r\n/g,`a=mid:video\r b=AS:${this.constrainVideoBitrateKbps}\r -`)),this.pc2.setLocalDescription(t),this.pc1.setRemoteDescription(t)}establishConnection(){this.pc1.createOffer().then(this.gotOffer.bind(this),this.reportFatal.bind(this))}reportFatal(t){console.error("Error:",t)}async getRoundTripTime(){const[t,e]=await Promise.all([this.pc1.getStats(),this.pc2.getStats()]);let r,n;if(t.forEach(i=>{i.type==="candidate-pair"&&i.nominated===!0&&i.bytesSent>0&&(r=i)}),e.forEach(i=>{i.type==="candidate-pair"&&i.nominated===!0&&i.bytesReceived>0&&(n=i)}),r&&n)try{if(r.currentRoundTripTime&&n.currentRoundTripTime)return{rtt:r.currentRoundTripTime,backendRTT:n.currentRoundTripTime};const i=(n.lastPacketReceivedTimestamp-r.lastPacketSentTimestamp)/1e3;return{rtt:i,backendRTT:i}}catch(i){return}}close(){this.pc1.close(),this.pc2.close()}}class bh extends de{constructor(e){super();m(this,"call");m(this,"timeOut");this.call=new xr(e)}start(e=1e4){this.call.establishConnection(),this.timeOut=setTimeout(this.testFailed.bind(this),e)}testComplete(e){clearTimeout(this.timeOut),this.call.close(),this.emit("done",e)}testFailed(e){this.call.close(),this.emit("failed",e)}}const uy=8,hy=1/1e3;class py extends bh{constructor(e){super(e);m(this,"senderChannel");m(this,"recieveChannel");m(this,"startTime");m(this,"lastBitrateMeasureTime");m(this,"sentPayloadBytes",0);m(this,"recievedPayloadBytes",0);m(this,"lastReceivedPayloadBytes",0);m(this,"stopSending",!1);m(this,"testProgress",0);m(this,"samplePacket","");m(this,"finalBitrateSum",0);m(this,"bitRateSampels",0);m(this,"maxNumberOfPacketsToSend",0);m(this,"bytesToKeepBuffered",0);m(this,"testDurationSeconds",5);this.call.setIceCandidateFilter(xr.isNotHostCandidate),this.senderChannel=this.call.pc1.createDataChannel(null);for(let r=0;r<262144;r+=1)this.samplePacket+="h";this.maxNumberOfPacketsToSend=1,this.bytesToKeepBuffered=1024*this.maxNumberOfPacketsToSend,this.testDurationSeconds=4,this.senderChannel.addEventListener("open",this.sendingStep.bind(this)),this.call.pc2.addEventListener("datachannel",this.onRecieverChannel.bind(this))}sendingStep(){const e=new Date;this.startTime||(this.startTime=e,this.lastBitrateMeasureTime=e);for(let n=0;n!==this.maxNumberOfPacketsToSend&&!(this.senderChannel.bufferedAmount>=this.bytesToKeepBuffered);n+=1){this.sentPayloadBytes+=this.samplePacket.length;try{this.senderChannel.send(this.samplePacket)}catch(i){}}const r=e.getTime()-this.startTime.getTime();r>=1e3*this.testDurationSeconds?(this.stopSending=!0,this.testProgress=100):(this.testProgress=r/(10*this.testDurationSeconds),setTimeout(this.sendingStep.bind(this),1))}onMessageRecieved(e){this.recievedPayloadBytes+=e.data.length;const r=new Date,n=r.getTime()-this.lastBitrateMeasureTime.getTime();if(n>=1e3){const a=(this.recievedPayloadBytes-this.lastReceivedPayloadBytes)*uy/(n/1e3);this.finalBitrateSum+=a,this.bitRateSampels+=1,this.lastReceivedPayloadBytes=this.recievedPayloadBytes,this.lastBitrateMeasureTime=r}if(this.stopSending&&this.sentPayloadBytes===this.recievedPayloadBytes){const i=this.finalBitrateSum/this.bitRateSampels;this.testComplete({throughput:Math.round(i*hy)})}}testComplete(e){this.call.getRoundTripTime().then(({rtt:r,backendRTT:n})=>super.testComplete({RTT:r,backendRTT:n,throughput:e.throughput}))}onRecieverChannel(e){this.recieveChannel=e.channel,this.recieveChannel.addEventListener("message",this.onMessageRecieved.bind(this))}}class xd extends bh{constructor(e,r=xr.noFilter){super(e);m(this,"ch1");m(this,"ch2");this.call.setIceCandidateFilter(r);const n=this.call.pc1.createDataChannel(null);this.ch1=n,n.addEventListener("open",()=>{n.send("hello")}),n.addEventListener("message",this.onCh1Recieve.bind(this)),this.call.pc2.addEventListener("datachannel",this.dataChannelHandler.bind(this))}onCh1Recieve(e){e.data!=="world"?this.hangup("Invalid data transmitted."):this.testComplete({connectivity:!0})}onCh2Recieve(e){if(e.data!=="hello")this.hangup("Invalid data transmitted.");else try{this.ch2.send("world")}catch(r){}}dataChannelHandler(e){const r=e.channel;this.ch2=r,r.addEventListener("message",this.onCh2Recieve.bind(this))}hangup(e){this.testFailed(e)}}class my extends xd{constructor(t){super(t,xr.isHost)}}class fy extends xd{constructor(t){super(t,xr.isRelay)}}class gy extends xd{constructor(t){super(t,xr.isReflexive)}}class vy{constructor(){m(this,"ipInformation",null)}async getIPDetails({peerId:t,apiHostnames:e}){var r;if(!this.ipInformation){try{const i=`https://${e.location}`,o=await(await fetch(i)).json();if(((r=o.loc)==null?void 0:r.length)>5)return this.ipInformation=o,o;throw Error("Insufficient data")}catch(i){}const n=await fetch(`https://${e.locationLegacy}/?token=3c493932b0624c&peerId=${t}`,{method:"POST"});this.ipInformation=await n.json()}return this.ipInformation}resetCache(){this.ipInformation=null}}const Ud=new vy,Ph=[{urls:"turn:turn.dyte.in:443?transport=tcp",username:"dyte",credential:"dytein",credentialType:"password"},{urls:"turn:turn.dyte.in:3478?transport=udp",username:"dyte",credential:"dytein",credentialType:"password"}];function Rh(s){const[t,e]=s.split(",");return{coords:{latitude:Number(t),longitude:Number(e)}}}class kh{constructor(){m(this,"transport");m(this,"candidatePair");m(this,"outboundVideoRtp",new Map);m(this,"inboundVideoRtp",new Map);m(this,"outboundAudioRtp",new Map);m(this,"inboundAudioRtp",new Map);m(this,"remoteInboundRtp",new Map);m(this,"producerStreamMap",new Map);m(this,"consumerStreamMap",new Map);m(this,"staleProducerStreamMap",!1);m(this,"staleConsumerStreamMap",!1)}}class Ih extends de{constructor(){super();m(this,"observer");m(this,"outboundProducerMap",new Map);m(this,"inboundConsumerMap",new Map);m(this,"consumerPeerIdMap",new Map);m(this,"pausedConsumerMap",new Map);m(this,"pausedProducerMap",new Map);m(this,"overallProducingTransportsStatsMap",{});m(this,"overallConsumingTransportsStatsMap",{});m(this,"overallConsumersStatsMap",{});m(this,"overallProducersStatsMap",{});m(this,"videoProducerToStatsMap",new Map);m(this,"audioProducerToStatsMap",new Map);m(this,"videoConsumerToStatsMap",new Map);m(this,"audioConsumerToStatsMap",new Map);m(this,"consumerIdsWithFreezedVideo",new Set);m(this,"consumerIdsWithFreezedAudio",new Set);m(this,"producerIdsWithFreezedVideo",new Set);m(this,"producerIdsWithFreezedAudio",new Set);m(this,"freezedProducingTransportIds",new Set);m(this,"freezedConsumingTransportIds",new Set);m(this,"screenShareProducers",new Set);m(this,"screenShareConsumers",new Set);m(this,"ipDetails");m(this,"callStatsInstance");this.observer=new de}async registerProducer(e){await this.generateProducerStreamMap(e),e.observer.on("close",this.deregisterProducer.bind(this,e)),e.observer.on("pause",this.pauseProducer.bind(this,e.id)),e.observer.on("resume",this.resumeProducer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareProducers.add(e.id)}pauseProducer(e){this.pausedProducerMap.set(e,{lastReportCalculated:!1})}resumeProducer(e){this.pausedProducerMap.delete(e)}processInboundConsumerVideoStats(e,r,n){var a,o;const i=((o=(a=this==null?void 0:this.callStatsInstance)==null?void 0:a.consumerSharedMediaStatesMap)==null?void 0:o.get(e))||{};r.totalVideoPacketsReceived===n.packetsReceived?(this.consumerIdsWithFreezedVideo.add(e),this.callStatsInstance&&i.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","pause",e))):(r.totalVideoPacketsReceived=n.packetsReceived,this.consumerIdsWithFreezedVideo.has(e)&&(this.consumerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&i.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","resume",e))))}processInboundConsumerAudioStats(e,r,n){var a,o;const i=((o=(a=this==null?void 0:this.callStatsInstance)==null?void 0:a.consumerSharedMediaStatesMap)==null?void 0:o.get(e))||{};r.totalAudioPacketsReceived===n.packetsReceived?(this.consumerIdsWithFreezedAudio.add(e),this.callStatsInstance&&i.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","pause",e))):(r.totalAudioPacketsReceived=n.packetsReceived,this.consumerIdsWithFreezedAudio.has(e)&&(this.consumerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&i.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","resume",e))))}processOutboundProducerVideoStats(e,r,n){var a;const i=((a=this==null?void 0:this.callStatsInstance)==null?void 0:a.currentUserMediaStates)||{};r.totalVideoPacketsSent===n.packetsSent?(this.producerIdsWithFreezedVideo.add(e),this.callStatsInstance&&i.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","pause",e))):(r.totalVideoPacketsSent=n.packetsSent,this.producerIdsWithFreezedVideo.has(e)&&(this.producerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&i.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","resume",e))))}processOutboundProducerAudioStats(e,r,n){var a;const i=((a=this==null?void 0:this.callStatsInstance)==null?void 0:a.currentUserMediaStates)||{};r.totalAudioPacketsSent===n.packetsSent?(this.producerIdsWithFreezedAudio.add(e),this.callStatsInstance&&i.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","pause",e))):(r.totalAudioPacketsSent=n.packetsSent,this.producerIdsWithFreezedAudio.has(e)&&(this.producerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&i.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","resume",e))))}processProducingTransportStats(e,r,n){var h;const i=((h=this==null?void 0:this.callStatsInstance)==null?void 0:h.currentUserMediaStates)||{},{audio:a,video:o,screen:d}=i,u=a||o||d;r.totalPacketsSent===n.packetsSent?(this.freezedProducingTransportIds.add(e),this.callStatsInstance&&u&&(this.callStatsInstance.logger.debug("callStats::measurements::producingTransportFreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("producing_transport_status","pause",e))):(r.totalPacketsSent=n.packetsSent,this.freezedProducingTransportIds.has(e)&&(this.freezedProducingTransportIds.delete(e),this.callStatsInstance&&u&&(this.callStatsInstance.logger.debug("callStats::measurements::producingTransportDefreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("producing_transport_status","resume",e))))}processConsumingTransportStats(e,r,n){var o,d;const a=!!Array.from(((d=(o=this==null?void 0:this.callStatsInstance)==null?void 0:o.consumerSharedMediaStatesMap)==null?void 0:d.values())||[]).reduce((u,h)=>u||h.audio||h.video||h.screen,!1);r.totalPacketsReceived===n.packetsSent?(this.freezedConsumingTransportIds.add(e),this.callStatsInstance&&a&&(this.callStatsInstance.logger.debug("callStats::measurements::consumingTransportFreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("consuming_transport_status","pause",e))):(r.totalPacketsReceived=n.packetsSent,this.freezedConsumingTransportIds.has(e)&&(this.freezedConsumingTransportIds.delete(e),this.callStatsInstance&&a&&(this.callStatsInstance.logger.debug("callStats::measurements::consumingTransportDefreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("consuming_transport_status","resume",e))))}async registerConsumer(e){await this.generateConsumerStreamMap(e),this.consumerPeerIdMap.set(e.id,{producerId:e.producerId,peerId:e.appData.peerId,appData:e.appData}),e.observer.on("close",this.deregisterConsumer.bind(this,e)),e.observer.on("pause",this.pauseConsumer.bind(this,e.id)),e.observer.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)}pauseConsumer(e){this.pausedConsumerMap.set(e,{lastReportCalculated:!1})}resumeConsumer(e){this.pausedConsumerMap.delete(e)}async generateProducerStreamMap(e,r=!1){const n=await e.getStats(),i=r?this.getProducerStatsFromReport(this.parseRTCReport(n,["outbound-rtp","remote-inbound-rtp"],!1,e.id))[0]:void 0;for(const a of n.values())switch(a.type){case"outbound-rtp":{this.outboundProducerMap.set(a.id,e.id);break}}return i}async generateConsumerStreamMap(e,r=!1){const n=await e.getStats(),i=r?this.getConsumerStatsFromReport(this.parseRTCReport(n,["inbound-rtp"],!1,e.id))[0]:void 0;for(const a of n.values())switch(a.type){case"inbound-rtp":{this.inboundConsumerMap.set(a.id,e.id);break}}return i}deregisterProducer(e){this.outboundProducerMap.forEach((r,n)=>{r===e.id&&this.outboundProducerMap.delete(n)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.inboundConsumerMap.forEach((r,n)=>{r===e.id&&this.inboundConsumerMap.delete(n)}),this.consumerPeerIdMap.delete(e.id),this.pausedConsumerMap.delete(e.id),this.screenShareConsumers.delete(e.id)}getIceCandidateStats(e){var r;return{id:e.id,type:e.candidateType||e.type,address:e.address,port:e.port,url:e.url,protocol:(r=e.relayProtocol)!=null?r:e.protocol,networkType:e.networkType,relatedAddress:e.relatedAddress,relatedPort:e.relatedPort}}getWorkingSimulcastVideoStats(e){return e.find(n=>{const i=n.framesEncoded>0,a=n.packetsSent>0,o=n.frameWidth&&n.frameHeight;return i&&a&&!!o})||e[e.length-1]}parseRTCReport(e,r=[],n=!1,i=void 0,a=void 0){var P,k,I,x,V,O,W,Q,oe,ve,Mt,Fe,Dt;const o=e,d=new kh,u=r.length?new Set(r):void 0,h=[],p=[],f=[],v=new Map,T=new Map;for(const M of o.values()){if(u){if(u.size===0)break;if(u.has(M.type))n&&u.delete(M.type);else continue}switch(M.type){case"local-candidate":{h.push(this.getIceCandidateStats(M));break}case"remote-candidate":{p.push(this.getIceCandidateStats(M));break}case"candidate-pair":{const{nominated:E}=M,{selected:R}=M,B=M,xe={nominated:E!=null?E:R,currentRoundTripTime:B.currentRoundTripTime,totalRoundTripTime:B.totalRoundTripTime,bytesReceived:B.bytesReceived,bytesSent:B.bytesSent,availableOutgoingBitrate:B.availableOutgoingBitrate,lastPacketReceivedTimestamp:B.lastPacketReceivedTimestamp,lastPacketSentTimestamp:B.lastPacketSentTimestamp,localCandidateId:B.localCandidateId,remoteCandidateId:B.remoteCandidateId,bytesDiscardedOnSend:B.bytesDiscardedOnSend,packetsSent:B.packetsSent,packetsReceived:B.packetsReceived,packetsDiscardedOnSend:B.packetsDiscardedOnSend};f.push(xe),(M.nominated===!0||M.selected===!0)&&(d.candidatePair=xe);break}case"transport":{const E=M;a&&(a.producing&&(this.overallProducingTransportsStatsMap[a.id]||(this.overallProducingTransportsStatsMap[a.id]={totalPacketsSent:0})),a.consuming&&(this.overallConsumingTransportsStatsMap[a.id]||(this.overallConsumingTransportsStatsMap[a.id]={totalPacketsReceived:0})));const R={bytesReceived:E.bytesReceived,bytesSent:E.bytesSent,packetsSent:E.packetsSent,packetsReceived:E.packetsReceived,dtlsCipher:E.dtlsCipher,dtlsState:E.dtlsState,iceRole:E.iceRole};if(d.transport=R,a){if(a.producing){const B=this.overallProducingTransportsStatsMap[a.id];this.processProducingTransportStats(a.id,B,R)}if(a.consuming){const B=this.overallConsumingTransportsStatsMap[a.id];this.processConsumingTransportStats(a.id,B,R)}}break}case"remote-inbound-rtp":{const E=M,R={jitter:E.jitter,fractionLost:E.fractionLost,roundTripTime:E.roundTripTime,roundTripTimeMeasurements:E.roundTripTimeMeasurements,totalRoundTripTime:E.totalRoundTripTime,packetsLost:E.packetsLost};d.remoteInboundRtp.set(E.localId,R);break}case"outbound-rtp":{const E=M,R=i||this.outboundProducerMap.get(M.id),B=this.pausedProducerMap.get(R);if(B){if(B.lastReportCalculated===!0)break;this.pausedProducerMap.set(R,{lastReportCalculated:!0})}this.overallProducersStatsMap[R]||(this.overallProducersStatsMap[R]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const xe=this.overallProducersStatsMap[R];if(["video","audio"].includes(E.mediaType)||["video","audio"].includes(E.kind)){if(!this.outboundProducerMap.has(M.id)){d.staleProducerStreamMap=!0;break}const Qe=this.callStatsInstance.producers.get(R);if(((P=Qe==null?void 0:Qe.track)==null?void 0:P.readyState)==="ended")break;d.producerStreamMap.has(R)||d.producerStreamMap.set(R,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const G={bytesSent:E.bytesSent,packetsSent:E.packetsSent,nackCount:E.nackCount,ssrc:E.ssrc,mid:E.mid};if(E.mediaType==="video"||E.kind==="video"){if(E.decoderImplementation==="unknown")break;const A=E,rt={frameHeight:A.frameHeight,frameWidth:A.frameWidth,framesEncoded:A.framesEncoded,framesDropped:A.framesDropped,framesPerSecond:A.framesPerSecond,framesSent:A.framesSent,keyFramesEncoded:A.keyFramesEncoded,firCount:A.firCount,encoderImplementation:A.encoderImplementation,hugeFramesSent:A.hugeFramesSent,pliCount:A.pliCount,qpSum:A.qpSum,qualityLimitationDurations:A.qualityLimitationDurations,qualityLimitationReason:A.qualityLimitationReason,qualityLimitationResolutionChanges:A.qualityLimitationResolutionChanges,totalEncodeTime:A.targetBitrate,totalPacketSendDelay:A.totalPacketSendDelay,retransmittedBytesSent:A.retransmittedBytesSent,retransmittedPacketsSent:A.retransmittedPacketsSent,...G};d.outboundVideoRtp.set(M.id,rt),d.producerStreamMap.get(R).outboundVideoRtpId.push(M.id),this.processOutboundProducerVideoStats(R,xe,rt)}else if(E.mediaType==="audio"||E.kind==="audio"){const A=E,rt={retransmittedBytesSent:A.retransmittedBytesSent,retransmittedPacketsSent:A.retransmittedPacketsSent,...G};d.outboundAudioRtp.set(M.id,rt),d.producerStreamMap.get(R).outboundAudioRtpId.push(M.id),this.processOutboundProducerAudioStats(R,xe,rt)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${E.mediaType} kind: ${E.kind}`);break}case"inbound-rtp":{const E=M,R=i||this.inboundConsumerMap.get(M.id),B=this.pausedConsumerMap.get(R);if(B){if(B.lastReportCalculated===!0)break;this.pausedConsumerMap.set(R,{lastReportCalculated:!0})}if(E.ssrc===1234)break;this.overallConsumersStatsMap[R]||(this.overallConsumersStatsMap[R]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const xe=this.overallConsumersStatsMap[R];if(["video","audio"].includes(E.mediaType)||["video","audio"].includes(E.kind)){if(!this.inboundConsumerMap.has(M.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(R)||d.consumerStreamMap.set(R,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const Qe={bytesReceived:E.bytesReceived,packetsReceived:E.packetsReceived,packetsLost:E.packetsLost,jitter:E.jitter,nackCount:E.nackCount,jitterBufferDelay:E.jitterBufferDelay,jitterBufferEmittedCount:E.jitterBufferEmittedCount,lastPacketReceivedTimestamp:E.lastPacketReceivedTimestamp,ssrc:E.ssrc,mid:E.mid};if(E.mediaType==="video"||E.kind==="video"){if(E.decoderImplementation==="unknown")break;const G=E,A={frameHeight:G.frameHeight,frameWidth:G.frameWidth,framesDecoded:G.framesDecoded,framesDropped:G.framesDropped,framesPerSecond:G.framesPerSecond,framesReceived:G.framesReceived,keyFramesDecoded:G.keyFramesDecoded,firCount:G.firCount,decoderImplementation:G.decoderImplementation,pliCount:G.pliCount,totalProcessingDelay:G.totalProcessingDelay,...Qe};A.score=Ch({frameWidth:A.frameWidth||0,framesDecoded:(A.framesDecoded||0)-(((k=this.videoConsumerToStatsMap.get(R))==null?void 0:k.framesDecoded)||0),framesPerSecond:A.framesPerSecond||0,packetsLost:(A.packetsLost||0)-(((I=this.videoConsumerToStatsMap.get(R))==null?void 0:I.packetsLost)||0),packetsReceived:(A.packetsReceived||0)-(((x=this.videoConsumerToStatsMap.get(R))==null?void 0:x.packetsReceived)||0),jitter:A.jitter||0,isScreenShare:this.screenShareConsumers.has(R)}),T.set(R,{score:+(A.score*10).toFixed(),frameWidth:A.frameWidth||0,frameHeight:A.frameHeight||0,framesPerSecond:A.framesPerSecond||0,packetsLostPercentage:$o({packetsLost:(A.packetsLost||0)-(((V=this.videoConsumerToStatsMap.get(R))==null?void 0:V.packetsLost)||0),packetsReceived:(A.packetsReceived||0)-(((O=this.videoConsumerToStatsMap.get(R))==null?void 0:O.packetsReceived)||0)}),jitter:A.jitter||0,isScreenShare:this.screenShareConsumers.has(R),bitrate:((A.bytesReceived||0)-(((W=this.videoConsumerToStatsMap.get(R))==null?void 0:W.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(R,A),d.inboundVideoRtp.set(M.id,A),d.consumerStreamMap.get(R).inboundVideoRtpId.push(M.id),this.processInboundConsumerVideoStats(R,xe,A)}else if(E.mediaType==="audio"||E.kind==="audio"){const G=E,A={audioLevel:G.audioLevel,concealedSampels:G.concealedSampels,concealmentEvents:G.concealmentEvents,totalAudioEnergy:G.totalAudioEnergy,totalSamplesDuration:G.totalSamplesDuration,totalSamplesReceived:G.totalSamplesReceived,...Qe};A.score=wh({concealmentEvents:(A.concealmentEvents||0)-(((Q=this.audioConsumerToStatsMap.get(R))==null?void 0:Q.concealmentEvents)||0),packetsLost:(A.packetsLost||0)-(((oe=this.audioConsumerToStatsMap.get(R))==null?void 0:oe.packetsLost)||0),packetsReceived:(A.packetsReceived||0)-(((ve=this.audioConsumerToStatsMap.get(R))==null?void 0:ve.packetsReceived)||0),jitter:A.jitter||0}),T.set(R,{score:+(A.score*10).toFixed(),packetsLostPercentage:$o({packetsLost:(A.packetsLost||0)-(((Mt=this.audioConsumerToStatsMap.get(R))==null?void 0:Mt.packetsLost)||0),packetsReceived:(A.packetsReceived||0)-(((Fe=this.audioConsumerToStatsMap.get(R))==null?void 0:Fe.packetsReceived)||0)}),jitter:A.jitter||0,isScreenShare:this.screenShareConsumers.has(R),bitrate:((A.bytesReceived||0)-(((Dt=this.audioConsumerToStatsMap.get(R))==null?void 0:Dt.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(R,A),d.inboundAudioRtp.set(M.id,A),d.consumerStreamMap.get(R).inboundAudioRtpId.push(M.id),this.processInboundConsumerAudioStats(R,xe,A)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${E.mediaType} kind: ${E.kind}`);break}}}if(d.producerStreamMap.forEach((M,E)=>{var R,B,xe,Qe,G,A,rt,cs,yo,To,_o,So,Eo,wo,Co,bo,Po,Ro,ko,Io,Ao,Mo,Do;if(M.outboundVideoRtpId.length>0){const Ce=[];M.outboundVideoRtpId.forEach(Wu=>{Ce.push(d.outboundVideoRtp.get(Wu))});const ce=this.getWorkingSimulcastVideoStats(Ce);ce.score=Sh({frameWidth:ce.frameWidth||0,framesPerSecond:ce.framesPerSecond||0,jitter:((R=ce.remoteData)==null?void 0:R.jitter)||0,isScreenShare:this.screenShareProducers.has(E),packetsSent:(ce.packetsSent||0)-(((B=this.videoProducerToStatsMap.get(E))==null?void 0:B.packetsSent)||0),packetsLost:(((xe=ce.remoteData)==null?void 0:xe.packetsLost)||0)-(((G=(Qe=this.videoProducerToStatsMap.get(E))==null?void 0:Qe.remoteData)==null?void 0:G.packetsLost)||0),framesEncoded:(ce.framesEncoded||0)-(((A=this.videoProducerToStatsMap.get(E))==null?void 0:A.framesEncoded)||0)}),v.set(E,{score:+(ce.score*10).toFixed(),frameWidth:ce.frameWidth||0,frameHeight:ce.frameHeight||0,framesPerSecond:ce.framesPerSecond||0,jitter:((rt=ce.remoteData)==null?void 0:rt.jitter)||0,isScreenShare:this.screenShareProducers.has(E),packetsLostPercentage:Vo({packetsSent:(ce.packetsSent||0)-(((cs=this.videoProducerToStatsMap.get(E))==null?void 0:cs.packetsSent)||0),packetsLost:(((yo=ce.remoteData)==null?void 0:yo.packetsLost)||0)-(((_o=(To=this.videoProducerToStatsMap.get(E))==null?void 0:To.remoteData)==null?void 0:_o.packetsLost)||0)}),bitrate:((ce.bytesSent||0)-(((So=this.videoProducerToStatsMap.get(E))==null?void 0:So.bytesSent)||0))*8/7,cpuLimitations:ce.qualityLimitationReason==="cpu",bandwidthLimitations:ce.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(E,ce)}else if(M.outboundAudioRtpId.length>0){const Ce=d.outboundAudioRtp.get(M.outboundAudioRtpId[0]);Ce.score=_h({packetsSent:(Ce.packetsSent||0)-(((Eo=this.audioProducerToStatsMap.get(E))==null?void 0:Eo.packetsSent)||0),packetsLost:(((wo=Ce.remoteData)==null?void 0:wo.packetsLost)||0)-(((bo=(Co=this.audioProducerToStatsMap.get(E))==null?void 0:Co.remoteData)==null?void 0:bo.packetsLost)||0),jitter:((Po=Ce.remoteData)==null?void 0:Po.jitter)||0}),v.set(E,{score:+(Ce.score*10).toFixed(),bitrate:((Ce.bytesSent||0)-(((Ro=this.audioProducerToStatsMap.get(E))==null?void 0:Ro.bytesSent)||0))*8/7,packetsLostPercentage:Vo({packetsSent:(Ce.packetsSent||0)-(((ko=this.audioProducerToStatsMap.get(E))==null?void 0:ko.packetsSent)||0),packetsLost:(((Io=Ce.remoteData)==null?void 0:Io.packetsLost)||0)-(((Mo=(Ao=this.audioProducerToStatsMap.get(E))==null?void 0:Ao.remoteData)==null?void 0:Mo.packetsLost)||0)}),jitter:((Do=Ce.remoteData)==null?void 0:Do.jitter)||0,isScreenShare:this.screenShareProducers.has(E)}),this.audioProducerToStatsMap.set(E,Ce)}}),f.forEach(M=>{const E=h.find(B=>B.id===M.localCandidateId?(M.localCandidateId=B.id,B):null),R=p.find(B=>B.id===M.remoteCandidateId?(M.remoteCandidateId=B.id,B):null);E&&(M.localCandidateType=E.type,M.localCandidateAddress=E.address,M.localCandidatePort=E.port,M.localCandidateProtocol=E.protocol,M.localCandidateUrl=E.url,M.localCandidateNetworkType=E.networkType,M.localCandidateRelatedAddress=E.relatedAddress,M.localCandidateRelatedPort=E.relatedPort),R&&(M.remoteCandidateType=R.type,M.remoteCandidateAddress=R.address,M.remoteCandidatePort=R.port,M.remoteCandidateProtocol=R.protocol,M.remoteCandidateUrl=R.url)}),d.candidatePair&&(d.transport?(d.transport.totalRoundTripTime=d.candidatePair.totalRoundTripTime,d.transport.availableOutgoingBitrate=d.candidatePair.availableOutgoingBitrate,d.transport.roundTripTime=d.candidatePair.currentRoundTripTime):d.transport={bytesReceived:d.candidatePair.bytesReceived,bytesSent:d.candidatePair.bytesSent,totalRoundTripTime:d.candidatePair.totalRoundTripTime,availableOutgoingBitrate:d.candidatePair.availableOutgoingBitrate,roundTripTime:d.candidatePair.currentRoundTripTime}),d.transport&&(d.transport.candidatePairs=f),d.transport&&!d.transport.roundTripTime){let M=0,E=0;d.remoteInboundRtp.forEach((R,B)=>{R.roundTripTime&&R.roundTripTime>M&&(M=R.roundTripTime,E=R.totalRoundTripTime)}),d.transport.roundTripTime=M,d.transport.totalRoundTripTime=E}if(T.size>0)try{this.observer.emit("consumer_score",T)}catch(M){}if(v.size>0)try{this.observer.emit("producer_score",v)}catch(M){}return d}async getProducersReport(e){const r=e.map(n=>this.generateProducerStreamMap(n,!0));return r.length>0?Promise.all(r):void 0}async getConsumersReport(e){const r=e.map(n=>this.generateConsumerStreamMap(n,!0));return r.length>0?Promise.all(r):void 0}async getTransportReport(e){return e.getStats()}async getProcessedStats(e,r,n){const i=await this.getTransportReport(e),a={producing:n,consuming:r,id:e.id},o=i,d=this.parseRTCReport(o,["transport","candidate-pair","inbound-rtp","outbound-rtp","remote-inbound-rtp","local-candidate","remote-candidate"],!1,void 0,a);if(!d)return;const u={stats:d.transport,transportId:e.id,consuming:r,producing:n},h=d.staleProducerStreamMap?void 0:this.getProducerStatsFromReport(d),p=d.staleConsumerStreamMap?void 0:this.getConsumerStatsFromReport(d);return{transportReport:u,producerReport:h,consumerReport:p}}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((n,i)=>{var a,o;r.push({producerId:i,videoStats:n.outboundVideoRtpId.map(d=>e.outboundVideoRtp.get(d)),audioStats:n.outboundAudioRtpId.map(d=>e.outboundAudioRtp.get(d)),appData:((o=(a=this.callStatsInstance.producers)==null?void 0:a.get(i))==null?void 0:o.appData)||null})})}catch(n){this.callStatsInstance.logger.error("callStats::measurements::getProducerStatsFromReport",{error:{reason:n.reason,message:n.message}})}return r}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((n,i)=>{const{peerId:a,producerId:o,appData:d}=this.consumerPeerIdMap.get(i);r.push({consumerId:i,peerId:a,producerId:o,appData:d,videoStats:n.inboundVideoRtpId.map(u=>e.inboundVideoRtp.get(u)),audioStats:n.inboundAudioRtpId.map(u=>e.inboundAudioRtp.get(u))})})}catch(n){console.error("getConsumersReport: ",n,e)}return r}async getUserLocation(){return new Promise((e,r)=>{try{navigator.geolocation?navigator.geolocation.getCurrentPosition(n=>{e(n)}):r()}catch(n){r(n)}})}async getConnectivity(e){try{const r={iceServers:e||Ph},n=new Promise((h,p)=>{try{const f=new my(r);f.addListener("done",h),f.addListener("failed",()=>{h({connectivity:!1})}),f.start(2e3)}catch(f){p(f)}}),i=new Promise((h,p)=>{try{const f=new fy(r);f.addListener("done",h),f.addListener("failed",()=>{h({connectivity:!1})}),f.start(2e3)}catch(f){p(f)}}),a=new Promise((h,p)=>{try{const f=new gy(r);f.addListener("done",h),f.addListener("failed",()=>{h({connectivity:!1})}),f.start(2e3)}catch(f){p(f)}}),[o,d,u]=await Promise.all([n,i,a]);return{host:o==null?void 0:o.connectivity,relay:d==null?void 0:d.connectivity,reflexive:u==null?void 0:u.connectivity}}catch(r){return{host:!1,relay:!1,reflexive:!1}}}async getThroughput(e){try{const n=await new Promise((i,a)=>{try{const o={iceServers:e||Ph},d=new py(o);d.addListener("done",i),d.addListener("failed",a),d.start(1e4)}catch(o){a(o)}});return{throughput:n.throughput,fractionalLoss:0,RTT:n.RTT,jitter:0,backendRTT:n.backendRTT}}catch(r){return}}async getIPDetails(){var e,r;try{return this.ipDetails||(this.ipDetails=await Ud.getIPDetails({peerId:(e=this.callStatsInstance)==null?void 0:e.peerId,apiHostnames:(r=this.callStatsInstance)==null?void 0:r.apiHostnames})),this.ipDetails}catch(n){return}}async getNetworkQuality(e){const[r,n]=await Promise.all([this.getConnectivity(e),this.getThroughput(e)]);return{connectivity:r,throughput:n==null?void 0:n.throughput,fractionalLoss:n==null?void 0:n.fractionalLoss,RTT:n==null?void 0:n.RTT,jitter:n==null?void 0:n.jitter,backendRTT:n==null?void 0:n.backendRTT}}async getNetworkInfo(e,r=!1){var o,d;if(r){const u=await this.getIPDetails();return{ipDetails:u,effectiveNetworkType:(o=navigator.connection)==null?void 0:o.effectiveType,location:u.loc?Rh(u.loc):void 0}}const[n,i,a]=await Promise.all([this.getConnectivity(e),this.getThroughput(e),this.getIPDetails()]);return{ipDetails:a,effectiveNetworkType:(d=navigator.connection)==null?void 0:d.effectiveType,location:a.loc?Rh(a.loc):void 0,turnConnectivity:n?n.host||n.relay||n.reflexive:!1,connectivity:n,throughput:i==null?void 0:i.throughput,fractionalLoss:i==null?void 0:i.fractionalLoss,RTT:i==null?void 0:i.RTT,jitter:i==null?void 0:i.jitter,backendRTT:i==null?void 0:i.backendRTT}}}class yy extends Ih{}class Ah extends Ih{constructor(){super(...arguments);m(this,"producerMap",new Map);m(this,"consumerMap",new Map)}async registerProducer(e){this.producerMap.set(e.id,e),await this.generateProducerStreamMap(e),e.observer.on("close",this.deregisterProducer.bind(this,e)),e.observer.on("pause",this.pauseProducer.bind(this,e.id)),e.observer.on("resume",this.resumeProducer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareProducers.add(e.id)}async registerConsumer(e){this.consumerMap.set(e.id,e),await this.generateConsumerStreamMap(e),this.consumerPeerIdMap.set(e.id,{producerId:e.producerId,peerId:e.appData.peerId,appData:e.appData}),e.observer.on("close",this.deregisterConsumer.bind(this,e)),e.observer.on("pause",this.pauseConsumer.bind(this,e.id)),e.observer.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)}async generateConsumerStreamMap(e,r=!1){const n=await e.getStats(),i=this.parseRTCReport(n,["inbound-rtp"],!1,e.id),a=[...i.consumerStreamMap.values()][0],o=r?this.getConsumerStatsFromParsedConsumerStats(i,a,e.id):void 0;for(const d of n.values())switch(d.type){case"inbound-rtp":{this.inboundConsumerMap.set(d.id,e.id);break}}return o}deregisterProducer(e){this.producerMap.delete(e.id),this.outboundProducerMap.forEach((r,n)=>{r===e.id&&this.outboundProducerMap.delete(n)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.consumerMap.delete(e.id),this.inboundConsumerMap.forEach((r,n)=>{r===e.id&&this.inboundConsumerMap.delete(n)}),this.consumerPeerIdMap.delete(e.id),this.pausedConsumerMap.delete(e.id),this.screenShareConsumers.delete(e.id)}getIceCandidateStats(e){var r;return{id:e.id,type:e.candidateType||e.type,address:e.address,port:e.port,url:e.url,protocol:(r=e.relayProtocol)!=null?r:e.protocol,networkType:e.networkType,relatedAddress:e.relatedAddress,relatedPort:e.relatedPort}}parseRTCReport(e,r=[],n=!1,i=void 0,a=void 0){var P,k,I,x,V,O,W,Q,oe,ve,Mt,Fe,Dt;const o=e,d=new kh,u=r.length?new Set(r):void 0,h=[],p=[],f=[],v=new Map,T=new Map;for(const M of o.values()){if(u){if(u.size===0)break;if(u.has(M.type))n&&u.delete(M.type);else continue}switch(M.type){case"local-candidate":{h.push(this.getIceCandidateStats(M));break}case"remote-candidate":{p.push(this.getIceCandidateStats(M));break}case"candidate-pair":{const{nominated:E}=M,{selected:R}=M,B=M,xe={nominated:E!=null?E:R,currentRoundTripTime:B.currentRoundTripTime,totalRoundTripTime:B.totalRoundTripTime,bytesReceived:B.bytesReceived,bytesSent:B.bytesSent,availableOutgoingBitrate:B.availableOutgoingBitrate,lastPacketReceivedTimestamp:B.lastPacketReceivedTimestamp,lastPacketSentTimestamp:B.lastPacketSentTimestamp,localCandidateId:B.localCandidateId,remoteCandidateId:B.remoteCandidateId,bytesDiscardedOnSend:B.bytesDiscardedOnSend,packetsSent:B.packetsSent,packetsReceived:B.packetsReceived,packetsDiscardedOnSend:B.packetsDiscardedOnSend};f.push(xe),(M.nominated===!0||M.selected===!0)&&(d.candidatePair=xe);break}case"transport":{const E=M;a&&(a.producing&&(this.overallProducingTransportsStatsMap[a.id]||(this.overallProducingTransportsStatsMap[a.id]={totalPacketsSent:0})),a.consuming&&(this.overallConsumingTransportsStatsMap[a.id]||(this.overallConsumingTransportsStatsMap[a.id]={totalPacketsReceived:0})));const R={bytesReceived:E.bytesReceived,bytesSent:E.bytesSent,packetsSent:E.packetsSent,packetsReceived:E.packetsReceived,dtlsCipher:E.dtlsCipher,dtlsState:E.dtlsState,iceRole:E.iceRole};if(d.transport=R,a){if(a.producing){const B=this.overallProducingTransportsStatsMap[a.id];this.processProducingTransportStats(a.id,B,R)}if(a.consuming){const B=this.overallConsumingTransportsStatsMap[a.id];this.processConsumingTransportStats(a.id,B,R)}}break}case"remote-inbound-rtp":{const E=M,R={jitter:E.jitter,fractionLost:E.fractionLost,roundTripTime:E.roundTripTime,roundTripTimeMeasurements:E.roundTripTimeMeasurements,totalRoundTripTime:E.totalRoundTripTime,packetsLost:E.packetsLost};d.remoteInboundRtp.set(E.localId,R);break}case"outbound-rtp":{const E=M,R=i||this.outboundProducerMap.get(M.id),B=this.pausedProducerMap.get(R);if(B){if(B.lastReportCalculated===!0)break;this.pausedProducerMap.set(R,{lastReportCalculated:!0})}this.overallProducersStatsMap[R]||(this.overallProducersStatsMap[R]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const xe=this.overallProducersStatsMap[R];if(["video","audio"].includes(E.mediaType)||["video","audio"].includes(E.kind)){if(!this.outboundProducerMap.has(M.id)){d.staleProducerStreamMap=!0;break}const Qe=this.callStatsInstance.producers.get(R);if(((P=Qe==null?void 0:Qe.track)==null?void 0:P.readyState)==="ended")break;d.producerStreamMap.has(R)||d.producerStreamMap.set(R,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const G={bytesSent:E.bytesSent,packetsSent:E.packetsSent,nackCount:E.nackCount,ssrc:E.ssrc,mid:E.mid};if(E.mediaType==="video"||E.kind==="video"){if(E.decoderImplementation==="unknown")break;const A=E,rt={frameHeight:A.frameHeight,frameWidth:A.frameWidth,framesEncoded:A.framesEncoded,framesDropped:A.framesDropped?A.framesDropped:A.droppedFrames,framesPerSecond:A.framesPerSecond?A.framesPerSecond:A.framerateMean,framesSent:A.framesSent,keyFramesEncoded:A.keyFramesEncoded,firCount:A.firCount,encoderImplementation:A.encoderImplementation,hugeFramesSent:A.hugeFramesSent,pliCount:A.pliCount,qpSum:A.qpSum,qualityLimitationReason:A.qualityLimitationReason,qualityLimitationDurations:A.qualityLimitationDurations,qualityLimitationResolutionChanges:A.qualityLimitationResolutionChanges,totalEncodeTime:A.totalEncodeTime,totalPacketSendDelay:A.totalEncodeTime,retransmittedBytesSent:A.retransmittedBytesSent,retransmittedPacketsSent:A.retransmittedPacketsSent,...G};d.outboundVideoRtp.set(M.id,rt),d.producerStreamMap.get(R).outboundVideoRtpId.push(M.id),this.processOutboundProducerVideoStats(R,xe,rt)}else if(E.mediaType==="audio"||E.kind==="audio"){const A=E,rt={retransmittedBytesSent:A.retransmittedBytesSent,retransmittedPacketsSent:A.retransmittedPacketsSent,...G};d.outboundAudioRtp.set(M.id,rt),d.producerStreamMap.get(R).outboundAudioRtpId.push(M.id),this.processOutboundProducerAudioStats(R,xe,rt)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${E.mediaType} kind: ${E.kind}`);break}case"inbound-rtp":{const E=M,R=i||this.inboundConsumerMap.get(M.id),B=this.pausedConsumerMap.get(R);if(B){if(B.lastReportCalculated===!0)break;this.pausedConsumerMap.set(R,{lastReportCalculated:!0})}if(E.ssrc===1234)break;this.overallConsumersStatsMap[R]||(this.overallConsumersStatsMap[R]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const xe=this.overallConsumersStatsMap[R];if(["video","audio"].includes(E.mediaType)||["video","audio"].includes(E.kind)){if(!this.inboundConsumerMap.has(M.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(R)||d.consumerStreamMap.set(R,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const Qe={bytesReceived:E.bytesReceived,packetsReceived:E.packetsReceived,packetsLost:E.packetsLost,jitter:E.jitter,nackCount:E.nackCount,jitterBufferDelay:E.jitterBufferDelay,jitterBufferEmittedCount:E.jitterBufferEmittedCount,lastPacketReceivedTimestamp:E.lastPacketReceivedTimestamp,ssrc:E.ssrc,mid:E.mid};if(E.mediaType==="video"||E.kind==="video"){if(E.decoderImplementation==="unknown")break;const G=E,A={frameHeight:G.frameHeight,frameWidth:G.frameWidth,framesDecoded:G.framesDecoded,framesDropped:G.framesDropped?G.framesDropped:G.droppedFrames,framesPerSecond:G.framesPerSecond?G.framesPerSecond:G.framerateMean,framesReceived:G.framesReceived,keyFramesDecoded:G.keyFramesDecoded,firCount:G.firCount,decoderImplementation:G.decoderImplementation,pliCount:G.pliCount,totalProcessingDelay:G.totalProcessingDelay,...Qe};A.score=Ch({frameWidth:A.frameWidth||0,framesDecoded:(A.framesDecoded||0)-(((k=this.videoConsumerToStatsMap.get(R))==null?void 0:k.framesDecoded)||0),framesPerSecond:A.framesPerSecond||0,packetsLost:(A.packetsLost||0)-(((I=this.videoConsumerToStatsMap.get(R))==null?void 0:I.packetsLost)||0),packetsReceived:(A.packetsReceived||0)-(((x=this.videoConsumerToStatsMap.get(R))==null?void 0:x.packetsReceived)||0),jitter:A.jitter||0,isScreenShare:this.screenShareConsumers.has(R)}),T.set(R,{score:+(A.score*10).toFixed(),frameWidth:A.frameWidth||0,frameHeight:A.frameHeight||0,framesPerSecond:A.framesPerSecond||0,packetsLostPercentage:$o({packetsLost:(A.packetsLost||0)-(((V=this.videoConsumerToStatsMap.get(R))==null?void 0:V.packetsLost)||0),packetsReceived:(A.packetsReceived||0)-(((O=this.videoConsumerToStatsMap.get(R))==null?void 0:O.packetsReceived)||0)}),jitter:A.jitter||0,isScreenShare:this.screenShareConsumers.has(R),bitrate:((A.bytesReceived||0)-(((W=this.videoConsumerToStatsMap.get(R))==null?void 0:W.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(R,A),d.inboundVideoRtp.set(M.id,A),d.consumerStreamMap.get(R).inboundVideoRtpId.push(M.id),this.processInboundConsumerVideoStats(R,xe,A)}else if(E.mediaType==="audio"||E.kind==="audio"){const G=E,A={audioLevel:G.audioLevel,concealedSampels:G.concealedSampels,concealmentEvents:G.concealmentEvents,totalAudioEnergy:G.totalAudioEnergy,totalSamplesDuration:G.totalSamplesDuration,totalSamplesReceived:G.totalSamplesReceived,...Qe};A.score=wh({concealmentEvents:(A.concealmentEvents||0)-(((Q=this.audioConsumerToStatsMap.get(R))==null?void 0:Q.concealmentEvents)||0),packetsLost:(A.packetsLost||0)-(((oe=this.audioConsumerToStatsMap.get(R))==null?void 0:oe.packetsLost)||0),packetsReceived:(A.packetsReceived||0)-(((ve=this.audioConsumerToStatsMap.get(R))==null?void 0:ve.packetsReceived)||0),jitter:A.jitter||0}),T.set(R,{score:+(A.score*10).toFixed(),packetsLostPercentage:$o({packetsLost:(A.packetsLost||0)-(((Mt=this.audioConsumerToStatsMap.get(R))==null?void 0:Mt.packetsLost)||0),packetsReceived:(A.packetsReceived||0)-(((Fe=this.audioConsumerToStatsMap.get(R))==null?void 0:Fe.packetsReceived)||0)}),jitter:A.jitter||0,isScreenShare:this.screenShareConsumers.has(R),bitrate:((A.bytesReceived||0)-(((Dt=this.audioConsumerToStatsMap.get(R))==null?void 0:Dt.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(R,A),d.inboundAudioRtp.set(M.id,A),d.consumerStreamMap.get(R).inboundAudioRtpId.push(M.id),this.processInboundConsumerAudioStats(R,xe,A)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${E.mediaType} kind: ${E.kind}`);break}}}if(d.producerStreamMap.forEach((M,E)=>{var R,B,xe,Qe,G,A,rt,cs,yo,To,_o,So,Eo,wo,Co,bo,Po,Ro,ko,Io,Ao,Mo,Do;if(M.outboundVideoRtpId.length>0){const Ce=[];M.outboundVideoRtpId.forEach(Wu=>{Ce.push(d.outboundVideoRtp.get(Wu))});const ce=this.getWorkingSimulcastVideoStats(Ce);ce.score=Sh({frameWidth:ce.frameWidth||0,framesPerSecond:ce.framesPerSecond||0,jitter:((R=ce.remoteData)==null?void 0:R.jitter)||0,isScreenShare:this.screenShareProducers.has(E),packetsSent:(ce.packetsSent||0)-(((B=this.videoProducerToStatsMap.get(E))==null?void 0:B.packetsSent)||0),packetsLost:(((xe=ce.remoteData)==null?void 0:xe.packetsLost)||0)-(((G=(Qe=this.videoProducerToStatsMap.get(E))==null?void 0:Qe.remoteData)==null?void 0:G.packetsLost)||0),framesEncoded:(ce.framesEncoded||0)-(((A=this.videoProducerToStatsMap.get(E))==null?void 0:A.framesEncoded)||0)}),v.set(E,{score:+(ce.score*10).toFixed(),frameWidth:ce.frameWidth||0,frameHeight:ce.frameHeight||0,framesPerSecond:ce.framesPerSecond||0,jitter:((rt=ce.remoteData)==null?void 0:rt.jitter)||0,isScreenShare:this.screenShareProducers.has(E),packetsLostPercentage:Vo({packetsSent:(ce.packetsSent||0)-(((cs=this.videoProducerToStatsMap.get(E))==null?void 0:cs.packetsSent)||0),packetsLost:(((yo=ce.remoteData)==null?void 0:yo.packetsLost)||0)-(((_o=(To=this.videoProducerToStatsMap.get(E))==null?void 0:To.remoteData)==null?void 0:_o.packetsLost)||0)}),bitrate:((ce.bytesSent||0)-(((So=this.videoProducerToStatsMap.get(E))==null?void 0:So.bytesSent)||0))*8/7,cpuLimitations:ce.qualityLimitationReason==="cpu",bandwidthLimitations:ce.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(E,ce)}else if(M.outboundAudioRtpId.length>0){const Ce=d.outboundAudioRtp.get(M.outboundAudioRtpId[0]);Ce.score=_h({packetsSent:(Ce.packetsSent||0)-(((Eo=this.audioProducerToStatsMap.get(E))==null?void 0:Eo.packetsSent)||0),packetsLost:(((wo=Ce.remoteData)==null?void 0:wo.packetsLost)||0)-(((bo=(Co=this.audioProducerToStatsMap.get(E))==null?void 0:Co.remoteData)==null?void 0:bo.packetsLost)||0),jitter:((Po=Ce.remoteData)==null?void 0:Po.jitter)||0}),v.set(E,{score:+(Ce.score*10).toFixed(),bitrate:((Ce.bytesSent||0)-(((Ro=this.audioProducerToStatsMap.get(E))==null?void 0:Ro.bytesSent)||0))*8/7,packetsLostPercentage:Vo({packetsSent:(Ce.packetsSent||0)-(((ko=this.audioProducerToStatsMap.get(E))==null?void 0:ko.packetsSent)||0),packetsLost:(((Io=Ce.remoteData)==null?void 0:Io.packetsLost)||0)-(((Mo=(Ao=this.audioProducerToStatsMap.get(E))==null?void 0:Ao.remoteData)==null?void 0:Mo.packetsLost)||0)}),jitter:((Do=Ce.remoteData)==null?void 0:Do.jitter)||0,isScreenShare:this.screenShareProducers.has(E)}),this.audioProducerToStatsMap.set(E,Ce)}}),f.forEach(M=>{const E=h.find(B=>B.id===M.localCandidateId?(M.localCandidateId=B.id,B):null),R=p.find(B=>B.id===M.remoteCandidateId?(M.remoteCandidateId=B.id,B):null);E&&(M.localCandidateType=E.type,M.localCandidateAddress=E.address,M.localCandidatePort=E.port,M.localCandidateProtocol=E.protocol,M.localCandidateUrl=E.url,M.localCandidateNetworkType=E.networkType,M.localCandidateRelatedAddress=E.relatedAddress,M.localCandidateRelatedPort=E.relatedPort),R&&(M.remoteCandidateType=R.type,M.remoteCandidateAddress=R.address,M.remoteCandidatePort=R.port,M.remoteCandidateProtocol=R.protocol,M.remoteCandidateUrl=R.url)}),d.candidatePair&&(d.transport?(d.transport.bytesReceived=d.candidatePair.bytesReceived,d.transport.bytesSent=d.candidatePair.bytesSent,d.transport.totalRoundTripTime=d.candidatePair.totalRoundTripTime,d.transport.availableOutgoingBitrate=d.candidatePair.availableOutgoingBitrate,d.transport.roundTripTime=d.candidatePair.currentRoundTripTime):d.transport={bytesReceived:d.candidatePair.bytesReceived,bytesSent:d.candidatePair.bytesSent,totalRoundTripTime:d.candidatePair.totalRoundTripTime,availableOutgoingBitrate:d.candidatePair.availableOutgoingBitrate,roundTripTime:d.candidatePair.currentRoundTripTime}),d.transport&&(d.transport.candidatePairs=f),d.transport&&!d.transport.roundTripTime){let M=0,E=0;d.remoteInboundRtp.forEach((R,B)=>{R.roundTripTime&&R.roundTripTime>M&&(M=R.roundTripTime,E=R.totalRoundTripTime)}),d.transport.roundTripTime=M,d.transport.totalRoundTripTime=E}if(T.size>0)try{this.observer.emit("consumer_score",T)}catch(M){}if(v.size>0)try{this.observer.emit("producer_score",v)}catch(M){}return d}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((n,i)=>{const a=this.producerMap.get(i),o=a.track.getSettings(),d=n.outboundVideoRtpId.map(h=>{const p=e.outboundVideoRtp.get(h);return p.frameHeight||(p.frameHeight=o.height,p.frameWidth=o.width,p.framesPerSecond=o.frameRate),p}),u={producerId:i,appData:a.appData,videoStats:d,audioStats:n.outboundAudioRtpId.map(h=>e.outboundAudioRtp.get(h))};r.push(u)})}catch(n){console.error("getProducersReport: ",n,e)}return r}getConsumerStatsFromParsedConsumerStats(e,r,n){let i;try{const{peerId:a,producerId:o,appData:d}=this.consumerPeerIdMap.get(n),u=r==null?void 0:r.inboundVideoRtpId.map(h=>{const f=this.consumerMap.get(n).track.getSettings(),v=e.inboundVideoRtp.get(h);return v.frameHeight||(v.frameHeight=f.height,v.frameWidth=f.width,v.framesPerSecond=f.frameRate),v});i={consumerId:n,peerId:a,producerId:o,appData:d,videoStats:u,audioStats:r==null?void 0:r.inboundAudioRtpId.map(h=>e.inboundAudioRtp.get(h))}}catch(a){console.error("getConsumerStatsFromParsedConsumerStats: ",a,e)}return i}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((n,i)=>{r.push(this.getConsumerStatsFromParsedConsumerStats(e,n,i))})}catch(n){console.error("getConsumerStatsFromReport: ",n,e)}return r}}class Ty extends Ah{}function jo(s,t,e,r){if(s!=null&&s.logger&&s.logger.error("Callstats::handleError",{error:r}),typeof e=="function"&&r instanceof t)e.call(null,r,s);else throw r}function Mh(s,t,e){const r=s.value;return s.value=function(...n){try{const i=r.apply(this,n);return i&&i instanceof Promise?i.catch(a=>{jo(this,t,e,a)}):i}catch(i){jo(this,t,e,i)}return null},s}const te=(s,t)=>(e,r,n)=>{const i=n.value;return n.value=function(...a){try{const o=i.apply(this,a);return o&&o instanceof Promise?o.catch(d=>{jo(this,s,t,d)}):o}catch(o){jo(this,s,t,o)}return null},n},_y=(s,t)=>(e,r,n)=>{if(n)return Mh(n,s,t);for(const i of Reflect.ownKeys(e.prototype).filter(a=>a!=="constructor")){const a=Object.getOwnPropertyDescriptor(e.prototype,i);a.value instanceof Function&&Object.defineProperty(e.prototype,i,Mh(a,s,t))}};var Z=globalThis&&globalThis.__decorate||function(s,t,e,r){var n=arguments.length,i=n<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(s,t,e,r);else for(var o=s.length-1;o>=0;o--)(a=s[o])&&(i=(n<3?a(i):n>3?a(t,e,i):a(t,e))||i);return n>3&&i&&Object.defineProperty(t,e,i),i};const ee=console;let z=class extends de{constructor(e="https://api.testingv3.dyte.in",r="Blink",n=ta.PROD,i,a,o,d){super();m(this,"observer");m(this,"eventHandler");m(this,"measurements");m(this,"producingTransport");m(this,"consumingTransport");m(this,"producers",new Map);m(this,"consumers",new Map);m(this,"iceServers");m(this,"connectionInfoPromise");m(this,"pingStatsTimeout");m(this,"logger");m(this,"env");m(this,"apiHostnames");m(this,"peerId");m(this,"consumerSharedMediaStatesMap",new Map);m(this,"currentUserMediaStates",{});switch(this.env=n,this.apiHostnames=d,this.logger=a,this.peerId=o,this.eventHandler=new ny({logger:a,peerId:o,apiHostnames:d}),this.logger.debug("callStats::engineName: ",{engineName:r}),r){case"Blink":this.measurements=new yy;break;case"Gecko":this.measurements=new Ah;break;case"WebKit":this.measurements=new Ty;break;default:throw Error(`Unknown engineName! ${r}`)}this.measurements.callStatsInstance=this,this.registerProducer=this.registerProducer.bind(this),this.registerConsumer=this.registerConsumer.bind(this),this.observer=new de,this.measurements.observer.on("consumer_score",u=>{a.debug(`callStats::consumer_score ${[...u.entries()]}`),this.eventHandler.emit("consumer_score",u)}),this.measurements.observer.on("producer_score",u=>{a.debug(`callStats::producer_score ${[...u.entries()]}`),this.eventHandler.emit("producer_score",u)})}registerIceServers(e){this.iceServers=e}registerConsumer(e){var r;this.consumerSharedMediaStatesMap.has(e.id)||this.consumerSharedMediaStatesMap.set(e.id,{}),this.consumers.set(e.id,e),this.measurements.registerConsumer(e),this.logger.debug("callStats::registerConsumer",{consumerId:e.id,consumerkind:e.kind,isScreenShare:!!((r=e.appData)!=null&&r.screenShare)}),e.observer.on("close",this.deRegisterConsumer.bind(this,e))}registerProducer(e){var r;this.producers.set(e.id,e),this.measurements.registerProducer(e),this.logger.debug("callStats::registerProducer",{producerId:e.id,producerKind:e.kind,isScreenShare:!!((r=e.appData)!=null&&r.screenShare)}),e.observer.on("close",this.deRegisterProducer.bind(this,e))}sendConsumerSharedMediaStateEvent(e,r){this.consumerSharedMediaStatesMap.has(e)||this.consumerSharedMediaStatesMap.set(e,{});const n=this.consumerSharedMediaStatesMap.get(e);this.consumerSharedMediaStatesMap.set(e,Object.assign(n,r))}registerProducingTransport(e){var n;this.producingTransport=e,e.observer.on("close",this.disconnectProducingTransport.bind(this,e)),e.observer.on("disconnect",this.disconnectProducingTransport.bind(this,e)),Array.from(((n=e._producers)==null?void 0:n.values())||[]).forEach(i=>{this.registerProducer(i)}),e.observer.on("newproducer",this.registerProducer)}registerConsumingTransport(e){var n;this.consumingTransport=e,e.observer.on("close",this.disconnectConsumingTransport.bind(this,e)),e.observer.on("disconnect",this.disconnectConsumingTransport.bind(this,e)),Array.from(((n=e._consumers)==null?void 0:n.values())||[]).forEach(i=>{this.registerConsumer(i)}),e.observer.on("newconsumer",this.registerConsumer)}deRegisterConsumer(e){this.consumers.delete(e.id)}deRegisterProducer(e){var r;this.producers.delete(e.id),this.logger.debug("callStats::deRegisterProducer",{producerId:e.id,producerKind:e.kind,isScreenShare:!!((r=e.appData)!=null&&r.screenShare)})}disconnectConsumingTransport(){this.consumingTransport=void 0}disconnectProducingTransport(){this.producingTransport=void 0}callEvent(e){this.eventHandler.callEvent(e)}sendPreCallTestBeginEvent(e=!1){this.connectionInfoPromise=this.measurements.getNetworkInfo(this.iceServers,e),this.eventHandler.callEvent({event:F.PRECALL_TEST_BEGIN,timestamp:new Date}),this.connectionInfoPromise&&this.connectionInfoPromise.then(r=>{this.eventHandler.callEvent({event:F.PRECALL_TEST_COMPLETE,metaData:{connectionInfo:r},timestamp:new Date})})}sendScreenShareToggleEvent(e,r){this.currentUserMediaStates.screen=e,this.eventHandler.callEvent({event:e?F.SCREENSHARE_STARTED:F.SCREENSHARE_STOPPED,metaData:{ssrc:r},timestamp:new Date})}sendScreenShareRequestedEvent(){this.eventHandler.callEvent({event:F.SCREENSHARE_START_REQUESTED,timestamp:new Date})}sendActiveSpeakerEvent(e){this.eventHandler.callEvent({event:F.DOMINANT_SPEAKER,metaData:{peerId:e},timestamp:new Date})}devices(e,r){this.eventHandler.callEvent({event:e===Yt.AUDIO&&F.AUDIO_DEVICES_UPDATES||e===Yt.VIDEO&&F.VIDEO_DEVICES_UPDATES||e===Yt.SPEAKER&&F.SPEAKER_DEVICES_UPDATES,metaData:{deviceList:r},timestamp:new Date})}selectedDevice(e,r){this.eventHandler.callEvent({event:e===Yt.AUDIO&&F.SELECTED_MICROHPONE_UPDATE||e===Yt.VIDEO&&F.SELECTED_CAMERA_UPDATE||e===Yt.SPEAKER&&F.SELECTED_SPEAKER_UPDATE,metaData:{device:r},timestamp:new Date})}mediaPermission(e,r){this.eventHandler.callEvent({event:F.MEDIA_PERMISSION,metaData:{deviceType:e,permission:r},timestamp:new Date})}mediaPlaybackFailed(e){this.eventHandler.callEvent({event:e===Yt.AUDIO&&F.AUDIO_PLAY_FAILED||e===Yt.VIDEO&&F.VIDEO_PLAY_FAILED,metaData:{deviceType:e},timestamp:new Date})}mediaTrackMuted(e){this.eventHandler.callEvent({event:e===Yt.AUDIO&&F.AUDIO_TRACK_MUTED||e===Yt.VIDEO&&F.VIDEO_TRACK_MUTED,metaData:{deviceType:e},timestamp:new Date})}tabChanged(e){this.eventHandler.callEvent({event:F.TAB_CHANGE,metaData:{isMeetingsTabActive:e},timestamp:new Date})}browserBackgrounded(){this.eventHandler.callEvent({event:F.BROWSER_BACKGROUNDED,timestamp:new Date})}browserForegrounded(){this.eventHandler.callEvent({event:F.BROWSER_FOREGROUNDED,timestamp:new Date})}legacySwitch(e){this.eventHandler.callEvent({event:F.LEGACY_SWITCH,metadata:{on:e},timestamp:new Date})}async getPreCallTestResults(){return this.connectionInfoPromise}sendCallJoinBeginEvent(e){e={...e,meetingEnv:this.env},e.deviceInfo={...e.deviceInfo,userAgent:navigator.userAgent,cpus:navigator.hardwareConcurrency,memory:navigator.deviceMemory},this.eventHandler.callEvent({event:F.CALL_JOIN_BEGIN,metaData:{peerMetaData:e},timestamp:new Date})}sendNetworkQualityTestBeginEvent(e){this.eventHandler.callEvent({event:F.NET_QUALITY_TEST_BEGIN,timestamp:new Date}),new Promise(async(n,i)=>{const a=[];try{for(const o of e)try{if(o.iceServers&&o.iceServers.length>0){const d=await this.measurements.getNetworkQuality(o.iceServers);a.push({...o,networkResults:d})}}catch(d){console.warn("Error handling ",d)}n({regionData:a})}catch(o){console.warn("Error in callstats, ",o),i(o)}}).then(n=>{this.eventHandler.callEvent({event:F.NET_QUALITY_TEST_END,timestamp:new Date,metaData:n})})}sendWebSocketConnectedEvent(){this.eventHandler.callEvent({event:F.WEBSOCKET_CONNECTED,timestamp:new Date})}sendTransportConnectedEvent(){this.eventHandler.callEvent({event:F.TRANSPORT_CONNECTED,timestamp:new Date})}sendAudioToggleEvent(e){this.currentUserMediaStates.audio=e;let r;e?r=F.AUDIO_ON:r=F.AUDIO_OFF,this.eventHandler.callEvent({event:r,timestamp:new Date})}sendVideoToggleEvent(e){this.currentUserMediaStates.video=e;let r;e?r=F.VIDEO_ON:r=F.VIDEO_OFF,this.eventHandler.callEvent({event:r,timestamp:new Date})}sendParticipantRoleToggleEvent(e){this.eventHandler.callEvent({event:F.PARTICIPANT_ROLE,timestamp:new Date,metaData:e})}startPingStats(e=7e3){this.sendPingStatsEvent(!1),this.pingStatsTimeout=setInterval(this.sendPingStatsEvent.bind(this),e)}stopPingStats(){clearInterval(this.pingStatsTimeout)}async sendPingStatsEvent(e=!0){let r,n;if(this.producingTransport&&(r=await this.measurements.getProcessedStats(this.producingTransport,!1,!0),!r||!(r!=null&&r.producerReport))){this.logger.debug("callStats::sendPingStatsEvent::staleProducingTransport",{disclaimer:"Stale producer? Regenerating Stream Maps!"});const a=await this.measurements.getProducersReport([...this.producers.values()]);r&&a?r.producerReport=a:(r=await this.measurements.getProcessedStats(this.producingTransport,!1,!0),(!r||!(r!=null&&r.producerReport))&&this.logger.debug("callStats::sendPingStatsEvent::noProducingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}if(this.consumingTransport&&(n=await this.measurements.getProcessedStats(this.consumingTransport,!0,!1),!n||!n.consumerReport)){this.logger.debug("callStats::sendPingStatsEvent::staleConsumingTransport",{disclaimer:"Stale consumer? Regenerating Stream Maps!"});const a=await this.measurements.getConsumersReport([...this.consumers.values()]);n&&a?n.consumerReport=a:(n=await this.measurements.getProcessedStats(this.consumingTransport,!0,!1),(!n||!n.consumerReport)&&this.logger.debug("callStats::sendPingStatsEvent::noConsumingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}const i={producingTransportStats:r?r==null?void 0:r.transportReport:void 0,consumingTransportStats:n?n==null?void 0:n.transportReport:void 0,producerStats:[].concat((r==null?void 0:r.producerReport)||[]).concat((n==null?void 0:n.producerReport)||[]),consumerStats:[].concat((n==null?void 0:n.consumerReport)||[]).concat((r==null?void 0:r.consumerReport)||[])};if(e&&i.producerStats.length===0&&i.consumerStats.length===0){await this.eventHandler.flush();return}this.eventHandler.callEvent({event:F.PING_STAT,metaData:i,timestamp:new Date})}sendIVSPlayerRebufferEvent(){this.eventHandler.callEvent({event:F.IVS_PLAYER_REBUFFERING,timestamp:new Date})}sendIVSPlayerAudioBlockEvent(){this.eventHandler.callEvent({event:F.IVS_PLAYER_AUDIO_BLOCKED,timestamp:new Date})}sendIVSPlayerPlaybackBlockedEvent(){this.eventHandler.callEvent({event:F.IVS_PLAYER_PLAYBACK_BLOCKED,timestamp:new Date})}sendIVSPlayerNetworkUnavailableEvent(){this.eventHandler.callEvent({event:F.IVS_PLAYER_NETWORK_UNAVAILABLE,timestamp:new Date})}sendIVSPlayerInitializedEvent(){this.eventHandler.callEvent({event:F.IVS_PLAYER_INITIALIZED,timestamp:new Date})}sendIVSPlayerWorkerErrorEvent(){this.eventHandler.callEvent({event:F.IVS_PLAYER_WORKER_ERROR,timestamp:new Date})}sendIVSPlayerErrorEvent(e){this.eventHandler.callEvent({event:F.IVS_PLAYER_ERROR,timestamp:new Date,metaData:e})}sendIVSPlayerRecoverableErrorEvent(e){this.eventHandler.callEvent({event:F.IVS_PLAYER_RECOVERABLE_ERROR,timestamp:new Date,metaData:e})}sendIVSPlayerAnalyticsEvent(e){this.eventHandler.callEvent({event:F.IVS_PLAYER_ANALYTICS_EVENT,timestamp:new Date,metaData:e})}sendIVSPlayerPlaybackRateChangedEvent(e){this.eventHandler.callEvent({event:F.IVS_PLAYER_PLAYBACK_RATE_CHANGED,timestamp:new Date,metaData:{updatedPlaybackRate:e}})}sendIVSPlayerQualityChanged(e){this.eventHandler.callEvent({event:F.IVS_PLAYER_QUALITY_CHANGED,timestamp:new Date,metaData:e})}sendPlayerLiveLatency(e){this.eventHandler.callEvent({event:F.LIVESTREAM_LATENCY,timestamp:new Date,metaData:{latency:e}})}sendDisconnectEvent(){this.eventHandler.callEvent({event:F.DISCONNECT,timestamp:new Date})}sendReconnectEvent(){this.eventHandler.callEvent({event:F.RECONNECT_ATTEMPT,timestamp:new Date})}};Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"registerIceServers",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"registerConsumer",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"registerProducer",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendConsumerSharedMediaStateEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"registerProducingTransport",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"registerConsumingTransport",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"deRegisterConsumer",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"deRegisterProducer",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"disconnectConsumingTransport",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"disconnectProducingTransport",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendPreCallTestBeginEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendScreenShareToggleEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendScreenShareRequestedEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendActiveSpeakerEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"devices",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"selectedDevice",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"mediaPermission",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"mediaPlaybackFailed",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"mediaTrackMuted",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"tabChanged",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"browserBackgrounded",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"browserForegrounded",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"legacySwitch",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"getPreCallTestResults",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendCallJoinBeginEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendNetworkQualityTestBeginEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendWebSocketConnectedEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendTransportConnectedEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendAudioToggleEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendVideoToggleEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendParticipantRoleToggleEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"startPingStats",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"stopPingStats",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendPingStatsEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendIVSPlayerRebufferEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendIVSPlayerAudioBlockEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendIVSPlayerPlaybackBlockedEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendIVSPlayerNetworkUnavailableEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendIVSPlayerInitializedEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendIVSPlayerWorkerErrorEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendIVSPlayerErrorEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendIVSPlayerRecoverableErrorEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendIVSPlayerAnalyticsEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendIVSPlayerPlaybackRateChangedEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendIVSPlayerQualityChanged",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendPlayerLiveLatency",null),z=Z([_y(TypeError,(s,t)=>ee.error(t,s))],z);const Sy=z;class Ey extends de{constructor(){super(...arguments);m(this,"stats");m(this,"roomURL");m(this,"peerId");m(this,"backend");m(this,"iceServers");m(this,"initialized",!1);m(this,"stalled",!1);m(this,"ipInformation");m(this,"logger")}async initialize({peerId:e,engineName:r,env:n=ta.PROD,iceServers:i,apiBase:a="https://api.cluster.dyte.in",flags:o,logger:d=console,apiHostnames:u,skipConnectivityChecks:h=!1}){var p,f,v;try{this.peerId=e,this.logger=d,this.ipInformation=await Ud.getIPDetails({peerId:e,apiHostnames:u}),this.backend=new Sy(a,r,n,o,d,e,u),this.iceServers=i,(p=this.backend)==null||p.registerIceServers(this.iceServers),this.initialized=!0,(v=(f=this.backend)==null?void 0:f.eventHandler)==null||v.emit("initialized",this.ipInformation),this.emit("initialized",this.ipInformation),this.startPreCallTest(h)}catch(T){this.logger.error("callStats::CallStatsIntegration: ",{error:T}),this.stallCallStats()}}setRoomName(e){this.roomURL=e}configureSendTransport(e){var r;(r=this.backend)==null||r.registerProducingTransport(e)}configureRecvTransport(e){var r;(r=this.backend)==null||r.registerConsumingTransport(e)}async candidateRegionalNetworkQualityTest(e){var r;try{(r=this.backend)==null||r.sendNetworkQualityTestBeginEvent(e)}catch(n){this.logger.error("callStats::sendNetworkQualityTestBeginEvent",{error:{reason:n.reason}})}}async roomJoined(e){var r,n;(r=this.backend)==null||r.sendCallJoinBeginEvent(e),this.backend,(n=this.backend)==null||n.startPingStats()}audioOff(){var e;(e=this.backend)==null||e.sendAudioToggleEvent(!1)}audioOn(){var e;(e=this.backend)==null||e.sendAudioToggleEvent(!0)}videoOff(){var e;(e=this.backend)==null||e.sendVideoToggleEvent(!1)}videoOn(){var e;(e=this.backend)==null||e.sendVideoToggleEvent(!0)}callEnded(){var e,r;(e=this.backend)==null||e.stopPingStats(),(r=this.backend)==null||r.sendDisconnectEvent()}screenShareStart(e){var r;(r=this.backend)==null||r.sendScreenShareToggleEvent(!0,e)}consumerSharedMediaState(e,r){var n;(n=this.backend)==null||n.sendConsumerSharedMediaStateEvent(e,r)}screenShareStop(e){var r;(r=this.backend)==null||r.sendScreenShareToggleEvent(!1,e)}screenShareRequested(){var e;(e=this.backend)==null||e.sendScreenShareRequestedEvent()}activeSpeaker(e){var r;e===this.peerId&&((r=this.backend)==null||r.sendActiveSpeakerEvent(e))}devices(e,r){var n;(n=this.backend)==null||n.devices(e,r)}selectedDevice(e,r){var n;(n=this.backend)==null||n.selectedDevice(e,r)}mediaPermission(e,r){var n;(n=this.backend)==null||n.mediaPermission(e,r)}mediaPlaybackFailed(e){var r;(r=this.backend)==null||r.mediaPlaybackFailed(e)}mediaTrackMuted(e){var r;(r=this.backend)==null||r.mediaTrackMuted(e)}tabChanged(e=!1){var r;(r=this.backend)==null||r.tabChanged(e)}browserBackgrounded(){var e;(e=this.backend)==null||e.browserBackgrounded()}browserForegrounded(){var e;(e=this.backend)==null||e.browserForegrounded()}legacySwitch(e){var r;(r=this.backend)==null||r.legacySwitch(e)}async startPreCallTest(e=!1){var r;(r=this.backend)==null||r.sendPreCallTestBeginEvent(e)}onPreCallTestResults(e){var r;return(r=this.backend)==null||r.eventHandler.once("precall_end",e),e}onReceivingConsumerAudioStatus(e){var r;(r=this.backend)==null||r.eventHandler.on("consumer_audio_status",e)}onReceivingConsumerVideoStatus(e){var r;(r=this.backend)==null||r.eventHandler.on("consumer_video_status",e)}onReceivingProducerAudioStatus(e){var r;(r=this.backend)==null||r.eventHandler.on("producer_audio_status",e)}onReceivingProducerVideoStatus(e){var r;(r=this.backend)==null||r.eventHandler.on("producer_video_status",e)}onReceivingProducingTransportStatus(e){var r;(r=this.backend)==null||r.eventHandler.on("producing_transport_status",e)}onReceivingConsumingTransportStatus(e){var r;(r=this.backend)==null||r.eventHandler.on("consuming_transport_status",e)}onProducerScore(e){var r;(r=this.backend)==null||r.eventHandler.on("producer_score",e)}onConsumerScore(e){var r;(r=this.backend)==null||r.eventHandler.on("consumer_score",e)}onSafeInitialization(e){if(this.initialized)e(this.ipInformation,!1);else if(!this.stalled){const r=n=>{e(n,!0)};return this.once("initialized",r),r}return()=>{}}removeInitializationListener(e){this.removeListener("initialized",e)}stallCallStats(){this.stalled=!0,this.removeAllListeners("initialized")}ivsPlayerEvent(e,r){var n,i,a,o,d,u,h,p,f,v,T;switch(e){case"PlayerRebuffering":(n=this.backend)==null||n.sendIVSPlayerRebufferEvent();break;case"PlayerAudioBlocked":(i=this.backend)==null||i.sendIVSPlayerAudioBlockEvent();break;case"PlayerPlaybackBlocked":(a=this.backend)==null||a.sendIVSPlayerPlaybackBlockedEvent();break;case"PlayerNetworkUnavailable":(o=this.backend)==null||o.sendIVSPlayerNetworkUnavailableEvent();break;case"PlayerInitialized":(d=this.backend)==null||d.sendIVSPlayerInitializedEvent();break;case"PlayerWorkerError":(u=this.backend)==null||u.sendIVSPlayerWorkerErrorEvent();break;case"PlayerError":(h=this.backend)==null||h.sendIVSPlayerErrorEvent(r);break;case"PlayerRecoverableError":(p=this.backend)==null||p.sendIVSPlayerRecoverableErrorEvent(r);break;case"PlayerAnalyticsEvent":(f=this.backend)==null||f.sendIVSPlayerAnalyticsEvent(r);break;case"PlayerPlaybackRateChanged":(v=this.backend)==null||v.sendIVSPlayerPlaybackRateChangedEvent(r);break;case"PlayerQualityChanged":(T=this.backend)==null||T.sendIVSPlayerQualityChanged(r);break}}livestreamLatency(e){var r;(r=this.backend)==null||r.sendPlayerLiveLatency(e)}}const U=new Ey;U.setMaxListeners(30);function wy(s){const{length:t}=this,e=s>=0?s:t+s;return e<0||e>=t?void 0:this[e]}Array.prototype.at||Object.assign(Array.prototype,{at:wy});function Cy(s){const{length:t}=this,e=s>=0?s:t+s;return e<0||e>=t?void 0:this[e]}String.prototype.at||Object.assign(String.prototype,{at:Cy});var Go,by=new Uint8Array(16);function Py(){if(!Go&&(Go=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!Go))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Go(by)}const Ry=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function Vd(s){return typeof s=="string"&&Ry.test(s)}for(var dt=[],$d=0;$d<256;++$d)dt.push(($d+256).toString(16).substr(1));function ky(s){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(dt[s[t+0]]+dt[s[t+1]]+dt[s[t+2]]+dt[s[t+3]]+"-"+dt[s[t+4]]+dt[s[t+5]]+"-"+dt[s[t+6]]+dt[s[t+7]]+"-"+dt[s[t+8]]+dt[s[t+9]]+"-"+dt[s[t+10]]+dt[s[t+11]]+dt[s[t+12]]+dt[s[t+13]]+dt[s[t+14]]+dt[s[t+15]]).toLowerCase();if(!Vd(e))throw TypeError("Stringified UUID is invalid");return e}function Xs(s,t,e){s=s||{};var r=s.random||(s.rng||Py)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){e=e||0;for(var n=0;n<16;++n)t[e+n]=r[n];return t}return ky(r)}var Xe;(function(s){s.GroupCall="GROUP_CALL",s.Webinar="WEBINAR",s.AudioRoom="AUDIO_ROOM",s.Livestream="LIVESTREAM",s.Chat="CHAT"})(Xe||(Xe={}));var Jo;(function(s){s.Skip="SKIP",s.OnPrivilegedUserEntry="ON_PRIVILEGED_USER_ENTRY",s.SkipOnAccept="SKIP_ON_ACCEPT"})(Jo||(Jo={}));var H;(function(s){s.Allowed="ALLOWED",s.NotAllowed="NOT_ALLOWED",s.CanRequest="CAN_REQUEST"})(H||(H={}));var Wo;(function(s){s.Allowed="ALLOWED",s.NotAllowed="NOT_ALLOWED"})(Wo||(Wo={}));var Dh;(function(s){s.FULL_ACCESS="FULL_ACCESS",s.VIEW_ONLY="VIEW_ONLY"})(Dh||(Dh={}));var Ko;(function(s){s.skip="SKIP",s.onAccept="ON_ACCEPT",s.skipOnPrivilegedUserEntry="SKIP_ON_PRIVILEGED_USER_ENTRY",s.skipOnAccept="SKIP_ON_ACCEPT"})(Ko||(Ko={}));var Jn;(function(s){s.none="NONE",s.recorder="RECORDER",s.livestreamer="LIVESTREAMER"})(Jn||(Jn={}));var Bd;(function(s){s.groupCall="GROUP_CALL",s.webinar="WEBINAR",s.audioRoom="AUDIO_ROOM",s.livestream="LIVESTREAM",s.chat="CHAT"})(Bd||(Bd={}));var Oh;(function(s){s.SKIP="skip",s.SKIP_ON_PRIVILEGED_USER_ENTRY="skipOnPrivilegedUserEntry",s.ON_ACCEPT="skipOnAccept",s.SKIP_ON_ACCEPT="skipOnAccept"})(Oh||(Oh={})),Bd.groupCall,Ko.skipOnAccept,Jn.none;var Hd={},Iy={get exports(){return Hd},set exports(s){Hd=s}},zo={},Ay={get exports(){return zo},set exports(s){zo=s}},Nh=function(t,e){return function(){for(var n=new Array(arguments.length),i=0;i{i.type==="candidate-pair"&&i.nominated===!0&&i.bytesSent>0&&(r=i)}),e.forEach(i=>{i.type==="candidate-pair"&&i.nominated===!0&&i.bytesReceived>0&&(n=i)}),r&&n)try{if(r.currentRoundTripTime&&n.currentRoundTripTime)return{rtt:r.currentRoundTripTime,backendRTT:n.currentRoundTripTime};const i=(n.lastPacketReceivedTimestamp-r.lastPacketSentTimestamp)/1e3;return{rtt:i,backendRTT:i}}catch(i){return}}close(){this.pc1.close(),this.pc2.close()}}class bh extends de{constructor(e){super();m(this,"call");m(this,"timeOut");this.call=new xr(e)}start(e=1e4){this.call.establishConnection(),this.timeOut=setTimeout(this.testFailed.bind(this),e)}testComplete(e){clearTimeout(this.timeOut),this.call.close(),this.emit("done",e)}testFailed(e){this.call.close(),this.emit("failed",e)}}const uy=8,hy=1/1e3;class py extends bh{constructor(e){super(e);m(this,"senderChannel");m(this,"recieveChannel");m(this,"startTime");m(this,"lastBitrateMeasureTime");m(this,"sentPayloadBytes",0);m(this,"recievedPayloadBytes",0);m(this,"lastReceivedPayloadBytes",0);m(this,"stopSending",!1);m(this,"testProgress",0);m(this,"samplePacket","");m(this,"finalBitrateSum",0);m(this,"bitRateSampels",0);m(this,"maxNumberOfPacketsToSend",0);m(this,"bytesToKeepBuffered",0);m(this,"testDurationSeconds",5);this.call.setIceCandidateFilter(xr.isNotHostCandidate),this.senderChannel=this.call.pc1.createDataChannel(null);for(let r=0;r<262144;r+=1)this.samplePacket+="h";this.maxNumberOfPacketsToSend=1,this.bytesToKeepBuffered=1024*this.maxNumberOfPacketsToSend,this.testDurationSeconds=4,this.senderChannel.addEventListener("open",this.sendingStep.bind(this)),this.call.pc2.addEventListener("datachannel",this.onRecieverChannel.bind(this))}sendingStep(){const e=new Date;this.startTime||(this.startTime=e,this.lastBitrateMeasureTime=e);for(let n=0;n!==this.maxNumberOfPacketsToSend&&!(this.senderChannel.bufferedAmount>=this.bytesToKeepBuffered);n+=1){this.sentPayloadBytes+=this.samplePacket.length;try{this.senderChannel.send(this.samplePacket)}catch(i){}}const r=e.getTime()-this.startTime.getTime();r>=1e3*this.testDurationSeconds?(this.stopSending=!0,this.testProgress=100):(this.testProgress=r/(10*this.testDurationSeconds),setTimeout(this.sendingStep.bind(this),1))}onMessageRecieved(e){this.recievedPayloadBytes+=e.data.length;const r=new Date,n=r.getTime()-this.lastBitrateMeasureTime.getTime();if(n>=1e3){const a=(this.recievedPayloadBytes-this.lastReceivedPayloadBytes)*uy/(n/1e3);this.finalBitrateSum+=a,this.bitRateSampels+=1,this.lastReceivedPayloadBytes=this.recievedPayloadBytes,this.lastBitrateMeasureTime=r}if(this.stopSending&&this.sentPayloadBytes===this.recievedPayloadBytes){const i=this.finalBitrateSum/this.bitRateSampels;this.testComplete({throughput:Math.round(i*hy)})}}testComplete(e){this.call.getRoundTripTime().then(({rtt:r,backendRTT:n})=>super.testComplete({RTT:r,backendRTT:n,throughput:e.throughput}))}onRecieverChannel(e){this.recieveChannel=e.channel,this.recieveChannel.addEventListener("message",this.onMessageRecieved.bind(this))}}class xd extends bh{constructor(e,r=xr.noFilter){super(e);m(this,"ch1");m(this,"ch2");this.call.setIceCandidateFilter(r);const n=this.call.pc1.createDataChannel(null);this.ch1=n,n.addEventListener("open",()=>{n.send("hello")}),n.addEventListener("message",this.onCh1Recieve.bind(this)),this.call.pc2.addEventListener("datachannel",this.dataChannelHandler.bind(this))}onCh1Recieve(e){e.data!=="world"?this.hangup("Invalid data transmitted."):this.testComplete({connectivity:!0})}onCh2Recieve(e){if(e.data!=="hello")this.hangup("Invalid data transmitted.");else try{this.ch2.send("world")}catch(r){}}dataChannelHandler(e){const r=e.channel;this.ch2=r,r.addEventListener("message",this.onCh2Recieve.bind(this))}hangup(e){this.testFailed(e)}}class my extends xd{constructor(t){super(t,xr.isHost)}}class fy extends xd{constructor(t){super(t,xr.isRelay)}}class gy extends xd{constructor(t){super(t,xr.isReflexive)}}class vy{constructor(){m(this,"ipInformation",null)}async getIPDetails({peerId:t,apiHostnames:e}){var r;if(!this.ipInformation){try{const i=`https://${e.location}`,o=await(await fetch(i)).json();if(((r=o.loc)==null?void 0:r.length)>5)return this.ipInformation=o,o;throw Error("Insufficient data")}catch(i){}const n=await fetch(`https://${e.locationLegacy}/?token=3c493932b0624c&peerId=${t}`,{method:"POST"});this.ipInformation=await n.json()}return this.ipInformation}resetCache(){this.ipInformation=null}}const Ud=new vy,Ph=[{urls:"turn:turn.dyte.in:443?transport=tcp",username:"dyte",credential:"dytein",credentialType:"password"},{urls:"turn:turn.dyte.in:3478?transport=udp",username:"dyte",credential:"dytein",credentialType:"password"}];function Rh(s){const[t,e]=s.split(",");return{coords:{latitude:Number(t),longitude:Number(e)}}}class kh{constructor(){m(this,"transport");m(this,"candidatePair");m(this,"outboundVideoRtp",new Map);m(this,"inboundVideoRtp",new Map);m(this,"outboundAudioRtp",new Map);m(this,"inboundAudioRtp",new Map);m(this,"remoteInboundRtp",new Map);m(this,"producerStreamMap",new Map);m(this,"consumerStreamMap",new Map);m(this,"staleProducerStreamMap",!1);m(this,"staleConsumerStreamMap",!1)}}class Ih extends de{constructor(){super();m(this,"observer");m(this,"outboundProducerMap",new Map);m(this,"inboundConsumerMap",new Map);m(this,"consumerPeerIdMap",new Map);m(this,"pausedConsumerMap",new Map);m(this,"pausedProducerMap",new Map);m(this,"overallProducingTransportsStatsMap",{});m(this,"overallConsumingTransportsStatsMap",{});m(this,"overallConsumersStatsMap",{});m(this,"overallProducersStatsMap",{});m(this,"videoProducerToStatsMap",new Map);m(this,"audioProducerToStatsMap",new Map);m(this,"videoConsumerToStatsMap",new Map);m(this,"audioConsumerToStatsMap",new Map);m(this,"consumerIdsWithFreezedVideo",new Set);m(this,"consumerIdsWithFreezedAudio",new Set);m(this,"producerIdsWithFreezedVideo",new Set);m(this,"producerIdsWithFreezedAudio",new Set);m(this,"freezedProducingTransportIds",new Set);m(this,"freezedConsumingTransportIds",new Set);m(this,"screenShareProducers",new Set);m(this,"screenShareConsumers",new Set);m(this,"ipDetails");m(this,"callStatsInstance");this.observer=new de}async registerProducer(e){await this.generateProducerStreamMap(e),e.observer.on("close",this.deregisterProducer.bind(this,e)),e.observer.on("pause",this.pauseProducer.bind(this,e.id)),e.observer.on("resume",this.resumeProducer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareProducers.add(e.id)}pauseProducer(e){this.pausedProducerMap.set(e,{lastReportCalculated:!1})}resumeProducer(e){this.pausedProducerMap.delete(e)}processInboundConsumerVideoStats(e,r,n){var a,o;const i=((o=(a=this==null?void 0:this.callStatsInstance)==null?void 0:a.consumerSharedMediaStatesMap)==null?void 0:o.get(e))||{};r.totalVideoPacketsReceived===n.packetsReceived?(this.consumerIdsWithFreezedVideo.add(e),this.callStatsInstance&&i.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","pause",e))):(r.totalVideoPacketsReceived=n.packetsReceived,this.consumerIdsWithFreezedVideo.has(e)&&(this.consumerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&i.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","resume",e))))}processInboundConsumerAudioStats(e,r,n){var a,o;const i=((o=(a=this==null?void 0:this.callStatsInstance)==null?void 0:a.consumerSharedMediaStatesMap)==null?void 0:o.get(e))||{};r.totalAudioPacketsReceived===n.packetsReceived?(this.consumerIdsWithFreezedAudio.add(e),this.callStatsInstance&&i.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","pause",e))):(r.totalAudioPacketsReceived=n.packetsReceived,this.consumerIdsWithFreezedAudio.has(e)&&(this.consumerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&i.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","resume",e))))}processOutboundProducerVideoStats(e,r,n){var a;const i=((a=this==null?void 0:this.callStatsInstance)==null?void 0:a.currentUserMediaStates)||{};r.totalVideoPacketsSent===n.packetsSent?(this.producerIdsWithFreezedVideo.add(e),this.callStatsInstance&&i.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","pause",e))):(r.totalVideoPacketsSent=n.packetsSent,this.producerIdsWithFreezedVideo.has(e)&&(this.producerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&i.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","resume",e))))}processOutboundProducerAudioStats(e,r,n){var a;const i=((a=this==null?void 0:this.callStatsInstance)==null?void 0:a.currentUserMediaStates)||{};r.totalAudioPacketsSent===n.packetsSent?(this.producerIdsWithFreezedAudio.add(e),this.callStatsInstance&&i.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","pause",e))):(r.totalAudioPacketsSent=n.packetsSent,this.producerIdsWithFreezedAudio.has(e)&&(this.producerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&i.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","resume",e))))}processProducingTransportStats(e,r,n){var h;const i=((h=this==null?void 0:this.callStatsInstance)==null?void 0:h.currentUserMediaStates)||{},{audio:a,video:o,screen:d}=i,u=a||o||d;r.totalPacketsSent===n.packetsSent?(this.freezedProducingTransportIds.add(e),this.callStatsInstance&&u&&(this.callStatsInstance.logger.debug("callStats::measurements::producingTransportFreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("producing_transport_status","pause",e))):(r.totalPacketsSent=n.packetsSent,this.freezedProducingTransportIds.has(e)&&(this.freezedProducingTransportIds.delete(e),this.callStatsInstance&&u&&(this.callStatsInstance.logger.debug("callStats::measurements::producingTransportDefreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("producing_transport_status","resume",e))))}processConsumingTransportStats(e,r,n){var o,d;const a=!!Array.from(((d=(o=this==null?void 0:this.callStatsInstance)==null?void 0:o.consumerSharedMediaStatesMap)==null?void 0:d.values())||[]).reduce((u,h)=>u||h.audio||h.video||h.screen,!1);r.totalPacketsReceived===n.packetsSent?(this.freezedConsumingTransportIds.add(e),this.callStatsInstance&&a&&(this.callStatsInstance.logger.debug("callStats::measurements::consumingTransportFreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("consuming_transport_status","pause",e))):(r.totalPacketsReceived=n.packetsSent,this.freezedConsumingTransportIds.has(e)&&(this.freezedConsumingTransportIds.delete(e),this.callStatsInstance&&a&&(this.callStatsInstance.logger.debug("callStats::measurements::consumingTransportDefreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("consuming_transport_status","resume",e))))}async registerConsumer(e){await this.generateConsumerStreamMap(e),this.consumerPeerIdMap.set(e.id,{producerId:e.producerId,peerId:e.appData.peerId,appData:e.appData}),e.observer.on("close",this.deregisterConsumer.bind(this,e)),e.observer.on("pause",this.pauseConsumer.bind(this,e.id)),e.observer.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)}pauseConsumer(e){this.pausedConsumerMap.set(e,{lastReportCalculated:!1})}resumeConsumer(e){this.pausedConsumerMap.delete(e)}async generateProducerStreamMap(e,r=!1){const n=await e.getStats(),i=r?this.getProducerStatsFromReport(this.parseRTCReport(n,["outbound-rtp","remote-inbound-rtp"],!1,e.id))[0]:void 0;for(const a of n.values())switch(a.type){case"outbound-rtp":{this.outboundProducerMap.set(a.id,e.id);break}}return i}async generateConsumerStreamMap(e,r=!1){const n=await e.getStats(),i=r?this.getConsumerStatsFromReport(this.parseRTCReport(n,["inbound-rtp"],!1,e.id))[0]:void 0;for(const a of n.values())switch(a.type){case"inbound-rtp":{this.inboundConsumerMap.set(a.id,e.id);break}}return i}deregisterProducer(e){this.outboundProducerMap.forEach((r,n)=>{r===e.id&&this.outboundProducerMap.delete(n)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.inboundConsumerMap.forEach((r,n)=>{r===e.id&&this.inboundConsumerMap.delete(n)}),this.consumerPeerIdMap.delete(e.id),this.pausedConsumerMap.delete(e.id),this.screenShareConsumers.delete(e.id)}getIceCandidateStats(e){var r;return{id:e.id,type:e.candidateType||e.type,address:e.address,port:e.port,url:e.url,protocol:(r=e.relayProtocol)!=null?r:e.protocol,networkType:e.networkType,relatedAddress:e.relatedAddress,relatedPort:e.relatedPort}}getWorkingSimulcastVideoStats(e){return e.find(n=>{const i=n.framesEncoded>0,a=n.packetsSent>0,o=n.frameWidth&&n.frameHeight;return i&&a&&!!o})||e[e.length-1]}parseRTCReport(e,r=[],n=!1,i=void 0,a=void 0){var P,k,I,x,V,O,W,Q,oe,ve,Mt,Fe,Dt;const o=e,d=new kh,u=r.length?new Set(r):void 0,h=[],p=[],f=[],v=new Map,T=new Map;for(const M of o.values()){if(u){if(u.size===0)break;if(u.has(M.type))n&&u.delete(M.type);else continue}switch(M.type){case"local-candidate":{h.push(this.getIceCandidateStats(M));break}case"remote-candidate":{p.push(this.getIceCandidateStats(M));break}case"candidate-pair":{const{nominated:E}=M,{selected:R}=M,B=M,xe={nominated:E!=null?E:R,currentRoundTripTime:B.currentRoundTripTime,totalRoundTripTime:B.totalRoundTripTime,bytesReceived:B.bytesReceived,bytesSent:B.bytesSent,availableOutgoingBitrate:B.availableOutgoingBitrate,lastPacketReceivedTimestamp:B.lastPacketReceivedTimestamp,lastPacketSentTimestamp:B.lastPacketSentTimestamp,localCandidateId:B.localCandidateId,remoteCandidateId:B.remoteCandidateId,bytesDiscardedOnSend:B.bytesDiscardedOnSend,packetsSent:B.packetsSent,packetsReceived:B.packetsReceived,packetsDiscardedOnSend:B.packetsDiscardedOnSend};f.push(xe),(M.nominated===!0||M.selected===!0)&&(d.candidatePair=xe);break}case"transport":{const E=M;a&&(a.producing&&(this.overallProducingTransportsStatsMap[a.id]||(this.overallProducingTransportsStatsMap[a.id]={totalPacketsSent:0})),a.consuming&&(this.overallConsumingTransportsStatsMap[a.id]||(this.overallConsumingTransportsStatsMap[a.id]={totalPacketsReceived:0})));const R={bytesReceived:E.bytesReceived,bytesSent:E.bytesSent,packetsSent:E.packetsSent,packetsReceived:E.packetsReceived,dtlsCipher:E.dtlsCipher,dtlsState:E.dtlsState,iceRole:E.iceRole};if(d.transport=R,a){if(a.producing){const B=this.overallProducingTransportsStatsMap[a.id];this.processProducingTransportStats(a.id,B,R)}if(a.consuming){const B=this.overallConsumingTransportsStatsMap[a.id];this.processConsumingTransportStats(a.id,B,R)}}break}case"remote-inbound-rtp":{const E=M,R={jitter:E.jitter,fractionLost:E.fractionLost,roundTripTime:E.roundTripTime,roundTripTimeMeasurements:E.roundTripTimeMeasurements,totalRoundTripTime:E.totalRoundTripTime,packetsLost:E.packetsLost};d.remoteInboundRtp.set(E.localId,R);break}case"outbound-rtp":{const E=M,R=i||this.outboundProducerMap.get(M.id),B=this.pausedProducerMap.get(R);if(B){if(B.lastReportCalculated===!0)break;this.pausedProducerMap.set(R,{lastReportCalculated:!0})}this.overallProducersStatsMap[R]||(this.overallProducersStatsMap[R]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const xe=this.overallProducersStatsMap[R];if(["video","audio"].includes(E.mediaType)||["video","audio"].includes(E.kind)){if(!this.outboundProducerMap.has(M.id)){d.staleProducerStreamMap=!0;break}const Qe=this.callStatsInstance.producers.get(R);if(((P=Qe==null?void 0:Qe.track)==null?void 0:P.readyState)==="ended")break;d.producerStreamMap.has(R)||d.producerStreamMap.set(R,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const G={bytesSent:E.bytesSent,packetsSent:E.packetsSent,nackCount:E.nackCount,ssrc:E.ssrc,mid:E.mid};if(E.mediaType==="video"||E.kind==="video"){if(E.decoderImplementation==="unknown")break;const A=E,rt={frameHeight:A.frameHeight,frameWidth:A.frameWidth,framesEncoded:A.framesEncoded,framesDropped:A.framesDropped,framesPerSecond:A.framesPerSecond,framesSent:A.framesSent,keyFramesEncoded:A.keyFramesEncoded,firCount:A.firCount,encoderImplementation:A.encoderImplementation,hugeFramesSent:A.hugeFramesSent,pliCount:A.pliCount,qpSum:A.qpSum,qualityLimitationDurations:A.qualityLimitationDurations,qualityLimitationReason:A.qualityLimitationReason,qualityLimitationResolutionChanges:A.qualityLimitationResolutionChanges,totalEncodeTime:A.targetBitrate,totalPacketSendDelay:A.totalPacketSendDelay,retransmittedBytesSent:A.retransmittedBytesSent,retransmittedPacketsSent:A.retransmittedPacketsSent,...G};d.outboundVideoRtp.set(M.id,rt),d.producerStreamMap.get(R).outboundVideoRtpId.push(M.id),this.processOutboundProducerVideoStats(R,xe,rt)}else if(E.mediaType==="audio"||E.kind==="audio"){const A=E,rt={retransmittedBytesSent:A.retransmittedBytesSent,retransmittedPacketsSent:A.retransmittedPacketsSent,...G};d.outboundAudioRtp.set(M.id,rt),d.producerStreamMap.get(R).outboundAudioRtpId.push(M.id),this.processOutboundProducerAudioStats(R,xe,rt)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${E.mediaType} kind: ${E.kind}`);break}case"inbound-rtp":{const E=M,R=i||this.inboundConsumerMap.get(M.id),B=this.pausedConsumerMap.get(R);if(B){if(B.lastReportCalculated===!0)break;this.pausedConsumerMap.set(R,{lastReportCalculated:!0})}if(E.ssrc===1234)break;this.overallConsumersStatsMap[R]||(this.overallConsumersStatsMap[R]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const xe=this.overallConsumersStatsMap[R];if(["video","audio"].includes(E.mediaType)||["video","audio"].includes(E.kind)){if(!this.inboundConsumerMap.has(M.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(R)||d.consumerStreamMap.set(R,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const Qe={bytesReceived:E.bytesReceived,packetsReceived:E.packetsReceived,packetsLost:E.packetsLost,jitter:E.jitter,nackCount:E.nackCount,jitterBufferDelay:E.jitterBufferDelay,jitterBufferEmittedCount:E.jitterBufferEmittedCount,lastPacketReceivedTimestamp:E.lastPacketReceivedTimestamp,ssrc:E.ssrc,mid:E.mid};if(E.mediaType==="video"||E.kind==="video"){if(E.decoderImplementation==="unknown")break;const G=E,A={frameHeight:G.frameHeight,frameWidth:G.frameWidth,framesDecoded:G.framesDecoded,framesDropped:G.framesDropped,framesPerSecond:G.framesPerSecond,framesReceived:G.framesReceived,keyFramesDecoded:G.keyFramesDecoded,firCount:G.firCount,decoderImplementation:G.decoderImplementation,pliCount:G.pliCount,totalProcessingDelay:G.totalProcessingDelay,...Qe};A.score=Ch({frameWidth:A.frameWidth||0,framesDecoded:(A.framesDecoded||0)-(((k=this.videoConsumerToStatsMap.get(R))==null?void 0:k.framesDecoded)||0),framesPerSecond:A.framesPerSecond||0,packetsLost:(A.packetsLost||0)-(((I=this.videoConsumerToStatsMap.get(R))==null?void 0:I.packetsLost)||0),packetsReceived:(A.packetsReceived||0)-(((x=this.videoConsumerToStatsMap.get(R))==null?void 0:x.packetsReceived)||0),jitter:A.jitter||0,isScreenShare:this.screenShareConsumers.has(R)}),T.set(R,{score:+(A.score*10).toFixed(),frameWidth:A.frameWidth||0,frameHeight:A.frameHeight||0,framesPerSecond:A.framesPerSecond||0,packetsLostPercentage:$o({packetsLost:(A.packetsLost||0)-(((V=this.videoConsumerToStatsMap.get(R))==null?void 0:V.packetsLost)||0),packetsReceived:(A.packetsReceived||0)-(((O=this.videoConsumerToStatsMap.get(R))==null?void 0:O.packetsReceived)||0)}),jitter:A.jitter||0,isScreenShare:this.screenShareConsumers.has(R),bitrate:((A.bytesReceived||0)-(((W=this.videoConsumerToStatsMap.get(R))==null?void 0:W.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(R,A),d.inboundVideoRtp.set(M.id,A),d.consumerStreamMap.get(R).inboundVideoRtpId.push(M.id),this.processInboundConsumerVideoStats(R,xe,A)}else if(E.mediaType==="audio"||E.kind==="audio"){const G=E,A={audioLevel:G.audioLevel,concealedSampels:G.concealedSampels,concealmentEvents:G.concealmentEvents,totalAudioEnergy:G.totalAudioEnergy,totalSamplesDuration:G.totalSamplesDuration,totalSamplesReceived:G.totalSamplesReceived,...Qe};A.score=wh({concealmentEvents:(A.concealmentEvents||0)-(((Q=this.audioConsumerToStatsMap.get(R))==null?void 0:Q.concealmentEvents)||0),packetsLost:(A.packetsLost||0)-(((oe=this.audioConsumerToStatsMap.get(R))==null?void 0:oe.packetsLost)||0),packetsReceived:(A.packetsReceived||0)-(((ve=this.audioConsumerToStatsMap.get(R))==null?void 0:ve.packetsReceived)||0),jitter:A.jitter||0}),T.set(R,{score:+(A.score*10).toFixed(),packetsLostPercentage:$o({packetsLost:(A.packetsLost||0)-(((Mt=this.audioConsumerToStatsMap.get(R))==null?void 0:Mt.packetsLost)||0),packetsReceived:(A.packetsReceived||0)-(((Fe=this.audioConsumerToStatsMap.get(R))==null?void 0:Fe.packetsReceived)||0)}),jitter:A.jitter||0,isScreenShare:this.screenShareConsumers.has(R),bitrate:((A.bytesReceived||0)-(((Dt=this.audioConsumerToStatsMap.get(R))==null?void 0:Dt.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(R,A),d.inboundAudioRtp.set(M.id,A),d.consumerStreamMap.get(R).inboundAudioRtpId.push(M.id),this.processInboundConsumerAudioStats(R,xe,A)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${E.mediaType} kind: ${E.kind}`);break}}}if(d.producerStreamMap.forEach((M,E)=>{var R,B,xe,Qe,G,A,rt,cs,yo,To,_o,So,Eo,wo,Co,bo,Po,Ro,ko,Io,Ao,Mo,Do;if(M.outboundVideoRtpId.length>0){const Ce=[];M.outboundVideoRtpId.forEach(Wu=>{Ce.push(d.outboundVideoRtp.get(Wu))});const ce=this.getWorkingSimulcastVideoStats(Ce);ce.score=Sh({frameWidth:ce.frameWidth||0,framesPerSecond:ce.framesPerSecond||0,jitter:((R=ce.remoteData)==null?void 0:R.jitter)||0,isScreenShare:this.screenShareProducers.has(E),packetsSent:(ce.packetsSent||0)-(((B=this.videoProducerToStatsMap.get(E))==null?void 0:B.packetsSent)||0),packetsLost:(((xe=ce.remoteData)==null?void 0:xe.packetsLost)||0)-(((G=(Qe=this.videoProducerToStatsMap.get(E))==null?void 0:Qe.remoteData)==null?void 0:G.packetsLost)||0),framesEncoded:(ce.framesEncoded||0)-(((A=this.videoProducerToStatsMap.get(E))==null?void 0:A.framesEncoded)||0)}),v.set(E,{score:+(ce.score*10).toFixed(),frameWidth:ce.frameWidth||0,frameHeight:ce.frameHeight||0,framesPerSecond:ce.framesPerSecond||0,jitter:((rt=ce.remoteData)==null?void 0:rt.jitter)||0,isScreenShare:this.screenShareProducers.has(E),packetsLostPercentage:Vo({packetsSent:(ce.packetsSent||0)-(((cs=this.videoProducerToStatsMap.get(E))==null?void 0:cs.packetsSent)||0),packetsLost:(((yo=ce.remoteData)==null?void 0:yo.packetsLost)||0)-(((_o=(To=this.videoProducerToStatsMap.get(E))==null?void 0:To.remoteData)==null?void 0:_o.packetsLost)||0)}),bitrate:((ce.bytesSent||0)-(((So=this.videoProducerToStatsMap.get(E))==null?void 0:So.bytesSent)||0))*8/7,cpuLimitations:ce.qualityLimitationReason==="cpu",bandwidthLimitations:ce.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(E,ce)}else if(M.outboundAudioRtpId.length>0){const Ce=d.outboundAudioRtp.get(M.outboundAudioRtpId[0]);Ce.score=_h({packetsSent:(Ce.packetsSent||0)-(((Eo=this.audioProducerToStatsMap.get(E))==null?void 0:Eo.packetsSent)||0),packetsLost:(((wo=Ce.remoteData)==null?void 0:wo.packetsLost)||0)-(((bo=(Co=this.audioProducerToStatsMap.get(E))==null?void 0:Co.remoteData)==null?void 0:bo.packetsLost)||0),jitter:((Po=Ce.remoteData)==null?void 0:Po.jitter)||0}),v.set(E,{score:+(Ce.score*10).toFixed(),bitrate:((Ce.bytesSent||0)-(((Ro=this.audioProducerToStatsMap.get(E))==null?void 0:Ro.bytesSent)||0))*8/7,packetsLostPercentage:Vo({packetsSent:(Ce.packetsSent||0)-(((ko=this.audioProducerToStatsMap.get(E))==null?void 0:ko.packetsSent)||0),packetsLost:(((Io=Ce.remoteData)==null?void 0:Io.packetsLost)||0)-(((Mo=(Ao=this.audioProducerToStatsMap.get(E))==null?void 0:Ao.remoteData)==null?void 0:Mo.packetsLost)||0)}),jitter:((Do=Ce.remoteData)==null?void 0:Do.jitter)||0,isScreenShare:this.screenShareProducers.has(E)}),this.audioProducerToStatsMap.set(E,Ce)}}),f.forEach(M=>{const E=h.find(B=>B.id===M.localCandidateId?(M.localCandidateId=B.id,B):null),R=p.find(B=>B.id===M.remoteCandidateId?(M.remoteCandidateId=B.id,B):null);E&&(M.localCandidateType=E.type,M.localCandidateAddress=E.address,M.localCandidatePort=E.port,M.localCandidateProtocol=E.protocol,M.localCandidateUrl=E.url,M.localCandidateNetworkType=E.networkType,M.localCandidateRelatedAddress=E.relatedAddress,M.localCandidateRelatedPort=E.relatedPort),R&&(M.remoteCandidateType=R.type,M.remoteCandidateAddress=R.address,M.remoteCandidatePort=R.port,M.remoteCandidateProtocol=R.protocol,M.remoteCandidateUrl=R.url)}),d.candidatePair&&(d.transport?(d.transport.totalRoundTripTime=d.candidatePair.totalRoundTripTime,d.transport.availableOutgoingBitrate=d.candidatePair.availableOutgoingBitrate,d.transport.roundTripTime=d.candidatePair.currentRoundTripTime):d.transport={bytesReceived:d.candidatePair.bytesReceived,bytesSent:d.candidatePair.bytesSent,totalRoundTripTime:d.candidatePair.totalRoundTripTime,availableOutgoingBitrate:d.candidatePair.availableOutgoingBitrate,roundTripTime:d.candidatePair.currentRoundTripTime}),d.transport&&(d.transport.candidatePairs=f),d.transport&&!d.transport.roundTripTime){let M=0,E=0;d.remoteInboundRtp.forEach((R,B)=>{R.roundTripTime&&R.roundTripTime>M&&(M=R.roundTripTime,E=R.totalRoundTripTime)}),d.transport.roundTripTime=M,d.transport.totalRoundTripTime=E}if(T.size>0)try{this.observer.emit("consumer_score",T)}catch(M){}if(v.size>0)try{this.observer.emit("producer_score",v)}catch(M){}return d}async getProducersReport(e){const r=e.map(n=>this.generateProducerStreamMap(n,!0));return r.length>0?Promise.all(r):void 0}async getConsumersReport(e){const r=e.map(n=>this.generateConsumerStreamMap(n,!0));return r.length>0?Promise.all(r):void 0}async getTransportReport(e){return e.getStats()}async getProcessedStats(e,r,n){const i=await this.getTransportReport(e),a={producing:n,consuming:r,id:e.id},o=i,d=this.parseRTCReport(o,["transport","candidate-pair","inbound-rtp","outbound-rtp","remote-inbound-rtp","local-candidate","remote-candidate"],!1,void 0,a);if(!d)return;const u={stats:d.transport,transportId:e.id,consuming:r,producing:n},h=d.staleProducerStreamMap?void 0:this.getProducerStatsFromReport(d),p=d.staleConsumerStreamMap?void 0:this.getConsumerStatsFromReport(d);return{transportReport:u,producerReport:h,consumerReport:p}}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((n,i)=>{var a,o;r.push({producerId:i,videoStats:n.outboundVideoRtpId.map(d=>e.outboundVideoRtp.get(d)),audioStats:n.outboundAudioRtpId.map(d=>e.outboundAudioRtp.get(d)),appData:((o=(a=this.callStatsInstance.producers)==null?void 0:a.get(i))==null?void 0:o.appData)||null})})}catch(n){this.callStatsInstance.logger.error("callStats::measurements::getProducerStatsFromReport",{error:{reason:n.reason,message:n.message}})}return r}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((n,i)=>{const{peerId:a,producerId:o,appData:d}=this.consumerPeerIdMap.get(i);r.push({consumerId:i,peerId:a,producerId:o,appData:d,videoStats:n.inboundVideoRtpId.map(u=>e.inboundVideoRtp.get(u)),audioStats:n.inboundAudioRtpId.map(u=>e.inboundAudioRtp.get(u))})})}catch(n){console.error("getConsumersReport: ",n,e)}return r}async getUserLocation(){return new Promise((e,r)=>{try{navigator.geolocation?navigator.geolocation.getCurrentPosition(n=>{e(n)}):r()}catch(n){r(n)}})}async getConnectivity(e){try{const r={iceServers:e||Ph},n=new Promise((h,p)=>{try{const f=new my(r);f.addListener("done",h),f.addListener("failed",()=>{h({connectivity:!1})}),f.start(2e3)}catch(f){p(f)}}),i=new Promise((h,p)=>{try{const f=new fy(r);f.addListener("done",h),f.addListener("failed",()=>{h({connectivity:!1})}),f.start(2e3)}catch(f){p(f)}}),a=new Promise((h,p)=>{try{const f=new gy(r);f.addListener("done",h),f.addListener("failed",()=>{h({connectivity:!1})}),f.start(2e3)}catch(f){p(f)}}),[o,d,u]=await Promise.all([n,i,a]);return{host:o==null?void 0:o.connectivity,relay:d==null?void 0:d.connectivity,reflexive:u==null?void 0:u.connectivity}}catch(r){return{host:!1,relay:!1,reflexive:!1}}}async getThroughput(e){try{const n=await new Promise((i,a)=>{try{const o={iceServers:e||Ph},d=new py(o);d.addListener("done",i),d.addListener("failed",a),d.start(1e4)}catch(o){a(o)}});return{throughput:n.throughput,fractionalLoss:0,RTT:n.RTT,jitter:0,backendRTT:n.backendRTT}}catch(r){return}}async getIPDetails(){var e,r;try{return this.ipDetails||(this.ipDetails=await Ud.getIPDetails({peerId:(e=this.callStatsInstance)==null?void 0:e.peerId,apiHostnames:(r=this.callStatsInstance)==null?void 0:r.apiHostnames})),this.ipDetails}catch(n){return}}async getNetworkQuality(e){const[r,n]=await Promise.all([this.getConnectivity(e),this.getThroughput(e)]);return{connectivity:r,throughput:n==null?void 0:n.throughput,fractionalLoss:n==null?void 0:n.fractionalLoss,RTT:n==null?void 0:n.RTT,jitter:n==null?void 0:n.jitter,backendRTT:n==null?void 0:n.backendRTT}}async getNetworkInfo(e,r=!1){var o,d;if(r){const u=await this.getIPDetails();return{ipDetails:u,effectiveNetworkType:(o=navigator.connection)==null?void 0:o.effectiveType,location:u.loc?Rh(u.loc):void 0}}const[n,i,a]=await Promise.all([this.getConnectivity(e),this.getThroughput(e),this.getIPDetails()]);return{ipDetails:a,effectiveNetworkType:(d=navigator.connection)==null?void 0:d.effectiveType,location:a.loc?Rh(a.loc):void 0,turnConnectivity:n?n.host||n.relay||n.reflexive:!1,connectivity:n,throughput:i==null?void 0:i.throughput,fractionalLoss:i==null?void 0:i.fractionalLoss,RTT:i==null?void 0:i.RTT,jitter:i==null?void 0:i.jitter,backendRTT:i==null?void 0:i.backendRTT}}}class yy extends Ih{}class Ah extends Ih{constructor(){super(...arguments);m(this,"producerMap",new Map);m(this,"consumerMap",new Map)}async registerProducer(e){this.producerMap.set(e.id,e),await this.generateProducerStreamMap(e),e.observer.on("close",this.deregisterProducer.bind(this,e)),e.observer.on("pause",this.pauseProducer.bind(this,e.id)),e.observer.on("resume",this.resumeProducer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareProducers.add(e.id)}async registerConsumer(e){this.consumerMap.set(e.id,e),await this.generateConsumerStreamMap(e),this.consumerPeerIdMap.set(e.id,{producerId:e.producerId,peerId:e.appData.peerId,appData:e.appData}),e.observer.on("close",this.deregisterConsumer.bind(this,e)),e.observer.on("pause",this.pauseConsumer.bind(this,e.id)),e.observer.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)}async generateConsumerStreamMap(e,r=!1){const n=await e.getStats(),i=this.parseRTCReport(n,["inbound-rtp"],!1,e.id),a=[...i.consumerStreamMap.values()][0],o=r?this.getConsumerStatsFromParsedConsumerStats(i,a,e.id):void 0;for(const d of n.values())switch(d.type){case"inbound-rtp":{this.inboundConsumerMap.set(d.id,e.id);break}}return o}deregisterProducer(e){this.producerMap.delete(e.id),this.outboundProducerMap.forEach((r,n)=>{r===e.id&&this.outboundProducerMap.delete(n)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.consumerMap.delete(e.id),this.inboundConsumerMap.forEach((r,n)=>{r===e.id&&this.inboundConsumerMap.delete(n)}),this.consumerPeerIdMap.delete(e.id),this.pausedConsumerMap.delete(e.id),this.screenShareConsumers.delete(e.id)}getIceCandidateStats(e){var r;return{id:e.id,type:e.candidateType||e.type,address:e.address,port:e.port,url:e.url,protocol:(r=e.relayProtocol)!=null?r:e.protocol,networkType:e.networkType,relatedAddress:e.relatedAddress,relatedPort:e.relatedPort}}parseRTCReport(e,r=[],n=!1,i=void 0,a=void 0){var P,k,I,x,V,O,W,Q,oe,ve,Mt,Fe,Dt;const o=e,d=new kh,u=r.length?new Set(r):void 0,h=[],p=[],f=[],v=new Map,T=new Map;for(const M of o.values()){if(u){if(u.size===0)break;if(u.has(M.type))n&&u.delete(M.type);else continue}switch(M.type){case"local-candidate":{h.push(this.getIceCandidateStats(M));break}case"remote-candidate":{p.push(this.getIceCandidateStats(M));break}case"candidate-pair":{const{nominated:E}=M,{selected:R}=M,B=M,xe={nominated:E!=null?E:R,currentRoundTripTime:B.currentRoundTripTime,totalRoundTripTime:B.totalRoundTripTime,bytesReceived:B.bytesReceived,bytesSent:B.bytesSent,availableOutgoingBitrate:B.availableOutgoingBitrate,lastPacketReceivedTimestamp:B.lastPacketReceivedTimestamp,lastPacketSentTimestamp:B.lastPacketSentTimestamp,localCandidateId:B.localCandidateId,remoteCandidateId:B.remoteCandidateId,bytesDiscardedOnSend:B.bytesDiscardedOnSend,packetsSent:B.packetsSent,packetsReceived:B.packetsReceived,packetsDiscardedOnSend:B.packetsDiscardedOnSend};f.push(xe),(M.nominated===!0||M.selected===!0)&&(d.candidatePair=xe);break}case"transport":{const E=M;a&&(a.producing&&(this.overallProducingTransportsStatsMap[a.id]||(this.overallProducingTransportsStatsMap[a.id]={totalPacketsSent:0})),a.consuming&&(this.overallConsumingTransportsStatsMap[a.id]||(this.overallConsumingTransportsStatsMap[a.id]={totalPacketsReceived:0})));const R={bytesReceived:E.bytesReceived,bytesSent:E.bytesSent,packetsSent:E.packetsSent,packetsReceived:E.packetsReceived,dtlsCipher:E.dtlsCipher,dtlsState:E.dtlsState,iceRole:E.iceRole};if(d.transport=R,a){if(a.producing){const B=this.overallProducingTransportsStatsMap[a.id];this.processProducingTransportStats(a.id,B,R)}if(a.consuming){const B=this.overallConsumingTransportsStatsMap[a.id];this.processConsumingTransportStats(a.id,B,R)}}break}case"remote-inbound-rtp":{const E=M,R={jitter:E.jitter,fractionLost:E.fractionLost,roundTripTime:E.roundTripTime,roundTripTimeMeasurements:E.roundTripTimeMeasurements,totalRoundTripTime:E.totalRoundTripTime,packetsLost:E.packetsLost};d.remoteInboundRtp.set(E.localId,R);break}case"outbound-rtp":{const E=M,R=i||this.outboundProducerMap.get(M.id),B=this.pausedProducerMap.get(R);if(B){if(B.lastReportCalculated===!0)break;this.pausedProducerMap.set(R,{lastReportCalculated:!0})}this.overallProducersStatsMap[R]||(this.overallProducersStatsMap[R]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const xe=this.overallProducersStatsMap[R];if(["video","audio"].includes(E.mediaType)||["video","audio"].includes(E.kind)){if(!this.outboundProducerMap.has(M.id)){d.staleProducerStreamMap=!0;break}const Qe=this.callStatsInstance.producers.get(R);if(((P=Qe==null?void 0:Qe.track)==null?void 0:P.readyState)==="ended")break;d.producerStreamMap.has(R)||d.producerStreamMap.set(R,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const G={bytesSent:E.bytesSent,packetsSent:E.packetsSent,nackCount:E.nackCount,ssrc:E.ssrc,mid:E.mid};if(E.mediaType==="video"||E.kind==="video"){if(E.decoderImplementation==="unknown")break;const A=E,rt={frameHeight:A.frameHeight,frameWidth:A.frameWidth,framesEncoded:A.framesEncoded,framesDropped:A.framesDropped?A.framesDropped:A.droppedFrames,framesPerSecond:A.framesPerSecond?A.framesPerSecond:A.framerateMean,framesSent:A.framesSent,keyFramesEncoded:A.keyFramesEncoded,firCount:A.firCount,encoderImplementation:A.encoderImplementation,hugeFramesSent:A.hugeFramesSent,pliCount:A.pliCount,qpSum:A.qpSum,qualityLimitationReason:A.qualityLimitationReason,qualityLimitationDurations:A.qualityLimitationDurations,qualityLimitationResolutionChanges:A.qualityLimitationResolutionChanges,totalEncodeTime:A.totalEncodeTime,totalPacketSendDelay:A.totalEncodeTime,retransmittedBytesSent:A.retransmittedBytesSent,retransmittedPacketsSent:A.retransmittedPacketsSent,...G};d.outboundVideoRtp.set(M.id,rt),d.producerStreamMap.get(R).outboundVideoRtpId.push(M.id),this.processOutboundProducerVideoStats(R,xe,rt)}else if(E.mediaType==="audio"||E.kind==="audio"){const A=E,rt={retransmittedBytesSent:A.retransmittedBytesSent,retransmittedPacketsSent:A.retransmittedPacketsSent,...G};d.outboundAudioRtp.set(M.id,rt),d.producerStreamMap.get(R).outboundAudioRtpId.push(M.id),this.processOutboundProducerAudioStats(R,xe,rt)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${E.mediaType} kind: ${E.kind}`);break}case"inbound-rtp":{const E=M,R=i||this.inboundConsumerMap.get(M.id),B=this.pausedConsumerMap.get(R);if(B){if(B.lastReportCalculated===!0)break;this.pausedConsumerMap.set(R,{lastReportCalculated:!0})}if(E.ssrc===1234)break;this.overallConsumersStatsMap[R]||(this.overallConsumersStatsMap[R]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const xe=this.overallConsumersStatsMap[R];if(["video","audio"].includes(E.mediaType)||["video","audio"].includes(E.kind)){if(!this.inboundConsumerMap.has(M.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(R)||d.consumerStreamMap.set(R,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const Qe={bytesReceived:E.bytesReceived,packetsReceived:E.packetsReceived,packetsLost:E.packetsLost,jitter:E.jitter,nackCount:E.nackCount,jitterBufferDelay:E.jitterBufferDelay,jitterBufferEmittedCount:E.jitterBufferEmittedCount,lastPacketReceivedTimestamp:E.lastPacketReceivedTimestamp,ssrc:E.ssrc,mid:E.mid};if(E.mediaType==="video"||E.kind==="video"){if(E.decoderImplementation==="unknown")break;const G=E,A={frameHeight:G.frameHeight,frameWidth:G.frameWidth,framesDecoded:G.framesDecoded,framesDropped:G.framesDropped?G.framesDropped:G.droppedFrames,framesPerSecond:G.framesPerSecond?G.framesPerSecond:G.framerateMean,framesReceived:G.framesReceived,keyFramesDecoded:G.keyFramesDecoded,firCount:G.firCount,decoderImplementation:G.decoderImplementation,pliCount:G.pliCount,totalProcessingDelay:G.totalProcessingDelay,...Qe};A.score=Ch({frameWidth:A.frameWidth||0,framesDecoded:(A.framesDecoded||0)-(((k=this.videoConsumerToStatsMap.get(R))==null?void 0:k.framesDecoded)||0),framesPerSecond:A.framesPerSecond||0,packetsLost:(A.packetsLost||0)-(((I=this.videoConsumerToStatsMap.get(R))==null?void 0:I.packetsLost)||0),packetsReceived:(A.packetsReceived||0)-(((x=this.videoConsumerToStatsMap.get(R))==null?void 0:x.packetsReceived)||0),jitter:A.jitter||0,isScreenShare:this.screenShareConsumers.has(R)}),T.set(R,{score:+(A.score*10).toFixed(),frameWidth:A.frameWidth||0,frameHeight:A.frameHeight||0,framesPerSecond:A.framesPerSecond||0,packetsLostPercentage:$o({packetsLost:(A.packetsLost||0)-(((V=this.videoConsumerToStatsMap.get(R))==null?void 0:V.packetsLost)||0),packetsReceived:(A.packetsReceived||0)-(((O=this.videoConsumerToStatsMap.get(R))==null?void 0:O.packetsReceived)||0)}),jitter:A.jitter||0,isScreenShare:this.screenShareConsumers.has(R),bitrate:((A.bytesReceived||0)-(((W=this.videoConsumerToStatsMap.get(R))==null?void 0:W.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(R,A),d.inboundVideoRtp.set(M.id,A),d.consumerStreamMap.get(R).inboundVideoRtpId.push(M.id),this.processInboundConsumerVideoStats(R,xe,A)}else if(E.mediaType==="audio"||E.kind==="audio"){const G=E,A={audioLevel:G.audioLevel,concealedSampels:G.concealedSampels,concealmentEvents:G.concealmentEvents,totalAudioEnergy:G.totalAudioEnergy,totalSamplesDuration:G.totalSamplesDuration,totalSamplesReceived:G.totalSamplesReceived,...Qe};A.score=wh({concealmentEvents:(A.concealmentEvents||0)-(((Q=this.audioConsumerToStatsMap.get(R))==null?void 0:Q.concealmentEvents)||0),packetsLost:(A.packetsLost||0)-(((oe=this.audioConsumerToStatsMap.get(R))==null?void 0:oe.packetsLost)||0),packetsReceived:(A.packetsReceived||0)-(((ve=this.audioConsumerToStatsMap.get(R))==null?void 0:ve.packetsReceived)||0),jitter:A.jitter||0}),T.set(R,{score:+(A.score*10).toFixed(),packetsLostPercentage:$o({packetsLost:(A.packetsLost||0)-(((Mt=this.audioConsumerToStatsMap.get(R))==null?void 0:Mt.packetsLost)||0),packetsReceived:(A.packetsReceived||0)-(((Fe=this.audioConsumerToStatsMap.get(R))==null?void 0:Fe.packetsReceived)||0)}),jitter:A.jitter||0,isScreenShare:this.screenShareConsumers.has(R),bitrate:((A.bytesReceived||0)-(((Dt=this.audioConsumerToStatsMap.get(R))==null?void 0:Dt.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(R,A),d.inboundAudioRtp.set(M.id,A),d.consumerStreamMap.get(R).inboundAudioRtpId.push(M.id),this.processInboundConsumerAudioStats(R,xe,A)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${E.mediaType} kind: ${E.kind}`);break}}}if(d.producerStreamMap.forEach((M,E)=>{var R,B,xe,Qe,G,A,rt,cs,yo,To,_o,So,Eo,wo,Co,bo,Po,Ro,ko,Io,Ao,Mo,Do;if(M.outboundVideoRtpId.length>0){const Ce=[];M.outboundVideoRtpId.forEach(Wu=>{Ce.push(d.outboundVideoRtp.get(Wu))});const ce=this.getWorkingSimulcastVideoStats(Ce);ce.score=Sh({frameWidth:ce.frameWidth||0,framesPerSecond:ce.framesPerSecond||0,jitter:((R=ce.remoteData)==null?void 0:R.jitter)||0,isScreenShare:this.screenShareProducers.has(E),packetsSent:(ce.packetsSent||0)-(((B=this.videoProducerToStatsMap.get(E))==null?void 0:B.packetsSent)||0),packetsLost:(((xe=ce.remoteData)==null?void 0:xe.packetsLost)||0)-(((G=(Qe=this.videoProducerToStatsMap.get(E))==null?void 0:Qe.remoteData)==null?void 0:G.packetsLost)||0),framesEncoded:(ce.framesEncoded||0)-(((A=this.videoProducerToStatsMap.get(E))==null?void 0:A.framesEncoded)||0)}),v.set(E,{score:+(ce.score*10).toFixed(),frameWidth:ce.frameWidth||0,frameHeight:ce.frameHeight||0,framesPerSecond:ce.framesPerSecond||0,jitter:((rt=ce.remoteData)==null?void 0:rt.jitter)||0,isScreenShare:this.screenShareProducers.has(E),packetsLostPercentage:Vo({packetsSent:(ce.packetsSent||0)-(((cs=this.videoProducerToStatsMap.get(E))==null?void 0:cs.packetsSent)||0),packetsLost:(((yo=ce.remoteData)==null?void 0:yo.packetsLost)||0)-(((_o=(To=this.videoProducerToStatsMap.get(E))==null?void 0:To.remoteData)==null?void 0:_o.packetsLost)||0)}),bitrate:((ce.bytesSent||0)-(((So=this.videoProducerToStatsMap.get(E))==null?void 0:So.bytesSent)||0))*8/7,cpuLimitations:ce.qualityLimitationReason==="cpu",bandwidthLimitations:ce.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(E,ce)}else if(M.outboundAudioRtpId.length>0){const Ce=d.outboundAudioRtp.get(M.outboundAudioRtpId[0]);Ce.score=_h({packetsSent:(Ce.packetsSent||0)-(((Eo=this.audioProducerToStatsMap.get(E))==null?void 0:Eo.packetsSent)||0),packetsLost:(((wo=Ce.remoteData)==null?void 0:wo.packetsLost)||0)-(((bo=(Co=this.audioProducerToStatsMap.get(E))==null?void 0:Co.remoteData)==null?void 0:bo.packetsLost)||0),jitter:((Po=Ce.remoteData)==null?void 0:Po.jitter)||0}),v.set(E,{score:+(Ce.score*10).toFixed(),bitrate:((Ce.bytesSent||0)-(((Ro=this.audioProducerToStatsMap.get(E))==null?void 0:Ro.bytesSent)||0))*8/7,packetsLostPercentage:Vo({packetsSent:(Ce.packetsSent||0)-(((ko=this.audioProducerToStatsMap.get(E))==null?void 0:ko.packetsSent)||0),packetsLost:(((Io=Ce.remoteData)==null?void 0:Io.packetsLost)||0)-(((Mo=(Ao=this.audioProducerToStatsMap.get(E))==null?void 0:Ao.remoteData)==null?void 0:Mo.packetsLost)||0)}),jitter:((Do=Ce.remoteData)==null?void 0:Do.jitter)||0,isScreenShare:this.screenShareProducers.has(E)}),this.audioProducerToStatsMap.set(E,Ce)}}),f.forEach(M=>{const E=h.find(B=>B.id===M.localCandidateId?(M.localCandidateId=B.id,B):null),R=p.find(B=>B.id===M.remoteCandidateId?(M.remoteCandidateId=B.id,B):null);E&&(M.localCandidateType=E.type,M.localCandidateAddress=E.address,M.localCandidatePort=E.port,M.localCandidateProtocol=E.protocol,M.localCandidateUrl=E.url,M.localCandidateNetworkType=E.networkType,M.localCandidateRelatedAddress=E.relatedAddress,M.localCandidateRelatedPort=E.relatedPort),R&&(M.remoteCandidateType=R.type,M.remoteCandidateAddress=R.address,M.remoteCandidatePort=R.port,M.remoteCandidateProtocol=R.protocol,M.remoteCandidateUrl=R.url)}),d.candidatePair&&(d.transport?(d.transport.bytesReceived=d.candidatePair.bytesReceived,d.transport.bytesSent=d.candidatePair.bytesSent,d.transport.totalRoundTripTime=d.candidatePair.totalRoundTripTime,d.transport.availableOutgoingBitrate=d.candidatePair.availableOutgoingBitrate,d.transport.roundTripTime=d.candidatePair.currentRoundTripTime):d.transport={bytesReceived:d.candidatePair.bytesReceived,bytesSent:d.candidatePair.bytesSent,totalRoundTripTime:d.candidatePair.totalRoundTripTime,availableOutgoingBitrate:d.candidatePair.availableOutgoingBitrate,roundTripTime:d.candidatePair.currentRoundTripTime}),d.transport&&(d.transport.candidatePairs=f),d.transport&&!d.transport.roundTripTime){let M=0,E=0;d.remoteInboundRtp.forEach((R,B)=>{R.roundTripTime&&R.roundTripTime>M&&(M=R.roundTripTime,E=R.totalRoundTripTime)}),d.transport.roundTripTime=M,d.transport.totalRoundTripTime=E}if(T.size>0)try{this.observer.emit("consumer_score",T)}catch(M){}if(v.size>0)try{this.observer.emit("producer_score",v)}catch(M){}return d}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((n,i)=>{const a=this.producerMap.get(i),o=a.track.getSettings(),d=n.outboundVideoRtpId.map(h=>{const p=e.outboundVideoRtp.get(h);return p.frameHeight||(p.frameHeight=o.height,p.frameWidth=o.width,p.framesPerSecond=o.frameRate),p}),u={producerId:i,appData:a.appData,videoStats:d,audioStats:n.outboundAudioRtpId.map(h=>e.outboundAudioRtp.get(h))};r.push(u)})}catch(n){console.error("getProducersReport: ",n,e)}return r}getConsumerStatsFromParsedConsumerStats(e,r,n){let i;try{const{peerId:a,producerId:o,appData:d}=this.consumerPeerIdMap.get(n),u=r==null?void 0:r.inboundVideoRtpId.map(h=>{const f=this.consumerMap.get(n).track.getSettings(),v=e.inboundVideoRtp.get(h);return v.frameHeight||(v.frameHeight=f.height,v.frameWidth=f.width,v.framesPerSecond=f.frameRate),v});i={consumerId:n,peerId:a,producerId:o,appData:d,videoStats:u,audioStats:r==null?void 0:r.inboundAudioRtpId.map(h=>e.inboundAudioRtp.get(h))}}catch(a){console.error("getConsumerStatsFromParsedConsumerStats: ",a,e)}return i}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((n,i)=>{r.push(this.getConsumerStatsFromParsedConsumerStats(e,n,i))})}catch(n){console.error("getConsumerStatsFromReport: ",n,e)}return r}}class Ty extends Ah{}function jo(s,t,e,r){if(s!=null&&s.logger&&s.logger.error("Callstats::handleError",{error:r}),typeof e=="function"&&r instanceof t)e.call(null,r,s);else throw r}function Mh(s,t,e){const r=s.value;return s.value=function(...n){try{const i=r.apply(this,n);return i&&i instanceof Promise?i.catch(a=>{jo(this,t,e,a)}):i}catch(i){jo(this,t,e,i)}return null},s}const te=(s,t)=>(e,r,n)=>{const i=n.value;return n.value=function(...a){try{const o=i.apply(this,a);return o&&o instanceof Promise?o.catch(d=>{jo(this,s,t,d)}):o}catch(o){jo(this,s,t,o)}return null},n},_y=(s,t)=>(e,r,n)=>{if(n)return Mh(n,s,t);for(const i of Reflect.ownKeys(e.prototype).filter(a=>a!=="constructor")){const a=Object.getOwnPropertyDescriptor(e.prototype,i);a.value instanceof Function&&Object.defineProperty(e.prototype,i,Mh(a,s,t))}};var Z=globalThis&&globalThis.__decorate||function(s,t,e,r){var n=arguments.length,i=n<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(s,t,e,r);else for(var o=s.length-1;o>=0;o--)(a=s[o])&&(i=(n<3?a(i):n>3?a(t,e,i):a(t,e))||i);return n>3&&i&&Object.defineProperty(t,e,i),i};const ee=console;let z=class extends de{constructor(e="https://api.testingv3.dyte.in",r="Blink",n=ta.PROD,i,a,o,d){super();m(this,"observer");m(this,"eventHandler");m(this,"measurements");m(this,"producingTransport");m(this,"consumingTransport");m(this,"producers",new Map);m(this,"consumers",new Map);m(this,"iceServers");m(this,"connectionInfoPromise");m(this,"pingStatsTimeout");m(this,"logger");m(this,"env");m(this,"apiHostnames");m(this,"peerId");m(this,"consumerSharedMediaStatesMap",new Map);m(this,"currentUserMediaStates",{});switch(this.env=n,this.apiHostnames=d,this.logger=a,this.peerId=o,this.eventHandler=new ny({logger:a,peerId:o,apiHostnames:d}),this.logger.debug("callStats::engineName: ",{engineName:r}),r){case"Blink":this.measurements=new yy;break;case"Gecko":this.measurements=new Ah;break;case"WebKit":this.measurements=new Ty;break;default:throw Error(`Unknown engineName! ${r}`)}this.measurements.callStatsInstance=this,this.registerProducer=this.registerProducer.bind(this),this.registerConsumer=this.registerConsumer.bind(this),this.observer=new de,this.measurements.observer.on("consumer_score",u=>{a.debug(`callStats::consumer_score ${[...u.entries()]}`),this.eventHandler.emit("consumer_score",u)}),this.measurements.observer.on("producer_score",u=>{a.debug(`callStats::producer_score ${[...u.entries()]}`),this.eventHandler.emit("producer_score",u)})}registerIceServers(e){this.iceServers=e}registerConsumer(e){var r;this.consumerSharedMediaStatesMap.has(e.id)||this.consumerSharedMediaStatesMap.set(e.id,{}),this.consumers.set(e.id,e),this.measurements.registerConsumer(e),this.logger.debug("callStats::registerConsumer",{consumerId:e.id,consumerkind:e.kind,isScreenShare:!!((r=e.appData)!=null&&r.screenShare)}),e.observer.on("close",this.deRegisterConsumer.bind(this,e))}registerProducer(e){var r;this.producers.set(e.id,e),this.measurements.registerProducer(e),this.logger.debug("callStats::registerProducer",{producerId:e.id,producerKind:e.kind,isScreenShare:!!((r=e.appData)!=null&&r.screenShare)}),e.observer.on("close",this.deRegisterProducer.bind(this,e))}sendConsumerSharedMediaStateEvent(e,r){this.consumerSharedMediaStatesMap.has(e)||this.consumerSharedMediaStatesMap.set(e,{});const n=this.consumerSharedMediaStatesMap.get(e);this.consumerSharedMediaStatesMap.set(e,Object.assign(n,r))}registerProducingTransport(e){var n;this.producingTransport=e,e.observer.on("close",this.disconnectProducingTransport.bind(this,e)),e.observer.on("disconnect",this.disconnectProducingTransport.bind(this,e)),Array.from(((n=e._producers)==null?void 0:n.values())||[]).forEach(i=>{this.registerProducer(i)}),e.observer.on("newproducer",this.registerProducer)}registerConsumingTransport(e){var n;this.consumingTransport=e,e.observer.on("close",this.disconnectConsumingTransport.bind(this,e)),e.observer.on("disconnect",this.disconnectConsumingTransport.bind(this,e)),Array.from(((n=e._consumers)==null?void 0:n.values())||[]).forEach(i=>{this.registerConsumer(i)}),e.observer.on("newconsumer",this.registerConsumer)}deRegisterConsumer(e){this.consumers.delete(e.id)}deRegisterProducer(e){var r;this.producers.delete(e.id),this.logger.debug("callStats::deRegisterProducer",{producerId:e.id,producerKind:e.kind,isScreenShare:!!((r=e.appData)!=null&&r.screenShare)})}disconnectConsumingTransport(){this.consumingTransport=void 0}disconnectProducingTransport(){this.producingTransport=void 0}callEvent(e){this.eventHandler.callEvent(e)}sendPreCallTestBeginEvent(e=!1){this.connectionInfoPromise=this.measurements.getNetworkInfo(this.iceServers,e),this.eventHandler.callEvent({event:F.PRECALL_TEST_BEGIN,timestamp:new Date}),this.connectionInfoPromise&&this.connectionInfoPromise.then(r=>{this.eventHandler.callEvent({event:F.PRECALL_TEST_COMPLETE,metaData:{connectionInfo:r},timestamp:new Date})})}sendScreenShareToggleEvent(e,r){this.currentUserMediaStates.screen=e,this.eventHandler.callEvent({event:e?F.SCREENSHARE_STARTED:F.SCREENSHARE_STOPPED,metaData:{ssrc:r},timestamp:new Date})}sendScreenShareRequestedEvent(){this.eventHandler.callEvent({event:F.SCREENSHARE_START_REQUESTED,timestamp:new Date})}sendActiveSpeakerEvent(e){this.eventHandler.callEvent({event:F.DOMINANT_SPEAKER,metaData:{peerId:e},timestamp:new Date})}devices(e,r){this.eventHandler.callEvent({event:e===Qt.AUDIO&&F.AUDIO_DEVICES_UPDATES||e===Qt.VIDEO&&F.VIDEO_DEVICES_UPDATES||e===Qt.SPEAKER&&F.SPEAKER_DEVICES_UPDATES,metaData:{deviceList:r},timestamp:new Date})}selectedDevice(e,r){this.eventHandler.callEvent({event:e===Qt.AUDIO&&F.SELECTED_MICROHPONE_UPDATE||e===Qt.VIDEO&&F.SELECTED_CAMERA_UPDATE||e===Qt.SPEAKER&&F.SELECTED_SPEAKER_UPDATE,metaData:{device:r},timestamp:new Date})}mediaPermission(e,r){this.eventHandler.callEvent({event:F.MEDIA_PERMISSION,metaData:{deviceType:e,permission:r},timestamp:new Date})}mediaPlaybackFailed(e){this.eventHandler.callEvent({event:e===Qt.AUDIO&&F.AUDIO_PLAY_FAILED||e===Qt.VIDEO&&F.VIDEO_PLAY_FAILED,metaData:{deviceType:e},timestamp:new Date})}mediaTrackMuted(e){this.eventHandler.callEvent({event:e===Qt.AUDIO&&F.AUDIO_TRACK_MUTED||e===Qt.VIDEO&&F.VIDEO_TRACK_MUTED,metaData:{deviceType:e},timestamp:new Date})}tabChanged(e){this.eventHandler.callEvent({event:F.TAB_CHANGE,metaData:{isMeetingsTabActive:e},timestamp:new Date})}browserBackgrounded(){this.eventHandler.callEvent({event:F.BROWSER_BACKGROUNDED,timestamp:new Date})}browserForegrounded(){this.eventHandler.callEvent({event:F.BROWSER_FOREGROUNDED,timestamp:new Date})}legacySwitch(e){this.eventHandler.callEvent({event:F.LEGACY_SWITCH,metadata:{on:e},timestamp:new Date})}async getPreCallTestResults(){return this.connectionInfoPromise}sendCallJoinBeginEvent(e){e={...e,meetingEnv:this.env},e.deviceInfo={...e.deviceInfo,userAgent:navigator.userAgent,cpus:navigator.hardwareConcurrency,memory:navigator.deviceMemory},this.eventHandler.callEvent({event:F.CALL_JOIN_BEGIN,metaData:{peerMetaData:e},timestamp:new Date})}sendNetworkQualityTestBeginEvent(e){this.eventHandler.callEvent({event:F.NET_QUALITY_TEST_BEGIN,timestamp:new Date}),new Promise(async(n,i)=>{const a=[];try{for(const o of e)try{if(o.iceServers&&o.iceServers.length>0){const d=await this.measurements.getNetworkQuality(o.iceServers);a.push({...o,networkResults:d})}}catch(d){console.warn("Error handling ",d)}n({regionData:a})}catch(o){console.warn("Error in callstats, ",o),i(o)}}).then(n=>{this.eventHandler.callEvent({event:F.NET_QUALITY_TEST_END,timestamp:new Date,metaData:n})})}sendWebSocketConnectedEvent(){this.eventHandler.callEvent({event:F.WEBSOCKET_CONNECTED,timestamp:new Date})}sendTransportConnectedEvent(){this.eventHandler.callEvent({event:F.TRANSPORT_CONNECTED,timestamp:new Date})}sendAudioToggleEvent(e){this.currentUserMediaStates.audio=e;let r;e?r=F.AUDIO_ON:r=F.AUDIO_OFF,this.eventHandler.callEvent({event:r,timestamp:new Date})}sendVideoToggleEvent(e){this.currentUserMediaStates.video=e;let r;e?r=F.VIDEO_ON:r=F.VIDEO_OFF,this.eventHandler.callEvent({event:r,timestamp:new Date})}sendParticipantRoleToggleEvent(e){this.eventHandler.callEvent({event:F.PARTICIPANT_ROLE,timestamp:new Date,metaData:e})}startPingStats(e=7e3){this.sendPingStatsEvent(!1),this.pingStatsTimeout=setInterval(this.sendPingStatsEvent.bind(this),e)}stopPingStats(){clearInterval(this.pingStatsTimeout)}async sendPingStatsEvent(e=!0){let r,n;if(this.producingTransport&&(r=await this.measurements.getProcessedStats(this.producingTransport,!1,!0),!r||!(r!=null&&r.producerReport))){this.logger.debug("callStats::sendPingStatsEvent::staleProducingTransport",{disclaimer:"Stale producer? Regenerating Stream Maps!"});const a=await this.measurements.getProducersReport([...this.producers.values()]);r&&a?r.producerReport=a:(r=await this.measurements.getProcessedStats(this.producingTransport,!1,!0),(!r||!(r!=null&&r.producerReport))&&this.logger.debug("callStats::sendPingStatsEvent::noProducingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}if(this.consumingTransport&&(n=await this.measurements.getProcessedStats(this.consumingTransport,!0,!1),!n||!n.consumerReport)){this.logger.debug("callStats::sendPingStatsEvent::staleConsumingTransport",{disclaimer:"Stale consumer? Regenerating Stream Maps!"});const a=await this.measurements.getConsumersReport([...this.consumers.values()]);n&&a?n.consumerReport=a:(n=await this.measurements.getProcessedStats(this.consumingTransport,!0,!1),(!n||!n.consumerReport)&&this.logger.debug("callStats::sendPingStatsEvent::noConsumingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}const i={producingTransportStats:r?r==null?void 0:r.transportReport:void 0,consumingTransportStats:n?n==null?void 0:n.transportReport:void 0,producerStats:[].concat((r==null?void 0:r.producerReport)||[]).concat((n==null?void 0:n.producerReport)||[]),consumerStats:[].concat((n==null?void 0:n.consumerReport)||[]).concat((r==null?void 0:r.consumerReport)||[])};if(e&&i.producerStats.length===0&&i.consumerStats.length===0){await this.eventHandler.flush();return}this.eventHandler.callEvent({event:F.PING_STAT,metaData:i,timestamp:new Date})}sendIVSPlayerRebufferEvent(){this.eventHandler.callEvent({event:F.IVS_PLAYER_REBUFFERING,timestamp:new Date})}sendIVSPlayerAudioBlockEvent(){this.eventHandler.callEvent({event:F.IVS_PLAYER_AUDIO_BLOCKED,timestamp:new Date})}sendIVSPlayerPlaybackBlockedEvent(){this.eventHandler.callEvent({event:F.IVS_PLAYER_PLAYBACK_BLOCKED,timestamp:new Date})}sendIVSPlayerNetworkUnavailableEvent(){this.eventHandler.callEvent({event:F.IVS_PLAYER_NETWORK_UNAVAILABLE,timestamp:new Date})}sendIVSPlayerInitializedEvent(){this.eventHandler.callEvent({event:F.IVS_PLAYER_INITIALIZED,timestamp:new Date})}sendIVSPlayerWorkerErrorEvent(){this.eventHandler.callEvent({event:F.IVS_PLAYER_WORKER_ERROR,timestamp:new Date})}sendIVSPlayerErrorEvent(e){this.eventHandler.callEvent({event:F.IVS_PLAYER_ERROR,timestamp:new Date,metaData:e})}sendIVSPlayerRecoverableErrorEvent(e){this.eventHandler.callEvent({event:F.IVS_PLAYER_RECOVERABLE_ERROR,timestamp:new Date,metaData:e})}sendIVSPlayerAnalyticsEvent(e){this.eventHandler.callEvent({event:F.IVS_PLAYER_ANALYTICS_EVENT,timestamp:new Date,metaData:e})}sendIVSPlayerPlaybackRateChangedEvent(e){this.eventHandler.callEvent({event:F.IVS_PLAYER_PLAYBACK_RATE_CHANGED,timestamp:new Date,metaData:{updatedPlaybackRate:e}})}sendIVSPlayerQualityChanged(e){this.eventHandler.callEvent({event:F.IVS_PLAYER_QUALITY_CHANGED,timestamp:new Date,metaData:e})}sendPlayerLiveLatency(e){this.eventHandler.callEvent({event:F.LIVESTREAM_LATENCY,timestamp:new Date,metaData:{latency:e}})}sendDisconnectEvent(){this.eventHandler.callEvent({event:F.DISCONNECT,timestamp:new Date})}sendReconnectEvent(){this.eventHandler.callEvent({event:F.RECONNECT_ATTEMPT,timestamp:new Date})}};Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"registerIceServers",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"registerConsumer",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"registerProducer",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendConsumerSharedMediaStateEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"registerProducingTransport",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"registerConsumingTransport",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"deRegisterConsumer",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"deRegisterProducer",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"disconnectConsumingTransport",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"disconnectProducingTransport",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendPreCallTestBeginEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendScreenShareToggleEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendScreenShareRequestedEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendActiveSpeakerEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"devices",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"selectedDevice",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"mediaPermission",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"mediaPlaybackFailed",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"mediaTrackMuted",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"tabChanged",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"browserBackgrounded",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"browserForegrounded",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"legacySwitch",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"getPreCallTestResults",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendCallJoinBeginEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendNetworkQualityTestBeginEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendWebSocketConnectedEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendTransportConnectedEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendAudioToggleEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendVideoToggleEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendParticipantRoleToggleEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"startPingStats",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"stopPingStats",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendPingStatsEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendIVSPlayerRebufferEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendIVSPlayerAudioBlockEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendIVSPlayerPlaybackBlockedEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendIVSPlayerNetworkUnavailableEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendIVSPlayerInitializedEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendIVSPlayerWorkerErrorEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendIVSPlayerErrorEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendIVSPlayerRecoverableErrorEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendIVSPlayerAnalyticsEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendIVSPlayerPlaybackRateChangedEvent",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendIVSPlayerQualityChanged",null),Z([te(TypeError,(s,t)=>ee.error(t,s))],z.prototype,"sendPlayerLiveLatency",null),z=Z([_y(TypeError,(s,t)=>ee.error(t,s))],z);const Sy=z;class Ey extends de{constructor(){super(...arguments);m(this,"stats");m(this,"roomURL");m(this,"peerId");m(this,"backend");m(this,"iceServers");m(this,"initialized",!1);m(this,"stalled",!1);m(this,"ipInformation");m(this,"logger")}async initialize({peerId:e,engineName:r,env:n=ta.PROD,iceServers:i,apiBase:a="https://api.cluster.dyte.in",flags:o,logger:d=console,apiHostnames:u,skipConnectivityChecks:h=!1}){var p,f,v;try{this.peerId=e,this.logger=d,this.ipInformation=await Ud.getIPDetails({peerId:e,apiHostnames:u}),this.backend=new Sy(a,r,n,o,d,e,u),this.iceServers=i,(p=this.backend)==null||p.registerIceServers(this.iceServers),this.initialized=!0,(v=(f=this.backend)==null?void 0:f.eventHandler)==null||v.emit("initialized",this.ipInformation),this.emit("initialized",this.ipInformation),this.startPreCallTest(h)}catch(T){this.logger.error("callStats::CallStatsIntegration: ",{error:T}),this.stallCallStats()}}setRoomName(e){this.roomURL=e}configureSendTransport(e){var r;(r=this.backend)==null||r.registerProducingTransport(e)}configureRecvTransport(e){var r;(r=this.backend)==null||r.registerConsumingTransport(e)}async candidateRegionalNetworkQualityTest(e){var r;try{(r=this.backend)==null||r.sendNetworkQualityTestBeginEvent(e)}catch(n){this.logger.error("callStats::sendNetworkQualityTestBeginEvent",{error:{reason:n.reason}})}}async roomJoined(e){var r,n;(r=this.backend)==null||r.sendCallJoinBeginEvent(e),this.backend,(n=this.backend)==null||n.startPingStats()}audioOff(){var e;(e=this.backend)==null||e.sendAudioToggleEvent(!1)}audioOn(){var e;(e=this.backend)==null||e.sendAudioToggleEvent(!0)}videoOff(){var e;(e=this.backend)==null||e.sendVideoToggleEvent(!1)}videoOn(){var e;(e=this.backend)==null||e.sendVideoToggleEvent(!0)}callEnded(){var e,r;(e=this.backend)==null||e.stopPingStats(),(r=this.backend)==null||r.sendDisconnectEvent()}screenShareStart(e){var r;(r=this.backend)==null||r.sendScreenShareToggleEvent(!0,e)}consumerSharedMediaState(e,r){var n;(n=this.backend)==null||n.sendConsumerSharedMediaStateEvent(e,r)}screenShareStop(e){var r;(r=this.backend)==null||r.sendScreenShareToggleEvent(!1,e)}screenShareRequested(){var e;(e=this.backend)==null||e.sendScreenShareRequestedEvent()}activeSpeaker(e){var r;e===this.peerId&&((r=this.backend)==null||r.sendActiveSpeakerEvent(e))}devices(e,r){var n;(n=this.backend)==null||n.devices(e,r)}selectedDevice(e,r){var n;(n=this.backend)==null||n.selectedDevice(e,r)}mediaPermission(e,r){var n;(n=this.backend)==null||n.mediaPermission(e,r)}mediaPlaybackFailed(e){var r;(r=this.backend)==null||r.mediaPlaybackFailed(e)}mediaTrackMuted(e){var r;(r=this.backend)==null||r.mediaTrackMuted(e)}tabChanged(e=!1){var r;(r=this.backend)==null||r.tabChanged(e)}browserBackgrounded(){var e;(e=this.backend)==null||e.browserBackgrounded()}browserForegrounded(){var e;(e=this.backend)==null||e.browserForegrounded()}legacySwitch(e){var r;(r=this.backend)==null||r.legacySwitch(e)}async startPreCallTest(e=!1){var r;(r=this.backend)==null||r.sendPreCallTestBeginEvent(e)}onPreCallTestResults(e){var r;return(r=this.backend)==null||r.eventHandler.once("precall_end",e),e}onReceivingConsumerAudioStatus(e){var r;(r=this.backend)==null||r.eventHandler.on("consumer_audio_status",e)}onReceivingConsumerVideoStatus(e){var r;(r=this.backend)==null||r.eventHandler.on("consumer_video_status",e)}onReceivingProducerAudioStatus(e){var r;(r=this.backend)==null||r.eventHandler.on("producer_audio_status",e)}onReceivingProducerVideoStatus(e){var r;(r=this.backend)==null||r.eventHandler.on("producer_video_status",e)}onReceivingProducingTransportStatus(e){var r;(r=this.backend)==null||r.eventHandler.on("producing_transport_status",e)}onReceivingConsumingTransportStatus(e){var r;(r=this.backend)==null||r.eventHandler.on("consuming_transport_status",e)}onProducerScore(e){var r;(r=this.backend)==null||r.eventHandler.on("producer_score",e)}onConsumerScore(e){var r;(r=this.backend)==null||r.eventHandler.on("consumer_score",e)}onSafeInitialization(e){if(this.initialized)e(this.ipInformation,!1);else if(!this.stalled){const r=n=>{e(n,!0)};return this.once("initialized",r),r}return()=>{}}removeInitializationListener(e){this.removeListener("initialized",e)}stallCallStats(){this.stalled=!0,this.removeAllListeners("initialized")}ivsPlayerEvent(e,r){var n,i,a,o,d,u,h,p,f,v,T;switch(e){case"PlayerRebuffering":(n=this.backend)==null||n.sendIVSPlayerRebufferEvent();break;case"PlayerAudioBlocked":(i=this.backend)==null||i.sendIVSPlayerAudioBlockEvent();break;case"PlayerPlaybackBlocked":(a=this.backend)==null||a.sendIVSPlayerPlaybackBlockedEvent();break;case"PlayerNetworkUnavailable":(o=this.backend)==null||o.sendIVSPlayerNetworkUnavailableEvent();break;case"PlayerInitialized":(d=this.backend)==null||d.sendIVSPlayerInitializedEvent();break;case"PlayerWorkerError":(u=this.backend)==null||u.sendIVSPlayerWorkerErrorEvent();break;case"PlayerError":(h=this.backend)==null||h.sendIVSPlayerErrorEvent(r);break;case"PlayerRecoverableError":(p=this.backend)==null||p.sendIVSPlayerRecoverableErrorEvent(r);break;case"PlayerAnalyticsEvent":(f=this.backend)==null||f.sendIVSPlayerAnalyticsEvent(r);break;case"PlayerPlaybackRateChanged":(v=this.backend)==null||v.sendIVSPlayerPlaybackRateChangedEvent(r);break;case"PlayerQualityChanged":(T=this.backend)==null||T.sendIVSPlayerQualityChanged(r);break}}livestreamLatency(e){var r;(r=this.backend)==null||r.sendPlayerLiveLatency(e)}}const U=new Ey;U.setMaxListeners(30);function wy(s){const{length:t}=this,e=s>=0?s:t+s;return e<0||e>=t?void 0:this[e]}Array.prototype.at||Object.assign(Array.prototype,{at:wy});function Cy(s){const{length:t}=this,e=s>=0?s:t+s;return e<0||e>=t?void 0:this[e]}String.prototype.at||Object.assign(String.prototype,{at:Cy});var Go,by=new Uint8Array(16);function Py(){if(!Go&&(Go=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!Go))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Go(by)}const Ry=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function Vd(s){return typeof s=="string"&&Ry.test(s)}for(var dt=[],$d=0;$d<256;++$d)dt.push(($d+256).toString(16).substr(1));function ky(s){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(dt[s[t+0]]+dt[s[t+1]]+dt[s[t+2]]+dt[s[t+3]]+"-"+dt[s[t+4]]+dt[s[t+5]]+"-"+dt[s[t+6]]+dt[s[t+7]]+"-"+dt[s[t+8]]+dt[s[t+9]]+"-"+dt[s[t+10]]+dt[s[t+11]]+dt[s[t+12]]+dt[s[t+13]]+dt[s[t+14]]+dt[s[t+15]]).toLowerCase();if(!Vd(e))throw TypeError("Stringified UUID is invalid");return e}function Xs(s,t,e){s=s||{};var r=s.random||(s.rng||Py)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){e=e||0;for(var n=0;n<16;++n)t[e+n]=r[n];return t}return ky(r)}var Xe;(function(s){s.GroupCall="GROUP_CALL",s.Webinar="WEBINAR",s.AudioRoom="AUDIO_ROOM",s.Livestream="LIVESTREAM",s.Chat="CHAT"})(Xe||(Xe={}));var Jo;(function(s){s.Skip="SKIP",s.OnPrivilegedUserEntry="ON_PRIVILEGED_USER_ENTRY",s.SkipOnAccept="SKIP_ON_ACCEPT"})(Jo||(Jo={}));var H;(function(s){s.Allowed="ALLOWED",s.NotAllowed="NOT_ALLOWED",s.CanRequest="CAN_REQUEST"})(H||(H={}));var Wo;(function(s){s.Allowed="ALLOWED",s.NotAllowed="NOT_ALLOWED"})(Wo||(Wo={}));var Dh;(function(s){s.FULL_ACCESS="FULL_ACCESS",s.VIEW_ONLY="VIEW_ONLY"})(Dh||(Dh={}));var Ko;(function(s){s.skip="SKIP",s.onAccept="ON_ACCEPT",s.skipOnPrivilegedUserEntry="SKIP_ON_PRIVILEGED_USER_ENTRY",s.skipOnAccept="SKIP_ON_ACCEPT"})(Ko||(Ko={}));var Jn;(function(s){s.none="NONE",s.recorder="RECORDER",s.livestreamer="LIVESTREAMER"})(Jn||(Jn={}));var Bd;(function(s){s.groupCall="GROUP_CALL",s.webinar="WEBINAR",s.audioRoom="AUDIO_ROOM",s.livestream="LIVESTREAM",s.chat="CHAT"})(Bd||(Bd={}));var Oh;(function(s){s.SKIP="skip",s.SKIP_ON_PRIVILEGED_USER_ENTRY="skipOnPrivilegedUserEntry",s.ON_ACCEPT="skipOnAccept",s.SKIP_ON_ACCEPT="skipOnAccept"})(Oh||(Oh={})),Bd.groupCall,Ko.skipOnAccept,Jn.none;var Hd={},Iy={get exports(){return Hd},set exports(s){Hd=s}},zo={},Ay={get exports(){return zo},set exports(s){zo=s}},Nh=function(t,e){return function(){for(var n=new Array(arguments.length),i=0;i=0)return;i==="set-cookie"?n[i]=(n[i]?n[i]:[]).concat([a]):n[i]=n[i]?n[i]+", "+a:a}}),n},Zd}var el,zh;function rT(){if(zh)return el;zh=1;var s=Ot;return el=s.isStandardBrowserEnv()?function(){var e=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a"),n;function i(a){var o=a;return e&&(r.setAttribute("href",o),o=r.href),r.setAttribute("href",o),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:r.pathname.charAt(0)==="/"?r.pathname:"/"+r.pathname}}return n=i(window.location.href),function(o){var d=s.isString(o)?i(o):o;return d.protocol===n.protocol&&d.host===n.host}}():function(){return function(){return!0}}(),el}var tl,Yh;function Xo(){if(Yh)return tl;Yh=1;function s(t){this.message=t}return s.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},s.prototype.__CANCEL__=!0,tl=s,tl}var rl,Qh;function Xh(){if(Qh)return rl;Qh=1;var s=Ot,t=Yy(),e=Qy(),r=Vh,n=eT(),i=tT(),a=rT(),o=Hh(),d=Zo(),u=Xo();return rl=function(p){return new Promise(function(v,T){var P=p.data,k=p.headers,I=p.responseType,x;function V(){p.cancelToken&&p.cancelToken.unsubscribe(x),p.signal&&p.signal.removeEventListener("abort",x)}s.isFormData(P)&&delete k["Content-Type"];var O=new XMLHttpRequest;if(p.auth){var W=p.auth.username||"",Q=p.auth.password?unescape(encodeURIComponent(p.auth.password)):"";k.Authorization="Basic "+btoa(W+":"+Q)}var oe=n(p.baseURL,p.url);O.open(p.method.toUpperCase(),r(oe,p.params,p.paramsSerializer),!0),O.timeout=p.timeout;function ve(){if(O){var Fe="getAllResponseHeaders"in O?i(O.getAllResponseHeaders()):null,Dt=!I||I==="text"||I==="json"?O.responseText:O.response,M={data:Dt,status:O.status,statusText:O.statusText,headers:Fe,config:p,request:O};t(function(R){v(R),V()},function(R){T(R),V()},M),O=null}}if("onloadend"in O?O.onloadend=ve:O.onreadystatechange=function(){!O||O.readyState!==4||O.status===0&&!(O.responseURL&&O.responseURL.indexOf("file:")===0)||setTimeout(ve)},O.onabort=function(){O&&(T(o("Request aborted",p,"ECONNABORTED",O)),O=null)},O.onerror=function(){T(o("Network Error",p,null,O)),O=null},O.ontimeout=function(){var Dt=p.timeout?"timeout of "+p.timeout+"ms exceeded":"timeout exceeded",M=p.transitional||d.transitional;p.timeoutErrorMessage&&(Dt=p.timeoutErrorMessage),T(o(Dt,p,M.clarifyTimeoutError?"ETIMEDOUT":"ECONNABORTED",O)),O=null},s.isStandardBrowserEnv()){var Mt=(p.withCredentials||a(oe))&&p.xsrfCookieName?e.read(p.xsrfCookieName):void 0;Mt&&(k[p.xsrfHeaderName]=Mt)}"setRequestHeader"in O&&s.forEach(k,function(Dt,M){typeof P=="undefined"&&M.toLowerCase()==="content-type"?delete k[M]:O.setRequestHeader(M,Dt)}),s.isUndefined(p.withCredentials)||(O.withCredentials=!!p.withCredentials),I&&I!=="json"&&(O.responseType=p.responseType),typeof p.onDownloadProgress=="function"&&O.addEventListener("progress",p.onDownloadProgress),typeof p.onUploadProgress=="function"&&O.upload&&O.upload.addEventListener("progress",p.onUploadProgress),(p.cancelToken||p.signal)&&(x=function(Fe){O&&(T(!Fe||Fe&&Fe.type?new u("canceled"):Fe),O.abort(),O=null)},p.cancelToken&&p.cancelToken.subscribe(x),p.signal&&(p.signal.aborted?x():p.signal.addEventListener("abort",x))),P||(P=null),O.send(P)})},rl}var sl,Zh;function Zo(){if(Zh)return sl;Zh=1;var s=Ot,t=zy,e=$h,r={"Content-Type":"application/x-www-form-urlencoded"};function n(d,u){!s.isUndefined(d)&&s.isUndefined(d["Content-Type"])&&(d["Content-Type"]=u)}function i(){var d;return(typeof XMLHttpRequest!="undefined"||typeof process!="undefined"&&Object.prototype.toString.call(process)==="[object process]")&&(d=Xh()),d}function a(d,u,h){if(s.isString(d))try{return(u||JSON.parse)(d),s.trim(d)}catch(p){if(p.name!=="SyntaxError")throw p}return(h||JSON.stringify)(d)}var o={transitional:{silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},adapter:i(),transformRequest:[function(u,h){return t(h,"Accept"),t(h,"Content-Type"),s.isFormData(u)||s.isArrayBuffer(u)||s.isBuffer(u)||s.isStream(u)||s.isFile(u)||s.isBlob(u)?u:s.isArrayBufferView(u)?u.buffer:s.isURLSearchParams(u)?(n(h,"application/x-www-form-urlencoded;charset=utf-8"),u.toString()):s.isObject(u)||h&&h["Content-Type"]==="application/json"?(n(h,"application/json"),a(u)):u}],transformResponse:[function(u){var h=this.transitional||o.transitional,p=h&&h.silentJSONParsing,f=h&&h.forcedJSONParsing,v=!p&&this.responseType==="json";if(v||f&&s.isString(u)&&u.length)try{return JSON.parse(u)}catch(T){if(v)throw T.name==="SyntaxError"?e(T,this,"E_JSON_PARSE"):T}return u}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,validateStatus:function(u){return u>=200&&u<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};return s.forEach(["delete","get","head"],function(u){o.headers[u]={}}),s.forEach(["post","put","patch"],function(u){o.headers[u]=s.merge(r)}),sl=o,sl}var sT=Ot,nT=Zo(),iT=function(t,e,r){var n=this||nT;return sT.forEach(r,function(a){t=a.call(n,t,e)}),t},nl,ep;function tp(){return ep||(ep=1,nl=function(t){return!!(t&&t.__CANCEL__)}),nl}var rp=Ot,il=iT,aT=tp(),oT=Zo(),cT=Xo();function al(s){if(s.cancelToken&&s.cancelToken.throwIfRequested(),s.signal&&s.signal.aborted)throw new cT("canceled")}var dT=function(t){al(t),t.headers=t.headers||{},t.data=il.call(t,t.data,t.headers,t.transformRequest),t.headers=rp.merge(t.headers.common||{},t.headers[t.method]||{},t.headers),rp.forEach(["delete","get","head","post","put","patch","common"],function(n){delete t.headers[n]});var e=t.adapter||oT.adapter;return e(t).then(function(n){return al(t),n.data=il.call(t,n.data,n.headers,t.transformResponse),n},function(n){return aT(n)||(al(t),n&&n.response&&(n.response.data=il.call(t,n.response.data,n.response.headers,t.transformResponse))),Promise.reject(n)})},Bt=Ot,sp=function(t,e){e=e||{};var r={};function n(h,p){return Bt.isPlainObject(h)&&Bt.isPlainObject(p)?Bt.merge(h,p):Bt.isPlainObject(p)?Bt.merge({},p):Bt.isArray(p)?p.slice():p}function i(h){if(Bt.isUndefined(e[h])){if(!Bt.isUndefined(t[h]))return n(void 0,t[h])}else return n(t[h],e[h])}function a(h){if(!Bt.isUndefined(e[h]))return n(void 0,e[h])}function o(h){if(Bt.isUndefined(e[h])){if(!Bt.isUndefined(t[h]))return n(void 0,t[h])}else return n(void 0,e[h])}function d(h){if(h in e)return n(t[h],e[h]);if(h in t)return n(void 0,t[h])}var u={url:a,method:a,data:a,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:d};return Bt.forEach(Object.keys(t).concat(Object.keys(e)),function(p){var f=u[p]||i,v=f(p);Bt.isUndefined(v)&&f!==d||(r[p]=v)}),r},ol,np;function ip(){return np||(np=1,ol={version:"0.25.0"}),ol}var lT=ip().version,cl={};["object","boolean","number","function","string","symbol"].forEach(function(s,t){cl[s]=function(r){return typeof r===s||"a"+(t<1?"n ":" ")+s}});var ap={};cl.transitional=function(t,e,r){function n(i,a){return"[Axios v"+lT+"] Transitional option '"+i+"'"+a+(r?". "+r:"")}return function(i,a,o){if(t===!1)throw new Error(n(a," has been removed"+(e?" in "+e:"")));return e&&!ap[a]&&(ap[a]=!0,console.warn(n(a," has been deprecated since v"+e+" and will be removed in the near future"))),t?t(i,a,o):!0}};function uT(s,t,e){if(typeof s!="object")throw new TypeError("options must be an object");for(var r=Object.keys(s),n=r.length;n-- >0;){var i=r[n],a=t[i];if(a){var o=s[i],d=o===void 0||a(o,i,s);if(d!==!0)throw new TypeError("option "+i+" must be "+d);continue}if(e!==!0)throw Error("Unknown option "+i)}}var hT={assertOptions:uT,validators:cl},op=Ot,pT=Vh,cp=Wy,dp=dT,ec=sp,lp=hT,Kn=lp.validators;function ra(s){this.defaults=s,this.interceptors={request:new cp,response:new cp}}ra.prototype.request=function(t,e){if(typeof t=="string"?(e=e||{},e.url=t):e=t||{},!e.url)throw new Error("Provided config url is not valid");e=ec(this.defaults,e),e.method?e.method=e.method.toLowerCase():this.defaults.method?e.method=this.defaults.method.toLowerCase():e.method="get";var r=e.transitional;r!==void 0&&lp.assertOptions(r,{silentJSONParsing:Kn.transitional(Kn.boolean),forcedJSONParsing:Kn.transitional(Kn.boolean),clarifyTimeoutError:Kn.transitional(Kn.boolean)},!1);var n=[],i=!0;this.interceptors.request.forEach(function(v){typeof v.runWhen=="function"&&v.runWhen(e)===!1||(i=i&&v.synchronous,n.unshift(v.fulfilled,v.rejected))});var a=[];this.interceptors.response.forEach(function(v){a.push(v.fulfilled,v.rejected)});var o;if(!i){var d=[dp,void 0];for(Array.prototype.unshift.apply(d,n),d=d.concat(a),o=Promise.resolve(e);d.length;)o=o.then(d.shift(),d.shift());return o}for(var u=e;n.length;){var h=n.shift(),p=n.shift();try{u=h(u)}catch(f){p(f);break}}try{o=dp(u)}catch(f){return Promise.reject(f)}for(;a.length;)o=o.then(a.shift(),a.shift());return o},ra.prototype.getUri=function(t){if(!t.url)throw new Error("Provided config url is not valid");return t=ec(this.defaults,t),pT(t.url,t.params,t.paramsSerializer).replace(/^\?/,"")},op.forEach(["delete","get","head","options"],function(t){ra.prototype[t]=function(e,r){return this.request(ec(r||{},{method:t,url:e,data:(r||{}).data}))}}),op.forEach(["post","put","patch"],function(t){ra.prototype[t]=function(e,r,n){return this.request(ec(n||{},{method:t,url:e,data:r}))}});var mT=ra,dl,up;function fT(){if(up)return dl;up=1;var s=Xo();function t(e){if(typeof e!="function")throw new TypeError("executor must be a function.");var r;this.promise=new Promise(function(a){r=a});var n=this;this.promise.then(function(i){if(n._listeners){var a,o=n._listeners.length;for(a=0;a{t[e.feature.name]={enabled:e.enabled,value:e.feature_state_value}}),t}class ET{constructor(t=gp){m(this,"flags",{});m(this,"environmentKey",null);this.environmentKey=t,this.identify=this.identify.bind(this),this.getValue=this.getValue.bind(this),this.hasFeature=this.hasFeature.bind(this),this.getAllFlags=this.getAllFlags.bind(this)}async identify(t,e={},r=!1,n=5e3,i="edge.api.flagsmith.com"){const a=JSON.parse(JSON.stringify(e)),o=Object.entries(a).map(d=>({trait_key:d[0],trait_value:d[1]}));try{const d="_"+(Math.random()+1).toString(36).substring(2),u=await rc.post(`https://${i}/api/v1/identities/`,{identifier:t+(r?d:""),traits:o},{headers:{"Content-Type":"application/json","X-Environment-Key":this.environmentKey},timeout:n});this.flags=ST(u.data.flags||[])}catch(d){}return this.flags}getValue(t){return this.flags&&this.flags[t]&&this.flags[t].value}hasFeature(t){return this.flags&&this.flags[t]&&this.flags[t].enabled}getAllFlags(){return this.flags}}const J=new ET,vp=[-2,-1,0,1,2],wT=[0,1,2,3,4];function CT(s){s=s.trim();let t="0",e="0",r="0";return s.length==4?(t="0x"+s[1]+s[1],e="0x"+s[2]+s[2],r="0x"+s[3]+s[3]):s.length>6&&(t="0x"+s[1]+s[2],e="0x"+s[3]+s[4],r="0x"+s[5]+s[6]),[+t,+e,+r]}const bT=(s,t,e)=>{let r,n,i;if(t==0)r=n=i=e;else{const a=(u,h,p)=>(p<0&&(p+=1),p>1&&(p-=1),p<.16666666666666666?u+(h-u)*6*p:p<.5?h:p<.6666666666666666?u+(h-u)*(.6666666666666666-p)*6:u),o=e<.5?e*(1+t):e+t-e*t,d=2*e-o;r=a(d,o,s+1/3),n=a(d,o,s),i=a(d,o,s-1/3)}return[Math.round(r*255),Math.round(n*255),Math.round(i*255)]},PT=(s,t,e)=>{s/=255,t/=255,e/=255;const r=Math.max(s,t,e),n=Math.min(s,t,e);let i,a;const o=(r+n)/2;if(r==n)i=a=0;else{const d=r-n;switch(a=o>.5?d/(2-r-n):d/(r+n),r){case s:i=(t-e)/d+(t{const r=n=>n.toString(16).padStart(2,"0");return`#${r(s)}${r(t)}${r(e)}`},yp=(s,t=vp,e=.4)=>{const r=[],[n,i,a]=CT(s),[o,d,u]=PT(n,i,a),h=Math.round(u*100);h>70?e=.8:h>60?e=.9:h<10?e=.075:h<42&&(e=.3);const p=t.findIndex(k=>k===0);if(p===-1)throw new Error("Invalid reducer provided, it must contain atleast one zero");const f=5-p,v=p+1,T=(100-h)/f,P=h/v;for(const k of t){let I;k<0?I=h+k*P*e:k>0?I=h+k*T*e:I=h;const[x,V,O]=bT(o,d,I/100);r.push(RT(x,V,O))}return r},Tp={dark:{background:{1e3:"#252525",900:"#2F2F2F",800:"#323232",700:"#3E3E3E",600:"#4A4A4A"},text:"#F5F5F5","video-bg":"#1C1C1C"},light:{background:{1e3:"#FFFFFF",900:"#F5F5F5",800:"#EBEBEB",700:"#E0E0E0",600:"#D6D6D6"},text:"#111111","text-on-brand":"#ffffff","video-bg":"#DADADA"}},kT=s=>{const[t,e,r,n,i]=yp(s,vp);return{300:t,400:e,500:r,600:n,700:i}},IT=s=>{if(s==="#FFFFFF")return Tp.light.background;if(s==="#000000")return Tp.dark.background;const[t,e,r,n,i]=yp(s,wT);return{1e3:t,900:e,800:r,700:n,600:i}};function AT(){this.__data__=[],this.size=0}function sa(s,t){return s===t||s!==s&&t!==t}function sc(s,t){for(var e=s.length;e--;)if(sa(s[e][0],t))return e;return-1}var MT=Array.prototype,DT=MT.splice;function OT(s){var t=this.__data__,e=sc(t,s);if(e<0)return!1;var r=t.length-1;return e==r?t.pop():DT.call(t,e,1),--this.size,!0}function NT(s){var t=this.__data__,e=sc(t,s);return e<0?void 0:t[e][1]}function LT(s){return sc(this.__data__,s)>-1}function FT(s,t){var e=this.__data__,r=sc(e,s);return r<0?(++this.size,e.push([s,t])):e[r][1]=t,this}function Ur(s){var t=-1,e=s==null?0:s.length;for(this.clear();++t-1&&s%1==0&&s-1&&s%1==0&&s<=Z_}var eS="[object Arguments]",tS="[object Array]",rS="[object Boolean]",sS="[object Date]",nS="[object Error]",iS="[object Function]",aS="[object Map]",oS="[object Number]",cS="[object Object]",dS="[object RegExp]",lS="[object Set]",uS="[object String]",hS="[object WeakMap]",pS="[object ArrayBuffer]",mS="[object DataView]",fS="[object Float32Array]",gS="[object Float64Array]",vS="[object Int8Array]",yS="[object Int16Array]",TS="[object Int32Array]",_S="[object Uint8Array]",SS="[object Uint8ClampedArray]",ES="[object Uint16Array]",wS="[object Uint32Array]",ke={};ke[fS]=ke[gS]=ke[vS]=ke[yS]=ke[TS]=ke[_S]=ke[SS]=ke[ES]=ke[wS]=!0,ke[eS]=ke[tS]=ke[pS]=ke[rS]=ke[mS]=ke[sS]=ke[nS]=ke[iS]=ke[aS]=ke[oS]=ke[cS]=ke[dS]=ke[lS]=ke[uS]=ke[hS]=!1;function CS(s){return Sr(s)&&Mp(s.length)&&!!ke[Zs(s)]}function fl(s){return function(t){return s(t)}}var Dp=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ca=Dp&&typeof module=="object"&&module&&!module.nodeType&&module,bS=ca&&ca.exports===Dp,gl=bS&&_p.process,PS=function(){try{var s=ca&&ca.require&&ca.require("util").types;return s||gl&&gl.binding&&gl.binding("util")}catch(t){}}();const Yn=PS;var Op=Yn&&Yn.isTypedArray,RS=Op?fl(Op):CS;const oc=RS;var kS=Object.prototype,IS=kS.hasOwnProperty;function Np(s,t){var e=hs(s),r=!e&&ac(s),n=!e&&!r&&zn(s),i=!e&&!r&&!n&&oc(s),a=e||r||n||i,o=a?B_(s.length,String):[],d=o.length;for(var u in s)(t||IS.call(s,u))&&!(a&&(u=="length"||n&&(u=="offset"||u=="parent")||i&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||Ap(u,d)))&&o.push(u);return o}var AS=Object.prototype;function cc(s){var t=s&&s.constructor,e=typeof t=="function"&&t.prototype||AS;return s===e}function Lp(s,t){return function(e){return s(t(e))}}var MS=Lp(Object.keys,Object);const DS=MS;var OS=Object.prototype,NS=OS.hasOwnProperty;function Fp(s){if(!cc(s))return DS(s);var t=[];for(var e in Object(s))NS.call(s,e)&&e!="constructor"&&t.push(e);return t}function da(s){return s!=null&&Mp(s.length)&&!hl(s)}function vl(s){return da(s)?Np(s):Fp(s)}function LS(s,t){return s&&oa(t,vl(t),s)}function FS(s){var t=[];if(s!=null)for(var e in Object(s))t.push(e);return t}var xS=Object.prototype,US=xS.hasOwnProperty;function VS(s){if(!or(s))return FS(s);var t=cc(s),e=[];for(var r in s)r=="constructor"&&(t||!US.call(s,r))||e.push(r);return e}function la(s){return da(s)?Np(s,!0):VS(s)}function $S(s,t){return s&&oa(t,la(t),s)}var xp=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Up=xp&&typeof module=="object"&&module&&!module.nodeType&&module,BS=Up&&Up.exports===xp,Vp=BS?ar.Buffer:void 0,$p=Vp?Vp.allocUnsafe:void 0;function Bp(s,t){if(t)return s.slice();var e=s.length,r=$p?$p(e):new s.constructor(e);return s.copy(r),r}function Hp(s,t){var e=-1,r=s.length;for(t||(t=Array(r));++e0){if(++t>=Lw)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}function Vw(s){return function(){return s}}var $w=ic?function(s,t){return ic(s,"toString",{configurable:!0,enumerable:!1,value:Vw(t),writable:!0})}:hm,Bw=Uw($w);const Hw=Bw;var pm=Math.max;function qw(s,t,e){return t=pm(t===void 0?s.length-1:t,0),function(){for(var r=arguments,n=-1,i=pm(r.length-t,0),a=Array(i);++n1?e[n-1]:void 0,a=n>2?e[2]:void 0;for(i=s.length>3&&typeof i=="function"?(n--,i):void 0,a&&Gw(e[0],e[1],a)&&(i=n<3?void 0:i,n=1),t=Object(t);++ro))return!1;var u=i.get(s),h=i.get(t);if(u&&h)return u==t&&h==s;var p=-1,f=!0,v=e&iC?new uc:void 0;for(i.set(s,t),i.set(t,s);++p=t||oe<0||p&&ve>=i}function I(){var Q=Il();if(k(Q))return x(Q);o=setTimeout(I,P(Q))}function x(Q){return o=void 0,f&&r?v(Q):(r=n=void 0,a)}function V(){o!==void 0&&clearTimeout(o),u=0,r=d=n=o=void 0}function O(){return o===void 0?a:x(Il())}function W(){var Q=Il(),oe=k(Q);if(r=arguments,n=this,d=Q,oe){if(o===void 0)return T(d);if(p)return clearTimeout(o),o=setTimeout(I,t),v(d)}return o===void 0&&(o=setTimeout(I,t)),a}return W.cancel=V,W.flush=O,W}function Al(s,t,e){(e!==void 0&&!sa(s[t],e)||e===void 0&&!(t in s))&&ml(s,t,e)}function FC(s){return Sr(s)&&da(s)}function Ml(s,t){if(!(t==="constructor"&&typeof s[t]=="function")&&t!="__proto__")return s[t]}function xC(s){return oa(s,la(s))}function UC(s,t,e,r,n,i,a){var o=Ml(s,e),d=Ml(t,e),u=a.get(d);if(u){Al(s,e,u);return}var h=i?i(o,d,e+"",s,t,a):void 0,p=h===void 0;if(p){var f=hs(d),v=!f&&zn(d),T=!f&&!v&&oc(d);h=d,f||v||T?hs(o)?h=o:FC(o)?h=Hp(o):v?(p=!1,h=Bp(d,!0)):T?(p=!1,h=tm(d,!0)):h=[]:Xw(d)||ac(d)?(h=o,ac(o)?h=xC(o):(!or(o)||hl(o))&&(h=sm(d))):p=!1}p&&(a.set(d,h),n(h,d,r,i,a),a.delete(d)),Al(s,e,h)}function Sm(s,t,e,r,n){s!==t&&MC(t,function(i,a){if(n||(n=new _r),or(i))UC(s,t,a,e,Sm,r,n);else{var o=r?r(Ml(s,a),i,a+"",s,t,n):void 0;o===void 0&&(o=i),Al(s,a,o)}},la)}var VC="[object Map]",$C="[object Set]",BC=Object.prototype,HC=BC.hasOwnProperty;function qC(s){if(s==null)return!0;if(da(s)&&(hs(s)||typeof s=="string"||typeof s.splice=="function"||zn(s)||oc(s)||ac(s)))return!s.length;var t=Qn(s);if(t==VC||t==$C)return!s.size;if(cc(s))return!Fp(s).length;for(var e in s)if(HC.call(s,e))return!1;return!0}function jC(s,t){return _m(s,t)}var GC=Jw(function(s,t,e){Sm(s,t,e)});const ps=GC;var Dl=(s=>(s.PARTICIPANT="PARTICIPANT",s.PEER="PEER",s.CLIENT="CLIENT",s))(Dl||{});const X={PROPAGATE_KICK_ALL:"propagate_kick_across_rooms",REFRESH_ID_ON_DISCONNECTION:"refresh_id_on_disconnection",SIMULCAST:"simulcast",CHAT_SOCKET_SERVER:"chat_socket_server",POLL_SOCKET_SERVER:"poll_socket_server",PLUGIN_SOCKET_SERVER:"plugin_socket_server",NR_OTEL_WEB:"nr_otel_web",CONNECTED_MEETINGS:"connected_meetings",ICE_RESTART_ON_FAILED_STATE:"ice_restart_on_failed_state",ICE_RESTART_ON_DISCONNECTED_STATE:"ice_restart_on_disconnected_state",ENABLE_ICE_STATE_LOGGING:"enable_ice_state_logging",SUPPRESS_PEER_MUTE_UNMUTE_EMITS:"web_core_suppress_peer_mute_unmute_emits",SKIP_OTEL_TRACES:"skip_otel_traces",USE_USERIDS_IN_CHAT:"use_userids_in_chat",CUSTOM_PING_PONG:"custom_ping_pong",ENABLE_HIVE_SIMULCAST:"enable_hive_simulcast",ENABLE_HIVE_TRANSPORT_RECONNECTION_ON_ICE_FAILED:"enable_hive_transport_reconnection_on_ice_failed",ENABLE_HIVE_EXPERIMENTAL_FAIL_RECOVERY:"enable_hive_fail_recovery",ENABLE_HIVE_INFINITE_RETRIES:"enable_hive_infinite_retries",HIVE_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED:"hive_transport_force_relay_on_ice_failed",ENABLE_HIVE_CONSUME_OVER_DC:"enable_hive_consume_over_dc",ENABLE_CF_SIMULCAST:"enable_cf_simulcast",ENABLE_CF_TRANSPORT_RECONNECTION_ON_ICE_FAILED:"enable_cf_transport_reconnection_on_ice_failed",ENABLE_CF_EXPERIMENTAL_FAIL_RECOVERY:"enable_cf_fail_recovery",ENABLE_CF_INFINITE_RETRIES:"enable_cf_infinite_retries",CF_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED:"cf_transport_force_relay_on_ice_failed",BYPASS_LOG_EXCLUSION_LIST:"bypass_log_exclusion_list",LOG_LEVEL:"log_level",V1_PLUGINS:"v1_plugins",SCREENSHARE_DTX:"screenshare_dtx",SCREENSHARE_PRIORITY:"screenshare_priority",SCREENSHARE_MIN_BITRATE:"screenshare_minbitrate",SCREENSHARE_SIMULCAST:"screenshare_simulcast",DISABLE_WEBCAM_LAYERS_ON_SCREENSHARE:"disable_webcam_layers_on_screenshare",SCREENSHARE_FORCE_GOOG_CONFERENCE:"screenshare_force_goog_conference",LIVESTREAM:"feat_livestream",FETCH_RETRY:"fetch_retry",DISABLE_WEBCAM_SIMULCAST:"webcore_disable_webcam_simulcast",OVERRIDE_WEBCAM_SIMULCAST:"override_webcam_simulcast",SOCKET_POLLING:"socket_polling",FEAT_PAGINATED_CHAT:"feat_paginated_chat",VAL_MIN_FRAMERATE:"val_min_framerate",SCREEENSHARE_ERR_HACK:"screenshare_err_hack",SCREEENSHARE_CONSTRAINTS_RETRY:"screenshare_constraints_retry",TROUBLESHOOTING:"feat_troubleshooting",VIDEO_CONSTRAINTS:"video_constraints",SCREENSHARE_CONSTRAINTS:"screenshare_constraints",FEAT_CHAT_SDK:"feat_chat_sdk",FEAT_CHAT_SDK_SEARCH:"chat_search",OBS_QUALITY:"obs_quality",ALLOW_SAFARI_MEDIA_MIDDLEWARES:"allow_safari_media_middlewares",DYNAMIC_VIDEO_QUALITY:"dynamic_video_quality",EXP_RESHARE:"exp_reshare",LEAVE_STAGE_ON_END:"leave_stage_on_end",SKIP_SETTING_IN_USE_DEVICE:"skip_setting_in_use_device",PRECALL_BANDWIDTH_TEST:"precall_bandwidth_test",CONSUMER_BIND_NO_RETRY:"consumer_bind_no_retry",DEBUG_SOCKET_JOIN:"debug_socket_join"};function pc(s){const t={};return typeof(s==null?void 0:s.code)=="number"&&(t.code=s.code),typeof(s==null?void 0:s.code)=="string"&&(t.code=s.code.substring(0,100)),typeof(s==null?void 0:s.name)=="string"&&(t.name=s.name.substring(0,500)),typeof(s==null?void 0:s.message)=="string"&&(t.message=s.message.substring(0,500)),typeof(s==null?void 0:s.reason)=="string"&&(t.reason=s.reason.substring(0,500)),typeof(s==null?void 0:s.stack)=="string"&&(t.stack=s.stack.substring(0,500)),t}function Em(s){var r,n,i,a;const t=typeof navigator!="undefined"&&!navigator.isReactNative&&typeof window!="undefined"&&((r=window.location.host)==null?void 0:r.includes("devel"))&&((n=window.location.host)==null?void 0:n.includes("dyte.io")),e=!!((a=(i=s==null?void 0:s.getValue("modules"))==null?void 0:i.devTools)!=null&&a.logs);return t||e}function JC(s){if(J.hasFeature(X.LOG_LEVEL)){let t=J.getValue(X.LOG_LEVEL)||"all";if(t=t.toLowerCase().trim(),t==="off")return!1;if(t!=="all"){const e=["debug","log","info","warn","error"],r=e.indexOf(s),n=e.indexOf(t);if(r{var i;if([null,void 0,NaN].includes(s[r])||t&&(((i=t.match(/\./g))==null?void 0:i.length)||0)>=10)return;const n=t?`${t}.${r}`:r;typeof s[r]=="object"?wm(s[r],n,e):["number","string","boolean"].includes(typeof s[r])&&(e[n]=s[r])}),e}function Cm(s,t,e={},r=""){const n={};try{const i=JSON.stringify(e),a=JSON.parse(i),o=wm(a,r),d=JSON.stringify(o);if(d.length>5e3){const u=`Log named: "${t}" is trying to log an flattened object of size ${d.length} chars that is beyond permitted limit of 5000 chars. Please optimize.`;throw Em(s)&&console.error(u,{log:e,flattened:d}),new Error(u)}return JSON.parse(d)}catch(i){const a=pc(i);n[`${r}.error.message`]=a.message||"",n[`${r}.error.stack`]=a.stack||"",n[`${r}.error.reason`]=a.reason||"",n[`${r}.error.source`]="safelyFlattenObjForOpenTelemetry"}return n}const WC={"Amazon Silk":"amazon_silk","Android Browser":"android",Bada:"bada",BlackBerry:"blackberry",Chrome:"chrome",Chromium:"chromium",Electron:"electron",Epiphany:"epiphany",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot","Internet Explorer":"ie","K-Meleon":"k_meleon",Maxthon:"maxthon","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver",Opera:"opera","Opera Coast":"opera_coast",PhantomJS:"phantomjs",Puffin:"puffin",QupZilla:"qupzilla",QQ:"qq",QQLite:"qqlite",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SeaMonkey:"seamonkey",Sleipnir:"sleipnir",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat","Yandex Browser":"yandex",Roku:"roku"},bm={amazon_silk:"Amazon Silk",android:"Android Browser",bada:"Bada",blackberry:"BlackBerry",chrome:"Chrome",chromium:"Chromium",electron:"Electron",epiphany:"Epiphany",firefox:"Firefox",focus:"Focus",generic:"Generic",googlebot:"Googlebot",google_search:"Google Search",ie:"Internet Explorer",k_meleon:"K-Meleon",maxthon:"Maxthon",edge:"Microsoft Edge",mz:"MZ Browser",naver:"NAVER Whale Browser",opera:"Opera",opera_coast:"Opera Coast",phantomjs:"PhantomJS",puffin:"Puffin",qupzilla:"QupZilla",qq:"QQ Browser",qqlite:"QQ Browser Lite",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",sleipnir:"Sleipnir",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yandex:"Yandex Browser"},Ge={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"},bt={WindowsPhone:"Windows Phone",Windows:"Windows",MacOS:"macOS",iOS:"iOS",Android:"Android",WebOS:"WebOS",BlackBerry:"BlackBerry",Bada:"Bada",Tizen:"Tizen",Linux:"Linux",ChromeOS:"Chrome OS",PlayStation4:"PlayStation 4",Roku:"Roku"},ms={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"};class N{static getFirstMatch(t,e){const r=e.match(t);return r&&r.length>0&&r[1]||""}static getSecondMatch(t,e){const r=e.match(t);return r&&r.length>1&&r[2]||""}static matchAndReturnConst(t,e,r){if(t.test(e))return r}static getWindowsVersionName(t){switch(t){case"NT":return"NT";case"XP":return"XP";case"NT 5.0":return"2000";case"NT 5.1":return"XP";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}}static getMacOSVersionName(t){const e=t.split(".").splice(0,2).map(r=>parseInt(r,10)||0);if(e.push(0),e[0]===10)switch(e[1]){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}}static getAndroidVersionName(t){const e=t.split(".").splice(0,2).map(r=>parseInt(r,10)||0);if(e.push(0),!(e[0]===1&&e[1]<5)){if(e[0]===1&&e[1]<6)return"Cupcake";if(e[0]===1&&e[1]>=6)return"Donut";if(e[0]===2&&e[1]<2)return"Eclair";if(e[0]===2&&e[1]===2)return"Froyo";if(e[0]===2&&e[1]>2)return"Gingerbread";if(e[0]===3)return"Honeycomb";if(e[0]===4&&e[1]<1)return"Ice Cream Sandwich";if(e[0]===4&&e[1]<4)return"Jelly Bean";if(e[0]===4&&e[1]>=4)return"KitKat";if(e[0]===5)return"Lollipop";if(e[0]===6)return"Marshmallow";if(e[0]===7)return"Nougat";if(e[0]===8)return"Oreo";if(e[0]===9)return"Pie"}}static getVersionPrecision(t){return t.split(".").length}static compareVersions(t,e,r=!1){const n=N.getVersionPrecision(t),i=N.getVersionPrecision(e);let a=Math.max(n,i),o=0;const d=N.map([t,e],u=>{const h=a-N.getVersionPrecision(u),p=u+new Array(h+1).join(".0");return N.map(p.split("."),f=>new Array(20-f.length).join("0")+f).reverse()});for(r&&(o=a-Math.min(n,i)),a-=1;a>=o;){if(d[0][a]>d[1][a])return 1;if(d[0][a]===d[1][a]){if(a===o)return 0;a-=1}else if(d[0][a]{r[d]=a[d]})}return t}static getBrowserAlias(t){return WC[t]}static getBrowserTypeByAlias(t){return bm[t]||""}}const _e=/version\/(\d+(\.?_?\d+)+)/i,KC=[{test:[/googlebot/i],describe(s){const t={name:"Googlebot"},e=N.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,s)||N.getFirstMatch(_e,s);return e&&(t.version=e),t}},{test:[/opera/i],describe(s){const t={name:"Opera"},e=N.getFirstMatch(_e,s)||N.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/opr\/|opios/i],describe(s){const t={name:"Opera"},e=N.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,s)||N.getFirstMatch(_e,s);return e&&(t.version=e),t}},{test:[/SamsungBrowser/i],describe(s){const t={name:"Samsung Internet for Android"},e=N.getFirstMatch(_e,s)||N.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/Whale/i],describe(s){const t={name:"NAVER Whale Browser"},e=N.getFirstMatch(_e,s)||N.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/MZBrowser/i],describe(s){const t={name:"MZ Browser"},e=N.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,s)||N.getFirstMatch(_e,s);return e&&(t.version=e),t}},{test:[/focus/i],describe(s){const t={name:"Focus"},e=N.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,s)||N.getFirstMatch(_e,s);return e&&(t.version=e),t}},{test:[/swing/i],describe(s){const t={name:"Swing"},e=N.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,s)||N.getFirstMatch(_e,s);return e&&(t.version=e),t}},{test:[/coast/i],describe(s){const t={name:"Opera Coast"},e=N.getFirstMatch(_e,s)||N.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe(s){const t={name:"Opera Touch"},e=N.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,s)||N.getFirstMatch(_e,s);return e&&(t.version=e),t}},{test:[/yabrowser/i],describe(s){const t={name:"Yandex Browser"},e=N.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,s)||N.getFirstMatch(_e,s);return e&&(t.version=e),t}},{test:[/ucbrowser/i],describe(s){const t={name:"UC Browser"},e=N.getFirstMatch(_e,s)||N.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/Maxthon|mxios/i],describe(s){const t={name:"Maxthon"},e=N.getFirstMatch(_e,s)||N.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/epiphany/i],describe(s){const t={name:"Epiphany"},e=N.getFirstMatch(_e,s)||N.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/puffin/i],describe(s){const t={name:"Puffin"},e=N.getFirstMatch(_e,s)||N.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/sleipnir/i],describe(s){const t={name:"Sleipnir"},e=N.getFirstMatch(_e,s)||N.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/k-meleon/i],describe(s){const t={name:"K-Meleon"},e=N.getFirstMatch(_e,s)||N.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/micromessenger/i],describe(s){const t={name:"WeChat"},e=N.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,s)||N.getFirstMatch(_e,s);return e&&(t.version=e),t}},{test:[/qqbrowser/i],describe(s){const t={name:/qqbrowserlite/i.test(s)?"QQ Browser Lite":"QQ Browser"},e=N.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,s)||N.getFirstMatch(_e,s);return e&&(t.version=e),t}},{test:[/msie|trident/i],describe(s){const t={name:"Internet Explorer"},e=N.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/\sedg\//i],describe(s){const t={name:"Microsoft Edge"},e=N.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/edg([ea]|ios)/i],describe(s){const t={name:"Microsoft Edge"},e=N.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/vivaldi/i],describe(s){const t={name:"Vivaldi"},e=N.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/seamonkey/i],describe(s){const t={name:"SeaMonkey"},e=N.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/sailfish/i],describe(s){const t={name:"Sailfish"},e=N.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,s);return e&&(t.version=e),t}},{test:[/silk/i],describe(s){const t={name:"Amazon Silk"},e=N.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/phantom/i],describe(s){const t={name:"PhantomJS"},e=N.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/slimerjs/i],describe(s){const t={name:"SlimerJS"},e=N.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(s){const t={name:"BlackBerry"},e=N.getFirstMatch(_e,s)||N.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/(web|hpw)[o0]s/i],describe(s){const t={name:"WebOS Browser"},e=N.getFirstMatch(_e,s)||N.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/bada/i],describe(s){const t={name:"Bada"},e=N.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/tizen/i],describe(s){const t={name:"Tizen"},e=N.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,s)||N.getFirstMatch(_e,s);return e&&(t.version=e),t}},{test:[/qupzilla/i],describe(s){const t={name:"QupZilla"},e=N.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,s)||N.getFirstMatch(_e,s);return e&&(t.version=e),t}},{test:[/firefox|iceweasel|fxios/i],describe(s){const t={name:"Firefox"},e=N.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/electron/i],describe(s){const t={name:"Electron"},e=N.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/MiuiBrowser/i],describe(s){const t={name:"Miui"},e=N.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/chromium/i],describe(s){const t={name:"Chromium"},e=N.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,s)||N.getFirstMatch(_e,s);return e&&(t.version=e),t}},{test:[/chrome|crios|crmo/i],describe(s){const t={name:"Chrome"},e=N.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/GSA/i],describe(s){const t={name:"Google Search"},e=N.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test(s){const t=!s.test(/like android/i),e=s.test(/android/i);return t&&e},describe(s){const t={name:"Android Browser"},e=N.getFirstMatch(_e,s);return e&&(t.version=e),t}},{test:[/playstation 4/i],describe(s){const t={name:"PlayStation 4"},e=N.getFirstMatch(_e,s);return e&&(t.version=e),t}},{test:[/safari|applewebkit/i],describe(s){const t={name:"Safari"},e=N.getFirstMatch(_e,s);return e&&(t.version=e),t}},{test:[/.*/i],describe(s){const t=/^(.*)\/(.*) /,e=/^(.*)\/(.*)[ \t]\((.*)/,n=s.search("\\(")!==-1?e:t;return{name:N.getFirstMatch(n,s),version:N.getSecondMatch(n,s)}}}],zC=[{test:[/Roku\/DVP/],describe(s){const t=N.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,s);return{name:bt.Roku,version:t}}},{test:[/windows phone/i],describe(s){const t=N.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,s);return{name:bt.WindowsPhone,version:t}}},{test:[/windows /i],describe(s){const t=N.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,s),e=N.getWindowsVersionName(t);return{name:bt.Windows,version:t,versionName:e}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(s){const t={name:bt.iOS},e=N.getSecondMatch(/(Version\/)(\d[\d.]+)/,s);return e&&(t.version=e),t}},{test:[/macintosh/i],describe(s){const t=N.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,s).replace(/[_\s]/g,"."),e=N.getMacOSVersionName(t),r={name:bt.MacOS,version:t};return e&&(r.versionName=e),r}},{test:[/(ipod|iphone|ipad)/i],describe(s){const t=N.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,s).replace(/[_\s]/g,".");return{name:bt.iOS,version:t}}},{test(s){const t=!s.test(/like android/i),e=s.test(/android/i);return t&&e},describe(s){const t=N.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,s),e=N.getAndroidVersionName(t),r={name:bt.Android,version:t};return e&&(r.versionName=e),r}},{test:[/(web|hpw)[o0]s/i],describe(s){const t=N.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,s),e={name:bt.WebOS};return t&&t.length&&(e.version=t),e}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(s){const t=N.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,s)||N.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,s)||N.getFirstMatch(/\bbb(\d+)/i,s);return{name:bt.BlackBerry,version:t}}},{test:[/bada/i],describe(s){const t=N.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,s);return{name:bt.Bada,version:t}}},{test:[/tizen/i],describe(s){const t=N.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,s);return{name:bt.Tizen,version:t}}},{test:[/linux/i],describe(){return{name:bt.Linux}}},{test:[/CrOS/],describe(){return{name:bt.ChromeOS}}},{test:[/PlayStation 4/],describe(s){const t=N.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,s);return{name:bt.PlayStation4,version:t}}}],YC=[{test:[/googlebot/i],describe(){return{type:"bot",vendor:"Google"}}},{test:[/huawei/i],describe(s){const t=N.getFirstMatch(/(can-l01)/i,s)&&"Nova",e={type:Ge.mobile,vendor:"Huawei"};return t&&(e.model=t),e}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe(){return{type:Ge.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe(){return{type:Ge.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(){return{type:Ge.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe(){return{type:Ge.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe(){return{type:Ge.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe(){return{type:Ge.tablet}}},{test(s){const t=s.test(/ipod|iphone/i),e=s.test(/like (ipod|iphone)/i);return t&&!e},describe(s){const t=N.getFirstMatch(/(ipod|iphone)/i,s);return{type:Ge.mobile,vendor:"Apple",model:t}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe(){return{type:Ge.mobile,vendor:"Nexus"}}},{test:[/[^-]mobi/i],describe(){return{type:Ge.mobile}}},{test(s){return s.getBrowserName(!0)==="blackberry"},describe(){return{type:Ge.mobile,vendor:"BlackBerry"}}},{test(s){return s.getBrowserName(!0)==="bada"},describe(){return{type:Ge.mobile}}},{test(s){return s.getBrowserName()==="windows phone"},describe(){return{type:Ge.mobile,vendor:"Microsoft"}}},{test(s){const t=Number(String(s.getOSVersion()).split(".")[0]);return s.getOSName(!0)==="android"&&t>=3},describe(){return{type:Ge.tablet}}},{test(s){return s.getOSName(!0)==="android"},describe(){return{type:Ge.mobile}}},{test(s){return s.getOSName(!0)==="macos"},describe(){return{type:Ge.desktop,vendor:"Apple"}}},{test(s){return s.getOSName(!0)==="windows"},describe(){return{type:Ge.desktop}}},{test(s){return s.getOSName(!0)==="linux"},describe(){return{type:Ge.desktop}}},{test(s){return s.getOSName(!0)==="playstation 4"},describe(){return{type:Ge.tv}}},{test(s){return s.getOSName(!0)==="roku"},describe(){return{type:Ge.tv}}}],QC=[{test(s){return s.getBrowserName(!0)==="microsoft edge"},describe(s){if(/\sedg\//i.test(s))return{name:ms.Blink};const e=N.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,s);return{name:ms.EdgeHTML,version:e}}},{test:[/trident/i],describe(s){const t={name:ms.Trident},e=N.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test(s){return s.test(/presto/i)},describe(s){const t={name:ms.Presto},e=N.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test(s){const t=s.test(/gecko/i),e=s.test(/like gecko/i);return t&&!e},describe(s){const t={name:ms.Gecko},e=N.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/(apple)?webkit\/537\.36/i],describe(){return{name:ms.Blink}}},{test:[/(apple)?webkit/i],describe(s){const t={name:ms.WebKit},e=N.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}}];class Pm{constructor(t,e=!1){if(t==null||t==="")throw new Error("UserAgent parameter can't be empty");this._ua=t,this.parsedResult={},e!==!0&&this.parse()}getUA(){return this._ua}test(t){return t.test(this._ua)}parseBrowser(){this.parsedResult.browser={};const t=N.find(KC,e=>{if(typeof e.test=="function")return e.test(this);if(e.test instanceof Array)return e.test.some(r=>this.test(r));throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.browser=t.describe(this.getUA())),this.parsedResult.browser}getBrowser(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()}getBrowserName(t){return t?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""}getBrowserVersion(){return this.getBrowser().version}getOS(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()}parseOS(){this.parsedResult.os={};const t=N.find(zC,e=>{if(typeof e.test=="function")return e.test(this);if(e.test instanceof Array)return e.test.some(r=>this.test(r));throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.os=t.describe(this.getUA())),this.parsedResult.os}getOSName(t){const{name:e}=this.getOS();return t?String(e).toLowerCase()||"":e||""}getOSVersion(){return this.getOS().version}getPlatform(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()}getPlatformType(t=!1){const{type:e}=this.getPlatform();return t?String(e).toLowerCase()||"":e||""}parsePlatform(){this.parsedResult.platform={};const t=N.find(YC,e=>{if(typeof e.test=="function")return e.test(this);if(e.test instanceof Array)return e.test.some(r=>this.test(r));throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.platform=t.describe(this.getUA())),this.parsedResult.platform}getEngine(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()}getEngineName(t){return t?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""}parseEngine(){this.parsedResult.engine={};const t=N.find(QC,e=>{if(typeof e.test=="function")return e.test(this);if(e.test instanceof Array)return e.test.some(r=>this.test(r));throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.engine=t.describe(this.getUA())),this.parsedResult.engine}parse(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this}getResult(){return N.assign({},this.parsedResult)}satisfies(t){const e={};let r=0;const n={};let i=0;if(Object.keys(t).forEach(o=>{const d=t[o];typeof d=="string"?(n[o]=d,i+=1):typeof d=="object"&&(e[o]=d,r+=1)}),r>0){const o=Object.keys(e),d=N.find(o,h=>this.isOS(h));if(d){const h=this.satisfies(e[d]);if(h!==void 0)return h}const u=N.find(o,h=>this.isPlatform(h));if(u){const h=this.satisfies(e[u]);if(h!==void 0)return h}}if(i>0){const o=Object.keys(n),d=N.find(o,u=>this.isBrowser(u,!0));if(d!==void 0)return this.compareVersion(n[d])}}isBrowser(t,e=!1){const r=this.getBrowserName().toLowerCase();let n=t.toLowerCase();const i=N.getBrowserTypeByAlias(n);return e&&i&&(n=i.toLowerCase()),n===r}compareVersion(t){let e=[0],r=t,n=!1;const i=this.getBrowserVersion();if(typeof i=="string")return t[0]===">"||t[0]==="<"?(r=t.substr(1),t[1]==="="?(n=!0,r=t.substr(2)):e=[],t[0]===">"?e.push(1):e.push(-1)):t[0]==="="?r=t.substr(1):t[0]==="~"&&(n=!0,r=t.substr(1)),e.indexOf(N.compareVersions(i,r,n))>-1}isOS(t){return this.getOSName(!0)===String(t).toLowerCase()}isPlatform(t){return this.getPlatformType(!0)===String(t).toLowerCase()}isEngine(t){return this.getEngineName(!0)===String(t).toLowerCase()}is(t,e=!1){return this.isBrowser(t,e)||this.isOS(t)||this.isPlatform(t)}some(t=[]){return t.some(e=>this.is(e))}}/*! * Bowser - a browser detector @@ -9,15 +9,15 @@ ${d.length} chars that is beyond permitted limit of 5000 chars. Please optimize. * MIT License | (c) Dustin Diaz 2012-2015 * MIT License | (c) Denis Demchenko 2015-2019 */class Rm{static getParser(t,e=!1){if(typeof t!="string")throw new Error("UserAgent should be a string");return new Pm(t,e)}static parse(t){return new Pm(t).getResult()}static get BROWSER_MAP(){return bm}static get ENGINE_MAP(){return ms}static get OS_MAP(){return bt}static get PLATFORMS_MAP(){return Ge}}const ua="chrome",km="opera",Im="firefox",Am="iexplorer",Mm="safari",Dm="nwjs",Om="electron",Nm="react-native",Ol="unknown",mc={Chrome:ua,Chromium:ua,Opera:km,Firefox:Im,"Internet Explorer":Am,Safari:Mm};function XC(){const{userAgent:s}=navigator,t={name:Ol,version:void 0};if(s.match(/Chrome/)&&!s.match(/Edge/))if(s.match(/Edg(A?)/)){const e=s.match(/Chrome\/([\d.]+)/)[1];Number.parseInt(e,10)>72&&(t.name=ua,t.version=e)}else t.name=ua,t.version=s.match(/Chrome\/([\d.]+)/)[1];return t}function ZC(){const{userAgent:s}=navigator;if(s.match(/Electron/)){const t=s.match(/Electron\/([\d.]+)/)[1];return{name:Om,version:t}}return null}function eb(){const{userAgent:s}=navigator;if(s.match(/JitsiMeetNW/)){const t=s.match(/JitsiMeetNW\/([\d.]+)/)[1];return{name:Dm,version:t}}}function tb(){const s=navigator.userAgent.match(/\b(react[ \t_-]*native)(?:\/(\S+))?/i);let t;if(s||navigator.product==="ReactNative")return s&&s.length>2&&(s[1],t=s[2]),t||(t="unknown"),{name:Nm,version:t}}function rb(s){let t;const e=[tb,ZC,eb];for(let n=0;n({isMobile:this.isMobile(),browserName:this._bowser.getBrowserName(),osName:this._bowser.getOSName(),browserVersion:this._bowser.getBrowserVersion(),osVersionName:this._bowser.getOSVersion(),engineName:this._bowser.getEngineName()}))}init(t){let e,r;if(this._bowser=Rm.getParser(navigator.userAgent),typeof t=="undefined"){const n=rb(this._bowser);e=n.name,r=n.version}else t.name in mc?(e=mc[t.name],r=t.version):(e=Ol,r=void 0);this._name=e,this._version=r}getName(){return this._name}isChrome(){return this._name===ua}isOpera(){return this._name===km}isFirefox(){return this._name===Im}isIExplorer(){return this._name===Am}isSafari(){return this._name===Mm}isNWJS(){return this._name===Dm}isElectron(){return this._name===Om}isReactNative(){return this._name===Nm||navigator.isReactNative===!0}getVersion(){return this._version}isMobile(){return this._bowser.getPlatformType()==="mobile"}_checkCondition(t){if(this._version)return this._bowser.satisfies(t)}isVersionGreaterThan(t){return this._checkCondition({[this._name]:`>${t}`})}isVersionLessThan(t){return this._checkCondition({[this._name]:`<${t}`})}isVersionEqualTo(t){return this._checkCondition({[this._name]:`~${t}`})}}class nb extends sb{doesVideoMuteByStreamRemove(){return this.isChromiumBased()||this.isWebKitBased()}supportsP2P(){return!this.usesUnifiedPlan()}isChromiumBased(){return this.isChrome()||this.isElectron()||this.isNWJS()||this.isOpera()}isWebKitBased(){return this._bowser.isEngine("webkit")&&typeof navigator.mediaDevices!="undefined"&&typeof navigator.mediaDevices.getUserMedia!="undefined"&&typeof window.RTCRtpTransceiver!="undefined"&&Object.keys(RTCRtpTransceiver.prototype).indexOf("currentDirection")>-1}isSupported(){return typeof RTCPeerConnection!="undefined"}isUserInteractionRequiredForUnmute(){return this.isFirefox()&&this.isVersionLessThan("68")}supportsVideoMuteOnConnInterrupted(){return this.isChromiumBased()||this.isReactNative()||this.isWebKitBased()}supportsBandwidthStatistics(){return!this.isFirefox()&&!this.isWebKitBased()}supportsCodecPreferences(){return this.usesUnifiedPlan()&&typeof window.RTCRtpTransceiver!="undefined"&&Object.keys(window.RTCRtpTransceiver.prototype).indexOf("setCodecPreferences")>-1&&Object.keys(RTCRtpSender.prototype).indexOf("getCapabilities")>-1&&!this.isWebKitBased()}supportsDeviceChangeEvent(){return navigator.mediaDevices&&typeof navigator.mediaDevices.ondevicechange!="undefined"&&typeof navigator.mediaDevices.addEventListener!="undefined"}supportsLocalCandidateRttStatistics(){return this.isChromiumBased()||this.isReactNative()||this.isWebKitBased()}supportsPerformanceObserver(){return typeof window.PerformanceObserver!="undefined"&&PerformanceObserver.supportedEntryTypes.indexOf("longtask")>-1}supportsReceiverStats(){return typeof window.RTCRtpReceiver!="undefined"&&Object.keys(RTCRtpReceiver.prototype).indexOf("getSynchronizationSources")>-1}supportsRTTStatistics(){return!this.isFirefox()}usesPlanB(){return!this.usesUnifiedPlan()}usesSdpMungingForSimulcast(){return this.isChromiumBased()||this.isReactNative()||this.isWebKitBased()}usesUnifiedPlan(){return!!(this.isFirefox()||this.isWebKitBased())}usesNewGumFlow(){return!!(this.isChromiumBased()||this.isFirefox()||this.isWebKitBased())}usesAdapter(){return this.usesNewGumFlow()}usesRidsForSimulcast(){return!1}supportsGetDisplayMedia(){return typeof navigator.getDisplayMedia!="undefined"||typeof navigator.mediaDevices!="undefined"&&typeof navigator.mediaDevices.getDisplayMedia!="undefined"}supportsInsertableStreams(){if(!(typeof window.RTCRtpSender!="undefined"&&(window.RTCRtpSender.prototype.createEncodedStreams||window.RTCRtpSender.prototype.createEncodedVideoStreams)))return!1;const t=new ReadableStream;try{return window.postMessage(t,"*",[t]),!0}catch(e){return!1}}supportsAudioRed(){return Boolean(window.RTCRtpSender&&window.RTCRtpSender.getCapabilities&&window.RTCRtpSender.getCapabilities("audio").codecs.some(t=>t.mimeType==="audio/red")&&window.RTCRtpReceiver&&window.RTCRtpReceiver.getCapabilities&&window.RTCRtpReceiver.getCapabilities("audio").codecs.some(t=>t.mimeType==="audio/red"))}supportsSdpSemantics(){return this.isChromiumBased()}_getChromiumBasedVersion(){if(this.isChromiumBased()){if(this.isNWJS())return Number.parseInt(process.versions.chromium,10);const t=navigator.userAgent;if(t.match(/Chrome/))return Number.parseInt(t.match(/Chrome\/([\d.]+)/)[1],10)}return-1}isIOSMobile(){return this.isMobile&&this._bowser.getOSName()==="iOS"}}const Se=new nb,ib={audio:!0,video:!0,screenshareAudio:!0,screenshareVideo:!0},ha={baseURL:"http://localhost:5000",createdAt:"2021-08-05T10:49:56.602Z",description:"Develop plugins locally",id:"09259e3b-7be8-46f6-9801-106bf1866e1c",name:"Localhost Dev",organizationId:"4ad15a19-80e2-4105-bf43-48039fd2963e",picture:"https://dyte-uploads.s3.ap-south-1.amazonaws.com/dyte.png",private:!1,published:!0,staggered:!1,tags:["#localhost","#dev"],type:"self_hosted",updatedAt:"2021-08-05T10:50:07.681Z"},ab={pip:!0,poll:!0,chat:!0,stage:!0,theme:!0,plugin:!0,tracing:!0,internals:!0,recording:!0,livestream:!0,participant:!0,devTools:{logs:!1}};function Nl(s,t){const e=s.getValue("overrides");return e&&e[t]?e[t]:!1}function ob({baseURI:s}){return s!=null&&s.includes("preprod.dyte")?ta.PREPROD:s!=null&&s.includes("devel.dyte")?ta.DEVEL:ta.PROD}function Xn({servicePrefix:s,baseURI:t}){return`${s}.${t}`}function Lm(s){const t=s.getValue("baseURI");return{location:Xn({servicePrefix:"location",baseURI:t}),locationLegacy:Xn({servicePrefix:"location-legacy",baseURI:t}),daCollector:Xn({servicePrefix:"da-collector",baseURI:t})}}const cb='',db='',fc=s=>{const t=s.startsWith("{i(s)});const r=new Blob([s],{type:"image/svg+xml"}),n=window.URL.createObjectURL(r);return new Promise((i,a)=>{e.onload=()=>{i(e),window.URL.revokeObjectURL(n)},e.onerror=()=>{a(),window.URL.revokeObjectURL(n)},e.src=n})};function lb(s){const t={...s},e=new Map,r=(u,h)=>(e.has(u)||e.set(u,new Set),e.get(u).add(h),()=>{var p;return(p=e.get(u))==null?void 0:p.delete(h)}),n=(u,h)=>{var p;(p=e.get(u))==null||p.delete(h)},i=u=>{var h;(h=e.get(u))==null||h.forEach(p=>{try{p(t[u])}catch(f){l.error(`Error in notifying for "${u.toString()}"`,f)}})};return{subscribe:r,unsubscribe:n,notify:i,setValue:(u,h,p=!0)=>{t[u]=h,p&&i(u)},getValue:u=>t[u],getAllValues:()=>t}}class ub{constructor(){m(this,"contexts",new Map)}createContext(t,e){return this.contexts.has(t)?this.contexts.get(t):(this.contexts.set(t,lb(e)),this.contexts.get(t))}remapContext(t,e){const r=e.getValue("peerId");r!==t&&(e.setValue("peerId",t),this.contexts.set(t,e),this.contexts.delete(r))}getContext(t){return this.contexts.get(t)}}const pa=new ub,he=class{static get logsEndpoint(){const t=pa.getContext(he.meetingMetadata.peerId);return`https://${Xn({servicePrefix:"api-silos",baseURI:t.getValue("baseURI")})}/otel/logs`}static resetPeerId(t){he.meetingMetadata.peerId=t}static init(t,e){const r=t.getValue("peerId");he.tracingEnabled=e,he.meetingMetadata.peerId=r,he.meetingMetadata.sdkVersion=t.getValue("sdkVersion"),he.meetingMetadata.deviceInfo=Se.getDeviceInfo(),he.meetingMetadata.visitedUrl=!navigator.isReactNative&&typeof window!="undefined"&&window.location.href,navigator.isReactNative||document.addEventListener("visibilitychange",he.processCachedLogs),he.logsProcessorTimer=setInterval(he.processCachedLogs,he.logsProcessingInterval),e&&(he.initialized=!0)}static trace(t){return(e,r,n)=>{const i=n.value;return n.value=function(...o){if(!he.initialized||navigator.isReactNative||!he.tracingEnabled||J.hasFeature(X.SKIP_OTEL_TRACES))return i.apply(this,o);he.addLogInCurrentSpan("info",t);const d=performance.now(),u=i.apply(this,o);return Promise.resolve(u).then(()=>{const h=performance.now();h-d>10&&he.addLogInCurrentSpan("info",`${t}_timing`,{execTime:h-d,country:he.location.country})}).catch(()=>{const h=performance.now();he.addLogInCurrentSpan("info",`${t}_timing`,{execTime:h-d})}),u},n}}static injectContext(t){var n;const e=Xs().replace(/-/g,"").substring(0,16),r=(n=he.meetingMetadata.peerId)==null?void 0:n.replace(/-/g,"");t.TRACEPARENT=`00-${r}-${e}-01`}static addLogInCurrentSpan(t,e,r={},n=!1){r!=null&&r.error&&Object.assign(r,{error:pc(r.error)});const i=pa.getContext(he.meetingMetadata.peerId);if(Em(i)&&(qC(r)?console[t]("DyteInternalLogs:: ",t,e):console[t]("DyteInternalLogs:: ",t,e,r)),!!JC(t))try{const o=Cm(i,e,r,"metadata"),d=new Date,u={message:e,level:t,...o,loggedAt:d.toISOString(),loggedAtTzOffset:d.getTimezoneOffset()};n?he.sendOtelLogsToNewRelic([u]):he.logsCache.push(u)}catch(o){he.addLogInCurrentSpan("error","opentelemetry::addLogInCurrentSpan_failed",{error:pc(o)})}}static sendOtelLogsToNewRelic(t){const e=pa.getContext(he.meetingMetadata.peerId);rc.post(he.logsEndpoint,{meetingMetadata:Cm(e,"sendOtelLogsToNewRelic",he.meetingMetadata,"meetingMetadata"),serviceName:e.getValue("sdkName"),logs:t}).catch(r=>{he.addLogInCurrentSpan("error","opentelemetry::sendOtelLogToNewRelic_failed",{error:pc(r)}),he.logsCache.push(...t)})}static processCachedLogs(){const t=he.logsCache.splice(0,25);t!=null&&t.length&&he.sendOtelLogsToNewRelic(t)}static destruct(){clearInterval(he.logsProcessorTimer),he.processCachedLogs(),navigator.isReactNative||document.removeEventListener("visibilitychange",he.processCachedLogs)}};let g=he;m(g,"logsCache",[]),m(g,"logsProcessorTimer"),m(g,"location",{country:void 0}),m(g,"tracingEnabled",!0),m(g,"initialized",!1),m(g,"logsProcessingInterval",7e3),m(g,"logExclusionList",["message","websocket/message","roomMessage","websocket/room-message","websocket/room-legacy-mode","chatMessage","websocket/new-chat-message","websocket/no-active-speaker","websocket/selected-peers","websocket/active-speaker","ping","websocket/new-consumer","websocket/producer-score","websocket/consumer-score","websocket/plugin-event","websocket/plugin-data","websocket/plugin-internal-data"]),m(g,"meetingMetadata",{});class l{static info(t,e,r){g.addLogInCurrentSpan("info",t,e,r)}static error(t,e,r){g.addLogInCurrentSpan("error",t,e,r)}static debug(t,e,r){g.addLogInCurrentSpan("debug",t,e,r)}static log(t,e,r){g.addLogInCurrentSpan("log",t,e,r)}static warn(t,e,r){g.addLogInCurrentSpan("warn",t,e,r)}}const hb=()=>{!navigator.isReactNative&&typeof window!="undefined"&&(window.addEventListener("error",s=>{var t;!((t=s.filename)!=null&&t.includes("localhost"))&&s.lineno!==0&&l.error("window::error",{error:s.error},!0)}),window.addEventListener("unhandledrejection",s=>{var t,e,r,n,i,a,o,d;l.error("window::unhandledrejection",{error:s==null?void 0:s.reason,networkCall:{url:(e=(t=s==null?void 0:s.reason)==null?void 0:t.config)==null?void 0:e.url,baseURL:(n=(r=s==null?void 0:s.reason)==null?void 0:r.config)==null?void 0:n.baseURL,method:(a=(i=s==null?void 0:s.reason)==null?void 0:i.config)==null?void 0:a.method,status:(o=s==null?void 0:s.reason)==null?void 0:o.status,statusText:(d=s==null?void 0:s.reason)==null?void 0:d.statusText}},!0)}),window.addEventListener("offline",()=>{l.info("window::offline")}),window.addEventListener("online",()=>{l.info("window::online")}))},pb={"00":"DyteClient","01":"Controller","02":"RoomNodeClient","03":"HiveNodeClient","04":"SocketService","05":"Chat","06":"Plugin","07":"Polls","08":"Meta","09":"Preset",10:"Recording",11:"Self",12:"Participant",13:"Spotlight",14:"Remote Request",15:"Webinar",16:"LocalMediaHandler",17:"End-End Encryption"},gc={"0000":"Internal exception.","0001":"Failed to initialize.","0002":"Failed to join room.","0003":"Failed to leave room.","0010":"Browser not supported","0011":"HTTP Network Error","0012":"Websocket Network Error","0100":"Internal exception","0200":"Internal exception.","0300":"Internal exception","0400":"Internal exception","0500":"Internal exception","0501":"Permission denied.","0502":"Invalid message body.","0510":"Invalid channel name.","0600":"Internal exception","0700":"Internal exception","0800":"Internal exception","0900":"Internal exception",1e3:"Internal exception",1100:"Internal exception",1200:"Internal exception",1300:"Internal exception",1400:"Internal exception",1500:"Internal exception",1600:"Internal exception",1601:"Failed to get audio track",1602:"Failed to get video track",1603:"Incorrect device",1604:"Failed to change device",1701:"Crypto error",9900:"Internal exception"};Object.keys(gc).forEach(s=>{gc[s]=`{${pb[s.slice(0,2)]}} ${gc[s]}`});class b extends Error{constructor(e,r,n=!1){super(e);m(this,"code");this.code=r,this.name="DyteError",this.message=`[ERR${this.code}]: ${gc[this.code]} -${this.message}`;try{let i=n;r&&r.endsWith("00")&&(i=!0),i&&l.error("DyteError",{error:{message:this.message,name:this.name,code:r}})}catch(i){}}}function vc(s,t,e,r){if(r instanceof b)throw r;if(r instanceof t){const n=new b(r.message,e);throw n.stack=r.stack,n}else throw r}function Fm(s,t,e){if(!s.value){const n=s.get,i=s.set;return n&&(s.get=function(){try{return n.apply(this)}catch(a){vc(this,t,e,a)}}),i&&(s.set=function(a){try{return i.apply(this,[a])}catch(o){vc(this,t,e,o)}}),s}const r=s.value;return s.value=function(...n){try{const i=r.apply(this,n);return i&&i instanceof Promise?i.catch(a=>{vc(this,t,e,a)}):i}catch(i){vc(this,t,e,i)}},s}function mb(s,t){return(e,r,n)=>{if(n)return Fm(n,s,t);for(const i of Reflect.ownKeys(e.prototype).filter(a=>a!=="constructor")){const a=Object.getOwnPropertyDescriptor(e.prototype,i);(a.value instanceof Function||a.get instanceof Function||a.set instanceof Function)&&Object.defineProperty(e.prototype,i,Fm(a,s,t))}}}const pt=s=>mb(Error,s);function fb(s){let t=0,e,r;if(!s)return t;for(e=0;enew Promise(i=>{c(this,Yr).get(e).push(i)}));super.emit(e,...r),await Promise.race([Promise.all(n),new Promise((i,a)=>setTimeout(()=>a(new Error(`emitAsync failed to resolve for event ${e}.`)),this.asyncPromiseTimeout))]),c(this,Yr).delete(e)}onAsync(e,r){const n=c(this,Yr),i=async(...a)=>{var d;try{await r(...a)}catch(u){l.error("[onAsync]",{error:u})}const o=(d=n.get(e))==null?void 0:d.shift();o==null||o()};return c(this,Qr).get(e)||c(this,Qr).set(e,[]),c(this,Qr).get(e).push(i),super.on(e,i)}reset(){y(this,Yr,new Map),y(this,Qr,new Map),super.removeAllListeners()}}Yr=new WeakMap,Qr=new WeakMap;const w=new gb;function vb(){Se.isElectron()&&window.dyteElectronGetDisplayMediaSource&&(navigator.mediaDevices.getDisplayMedia=async()=>{const s=await window.dyteElectronGetDisplayMediaSource({types:["window","screen"]});let t=[];if(s&&(Array.isArray(s)?t=s:t=[s]),!(t!=null&&t.length))throw new Error("Couldn't find any media source for screen share.");let e=t.find(i=>{var a;return(a=i.id)==null?void 0:a.includes("screen")});e=e!=null?e:t[0];const r={audio:!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e.id}}};return await navigator.mediaDevices.getUserMedia(r)})}var C=(s=>(s.NEW_PRODUCER="NEW_PRODUCER",s.PRODUCER_TRACK_ENDED="PRODUCER_TRACK_ENDED",s.ROOM_NODE_CONNECTION_ERROR="ROOM_NODE_CONNECTION_ERROR",s.SOCKET_SERVICE_ROOM_JOINED="SOCKET_SERVICE_ROOM_JOINED",s.SOCKET_SERVICE_RECONNECTED="SOCKET_SERVICE_RECONNECTED",s.SOCKET_SERVICE_DISCONNECTED="SOCKET_SERVICE_DISCONNECTED",s.SOCKET_SERVICE_FAILED="SOCKET_SERVICE_FAILED",s.SOCKET_STATE_UPDATE="SOCKET_STATE_UPDATE",s.ROOM_NODE_RECONNECTED="ROOM_NODE_RECONNECTED",s.ROOM_NODE_DISCONNECTED="ROOM_NODE_DISCONNECTED",s.ROOM_NODE_FAILED="ROOM_NODE_FAILED",s.TRANSPORT_STATE_UPDATE="TRANSPORT_STATE_UPDATE",s.PRODUCER_SCORE_UPDATE="PRODUCER_SCORE_UPDATE",s.CONSUMER_SCORE_UPDATE="CONSUMER_SCORE_UPDATE",s.PRODUCER_STATUS_UPDATE="PRODUCER_STATUS_UPDATE",s.CONSUMER_STATUS_UPDATE="CONSUMER_STATUS_UPDATE",s.LOW_PRODUCER_SCORE="LOW_PRODUCER_SCORE",s.LOW_CONSUMER_SCORE="LOW_CONSUMER_SCORE",s.MEDIA_PERMISSION_ERROR="MEDIA_PERMISSION_ERROR",s.MEDIA_PERMISSION_UPDATE="MEDIA_PERMISSION_UPDATE",s.WAITLISTED="WAIT_LISTED",s.MESSAGE="websocket/message",s.ROOM_MESSAGE="websocket/room-message",s.PEER_JOINED_INTERNAL="peer/joined-internal",s.PEER_CLOSED="websocket/peer-closed",s.CONSUMER_CLOSED="websocket/consumer-closed",s.CONSUMER_PAUSED="websocket/consumer-paused",s.CONSUMER_RESUMED="websocket/consumer-resumed",s.PRODUCER_CLOSED="websocket/producer-closed",s.NEW_CONSUMER="websocket/new-consumer",s.PRODUCER_SCORE="websocket/producer-score",s.CONSUMER_SCORE="websocket/consumer-score",s.PRODUCER_TOGGLE="hive/producer-toggle",s.CONSUMER_TOGGLE="hive/consumer-toggle",s.SELECTED_PEERS_DIFF="hive/selected-peers-diff",s.UPDATE_ACTIVE="media/update-active",s.RESET_PRODUCER_STATE="hive/reset-producer-state",s.CF_TRANSPORT_STATE_CHANGED="cf/transport-state-changed",s.CF_ROOM_REJOINING="cf/room-rejoining",s.CF_ROOM_REJOIN_FAILED="cf/room-rejoining-failed",s.CF_ROOM_REJOINED="cf/room-rejoined",s.CF_TRANPSORT_RECONNECTING="cf/transport-reconnecting",s.ROOM_STATE="sockethub/room-state",s.PEER_DISPLAY_NAME_CHANGED="hive/display-name-changed",s.GET_STAGE_REQUESTS="GET_STAGE_REQUESTS",s.UPDATE_STAGE_REQUESTS="UPDATE_STAGE_REQUESTS",s.KICK_PEER="KICK_PEER",s.UPDATE_PEER_STAGE_STATUS="UPDATE_PEER_STAGE_STATUS",s.JOIN_MEDIA_ROOM="JOIN_MEDIA_ROOM",s.LEAVE_MEDIA_ROOM="LEAVE_MEDIA_ROOM",s.PIP_HANGUP="PIP_HANGUP",s.E2EE_ACTIVE_PRODUCER="E2EE_ACTIVE_PRODUCER",s.E2EE_INACTIVE_PRODUCER="E2EE_INACTIVE_PRODUCER",s.E2EE_ACTIVE_CONSUMER="E2EE_ACTIVE_CONSUMER",s.E2EE_INACTIVE_CONSUMER="E2EE_INACTIVE_CONSUMER",s.SOCKET_PEERS="SOCKET_PEERS",s.UPDATE_PERMISSIONS="UPDATE_PERMISSIONS",s.MAX_SPATIAL_LAYER_CHANGE="MAX_SPATIAL_LAYER_CHANGE",s.MUTE_SELF="MUTE_SELF",s.MUTE_SELF_VIDEO="MUTE_SELF_VIDEO",s))(C||{});class Zn extends de.EventEmitter{constructor(){super(),super.setMaxListeners(25)}emit(t,...e){return super.emit("*",t,...e),super.emit(t,...e)}on(t,e){try{const r=this.listenerCount(t);r>25&&r%25===0&&l.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:t.toString(),listenerCount:this.listenerCount(t)}})}catch(r){}return super.on(t,e)}addListener(t,e){try{const r=this.listenerCount(t);r>25&&r%25===0&&l.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:t.toString(),listenerCount:this.listenerCount(t)}})}catch(r){}return super.addListener(t,e)}off(t,e){return super.off(t,e)}once(t,e){return super.once(t,e)}prependListener(t,e){return super.prependListener(t,e)}prependOnceListener(t,e){return super.prependOnceListener(t,e)}removeListener(t,e){return super.removeListener(t,e)}removeAllListeners(t){return super.removeAllListeners(t)}listeners(t){return super.listeners(t)}listenerCount(t){return super.listenerCount(t)}}class Ht extends de.EventEmitter{constructor(){super(),super.setMaxListeners(25)}emit(t,...e){return super.emit("*",t,...e),super.emit(t,...e)}on(t,e){try{const r=this.listenerCount(t);r>25&&r%25===0&&l.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:t.toString(),listenerCount:this.listenerCount(t)}})}catch(r){}return super.on(t,e)}addListener(t,e){try{const r=this.listenerCount(t);r>25&&r%25===0&&l.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:t.toString(),listenerCount:this.listenerCount(t)}})}catch(r){}return super.addListener(t,e)}off(t,e){return super.off(t,e)}once(t,e){return super.once(t,e)}prependListener(t,e){return super.prependListener(t,e)}prependOnceListener(t,e){return super.prependOnceListener(t,e)}removeListener(t,e){return super.removeListener(t,e)}removeAllListeners(t){return super.removeAllListeners(t)}listeners(t){return super.listeners(t)}listenerCount(t){return super.listenerCount(t)}}function yb(s,t=2){return s.replace(/[^\u00BF-\u1FFF\u2C00-\uD7FF\w\s]/g,"").trim().split(/\s+/).slice(0,t).map(n=>n.charAt(0)).join("").toUpperCase()}const xm=1080,Um=1920,Tb=(s,t,e,r,n,i)=>{let a=.5,o=.5;const d=n,u=i,h=Math.min(e/d,r/u);let p=d*h,f=u*h,v,T,P,k,I=1;return pd&&(P=d),k>u&&(k=u),[v,T,P,k,s,t,e,r]},ju=class extends Ht{constructor(e,r,n,i){super();S(this,Xt,void 0);S(this,fi,void 0);S(this,gt,void 0);S(this,Zt,void 0);S(this,qe,{height:xm,width:Um});S(this,mr,{brand:"#2160FD",background:"#141414",text:"#000000",videoBackground:"#191919",textOnBrand:"#EEEEEE"});S(this,Xr,void 0);S(this,It,{});S(this,Ze,void 0);S(this,gi,void 0);S(this,vi,void 0);S(this,Zr,void 0);S(this,yi,!1);m(this,"cleanupEventListeners",()=>{c(this,fi).unsubscribe("stageStatus",this.handlePipMediaControls),c(this,Ze).removeListener("videoUpdate",this.onSelfVideoUpdateListener),c(this,Ze).removeListener("audioUpdate",this.onSelfAudioUpdateListener),c(this,Ze).removeListener("roomLeft",()=>this.disable())});m(this,"enablePipMediaControls",()=>{this.mountAudioEvents(),this.mountVideoEvents()});m(this,"onSelfVideoUpdateListener",({videoEnabled:e})=>{this.updateMediaSession("CAMERA",e)});m(this,"onSelfAudioUpdateListener",({audioEnabled:e})=>{this.updateMediaSession("MIC",e)});m(this,"handlePipMediaControls",e=>{e==="ON_STAGE"?this.enablePipMediaControls():this.unmountEvents()});m(this,"eventCallback",e=>{e==="CAMERA"&&(c(this,Ze).videoEnabled?c(this,Ze).disableVideo():c(this,Ze).enableVideo(),this.emit("cameraToggled")),e==="MIC"&&(c(this,Ze).audioEnabled?c(this,Ze).disableAudio():c(this,Ze).enableAudio(),this.emit("micToggled")),e==="END"&&(w.emit(C.PIP_HANGUP),this.cleanupEventListeners(),this.emit("hangup"),this.cleanup())});m(this,"unmountEvents",()=>{navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||(navigator.mediaSession.setActionHandler("togglemicrophone",void 0),navigator.mediaSession.setActionHandler("togglecamera",void 0))});m(this,"animate",()=>{if(!this.isActive&&c(this,Zr)==="active"){this.disable(!0);return}c(this,It)!==void 0&&this.paintCanvas(),c(this,Xr)!==void 0&&y(this,Xr,requestAnimationFrame(()=>this.animate()))});m(this,"disable",(e=!1)=>{y(this,Zr,"idle"),this.cleanupEventListeners(),cancelAnimationFrame(c(this,Xr)),e!==!0&&document.body.removeChild(c(this,gt)),y(this,Xr,void 0),document.pictureInPictureElement&&document.exitPictureInPicture()});y(this,fi,e),y(this,Zr,"idle"),y(this,Ze,r),y(this,mr,{brand:r.config.designTokens.colors.brand[500],background:r.config.designTokens.colors.background[1e3],text:r.config.designTokens.colors.text,videoBackground:r.config.designTokens.colors.videoBg,textOnBrand:r.config.designTokens.colors.textOnBrand}),n&&this.setupIcon("pin",n),i&&this.setupIcon("handRaise",i)}static async _init(e,r){let n,i;try{n=await fc(cb),i=await fc(db)}catch(a){}return new ju(e,r,n,i)}async setupIcon(e,r){switch(e){case"handRaise":y(this,vi,r);break;case"pin":y(this,gi,r);break}}async overrideIcon(e,r){switch(e){case"handRaise":y(this,vi,await fc(r));break;case"pin":y(this,gi,await fc(r));break}}constructImage(e){const r=new Image,n=new Blob([e],{type:"image/svg+xml"}),i=window.URL.createObjectURL(n);return new Promise(a=>{r.onload=()=>{a(r),window.URL.revokeObjectURL(i)},r.src=i})}createVideoContainer(){y(this,gt,document.createElement("div")),c(this,gt).style.width="0.1px",c(this,gt).style.height="0.1px",c(this,gt).style.overflow="hidden",c(this,gt).style.position="absolute",c(this,gt).style.bottom="0",c(this,gt).style.right="0",c(this,gt).style.opacity="0",c(this,gt).appendChild(c(this,Zt))}setupEventListeners(){c(this,fi).subscribe("stageStatus",this.handlePipMediaControls),c(this,Ze).addListener("videoUpdate",this.onSelfVideoUpdateListener),c(this,Ze).addListener("audioUpdate",this.onSelfAudioUpdateListener),c(this,Ze).addListener("roomLeft",()=>this.disable())}createCanvas(){const e=document.createElement("canvas");e.height=c(this,qe).height,e.width=c(this,qe).width,y(this,Xt,e)}setupMediaSessionEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||(navigator.mediaSession.setActionHandler("hangup",()=>{this.eventCallback("END")}),this.mountAudioEvents(),this.mountVideoEvents())}mountAudioEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setMicrophoneActive===void 0||c(this,Ze).permissions.canProduceAudio&&navigator.mediaSession.setActionHandler("togglemicrophone",()=>{this.eventCallback("MIC")})}mountVideoEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||c(this,Ze).permissions.canProduceVideo&&navigator.mediaSession.setActionHandler("togglecamera",()=>{this.eventCallback("CAMERA")})}getSources(){const r=Object.values(c(this,It)).reduce((n,i)=>(n[i.pinned?"pinned":"regular"].push(i),n),{pinned:[],regular:[]});return[...r.pinned,...r.regular]}drawEmptyTile(e,r,n,i){if(c(this,Xt)===void 0)return;const a=c(this,Xt).getContext("2d"),o=c(this,Xt).width,d=0,u=0,h=r-d*2,p=n-d*2,f=Math.floor(o/h),v=Math.floor(e/f),P=e%f*(h+d)+d,k=v*(p+d)+d,{displayText:I,image:x}=i!=null?i:{};a.fillStyle=I||x?c(this,mr).videoBackground:c(this,mr).background,a.strokeStyle=c(this,mr).brand,a.beginPath(),a.moveTo(P+u,k),a.arcTo(P+h,k,P+h,k+u,u),a.arcTo(P+h,k+p,P+h-u,k+p,u),a.arcTo(P,k+p,P,k+p-u,u),a.arcTo(P,k,P+u,k,u),a.closePath(),a.fill(),a.stroke();const V=h/6,O=h/2+P,W=p/2+k;a.save(),(I||x)&&(a.beginPath(),a.arc(O,W,V,0,Math.PI*2),a.fillStyle=c(this,mr).brand,a.fill(),x?(a.clip(),a.drawImage(x,O-V,W-V,V*2,V*2),a.restore()):I&&(a.fillStyle=c(this,mr).textOnBrand,a.font=`${V/2}px sans-serif`,a.textAlign="center",a.textBaseline="middle",a.fillText(I,O,W)),this.drawIcons(i,P,k,Math.max(h,p)))}drawIcons(e,r,n,i){const a=Math.min(Math.max(i*.15,100),200),o=a*.2,d=a*.2;let u=r+o;const h=n+o,p=f=>{const v=c(this,Xt).getContext("2d");v.save(),v.fillStyle=c(this,mr).background,v.beginPath(),v.moveTo(u+d,h),v.arcTo(u+a,h,u+a,h+d,d),v.arcTo(u+a,h+a,u+a-d,h+a,d),v.arcTo(u,h+a,u,h+a-d,d),v.arcTo(u,h,u+d,h,d),v.closePath(),v.fill(),typeof f=="string"?(v.font=`${a/1.5}px sans-serif`,v.fillStyle=c(this,mr).text,v.textAlign="center",v.textBaseline="top",v.fillText(f,a/2+u,h+o)):v.drawImage(f,u+o,h+o,a-o*2,a-o*2),u+=a+o,v.restore()};e.pinned&&p(c(this,gi)),e.handRaised&&p(c(this,vi))}drawTile(e,r,n){var u,h;if(c(this,Xt)===void 0)return;const i=c(this,Xt).getContext("2d"),a=this.getSources();let o=0,d=0;for(;o0?e+1:e);const[r,n]=this.calcGridElemSize(e);this.drawTile(r,n,e)}isSupported(){return!!window.chrome&&document.pictureInPictureEnabled}get isActive(){return document.pictureInPictureElement!==null}cleanup(){if(y(this,yi,!1),this.isSupported()&&document.exitPictureInPicture!==void 0&&document.pictureInPictureElement!==null&&document.exitPictureInPicture(),c(this,gt))try{document.body.removeChild(c(this,gt))}catch(e){}this.removeAllSources(),y(this,Xt,void 0),y(this,Zt,void 0),y(this,Xr,void 0)}init({height:e,width:r}={}){if(c(this,yi))return;y(this,yi,!0),this.createCanvas(),this.setupMediaSessionEvents();const n=document.createElement("video");y(this,qe,{height:e!=null?e:xm,width:r!=null?r:Um}),n.height=c(this,qe).height,n.width=c(this,qe).width,n.autoplay=!0,n.muted=!0,n.srcObject=c(this,Xt).captureStream(24),y(this,Zt,n),c(this,Zt).onloadedmetadata=()=>{try{this.emit("pipStarted"),c(this,Zt).onleavepictureinpicture=()=>{this.emit("pipEnded")}}catch(i){this.emit("pipEnded")}},this.createVideoContainer(),this.paintCanvas()}updateMediaSession(e,r){navigator.mediaSession!==void 0&&(e==="CAMERA"&&navigator.mediaSession.setCameraActive!==void 0&&navigator.mediaSession.setCameraActive(r),e==="MIC"&&navigator.mediaSession.setMicrophoneActive!==void 0&&navigator.mediaSession.setMicrophoneActive(r))}enableSource(e){c(this,It)[e]!==void 0&&(c(this,It)[e].enabled=!0)}disableSource(e){c(this,It)[e]!==void 0&&(c(this,It)[e].enabled=!1)}async generateAvatar(e,r){const n=new Image,i=await fetch(r).then(o=>o.blob()),a=window.URL.createObjectURL(i);n.onload=()=>{this.updateSource(e,{image:n}),window.URL.revokeObjectURL(a)},n.src=a}addSource(e,r,n,i=!1,a=void 0,o=void 0,d=!1){l.info("DytePIP::AddSource",{pip:{id:e,handRaised:d}}),c(this,It)[e]={id:e,element:r,enabled:n,pinned:i,displayText:a?yb(a):void 0,imageUrl:o,handRaised:d},o&&this.generateAvatar(e,o)}updateSource(e,r){l.info("DytePIP::UpdateSource",{pip:{id:e,handRaised:r.handRaised}});const n=c(this,It)[e];n&&(c(this,It)[e]={...n,...r})}removeSource(e){delete c(this,It)[e]}removePinnedSource(){Object.values(c(this,It)).forEach(r=>{r.pinned&&this.removeSource(r.id)})}removeAllSources(){y(this,It,{})}enable(){y(this,Zr,"activating"),this.setupEventListeners(),this.updateMediaSession("CAMERA",c(this,Ze).videoEnabled),this.updateMediaSession("MIC",c(this,Ze).audioEnabled),document.body.appendChild(c(this,gt)),y(this,Xr,requestAnimationFrame(()=>this.animate())),c(this,Zt).onloadedmetadata=()=>{c(this,Zt).requestPictureInPicture().then(()=>{y(this,Zr,"active")})},c(this,Zt).readyState===4&&c(this,Zt).requestPictureInPicture().then(()=>{y(this,Zr,"active")})}};let Ll=ju;Xt=new WeakMap,fi=new WeakMap,gt=new WeakMap,Zt=new WeakMap,qe=new WeakMap,mr=new WeakMap,Xr=new WeakMap,It=new WeakMap,Ze=new WeakMap,gi=new WeakMap,vi=new WeakMap,Zr=new WeakMap,yi=new WeakMap;function Fl(s){let t=typeof s;if(t=="object"){if(Array.isArray(s))return"array";if(s===null)return"null"}return t}function _b(s){return s!==null&&typeof s=="object"&&!Array.isArray(s)}let $r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),yc=[];for(let s=0;s<$r.length;s++)yc[$r[s].charCodeAt(0)]=s;yc["-".charCodeAt(0)]=$r.indexOf("+"),yc["_".charCodeAt(0)]=$r.indexOf("/");function Sb(s){let t=s.length*3/4;s[s.length-2]=="="?t-=2:s[s.length-1]=="="&&(t-=1);let e=new Uint8Array(t),r=0,n=0,i,a=0;for(let o=0;o>4,a=i,n=2;break;case 2:e[r++]=(a&15)<<4|(i&60)>>2,a=i,n=3;break;case 3:e[r++]=(a&3)<<6|i,n=0;break}}if(n==1)throw Error("invalid base64 string.");return e.subarray(0,r)}function Eb(s){let t="",e=0,r,n=0;for(let i=0;i>2],n=(r&3)<<4,e=1;break;case 1:t+=$r[n|r>>4],n=(r&15)<<2,e=2;break;case 2:t+=$r[n|r>>6],t+=$r[r&63],e=0;break}return e&&(t+=$r[n],t+="=",e==1&&(t+="=")),t}var Tc;(function(s){s.symbol=Symbol.for("protobuf-ts/unknown"),s.onRead=(e,r,n,i,a)=>{(t(r)?r[s.symbol]:r[s.symbol]=[]).push({no:n,wireType:i,data:a})},s.onWrite=(e,r,n)=>{for(let{no:i,wireType:a,data:o}of s.list(r))n.tag(i,a).raw(o)},s.list=(e,r)=>{if(t(e)){let n=e[s.symbol];return r?n.filter(i=>i.no==r):n}return[]},s.last=(e,r)=>s.list(e,r).slice(-1)[0];const t=e=>e&&Array.isArray(e[s.symbol])})(Tc||(Tc={}));var Je;(function(s){s[s.Varint=0]="Varint",s[s.Bit64=1]="Bit64",s[s.LengthDelimited=2]="LengthDelimited",s[s.StartGroup=3]="StartGroup",s[s.EndGroup=4]="EndGroup",s[s.Bit32=5]="Bit32"})(Je||(Je={}));function wb(){let s=0,t=0;for(let r=0;r<28;r+=7){let n=this.buf[this.pos++];if(s|=(n&127)<>4,!(e&128))return this.assertBounds(),[s,t];for(let r=3;r<=31;r+=7){let n=this.buf[this.pos++];if(t|=(n&127)<>>i,o=!(!(a>>>7)&&t==0),d=(o?a|128:a)&255;if(e.push(d),!o)return}const r=s>>>28&15|(t&7)<<4,n=!!(t>>3);if(e.push((n?r|128:r)&255),!!n){for(let i=3;i<31;i=i+7){const a=t>>>i,o=!!(a>>>7),d=(o?a|128:a)&255;if(e.push(d),!o)return}e.push(t>>>31&1)}}const _c=(1<<16)*(1<<16);function Vm(s){let t=s[0]=="-";t&&(s=s.slice(1));const e=1e6;let r=0,n=0;function i(a,o){const d=Number(s.slice(a,o));n*=e,r=r*e+d,r>=_c&&(n=n+(r/_c|0),r=r%_c)}return i(-24,-18),i(-18,-12),i(-12,-6),i(-6),[t,r,n]}function Ul(s,t){if(t>>>0<=2097151)return""+(_c*t+(s>>>0));let e=s&16777215,r=(s>>>24|t<<8)>>>0&16777215,n=t>>16&65535,i=e+r*6777216+n*6710656,a=r+n*8147497,o=n*2,d=1e7;i>=d&&(a+=Math.floor(i/d),i%=d),a>=d&&(o+=Math.floor(a/d),a%=d);function u(h,p){let f=h?String(h):"";return p?"0000000".slice(f.length)+f:f}return u(o,0)+u(a,o)+u(i,1)}function $m(s,t){if(s>=0){for(;s>127;)t.push(s&127|128),s=s>>>7;t.push(s)}else{for(let e=0;e<9;e++)t.push(s&127|128),s=s>>7;t.push(1)}}function Cb(){let s=this.buf[this.pos++],t=s&127;if(!(s&128))return this.assertBounds(),t;if(s=this.buf[this.pos++],t|=(s&127)<<7,!(s&128))return this.assertBounds(),t;if(s=this.buf[this.pos++],t|=(s&127)<<14,!(s&128))return this.assertBounds(),t;if(s=this.buf[this.pos++],t|=(s&127)<<21,!(s&128))return this.assertBounds(),t;s=this.buf[this.pos++],t|=(s&15)<<28;for(let e=5;s&128&&e<10;e++)s=this.buf[this.pos++];if(s&128)throw new Error("invalid varint");return this.assertBounds(),t>>>0}let Ee;function bb(){const s=new DataView(new ArrayBuffer(8));Ee=globalThis.BigInt!==void 0&&typeof s.getBigInt64=="function"&&typeof s.getBigUint64=="function"&&typeof s.setBigInt64=="function"&&typeof s.setBigUint64=="function"?{MIN:BigInt("-9223372036854775808"),MAX:BigInt("9223372036854775807"),UMIN:BigInt("0"),UMAX:BigInt("18446744073709551615"),C:BigInt,V:s}:void 0}bb();function Bm(s){if(!s)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}const Hm=/^-?[0-9]+$/,Sc=4294967296,Ec=2147483648;class qm{constructor(t,e){this.lo=t|0,this.hi=e|0}isZero(){return this.lo==0&&this.hi==0}toNumber(){let t=this.hi*Sc+(this.lo>>>0);if(!Number.isSafeInteger(t))throw new Error("cannot convert to safe number");return t}}class mt extends qm{static from(t){if(Ee)switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=="")throw new Error("string is no integer");t=Ee.C(t);case"number":if(t===0)return this.ZERO;t=Ee.C(t);case"bigint":if(!t)return this.ZERO;if(tEe.UMAX)throw new Error("ulong too large");return Ee.V.setBigUint64(0,t,!0),new mt(Ee.V.getInt32(0,!0),Ee.V.getInt32(4,!0))}else switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=t.trim(),!Hm.test(t))throw new Error("string is no integer");let[e,r,n]=Vm(t);if(e)throw new Error("signed value for ulong");return new mt(r,n);case"number":if(t==0)return this.ZERO;if(!Number.isSafeInteger(t))throw new Error("number is no integer");if(t<0)throw new Error("signed value for ulong");return new mt(t,t/Sc)}throw new Error("unknown value "+typeof t)}toString(){return Ee?this.toBigInt().toString():Ul(this.lo,this.hi)}toBigInt(){return Bm(Ee),Ee.V.setInt32(0,this.lo,!0),Ee.V.setInt32(4,this.hi,!0),Ee.V.getBigUint64(0,!0)}}mt.ZERO=new mt(0,0);class Pe extends qm{static from(t){if(Ee)switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=="")throw new Error("string is no integer");t=Ee.C(t);case"number":if(t===0)return this.ZERO;t=Ee.C(t);case"bigint":if(!t)return this.ZERO;if(tEe.MAX)throw new Error("signed long too large");return Ee.V.setBigInt64(0,t,!0),new Pe(Ee.V.getInt32(0,!0),Ee.V.getInt32(4,!0))}else switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=t.trim(),!Hm.test(t))throw new Error("string is no integer");let[e,r,n]=Vm(t);if(e){if(n>Ec||n==Ec&&r!=0)throw new Error("signed long too small")}else if(n>=Ec)throw new Error("signed long too large");let i=new Pe(r,n);return e?i.negate():i;case"number":if(t==0)return this.ZERO;if(!Number.isSafeInteger(t))throw new Error("number is no integer");return t>0?new Pe(t,t/Sc):new Pe(-t,-t/Sc).negate()}throw new Error("unknown value "+typeof t)}isNegative(){return(this.hi&Ec)!==0}negate(){let t=~this.hi,e=this.lo;return e?e=~e+1:t+=1,new Pe(e,t)}toString(){if(Ee)return this.toBigInt().toString();if(this.isNegative()){let t=this.negate();return"-"+Ul(t.lo,t.hi)}return Ul(this.lo,this.hi)}toBigInt(){return Bm(Ee),Ee.V.setInt32(0,this.lo,!0),Ee.V.setInt32(4,this.hi,!0),Ee.V.getBigInt64(0,!0)}}Pe.ZERO=new Pe(0,0);const jm={readUnknownField:!0,readerFactory:s=>new Rb(s)};function Pb(s){return s?Object.assign(Object.assign({},jm),s):jm}class Rb{constructor(t,e){this.varint64=wb,this.uint32=Cb,this.buf=t,this.len=t.length,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.textDecoder=e!=null?e:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0})}tag(){let t=this.uint32(),e=t>>>3,r=t&7;if(e<=0||r<0||r>5)throw new Error("illegal tag: field no "+e+" wire type "+r);return[e,r]}skip(t){let e=this.pos;switch(t){case Je.Varint:for(;this.buf[this.pos++]&128;);break;case Je.Bit64:this.pos+=4;case Je.Bit32:this.pos+=4;break;case Je.LengthDelimited:let r=this.uint32();this.pos+=r;break;case Je.StartGroup:let n;for(;(n=this.tag()[1])!==Je.EndGroup;)this.skip(n);break;default:throw new Error("cant skip wire type "+t)}return this.assertBounds(),this.buf.subarray(e,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)}int64(){return new Pe(...this.varint64())}uint64(){return new mt(...this.varint64())}sint64(){let[t,e]=this.varint64(),r=-(t&1);return t=(t>>>1|(e&1)<<31)^r,e=e>>>1^r,new Pe(t,e)}bool(){let[t,e]=this.varint64();return t!==0||e!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return new mt(this.sfixed32(),this.sfixed32())}sfixed64(){return new Pe(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let t=this.uint32(),e=this.pos;return this.pos+=t,this.assertBounds(),this.buf.subarray(e,e+t)}string(){return this.textDecoder.decode(this.bytes())}}function fe(s,t){if(!s)throw new Error(t)}const kb=34028234663852886e22,Ib=-34028234663852886e22,Ab=4294967295,Mb=2147483647,Db=-2147483648;function ma(s){if(typeof s!="number")throw new Error("invalid int 32: "+typeof s);if(!Number.isInteger(s)||s>Mb||sAb||s<0)throw new Error("invalid uint 32: "+s)}function Vl(s){if(typeof s!="number")throw new Error("invalid float 32: "+typeof s);if(Number.isFinite(s)&&(s>kb||snew Nb};function Ob(s){return s?Object.assign(Object.assign({},Gm),s):Gm}class Nb{constructor(t){this.stack=[],this.textEncoder=t!=null?t:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let t=0;for(let n=0;n>>0)}raw(t){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(t),this}uint32(t){for(wc(t);t>127;)this.buf.push(t&127|128),t=t>>>7;return this.buf.push(t),this}int32(t){return ma(t),$m(t,this.buf),this}bool(t){return this.buf.push(t?1:0),this}bytes(t){return this.uint32(t.byteLength),this.raw(t)}string(t){let e=this.textEncoder.encode(t);return this.uint32(e.byteLength),this.raw(e)}float(t){Vl(t);let e=new Uint8Array(4);return new DataView(e.buffer).setFloat32(0,t,!0),this.raw(e)}double(t){let e=new Uint8Array(8);return new DataView(e.buffer).setFloat64(0,t,!0),this.raw(e)}fixed32(t){wc(t);let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!0),this.raw(e)}sfixed32(t){ma(t);let e=new Uint8Array(4);return new DataView(e.buffer).setInt32(0,t,!0),this.raw(e)}sint32(t){return ma(t),t=(t<<1^t>>31)>>>0,$m(t,this.buf),this}sfixed64(t){let e=new Uint8Array(8),r=new DataView(e.buffer),n=Pe.from(t);return r.setInt32(0,n.lo,!0),r.setInt32(4,n.hi,!0),this.raw(e)}fixed64(t){let e=new Uint8Array(8),r=new DataView(e.buffer),n=mt.from(t);return r.setInt32(0,n.lo,!0),r.setInt32(4,n.hi,!0),this.raw(e)}int64(t){let e=Pe.from(t);return xl(e.lo,e.hi,this.buf),this}sint64(t){let e=Pe.from(t),r=e.hi>>31,n=e.lo<<1^r,i=(e.hi<<1|e.lo>>>31)^r;return xl(n,i,this.buf),this}uint64(t){let e=mt.from(t);return xl(e.lo,e.hi,this.buf),this}}const Jm={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},Wm={ignoreUnknownFields:!1};function Lb(s){return s?Object.assign(Object.assign({},Wm),s):Wm}function Fb(s){return s?Object.assign(Object.assign({},Jm),s):Jm}const Km=Symbol.for("protobuf-ts/message-type");function zm(s){let t=!1;const e=[];for(let r=0;r!n.includes(a))||!r&&n.some(a=>!i.known.includes(a)))return!1;if(e<1)return!0;for(const a of i.oneofs){const o=t[a];if(!Ub(o))return!1;if(o.oneofKind===void 0)continue;const d=this.fields.find(u=>u.localName===o.oneofKind);if(!d||!this.field(o[o.oneofKind],d,r,e))return!1}for(const a of this.fields)if(a.oneof===void 0&&!this.field(t[a.localName],a,r,e))return!1;return!0}field(t,e,r,n){let i=e.repeat;switch(e.kind){case"scalar":return t===void 0?e.opt:i?this.scalars(t,e.T,n,e.L):this.scalar(t,e.T,e.L);case"enum":return t===void 0?e.opt:i?this.scalars(t,D.INT32,n):this.scalar(t,D.INT32);case"message":return t===void 0?!0:i?this.messages(t,e.T(),r,n):this.message(t,e.T(),r,n);case"map":if(typeof t!="object"||t===null)return!1;if(n<2)return!0;if(!this.mapKeys(t,e.K,n))return!1;switch(e.V.kind){case"scalar":return this.scalars(Object.values(t),e.V.T,n,e.V.L);case"enum":return this.scalars(Object.values(t),D.INT32,n);case"message":return this.messages(Object.values(t),e.V.T(),r,n)}break}return!0}message(t,e,r,n){return r?e.isAssignable(t,n):e.is(t,n)}messages(t,e,r,n){if(!Array.isArray(t))return!1;if(n<2)return!0;if(r){for(let i=0;iparseInt(i)),e,r);case D.BOOL:return this.scalars(n.slice(0,r).map(i=>i=="true"?!0:i=="false"?!1:i),e,r);default:return this.scalars(n,e,r,Er.STRING)}}}function cr(s,t){switch(t){case Er.BIGINT:return s.toBigInt();case Er.NUMBER:return s.toNumber();default:return s.toString()}}class $b{constructor(t){this.info=t}prepare(){var t;if(this.fMap===void 0){this.fMap={};const e=(t=this.info.fields)!==null&&t!==void 0?t:[];for(const r of e)this.fMap[r.name]=r,this.fMap[r.jsonName]=r,this.fMap[r.localName]=r}}assert(t,e,r){if(!t){let n=Fl(r);throw(n=="number"||n=="boolean")&&(n=r.toString()),new Error(`Cannot parse JSON ${n} for ${this.info.typeName}#${e}`)}}read(t,e,r){this.prepare();const n=[];for(const[i,a]of Object.entries(t)){const o=this.fMap[i];if(!o){if(!r.ignoreUnknownFields)throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${i}`);continue}const d=o.localName;let u;if(o.oneof){if(a===null&&(o.kind!=="enum"||o.T()[0]!=="google.protobuf.NullValue"))continue;if(n.includes(o.oneof))throw new Error(`Multiple members of the oneof group "${o.oneof}" of ${this.info.typeName} are present in JSON.`);n.push(o.oneof),u=e[o.oneof]={oneofKind:d}}else u=e;if(o.kind=="map"){if(a===null)continue;this.assert(_b(a),o.name,a);const h=u[d];for(const[p,f]of Object.entries(a)){this.assert(f!==null,o.name+" map value",null);let v;switch(o.V.kind){case"message":v=o.V.T().internalJsonRead(f,r);break;case"enum":if(v=this.enum(o.V.T(),f,o.name,r.ignoreUnknownFields),v===!1)continue;break;case"scalar":v=this.scalar(f,o.V.T,o.V.L,o.name);break}this.assert(v!==void 0,o.name+" map value",f);let T=p;o.K==D.BOOL&&(T=T=="true"?!0:T=="false"?!1:T),T=this.scalar(T,o.K,Er.STRING,o.name).toString(),h[T]=v}}else if(o.repeat){if(a===null)continue;this.assert(Array.isArray(a),o.name,a);const h=u[d];for(const p of a){this.assert(p!==null,o.name,null);let f;switch(o.kind){case"message":f=o.T().internalJsonRead(p,r);break;case"enum":if(f=this.enum(o.T(),p,o.name,r.ignoreUnknownFields),f===!1)continue;break;case"scalar":f=this.scalar(p,o.T,o.L,o.name);break}this.assert(f!==void 0,o.name,a),h.push(f)}}else switch(o.kind){case"message":if(a===null&&o.T().typeName!="google.protobuf.Value"){this.assert(o.oneof===void 0,o.name+" (oneof member)",null);continue}u[d]=o.T().internalJsonRead(a,r,u[d]);break;case"enum":let h=this.enum(o.T(),a,o.name,r.ignoreUnknownFields);if(h===!1)continue;u[d]=h;break;case"scalar":u[d]=this.scalar(a,o.T,o.L,o.name);break}}}enum(t,e,r,n){if(t[0]=="google.protobuf.NullValue"&&fe(e===null||e==="NULL_VALUE",`Unable to parse field ${this.info.typeName}#${r}, enum ${t[0]} only accepts null.`),e===null)return 0;switch(typeof e){case"number":return fe(Number.isInteger(e),`Unable to parse field ${this.info.typeName}#${r}, enum can only be integral number, got ${e}.`),e;case"string":let i=e;t[2]&&e.substring(0,t[2].length)===t[2]&&(i=e.substring(t[2].length));let a=t[1][i];return typeof a=="undefined"&&n?!1:(fe(typeof a=="number",`Unable to parse field ${this.info.typeName}#${r}, enum ${t[0]} has no value for "${e}".`),a)}fe(!1,`Unable to parse field ${this.info.typeName}#${r}, cannot parse enum value from ${typeof e}".`)}scalar(t,e,r,n){let i;try{switch(e){case D.DOUBLE:case D.FLOAT:if(t===null)return 0;if(t==="NaN")return Number.NaN;if(t==="Infinity")return Number.POSITIVE_INFINITY;if(t==="-Infinity")return Number.NEGATIVE_INFINITY;if(t===""){i="empty string";break}if(typeof t=="string"&&t.trim().length!==t.length){i="extra whitespace";break}if(typeof t!="string"&&typeof t!="number")break;let a=Number(t);if(Number.isNaN(a)){i="not a number";break}if(!Number.isFinite(a)){i="too large or small";break}return e==D.FLOAT&&Vl(a),a;case D.INT32:case D.FIXED32:case D.SFIXED32:case D.SINT32:case D.UINT32:if(t===null)return 0;let o;if(typeof t=="number"?o=t:t===""?i="empty string":typeof t=="string"&&(t.trim().length!==t.length?i="extra whitespace":o=Number(t)),o===void 0)break;return e==D.UINT32?wc(o):ma(o),o;case D.INT64:case D.SFIXED64:case D.SINT64:if(t===null)return cr(Pe.ZERO,r);if(typeof t!="number"&&typeof t!="string")break;return cr(Pe.from(t),r);case D.FIXED64:case D.UINT64:if(t===null)return cr(mt.ZERO,r);if(typeof t!="number"&&typeof t!="string")break;return cr(mt.from(t),r);case D.BOOL:if(t===null)return!1;if(typeof t!="boolean")break;return t;case D.STRING:if(t===null)return"";if(typeof t!="string"){i="extra whitespace";break}try{encodeURIComponent(t)}catch(d){d="invalid UTF8";break}return t;case D.BYTES:if(t===null||t==="")return new Uint8Array(0);if(typeof t!="string")break;return Sb(t)}}catch(a){i=a.message}this.assert(!1,n+(i?" - "+i:""),t)}}class Bb{constructor(t){var e;this.fields=(e=t.fields)!==null&&e!==void 0?e:[]}write(t,e){const r={},n=t;for(const i of this.fields){if(!i.oneof){let u=this.field(i,n[i.localName],e);u!==void 0&&(r[e.useProtoFieldName?i.name:i.jsonName]=u);continue}const a=n[i.oneof];if(a.oneofKind!==i.localName)continue;const o=i.kind=="scalar"||i.kind=="enum"?Object.assign(Object.assign({},e),{emitDefaultValues:!0}):e;let d=this.field(i,a[i.localName],o);fe(d!==void 0),r[e.useProtoFieldName?i.name:i.jsonName]=d}return r}field(t,e,r){let n;if(t.kind=="map"){fe(typeof e=="object"&&e!==null);const i={};switch(t.V.kind){case"scalar":for(const[d,u]of Object.entries(e)){const h=this.scalar(t.V.T,u,t.name,!1,!0);fe(h!==void 0),i[d.toString()]=h}break;case"message":const a=t.V.T();for(const[d,u]of Object.entries(e)){const h=this.message(a,u,t.name,r);fe(h!==void 0),i[d.toString()]=h}break;case"enum":const o=t.V.T();for(const[d,u]of Object.entries(e)){fe(u===void 0||typeof u=="number");const h=this.enum(o,u,t.name,!1,!0,r.enumAsInteger);fe(h!==void 0),i[d.toString()]=h}break}(r.emitDefaultValues||Object.keys(i).length>0)&&(n=i)}else if(t.repeat){fe(Array.isArray(e));const i=[];switch(t.kind){case"scalar":for(let d=0;d0||r.emitDefaultValues)&&(n=i)}else switch(t.kind){case"scalar":n=this.scalar(t.T,e,t.name,t.opt,r.emitDefaultValues);break;case"enum":n=this.enum(t.T(),e,t.name,t.opt,r.emitDefaultValues,r.enumAsInteger);break;case"message":n=this.message(t.T(),e,t.name,r);break}return n}enum(t,e,r,n,i,a){if(t[0]=="google.protobuf.NullValue")return!i&&!n?void 0:null;if(e===void 0){fe(n);return}if(!(e===0&&!i&&!n))return fe(typeof e=="number"),fe(Number.isInteger(e)),a||!t[1].hasOwnProperty(e)?e:t[2]?t[2]+t[1][e]:t[1][e]}message(t,e,r,n){return e===void 0?n.emitDefaultValues?null:void 0:t.internalJsonWrite(e,n)}scalar(t,e,r,n,i){if(e===void 0){fe(n);return}const a=i||n;switch(t){case D.INT32:case D.SFIXED32:case D.SINT32:return e===0?a?0:void 0:(ma(e),e);case D.FIXED32:case D.UINT32:return e===0?a?0:void 0:(wc(e),e);case D.FLOAT:Vl(e);case D.DOUBLE:return e===0?a?0:void 0:(fe(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e);case D.STRING:return e===""?a?"":void 0:(fe(typeof e=="string"),e);case D.BOOL:return e===!1?a?!1:void 0:(fe(typeof e=="boolean"),e);case D.UINT64:case D.FIXED64:fe(typeof e=="number"||typeof e=="string"||typeof e=="bigint");let o=mt.from(e);return o.isZero()&&!a?void 0:o.toString();case D.INT64:case D.SFIXED64:case D.SINT64:fe(typeof e=="number"||typeof e=="string"||typeof e=="bigint");let d=Pe.from(e);return d.isZero()&&!a?void 0:d.toString();case D.BYTES:return fe(e instanceof Uint8Array),e.byteLength?Eb(e):a?"":void 0}}}function $l(s,t=Er.STRING){switch(s){case D.BOOL:return!1;case D.UINT64:case D.FIXED64:return cr(mt.ZERO,t);case D.INT64:case D.SFIXED64:case D.SINT64:return cr(Pe.ZERO,t);case D.DOUBLE:case D.FLOAT:return 0;case D.BYTES:return new Uint8Array(0);case D.STRING:return"";default:return 0}}class Hb{constructor(t){this.info=t}prepare(){var t;if(!this.fieldNoToField){const e=(t=this.info.fields)!==null&&t!==void 0?t:[];this.fieldNoToField=new Map(e.map(r=>[r.no,r]))}}read(t,e,r,n){this.prepare();const i=n===void 0?t.len:t.pos+n;for(;t.pose.no-r.no)}}write(t,e,r){this.prepare();for(const i of this.fields){let a,o,d=i.repeat,u=i.localName;if(i.oneof){const h=t[i.oneof];if(h.oneofKind!==u)continue;a=h[u],o=!0}else a=t[u],o=!1;switch(i.kind){case"scalar":case"enum":let h=i.kind=="enum"?D.INT32:i.T;if(d)if(fe(Array.isArray(a)),d==Cc.PACKED)this.packed(e,h,i.no,a);else for(const p of a)this.scalar(e,h,i.no,p,!0);else a===void 0?fe(i.opt):this.scalar(e,h,i.no,a,o||i.opt);break;case"message":if(d){fe(Array.isArray(a));for(const p of a)this.message(e,r,i.T(),i.no,p)}else this.message(e,r,i.T(),i.no,a);break;case"map":fe(typeof a=="object"&&a!==null);for(const[p,f]of Object.entries(a))this.mapEntry(e,r,i,p,f);break}}let n=r.writeUnknownFields;n!==!1&&(n===!0?Tc.onWrite:n)(this.info.typeName,t,e)}mapEntry(t,e,r,n,i){t.tag(r.no,Je.LengthDelimited),t.fork();let a=n;switch(r.K){case D.INT32:case D.FIXED32:case D.UINT32:case D.SFIXED32:case D.SINT32:a=Number.parseInt(n);break;case D.BOOL:fe(n=="true"||n=="false"),a=n=="true";break}switch(this.scalar(t,r.K,1,a,!0),r.V.kind){case"scalar":this.scalar(t,r.V.T,2,i,!0);break;case"enum":this.scalar(t,D.INT32,2,i,!0);break;case"message":this.message(t,e,r.V.T(),2,i);break}t.join()}message(t,e,r,n,i){i!==void 0&&(r.internalBinaryWrite(i,t.tag(n,Je.LengthDelimited).fork(),e),t.join())}scalar(t,e,r,n,i){let[a,o,d]=this.scalarInfo(e,n);(!d||i)&&(t.tag(r,a),t[o](n))}packed(t,e,r,n){if(!n.length)return;fe(e!==D.BYTES&&e!==D.STRING),t.tag(r,Je.LengthDelimited),t.fork();let[,i]=this.scalarInfo(e);for(let a=0;a["media.Target",qt]},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"sdp",kind:"scalar",T:9}])}}const dr=new Xb;class Zb extends _{constructor(){super("media.CreateTransportRequest",[{no:1,name:"consuming",kind:"scalar",T:8},{no:2,name:"force_tcp",kind:"scalar",opt:!0,T:8},{no:3,name:"description",kind:"message",T:()=>dr}])}}const Zm=new Zb;class eP extends _{constructor(){super("media.CreateTransportResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>dr},{no:3,name:"transcription_enabled",kind:"scalar",opt:!0,T:8}])}}const Hl=new eP;class tP extends _{constructor(){super("media.RenegotiateRequest",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>dr}])}}const ef=new tP;class rP extends _{constructor(){super("media.RenegotiateResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>dr}])}}new rP;class sP extends _{constructor(){super("media.NestedScore",[{no:1,name:"encoding_idx",kind:"scalar",T:5},{no:2,name:"rid",kind:"scalar",T:9},{no:3,name:"score",kind:"scalar",T:5},{no:4,name:"ssrc",kind:"scalar",T:3,L:0}])}}const nP=new sP;class iP extends _{constructor(){super("media.ProducerTrack",[{no:1,name:"track_id",kind:"scalar",T:9},{no:2,name:"producer_id",kind:"scalar",T:9},{no:3,name:"stream_id",kind:"scalar",T:9}])}}const aP=new iP;class oP extends _{constructor(){super("media.ProducerEntry",[{no:1,name:"producing_transport_id",kind:"scalar",T:9},{no:2,name:"producer_id",kind:"scalar",T:9}])}}new oP;class cP extends _{constructor(){super("media.ConsumerEntry",[{no:1,name:"consuming_transport_id",kind:"scalar",T:9},{no:2,name:"consumer_id",kind:"scalar",T:9}])}}new cP;class dP extends _{constructor(){super("media.ProducerState",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"kind",kind:"enum",T:()=>["media.ProducerKind",Nt]},{no:3,name:"pause",kind:"scalar",T:8},{no:4,name:"screen_share",kind:"scalar",T:8},{no:5,name:"app_data",kind:"scalar",opt:!0,T:9},{no:6,name:"producing_transport_id",kind:"scalar",opt:!0,T:9},{no:7,name:"mime_type",kind:"scalar",opt:!0,T:9}])}}const fa=new dP;class lP extends _{constructor(){super("media.ConsumerState",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>fa},{no:3,name:"producer_track",kind:"message",T:()=>aP}])}}const uP=new lP;class hP extends _{constructor(){super("media.ProducerIdToConsumerMap",[{no:1,name:"map",kind:"map",K:9,V:{kind:"message",T:()=>uP}}])}}const tf=new hP;class pP extends _{constructor(){super("media.PeerRtpCapabilitites",[{no:1,name:"sender",kind:"message",T:()=>nf},{no:2,name:"receiver",kind:"message",T:()=>nf}])}}const rf=new pP;class mP extends _{constructor(){super("media.RtpCapability",[{no:1,name:"codecs",kind:"message",repeat:1,T:()=>Kb},{no:2,name:"header_extensions",kind:"message",repeat:1,T:()=>Yb}])}}const sf=new mP;class fP extends _{constructor(){super("media.RtpCapabilitites",[{no:1,name:"audio",kind:"message",T:()=>sf},{no:2,name:"video",kind:"message",T:()=>sf}])}}const nf=new fP;class gP extends _{constructor(){super("media.PreferredCodec",[{no:1,name:"audio",kind:"scalar",opt:!0,T:9},{no:2,name:"video",kind:"scalar",opt:!0,T:9}])}}const vP=new gP;class yP extends _{constructor(){super("media.edge.GeoLocation",[{no:1,name:"latitude",kind:"scalar",T:2},{no:2,name:"longitude",kind:"scalar",T:2},{no:3,name:"region",kind:"scalar",opt:!0,T:9}])}}const TP=new yP;class _P extends _{constructor(){super("media.edge.PeerJoinRequest",[{no:1,name:"display_name",kind:"scalar",opt:!0,T:9},{no:2,name:"prejoined",kind:"scalar",T:8},{no:3,name:"room_uuid",kind:"scalar",T:9},{no:4,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:5,name:"preset",kind:"scalar",opt:!0,T:12},{no:6,name:"user_id",kind:"scalar",opt:!0,T:9},{no:7,name:"organization_id",kind:"scalar",opt:!0,T:9},{no:8,name:"location",kind:"message",T:()=>TP},{no:9,name:"capabilities",kind:"message",T:()=>rf}])}}const af=new _P;class SP extends _{constructor(){super("media.edge.PeerJoinCompleteRequest",[])}}const of=new SP;class EP extends _{constructor(){super("media.edge.PeerLeaveRequest",[{no:1,name:"close_room",kind:"scalar",T:8}])}}const cf=new EP;class wP extends _{constructor(){super("media.edge.ConsumeMultipleProducerRequest",[{no:1,name:"producer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"paused",kind:"scalar",opt:!0,T:8}])}}new wP;class CP extends _{constructor(){super("media.edge.ConsumePeerRequest",[{no:1,name:"producing_peer_id",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",opt:!0,T:8},{no:3,name:"producer_id",kind:"scalar",opt:!0,T:9},{no:4,name:"preferred_codec",kind:"message",T:()=>vP}])}}const df=new CP;class bP extends _{constructor(){super("media.edge.ProducerCreateRequest",[{no:1,name:"kind",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",T:8},{no:3,name:"screen_share",kind:"scalar",T:8},{no:4,name:"description",kind:"message",T:()=>dr},{no:5,name:"msid",kind:"scalar",T:9},{no:6,name:"app_data",kind:"scalar",opt:!0,T:9},{no:7,name:"mime_type",kind:"scalar",opt:!0,T:9}])}}const lf=new bP;class PP extends _{constructor(){super("media.edge.SelectedPeersRequest",[])}}new PP;class RP extends _{constructor(){super("media.edge.GlobalPeerPinningRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const uf=new RP;class kP extends _{constructor(){super("media.edge.ProducerToggleRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}const fs=new kP;class IP extends _{constructor(){super("media.edge.ConsumerToggleRequest",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}const Pc=new IP;class AP extends _{constructor(){super("media.edge.ProducerCloseRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>dr}])}}const hf=new AP;class MP extends _{constructor(){super("media.edge.ConsumerCloseRequest",[{no:1,name:"consumer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"description",kind:"message",T:()=>dr}])}}const pf=new MP;class DP extends _{constructor(){super("media.edge.KickPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const mf=new DP;class OP extends _{constructor(){super("media.edge.KickAllPeersRequest",[{no:1,name:"propagate_kick_across_rooms",kind:"scalar",T:8}])}}const ql=new OP;class NP extends _{constructor(){super("media.edge.PeerDisplayNameEditRequest",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}const ff=new NP;class LP extends _{constructor(){super("media.edge.HostMediaControlForPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"audio",kind:"scalar",T:8},{no:3,name:"video",kind:"scalar",T:8},{no:4,name:"scree_share",kind:"scalar",T:8}])}}const gf=new LP;class FP extends _{constructor(){super("media.edge.HostMediaControlForAllPeerRequest",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8},{no:3,name:"screen_share",kind:"scalar",T:8}])}}const vf=new FP;class xP extends _{constructor(){super("media.edge.GetRoomStateResponse",[{no:1,name:"display_title",kind:"scalar",T:9},{no:2,name:"locked_mode",kind:"scalar",T:8},{no:3,name:"room_uuid",kind:"scalar",T:9},{no:4,name:"room_name",kind:"scalar",T:9},{no:5,name:"current_peer_id",kind:"scalar",T:9},{no:6,name:"is_recording",kind:"scalar",opt:!0,T:8},{no:7,name:"recorder_participant_id",kind:"scalar",opt:!0,T:9},{no:8,name:"pinned_peer_ids",kind:"scalar",repeat:2,T:9}])}}const UP=new xP;class VP extends _{constructor(){super("media.edge.ErrorResponse",[{no:1,name:"error_message",kind:"scalar",T:9},{no:2,name:"event_id",kind:"scalar",T:5}])}}const $P=new VP;class BP extends _{constructor(){super("media.edge.EmptyResponse",[])}}new BP;class HP extends _{constructor(){super("media.edge.RoomParticipants",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"producer_states",kind:"message",repeat:1,T:()=>fa},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"user_id",kind:"scalar",opt:!0,T:9},{no:5,name:"capabilities",kind:"message",T:()=>rf}])}}const yf=new HP;class qP extends _{constructor(){super("media.edge.SelectedPeersResponse",[{no:1,name:"audio_peers",kind:"scalar",repeat:2,T:9},{no:2,name:"compulsory_peers",kind:"scalar",repeat:2,T:9}])}}const jl=new qP;class jP extends _{constructor(){super("media.edge.SelectedPeersDiffEntry",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"priority",kind:"scalar",T:5}])}}const GP=new jP;class JP extends _{constructor(){super("media.edge.SelectedPeersDiffResponse",[{no:1,name:"entries",kind:"message",repeat:1,T:()=>GP}])}}const Tf=new JP;class WP extends _{constructor(){super("media.edge.PeerJoinResponse",[])}}new WP;class KP extends _{constructor(){super("media.edge.PeerJoinCompleteResponse",[{no:1,name:"room_state",kind:"message",T:()=>UP},{no:2,name:"participants",kind:"message",repeat:1,T:()=>yf},{no:3,name:"selected_peers",kind:"message",T:()=>jl},{no:4,name:"max_preferred_streams",kind:"scalar",T:5}])}}const Rc=new KP;class zP extends _{constructor(){super("media.edge.PeerLeaveResponse",[{no:1,name:"closed",kind:"scalar",T:8}])}}const _f=new zP;class YP extends _{constructor(){super("media.edge.ConsumeMultipleProducerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>tf}])}}new YP;class QP extends _{constructor(){super("media.edge.ConsumePeerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>tf},{no:3,name:"description",kind:"message",T:()=>dr}])}}const Sf=new QP;class XP extends _{constructor(){super("media.edge.ProducerCreateResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"producer_id",kind:"scalar",T:9},{no:4,name:"description",kind:"message",T:()=>dr}])}}const Ef=new XP;class ZP extends _{constructor(){super("media.edge.ProducerScoreResponse",[{no:1,name:"responseid",kind:"scalar",T:9},{no:2,name:"score",kind:"message",T:()=>nP}])}}new ZP;class eR extends _{constructor(){super("media.edge.ActiveSpeakerResponse",[{no:1,name:"responsepeer_id",kind:"scalar",T:9},{no:2,name:"volume",kind:"scalar",T:5}])}}new eR;class tR extends _{constructor(){super("media.edge.NoActiveSpeakerResponse",[])}}new tR;class rR extends _{constructor(){super("media.edge.ProducerToggleResponse",[])}}new rR;class sR extends _{constructor(){super("media.edge.ConsumerToggleResponse",[])}}new sR;class nR extends _{constructor(){super("media.edge.ProducerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>dr}])}}const wf=new nR;class iR extends _{constructor(){super("media.edge.ConsumerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>dr}])}}new iR;class aR extends _{constructor(){super("media.edge.GlobalPeerPinningResponse",[])}}new aR;class oR extends _{constructor(){super("media.edge.KickPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Cf=new oR;class cR extends _{constructor(){super("media.edge.KickAllPeersResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const bf=new cR;class dR extends _{constructor(){super("media.edge.HostMediaControlForPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Pf=new dR;class lR extends _{constructor(){super("media.edge.HostMediaControlForAllPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Rf=new lR;class uR extends _{constructor(){super("media.edge.PeerDisplayNameEditResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const kf=new uR;class hR extends _{constructor(){super("media.edge.PeerJoinBroadcastResponse",[{no:1,name:"participant",kind:"message",T:()=>yf}])}}const If=new hR;class pR extends _{constructor(){super("media.edge.TrackSubscriptionKind",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8}])}}const Af=new pR;class mR extends _{constructor(){super("media.edge.TrackSubscription",[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"webcam",kind:"message",T:()=>Af},{no:3,name:"screenshare",kind:"message",T:()=>Af}])}}const fR=new mR;class gR extends _{constructor(){super("media.edge.PeerProducingTransportCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"transport_details",kind:"message",T:()=>Hl},{no:3,name:"track_subscriptions",kind:"message",repeat:1,T:()=>fR}])}}new gR;class vR extends _{constructor(){super("media.edge.PeerProducerCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>fa}])}}const Mf=new vR;class yR extends _{constructor(){super("media.edge.PeerProducerToggleBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>fa}])}}const Df=new yR;class TR extends _{constructor(){super("media.edge.PeerProducerCloseBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>fa}])}}const Of=new TR;class _R extends _{constructor(){super("media.edge.PeerLeaveBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const kc=new _R;class SR extends _{constructor(){super("media.edge.GlobalPeerPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Nf=new SR;class ER extends _{constructor(){super("media.edge.GlobalPeerUnPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new ER;class wR extends _{constructor(){super("media.edge.RecordingStartedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new wR;class CR extends _{constructor(){super("media.edge.RecordingStoppedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new CR;class bR extends _{constructor(){super("media.edge.PeerDisplayNameEditBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}new bR;class PR extends _{constructor(){super("media.edge.PeerPingRequestBroadcastResponse",[{no:1,name:"password",kind:"scalar",T:9}])}}new PR;class RR extends _{constructor(){super("media.edge.MediaRoomTerminationBroadcastResponse",[{no:1,name:"reason",kind:"scalar",T:9}])}}new RR;class kR extends _{constructor(){super("socket.ai.MeetingTranscript",[{no:1,name:"meeting_id",kind:"scalar",T:9},{no:2,name:"transcript",kind:"scalar",T:9},{no:3,name:"is_partial",kind:"scalar",T:8}])}}const Gl=new kR;class IR extends _{constructor(){super("socket.api.BaseSocketHubMessage",[{no:1,name:"event",kind:"scalar",T:5},{no:2,name:"id",kind:"scalar",T:9},{no:3,name:"peer_id",kind:"scalar",T:9},{no:4,name:"room_id",kind:"scalar",T:9},{no:5,name:"user_id",kind:"scalar",T:9},{no:6,name:"payload",kind:"scalar",T:12},{no:7,name:"error",kind:"scalar",opt:!0,T:8},{no:8,name:"sid",kind:"scalar",opt:!0,T:9}])}}new IR;class AR extends _{constructor(){super("socket.api.ErrorMessage",[{no:1,name:"code",kind:"scalar",opt:!0,T:5},{no:2,name:"message",kind:"scalar",T:9}])}}const MR=new AR;var an;(function(s){s[s.BROWSER=0]="BROWSER",s[s.TRACK=1]="TRACK",s[s.COMPOSITE=2]="COMPOSITE"})(an||(an={}));var Br;(function(s){s[s.UNSPECIFIED=0]="UNSPECIFIED",s[s.ON_STAGE=1]="ON_STAGE",s[s.APPROVED_STAGE=2]="APPROVED_STAGE",s[s.REQUESTED_STAGE=3]="REQUESTED_STAGE",s[s.OFF_STAGE=4]="OFF_STAGE"})(Br||(Br={}));var Jl;(function(s){s[s.NONE=0]="NONE",s[s.RECORDER=1]="RECORDER",s[s.LIVESTREAMER=2]="LIVESTREAMER"})(Jl||(Jl={}));var Ic;(function(s){s[s.HIVE=0]="HIVE",s[s.CHAT=1]="CHAT",s[s.PING=2]="PING"})(Ic||(Ic={}));class DR extends _{constructor(){super("socket.room.PeerFlags",[{no:1,name:"preset_name",kind:"scalar",T:9},{no:2,name:"recorder_type",kind:"scalar",T:9},{no:3,name:"hidden_participant",kind:"scalar",T:8}])}}const OR=new DR;class NR extends _{constructor(){super("socket.room.Peer",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"stage_type",kind:"enum",opt:!0,T:()=>["socket.room.StageType",Br,"STAGE_TYPE_"]},{no:5,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:6,name:"preset_id",kind:"scalar",opt:!0,T:9},{no:7,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:8,name:"waitlisted",kind:"scalar",T:8},{no:9,name:"flags",kind:"message",T:()=>OR}])}}const Ac=new NR;class LR extends _{constructor(){super("socket.room.PeerInfoResponse",[{no:1,name:"peer",kind:"message",T:()=>Ac}])}}const ei=new LR;class FR extends _{constructor(){super("socket.room.PeerStatusUpdate",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"stage_type",kind:"enum",opt:!0,T:()=>["socket.room.StageType",Br,"STAGE_TYPE_"]}])}}const Lf=new FR;class xR extends _{constructor(){super("socket.room.RoomPeersInfoRequest",[{no:1,name:"seach_query",kind:"scalar",T:9},{no:2,name:"limit",kind:"scalar",T:5},{no:3,name:"offset",kind:"scalar",T:5}])}}const UR=new xR;class VR extends _{constructor(){super("socket.room.RoomPeersInfoResponse",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>Ac}])}}const Wl=new VR;class $R extends _{constructor(){super("socket.room.RoomPeerCountResponse",[{no:1,name:"count",kind:"scalar",T:4,L:2}])}}const Ff=new $R;class BR extends _{constructor(){super("socket.room.Room",[{no:1,name:"room_id",kind:"scalar",T:9},{no:2,name:"title",kind:"scalar",T:9},{no:4,name:"created_at",kind:"scalar",T:4,L:2},{no:5,name:"active_recordings",kind:"message",repeat:1,T:()=>qR},{no:6,name:"room_uuid",kind:"scalar",opt:!0,T:9}])}}const xf=new BR;class HR extends _{constructor(){super("socket.room.ActiveRecording",[{no:1,name:"recording_id",kind:"scalar",T:9},{no:2,name:"recording_type",kind:"enum",T:()=>["common.RecordingType",an]},{no:3,name:"recording_status",kind:"scalar",T:9}])}}const qR=new HR;class jR extends _{constructor(){super("socket.room.RoomInfoResponse",[{no:1,name:"room",kind:"message",T:()=>xf}])}}const Uf=new jR;class GR extends _{constructor(){super("socket.room.GetPeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9}])}}const Vf=new GR;class JR extends _{constructor(){super("socket.room.UpdatePeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",opt:!0,T:9}])}}new JR;class WR extends _{constructor(){super("socket.room.JoinRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>Ac},{no:3,name:"room_uuid",kind:"scalar",T:9},{no:4,name:"organization_id",kind:"scalar",opt:!0,T:9},{no:5,name:"use_hive",kind:"scalar",opt:!0,T:8},{no:6,name:"preset",kind:"scalar",opt:!0,T:12},{no:7,name:"capabilities",kind:"enum",repeat:1,T:()=>["socket.room.Capabilities",Ic,"CAPABILITIES_"]},{no:8,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const KR=new WR;class zR extends _{constructor(){super("socket.room.LeaveRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>Ac},{no:2,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const YR=new zR;class QR extends _{constructor(){super("socket.room.UpdateRoomInfoRequest",[{no:1,name:"room",kind:"message",T:()=>xf}])}}new QR;class XR extends _{constructor(){super("socket.room.GetConnectedRoomsDumpRequest",[])}}new XR;class ZR extends _{constructor(){super("socket.room.ServiceError",[{no:1,name:"message",kind:"scalar",opt:!0,T:9},{no:2,name:"code",kind:"scalar",opt:!0,T:9}])}}const Kl=new ZR;class ek extends _{constructor(){super("socket.room.ConnectedMeetingPeer",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"display_name",kind:"scalar",opt:!0,T:9},{no:3,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:4,name:"preset_id",kind:"scalar",opt:!0,T:9},{no:5,name:"display_picture_url",kind:"scalar",opt:!0,T:9}])}}const tk=new ek;class rk extends _{constructor(){super("socket.room.ConnectedMeetingDump",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"title",kind:"scalar",opt:!0,T:9},{no:3,name:"participants",kind:"message",repeat:1,T:()=>tk}])}}const $f=new rk;class sk extends _{constructor(){super("socket.room.GetConnectedRoomsDumpResponse",[{no:1,name:"parent_meeting",kind:"message",T:()=>$f},{no:2,name:"meetings",kind:"message",repeat:1,T:()=>$f}])}}const nk=new sk;class ik extends _{constructor(){super("socket.room.CreateRoomRequestPayload",[{no:1,name:"title",kind:"scalar",opt:!0,T:9}])}}const ak=new ik;class ok extends _{constructor(){super("socket.room.CreateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>ak}])}}const ck=new ok;class dk extends _{constructor(){super("socket.room.CreateRoomResponsePayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"title",kind:"scalar",opt:!0,T:9},{no:3,name:"error",kind:"message",T:()=>Kl}])}}const lk=new dk;class uk extends _{constructor(){super("socket.room.CreateConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>lk}])}}const Bf=new uk;class hk extends _{constructor(){super("socket.room.UpdateRoomRequestPayload",[{no:1,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"title",kind:"scalar",opt:!0,T:9}])}}const pk=new hk;class mk extends _{constructor(){super("socket.room.UpdateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>pk}])}}new mk;class fk extends _{constructor(){super("socket.room.DisableRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9}])}}const gk=new fk;class vk extends _{constructor(){super("socket.room.DisableConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>gk}])}}const yk=new vk;class Tk extends _{constructor(){super("socket.room.DisableConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Ek}])}}const _k=new Tk;class Sk extends _{constructor(){super("socket.room.DisableConnectedRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"status",kind:"scalar",opt:!0,T:9},{no:3,name:"title",kind:"scalar",opt:!0,T:9},{no:4,name:"error",kind:"message",T:()=>Kl}])}}const Ek=new Sk;class wk extends _{constructor(){super("socket.room.MovePeerPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"preset_id",kind:"scalar",opt:!0,T:9}])}}const Ck=new wk;class bk extends _{constructor(){super("socket.room.MovePeersBetweenRoomsRequest",[{no:1,name:"source_meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"destination_meeting_id",kind:"scalar",opt:!0,T:9},{no:3,name:"participants",kind:"message",repeat:1,T:()=>Ck}])}}const Pk=new bk;class Rk extends _{constructor(){super("socket.room.MovedPeer",[{no:1,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:3,name:"error",kind:"message",T:()=>Kl}])}}const Hf=new Rk;class kk extends _{constructor(){super("socket.room.MovePeersBetweenRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Hf}])}}new kk;class Ik extends _{constructor(){super("socket.room.TransferPeer",[{no:1,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"auth_token",kind:"scalar",opt:!0,T:9}])}}const Ak=new Ik;class Mk extends _{constructor(){super("socket.room.GetAllAddedParticipantsResponse",[{no:1,name:"participants",kind:"message",repeat:1,T:()=>Nk}])}}const Dk=new Mk;class Ok extends _{constructor(){super("socket.room.AddedParticipant",[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",opt:!0,T:9},{no:3,name:"picture",kind:"scalar",opt:!0,T:9},{no:4,name:"custom_participant_id",kind:"scalar",T:9}])}}const Nk=new Ok;class Lk extends _{constructor(){super("socket.room.RemoveParticipantsRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const Fk=new Lk;class xk extends _{constructor(){super("socket.room.BroadcastMessage",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"timestamp",kind:"scalar",T:4,L:2},{no:4,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const Mc=new xk;class Uk extends _{constructor(){super("socket.room.AcceptWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const Vk=new Uk;class $k extends _{constructor(){super("socket.room.DenyWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const Bk=new $k;class Hk extends _{constructor(){super("socket.room.WaitingRoomRequest",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"picture",kind:"scalar",opt:!0,T:9},{no:5,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:6,name:"preset_name",kind:"scalar",opt:!0,T:9}])}}const qk=new Hk;class jk extends _{constructor(){super("socket.room.GetWaitingRoomRequests",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>qk}])}}const qf=new jk;class Gk extends _{constructor(){super("socket.room.GetRoomStageStateResponse",[{no:1,name:"on_stage_peers",kind:"scalar",repeat:2,T:9},{no:2,name:"approved_stage_peers",kind:"scalar",repeat:2,T:9},{no:3,name:"requested_stage_peers",kind:"scalar",repeat:2,T:9}])}}const jf=new Gk;var zl;(function(s){s[s.NONE=0]="NONE",s[s.SKIP=1]="SKIP",s[s.ON_PRIVILEGED_USER_ENTRY=2]="ON_PRIVILEGED_USER_ENTRY",s[s.SKIP_ON_ACCEPT=3]="SKIP_ON_ACCEPT"})(zl||(zl={}));var gs;(function(s){s[s.NONE=0]="NONE",s[s.ALLOWED=1]="ALLOWED",s[s.NOT_ALLOWED=2]="NOT_ALLOWED",s[s.CAN_REQUEST=3]="CAN_REQUEST"})(gs||(gs={}));class Jk extends _{constructor(){super("socket.preset.PollsPermissionUpdate",[{no:1,name:"can_create",kind:"scalar",opt:!0,T:8},{no:2,name:"can_vote",kind:"scalar",opt:!0,T:8},{no:3,name:"can_view",kind:"scalar",opt:!0,T:8}])}}const Wk=new Jk;class Kk extends _{constructor(){super("socket.preset.PluginsPermissionsUpdate",[{no:1,name:"can_close",kind:"scalar",opt:!0,T:8},{no:2,name:"can_start",kind:"scalar",opt:!0,T:8}])}}const zk=new Kk;class Yk extends _{constructor(){super("socket.preset.PublicChatPermission",[{no:1,name:"can_send",kind:"scalar",opt:!0,T:8},{no:2,name:"text",kind:"scalar",opt:!0,T:8},{no:3,name:"files",kind:"scalar",opt:!0,T:8}])}}const Qk=new Yk;class Xk extends _{constructor(){super("socket.preset.PrivateChatPermission",[{no:1,name:"can_send",kind:"scalar",opt:!0,T:8},{no:2,name:"can_receive",kind:"scalar",opt:!0,T:8},{no:3,name:"text",kind:"scalar",opt:!0,T:8},{no:4,name:"files",kind:"scalar",opt:!0,T:8}])}}const Zk=new Xk;class eI extends _{constructor(){super("socket.preset.ChatPermissionUpdate",[{no:1,name:"public",kind:"message",T:()=>Qk},{no:2,name:"private",kind:"message",T:()=>Zk}])}}const tI=new eI;class rI extends _{constructor(){super("socket.preset.ConnectedMeetingPermissionUpdate",[{no:1,name:"can_alter_connected_meetings",kind:"scalar",opt:!0,T:8},{no:2,name:"can_switch_to_parent_meeting",kind:"scalar",opt:!0,T:8},{no:3,name:"can_switch_connected_meetings",kind:"scalar",opt:!0,T:8}])}}const sI=new rI;class nI extends _{constructor(){super("socket.preset.StreamPermission",[{no:1,name:"can_produce",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",gs,"STREAM_PERMISSION_TYPE_"]},{no:2,name:"can_consume",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",gs,"STREAM_PERMISSION_TYPE_"]}])}}const Yl=new nI;class iI extends _{constructor(){super("socket.preset.MediaPermissionUpdate",[{no:1,name:"video",kind:"message",T:()=>Yl},{no:2,name:"audio",kind:"message",T:()=>Yl},{no:3,name:"screenshare",kind:"message",T:()=>Yl}])}}const aI=new iI;class oI extends _{constructor(){super("socket.preset.PresetUpdates",[{no:1,name:"polls",kind:"message",T:()=>Wk},{no:2,name:"plugins",kind:"message",T:()=>zk},{no:3,name:"chat",kind:"message",T:()=>tI},{no:4,name:"accept_waiting_requests",kind:"scalar",opt:!0,T:8},{no:5,name:"can_accept_production_requests",kind:"scalar",opt:!0,T:8},{no:6,name:"can_edit_display_name",kind:"scalar",opt:!0,T:8},{no:7,name:"can_record",kind:"scalar",opt:!0,T:8},{no:8,name:"can_livestream",kind:"scalar",opt:!0,T:8},{no:9,name:"can_spotlight",kind:"scalar",opt:!0,T:8},{no:10,name:"disable_participant_audio",kind:"scalar",opt:!0,T:8},{no:11,name:"disable_participant_screensharing",kind:"scalar",opt:!0,T:8},{no:12,name:"disable_participant_video",kind:"scalar",opt:!0,T:8},{no:13,name:"kick_participant",kind:"scalar",opt:!0,T:8},{no:14,name:"pin_participant",kind:"scalar",opt:!0,T:8},{no:15,name:"transcription_enabled",kind:"scalar",opt:!0,T:8},{no:16,name:"waiting_room_type",kind:"enum",opt:!0,T:()=>["socket.preset.WaitingRoomType",zl,"WAITING_ROOM_TYPE_"]},{no:17,name:"is_recorder",kind:"scalar",opt:!0,T:8},{no:18,name:"recorder_type",kind:"enum",opt:!0,T:()=>["socket.room.RecorderType",Jl,"RECORDER_TYPE_"]},{no:19,name:"hidden_participant",kind:"scalar",opt:!0,T:8},{no:20,name:"show_participant_list",kind:"scalar",opt:!0,T:8},{no:21,name:"can_change_participant_permissions",kind:"scalar",opt:!0,T:8},{no:22,name:"connected_meetings",kind:"message",T:()=>sI},{no:23,name:"media",kind:"message",T:()=>aI}])}}const Ql=new oI;class cI extends _{constructor(){super("socket.preset.ReadPeersPresetRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const dI=new cI;class lI extends _{constructor(){super("socket.preset.PeerPreset",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"preset",kind:"scalar",T:12}])}}const uI=new lI;class hI extends _{constructor(){super("socket.preset.ReadPeersPresetResponse",[{no:1,name:"peer_presets",kind:"message",repeat:1,T:()=>uI}])}}const pI=new hI;class mI extends _{constructor(){super("socket.preset.UpdatePeerPreset",[{no:1,name:"user_ids",kind:"scalar",T:9},{no:2,name:"patch",kind:"message",T:()=>Ql}])}}const Gf=new mI;class fI extends _{constructor(){super("socket.preset.UpdatePeersPresetRequest",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>Gf}])}}const gI=new fI;class vI extends _{constructor(){super("socket.preset.UpdatePeersPresetResponse",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>Gf}])}}const Jf=new vI;class yI extends _{constructor(){super("socket.preset.PeerUserIDMap",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9}])}}const TI=new yI;class _I extends _{constructor(){super("socket.preset.BulkUpdatePeerPresetRequest",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>TI},{no:2,name:"patch",kind:"message",T:()=>Ql}])}}new _I;class SI extends _{constructor(){super("socket.preset.BulkUpdatePeerPresetResponse",[{no:2,name:"patch",kind:"message",T:()=>Ql}])}}new SI;class EI extends _{constructor(){super("socket.chat.ChatMessage",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"user_id",kind:"scalar",T:9},{no:4,name:"display_name",kind:"scalar",T:9},{no:5,name:"pinned",kind:"scalar",T:8},{no:6,name:"is_edited",kind:"scalar",T:8},{no:7,name:"payload_type",kind:"scalar",T:5},{no:8,name:"payload",kind:"scalar",T:9},{no:10,name:"target_user_ids",kind:"scalar",repeat:2,T:9},{no:11,name:"created_at",kind:"scalar",T:4,L:2},{no:12,name:"created_at_ms",kind:"scalar",opt:!0,T:4,L:2},{no:13,name:"channel_id",kind:"scalar",opt:!0,T:9},{no:14,name:"channel_index",kind:"scalar",opt:!0,T:9}])}}const on=new EI;class wI extends _{constructor(){super("socket.chat.GetPaginatedChatMessageRoomRequest",[{no:1,name:"time_stamp",kind:"scalar",T:4,L:2},{no:2,name:"size",kind:"scalar",T:5},{no:3,name:"from",kind:"scalar",T:5},{no:4,name:"reversed",kind:"scalar",T:8},{no:5,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const CI=new wI;class bI extends _{constructor(){super("socket.chat.GetPaginatedChatMessageRoomResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>on},{no:2,name:"next",kind:"scalar",T:8}])}}const PI=new bI;class RI extends _{constructor(){super("socket.chat.GetChatMessagesResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>on}])}}const Wf=new RI;class kI extends _{constructor(){super("socket.chat.SendChatMessageToRoomRequest",[{no:1,name:"payload_type",kind:"scalar",T:5},{no:2,name:"payload",kind:"scalar",T:9}])}}const II=new kI;class AI extends _{constructor(){super("socket.chat.SendChatMessageToRoomResponse",[{no:1,name:"message",kind:"message",T:()=>on}])}}const Xl=new AI;class MI extends _{constructor(){super("socket.chat.SendChatMessageToPeersRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"payload_type",kind:"scalar",T:5},{no:3,name:"payload",kind:"scalar",T:9}])}}const DI=new MI;class OI extends _{constructor(){super("socket.chat.SendChatMessageToPeersResponse",[{no:1,name:"message",kind:"message",T:()=>on}])}}const Zl=new OI;class NI extends _{constructor(){super("socket.chat.SendChatMessageToChannelRequest",[{no:1,name:"channel_id",kind:"scalar",T:9},{no:2,name:"payload_type",kind:"scalar",T:5},{no:3,name:"payload",kind:"scalar",T:9}])}}const LI=new NI;class FI extends _{constructor(){super("socket.chat.SendChatMessageToChannelResponse",[{no:1,name:"message",kind:"message",T:()=>on}])}}new FI;class xI extends _{constructor(){super("socket.chat.EditChatMessageRequest",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"payload_type",kind:"scalar",opt:!0,T:5},{no:3,name:"payload",kind:"scalar",opt:!0,T:9},{no:4,name:"pinned",kind:"scalar",opt:!0,T:8},{no:5,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const UI=new xI;class VI extends _{constructor(){super("socket.chat.PinChatMessageRequest",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"pinned",kind:"scalar",T:8},{no:3,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const $I=new VI;class BI extends _{constructor(){super("socket.chat.PinChatMessageResponse",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"pinned",kind:"scalar",T:8},{no:3,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const Dc=new BI;class HI extends _{constructor(){super("socket.chat.EditChatMessageResponse",[{no:1,name:"message",kind:"message",T:()=>on}])}}const Oc=new HI;class qI extends _{constructor(){super("socket.chat.DeleteChatMessageRequest",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const jI=new qI;class GI extends _{constructor(){super("socket.chat.DeleteChatMessageResponse",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const Nc=new GI;class JI extends _{constructor(){super("socket.chat.SearchChatMessagesRequest",[{no:1,name:"time_stamp",kind:"scalar",T:4,L:2},{no:2,name:"size",kind:"scalar",T:5},{no:3,name:"from",kind:"scalar",T:5},{no:4,name:"reversed",kind:"scalar",T:8},{no:5,name:"channel_id",kind:"scalar",opt:!0,T:9},{no:6,name:"search_term",kind:"scalar",T:9}])}}const WI=new JI;class KI extends _{constructor(){super("socket.chat.MarkChannelIndexAsReadRequest",[{no:1,name:"channel_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"channel_index",kind:"scalar",T:9}])}}const zI=new KI;class YI extends _{constructor(){super("socket.chat.MarkChannelIndexAsReadResponse",[{no:1,name:"channel_index",kind:"scalar",T:9}])}}const QI=new YI;class XI extends _{constructor(){super("socket.chat.CreateChatChannelRequest",[{no:1,name:"display_name",kind:"scalar",T:9},{no:2,name:"target_user_ids",kind:"scalar",repeat:2,T:9},{no:3,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:4,name:"visibility",kind:"scalar",T:9},{no:5,name:"is_direct_message",kind:"scalar",T:8}])}}const ZI=new XI;class eA extends _{constructor(){super("socket.chat.UpdateChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",opt:!0,T:9},{no:3,name:"target_user_ids",kind:"scalar",repeat:2,T:9},{no:4,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:5,name:"visibility",kind:"scalar",opt:!0,T:9},{no:6,name:"is_direct_message",kind:"scalar",opt:!0,T:8}])}}const tA=new eA;class rA extends _{constructor(){super("socket.chat.CreateChatChannelResponse",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new rA;class sA extends _{constructor(){super("socket.chat.GetChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}const nA=new sA;class iA extends _{constructor(){super("socket.chat.LatestMessageAndUnreadCount",[{no:1,name:"message",kind:"message",T:()=>on},{no:2,name:"unread_count",kind:"scalar",T:4,L:2}])}}const aA=new iA;class oA extends _{constructor(){super("socket.chat.ChatChannel",[{no:1,name:"chat_channel_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9},{no:3,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:4,name:"visibility",kind:"scalar",T:9},{no:5,name:"is_direct_message",kind:"scalar",T:8},{no:6,name:"latest_message_and_unread_count",kind:"message",T:()=>aA},{no:7,name:"target_user_ids",kind:"scalar",repeat:2,T:9}])}}const cA=new oA;class dA extends _{constructor(){super("socket.chat.GetChatChannelResponse",[{no:1,name:"chat_channels",kind:"message",repeat:1,T:()=>cA}])}}const Hr=new dA;class lA extends _{constructor(){super("socket.chat.ChannelMember",[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",opt:!0,T:9},{no:3,name:"picture",kind:"scalar",opt:!0,T:9},{no:4,name:"custom_participant_id",kind:"scalar",T:9}])}}const uA=new lA;class hA extends _{constructor(){super("socket.chat.GetChatChannelMembersResponse",[{no:1,name:"channel_members",kind:"message",repeat:1,T:()=>uA}])}}const pA=new hA;class mA extends _{constructor(){super("socket.plugin.AddPluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const fA=new mA;class gA extends _{constructor(){super("socket.plugin.RemovePluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const vA=new gA;class yA extends _{constructor(){super("socket.plugin.EnablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const TA=new yA;class _A extends _{constructor(){super("socket.plugin.DisablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const SA=new _A;class EA extends _{constructor(){super("socket.plugin.EnablePluginForPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const wA=new EA;class CA extends _{constructor(){super("socket.plugin.DisablePluginForPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const bA=new CA;class PA extends _{constructor(){super("socket.plugin.PluginEventToRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}const RA=new PA;class kA extends _{constructor(){super("socket.plugin.PluginEventToPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9},{no:3,name:"plugin_data",kind:"scalar",T:12}])}}const IA=new kA;class AA extends _{constructor(){super("socket.plugin.StoreKeys",[{no:1,name:"store_key",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",opt:!0,T:12}])}}const eu=new AA;class MA extends _{constructor(){super("socket.plugin.PluginStoreInsertKeysRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"insert_keys",kind:"message",repeat:1,T:()=>eu}])}}const Kf=new MA;class DA extends _{constructor(){super("socket.plugin.PluginStoreGetKeysRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"get_keys",kind:"message",repeat:1,T:()=>eu}])}}const OA=new DA;class NA extends _{constructor(){super("socket.plugin.PluginStoreDeleteKeysRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"delete_keys",kind:"message",repeat:1,T:()=>eu}])}}const LA=new NA;class FA extends _{constructor(){super("socket.plugin.PluginStoreDeleteRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9}])}}const xA=new FA;class UA extends _{constructor(){super("socket.plugin.EnablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"enabled_by",kind:"scalar",T:9}])}}const tu=new UA;class VA extends _{constructor(){super("socket.plugin.EnablePluginsResponse",[{no:1,name:"plugins",kind:"message",repeat:1,T:()=>tu}])}}const $A=new VA;class BA extends _{constructor(){super("socket.plugin.DisablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"disabled_by",kind:"scalar",T:9}])}}const zf=new BA;class HA extends _{constructor(){super("socket.plugin.PluginStoreItem",[{no:1,name:"timestamp",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"store_key",kind:"scalar",T:9},{no:4,name:"payload",kind:"scalar",T:12}])}}const qA=new HA;class jA extends _{constructor(){super("socket.plugin.PluginStoreResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"store_items",kind:"message",repeat:1,T:()=>qA}])}}const Yf=new jA;class GA extends _{constructor(){super("socket.plugin.PluginEventResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}const Qf=new GA;class JA extends _{constructor(){super("socket.livestreaming.LiveStreamingEvent",[{no:1,name:"livestream_id",kind:"scalar",T:9},{no:2,name:"err_message",kind:"scalar",T:9},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"meeting_id",kind:"scalar",T:9},{no:5,name:"playback_url",kind:"scalar",T:9},{no:6,name:"org_id",kind:"scalar",T:9},{no:7,name:"room_name",kind:"scalar",T:9},{no:8,name:"room_uuid",kind:"scalar",T:9},{no:9,name:"status",kind:"scalar",T:9}])}}const Xf=new JA;class WA extends _{constructor(){super("socket.livestreaming.GetStagePeersResponse",[{no:1,name:"stage_peers",kind:"scalar",repeat:2,T:9}])}}const Zf=new WA;class KA extends _{constructor(){super("socket.livestreaming.StageRequest",[{no:1,name:"display_name",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"peer_id",kind:"scalar",T:9}])}}const zA=new KA;class YA extends _{constructor(){super("socket.livestreaming.GetStageRequestsResponse",[{no:1,name:"stage_requests",kind:"message",repeat:1,T:()=>zA}])}}const ru=new YA;class QA extends _{constructor(){super("socket.livestreaming.GrantStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const XA=new QA;class ZA extends _{constructor(){super("socket.livestreaming.DenyStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const eM=new ZA;class tM extends _{constructor(){super("socket.livestreaming.LeaveStageRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const eg=new tM;class rM extends _{constructor(){super("socket.polls.Poll",[{no:1,name:"poll_id",kind:"scalar",T:9},{no:2,name:"created_by",kind:"scalar",T:9},{no:3,name:"created_by_user_id",kind:"scalar",T:9},{no:4,name:"question",kind:"scalar",T:9},{no:5,name:"options",kind:"message",repeat:1,T:()=>nM},{no:6,name:"hide_votes",kind:"scalar",T:8},{no:7,name:"anonymous",kind:"scalar",T:8},{no:8,name:"votes",kind:"scalar",repeat:2,T:9}])}}const tg=new rM;class sM extends _{constructor(){super("socket.polls.PollOption",[{no:1,name:"text",kind:"scalar",T:9},{no:2,name:"count",kind:"scalar",opt:!0,T:4,L:2},{no:3,name:"votes",kind:"message",repeat:1,T:()=>aM}])}}const nM=new sM;class iM extends _{constructor(){super("socket.polls.PollVote",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9}])}}const aM=new iM;class oM extends _{constructor(){super("socket.polls.NewPollRequest",[{no:1,name:"question",kind:"scalar",T:9},{no:2,name:"options",kind:"scalar",repeat:2,T:9},{no:3,name:"anonymous",kind:"scalar",T:8},{no:4,name:"hide_votes",kind:"scalar",T:8},{no:5,name:"created_by",kind:"scalar",opt:!0,T:9},{no:6,name:"created_by_user_id",kind:"scalar",opt:!0,T:9}])}}const cM=new oM;class dM extends _{constructor(){super("socket.polls.VotePollRequest",[{no:1,name:"poll_id",kind:"scalar",T:9},{no:2,name:"index",kind:"scalar",T:4,L:2}])}}const lM=new dM;class uM extends _{constructor(){super("socket.polls.UpdatePollResponse",[{no:1,name:"poll",kind:"message",T:()=>tg}])}}const su=new uM;class hM extends _{constructor(){super("socket.polls.GetPollsResponse",[{no:1,name:"polls",kind:"message",repeat:1,T:()=>tg}])}}const pM=new hM;class mM extends _{constructor(){super("socket.recording.RecordingEvent",[{no:1,name:"recording_id",kind:"scalar",T:9},{no:2,name:"err_message",kind:"scalar",T:9},{no:3,name:"recording_type",kind:"enum",T:()=>["common.RecordingType",an]}])}}const rg=new mM;class fM extends _{constructor(){super("google.protobuf.Timestamp",[{no:1,name:"seconds",kind:"scalar",T:3,L:0},{no:2,name:"nanos",kind:"scalar",T:5}])}now(){const t=this.create(),e=Date.now();return t.seconds=Pe.from(Math.floor(e/1e3)).toBigInt(),t.nanos=e%1e3*1e6,t}toDate(t){return new Date(Pe.from(t.seconds).toNumber()*1e3+Math.ceil(t.nanos/1e6))}fromDate(t){const e=this.create(),r=t.getTime();return e.seconds=Pe.from(Math.floor(r/1e3)).toBigInt(),e.nanos=r%1e3*1e6,e}internalJsonWrite(t,e){let r=Pe.from(t.seconds).toNumber()*1e3;if(rDate.parse("9999-12-31T23:59:59Z"))throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");if(t.nanos<0)throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative.");let n="Z";if(t.nanos>0){let i=(t.nanos+1e9).toString().substring(1);i.substring(3)==="000000"?n="."+i.substring(0,3)+"Z":i.substring(6)==="000"?n="."+i.substring(0,6)+"Z":n="."+i+"Z"}return new Date(r).toISOString().replace(".000Z",n)}internalJsonRead(t,e,r){if(typeof t!="string")throw new Error("Unable to parse Timestamp from JSON "+Fl(t)+".");let n=t.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw new Error("Unable to parse Timestamp from JSON. Invalid format.");let i=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[8]:"Z"));if(Number.isNaN(i))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(iDate.parse("9999-12-31T23:59:59Z"))throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");return r||(r=this.create()),r.seconds=Pe.from(i/1e3).toBigInt(),r.nanos=0,n[7]&&(r.nanos=parseInt("1"+n[7]+"0".repeat(9-n[7].length))-1e9),r}}new fM;const gM=0,vM=1,yM=2,TM=3,_M=4,SM=5,EM={getPeerInfo:0,updatePeerInfo:1,getRoomPeersInfo:2,joinRoom:3,leaveRoom:4,getRoomInfo:5,updateRoomInfo:6,closeRoom:7,startedLivestream:8,stoppedLivestream:9,erroredLivestream:10,getStagePeers:11,getStageRequests:12,requestStageAccess:13,cancelStageRequest:14,grantStageAccess:15,denyStageAccess:16,roomPeerCount:17,joinStage:18,leaveStage:19,getConnectedRoomsDump:20,createConnectedRooms:21,deleteConnectedRooms:22,movePeers:23,transferPeer:24,movedPeer:25,connectedRoomsUpdated:26,connectedRoomsDeleted:27,getAllAddedParticipants:28,broadcastMessage:29,kick:30,kickAll:31,transcript:32,getWaitingRoomRequests:33,acceptWaitingRoomRequests:34,waitingRoomRequestAccepted:35,denyWaitingRoomRequests:36,waitingRoomRequestDenied:37,peerStageStatusUpdate:38,broadcastToPeers:39,recordingStarted:40,recordingStopped:41,recordingPaused:42,getRoomStageState:43},wM={getMessages:0,sendMessageToRoom:1,sendMessageToPeers:2,editMessage:3,deleteMessage:4,getPaginatedMessages:5,sendMessageToChannel:6,searchChannelMessages:7,getAllChatChannels:8,markChannelIndexAsRead:9,pinMessage:10},CM={getPlugins:0,addPlugin:1,enablePluginForRoom:2,disablePluginForPeers:3,enablePluginForPeers:4,disablePluginForRoom:5,removePlugin:6,customPluginEventToRoom:7,customPluginEventToPeers:8,storeInsertKeys:9,storeGetKeys:10,storeDeleteKeys:11,storeDelete:12},bM={createPoll:0,getPolls:1,votePoll:2,updatePoll:3},sg={unknown:0,createWebRTCTransport:1,produce:2,consume:3,toggleProducer:4,toggleConsumer:5,closeProducer:6,closeConsumer:7,joinRoom:16,leaveRoom:17,selectedPeer:18,globalPinPeer:19,selfJoinComplete:20,peerJoinedBroadcast:25,peerLeaveBroadcast:26,peerProducerCreateBroadcast:27,peerProducerToggleBroadcast:28,peerProducerCloseBroadcast:29,globalPeerPinBroadcast:30,recordingStartedBroadcast:31,recordingStoppedBroadcast:32,peerDisplayNameEditBroadcast:33,mediaRoomTerminationBroadcastResponse:36,selectedPeerDiff:40,renegotiateSessionDescription:50,errorResponse:60,kickPeer:90,kickAll:91,changeDisplayName:92,hostControlPeer:93,hostControlAllPeers:94},PM={createChatChannel:0,getChatChannel:1,deprecatedGetAllChatChannels:2,getChannelMembers:3,updateChatChannel:4},RM={getUserPresets:0,updateUserPreset:1};function ti(s,t){return Object.keys(t).reduce((e,r)=>(e[r]=(s<<16)+t[r],e),{})}function ng(s,t){return Object.keys(s).reduce((e,r)=>(e[r]=t|s[r],e),{})}const $=ti(gM,EM),Ue=ti(vM,wM),j=ti(yM,CM),qr=ti(TM,bM),cn=ti(_M,PM),se=ng(sg,16777216),ne=ng(sg,50331648),Lc=ti(SM,RM);var kM=Object.defineProperty,IM=Object.getOwnPropertyDescriptor,nu=(s,t,e,r)=>{for(var n=r>1?void 0:r?IM(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&kM(t,e,n),n};const iu=(wv=class{constructor(s){S(this,ks,void 0);y(this,ks,s)}async createChannel(s,t,e,r="public",n=!1){const i={displayName:s,targetUserIds:t,displayPictureUrl:e,visibility:r,isDirectMessage:n};n&&(i.visibility="private");const a=await c(this,ks).sendMessagePromise(cn.createChatChannel,ZI.toBinary(i)),o=Hr.fromBinary(a.payload).chatChannels;return iu.formatChannel(o[0])}async updateChannel(s,t){const e=await c(this,ks).sendMessagePromise(cn.updateChatChannel,tA.toBinary({chatChannelId:s,targetUserIds:t.memberIds,displayName:t.displayName,displayPictureUrl:t.displayPictureUrl,visibility:t.visibility})),r=Hr.fromBinary(e.payload).chatChannels;return iu.formatChannel(r[0])}static formatChannel(s){var r;const{latestMessageAndUnreadCount:t}=s,e={...s,id:s.chatChannelId,memberIds:s.targetUserIds,unreadCount:(r=t==null?void 0:t.unreadCount)!=null?r:0};return t!=null&&t.message&&(e.latestMessage=ur.formatSocketServiceMessage(t.message)),delete e.chatChannelId,delete e.targetUserIds,delete e.latestMessageAndUnreadCount,e}async getChannelMembers(s){try{const t=await c(this,ks).sendMessagePromise(cn.getChannelMembers,nA.toBinary({chatChannelId:s}));return pA.fromBinary(t.payload).channelMembers.map(({id:e,...r})=>({...r,userId:e}))}catch(t){return[]}}on(s,t){let e,r;switch(s){case cn.createChatChannel:{e=Hr.fromBinary.bind(Hr),r=Hr.create();break}case cn.updateChatChannel:{e=Hr.fromBinary.bind(Hr),r=Hr.create();break}}if(!e){l.warn(`ChatChannelSocketHandler::Event ${s} is not recognized`);return}c(this,ks).on(s,({payload:n})=>{let i=r;try{i=e(n)}catch(a){l.error("ChatChannelSocketHandler::on::binary_decode_error",{error:a})}return t(i)})}},ks=new WeakMap,wv);let dn=iu;nu([g.trace("ChatChannelHandler.createChannel")],dn.prototype,"createChannel",1),nu([g.trace("ChatChannelHandler.updateChannel")],dn.prototype,"updateChannel",1),nu([g.trace("ChatChannelHandler.getChannelMembers")],dn.prototype,"getChannelMembers",1);var AM=Object.defineProperty,MM=Object.getOwnPropertyDescriptor,lr=(s,t,e,r)=>{for(var n=r>1?void 0:r?MM(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&AM(t,e,n),n},Pt=(s=>(s[s.TEXT=0]="TEXT",s[s.IMAGE=1]="IMAGE",s[s.FILE=2]="FILE",s[s.CUSTOM=3]="CUSTOM",s))(Pt||{});class Qt{constructor(t){S(this,vt,void 0);y(this,vt,t)}getChatMessages(){return c(this,vt).sendMessagePromise(Ue.getMessages)}async getChatMessagesPaginated(t,e,r,n=0,i=""){const a={timeStamp:t,size:e,from:n,reversed:r,channelId:i},o=await c(this,vt).sendMessagePromise(Ue.getPaginatedMessages,CI.toBinary(a));return o.payload?PI.fromBinary(o.payload):{messages:[],next:!1}}sendMessageToRoom(t,e){const r={payloadType:e,payload:t};c(this,vt).sendMessage(Ue.sendMessageToRoom,II.toBinary(r))}sendMessageToPeers(t,e,r){const n={payloadType:e,peerIds:r,payload:t};c(this,vt).sendMessage(Ue.sendMessageToPeers,DI.toBinary(n))}sendMessageToChannel(t,e,r){const n={payloadType:e,channelId:r,payload:t};c(this,vt).sendMessage(Ue.sendMessageToChannel,LI.toBinary(n))}sendMessage(t,e,r,n){if(n&&this.sendMessageToChannel(t,e,n),r&&r.length>0){this.sendMessageToPeers(t,e,r);return}this.sendMessageToRoom(t,e)}async editMessage(t,e,r,n,i){const a={chatId:t,payloadType:r,payload:e};n&&(a.channelId=n),i!==void 0&&(a.pinned=i);const o=await c(this,vt).sendMessagePromise(Ue.editMessage,UI.toBinary(a));return Oc.fromBinary(o.payload).message}async deleteMessage(t,e){const r={chatId:t};e&&(r.channelId=e);const n=await c(this,vt).sendMessagePromise(Ue.deleteMessage,jI.toBinary(r)),i=Nc.fromBinary(n.payload);return{id:i.chatId,...i.channelId?{channelId:i.channelId}:{}}}async searchMessages(t,e){var n,i,a;const r={searchTerm:t,timeStamp:(n=e.timestamp)!=null?n:Date.now(),size:(i=e.size)!=null?i:75,from:0,reversed:(a=e.reversed)!=null?a:!0};e.channelId&&(r.channelId=e.channelId);try{const o=await c(this,vt).sendMessagePromise(Ue.searchChannelMessages,WI.toBinary(r));return Wf.fromBinary(o.payload).messages}catch(o){return[]}}async getAllChannels(){try{const t=await c(this,vt).sendMessagePromise(Ue.getAllChatChannels);return Hr.fromBinary(t.payload).chatChannels.map(dn.formatChannel)}catch(t){return[]}}async markLastReadMessage(t,e){const r=await c(this,vt).sendMessagePromise(Ue.markChannelIndexAsRead,zI.toBinary({channelId:t,userId:e.userId,channelIndex:e.channelIndex}));return QI.fromBinary(r.payload).channelIndex}async setPinState(t,e){const r={chatId:t.id,pinned:e,channelId:t.channelId},n=await c(this,vt).sendMessagePromise(Ue.pinMessage,$I.toBinary(r));return Dc.fromBinary(n.payload)}on(t,e){let r,n;switch(t){case Ue.sendMessageToRoom:{r=Xl.fromBinary.bind(Xl),n=Xl.create();break}case Ue.sendMessageToPeers:{r=Zl.fromBinary.bind(Zl),n=Zl.create();break}case Ue.editMessage:{r=Oc.fromBinary.bind(Oc),n=Oc.create();break}case Ue.pinMessage:{r=Dc.fromBinary.bind(Dc),n=Dc.create();break}case Ue.deleteMessage:{r=Nc.fromBinary.bind(Nc),n=Nc.create();break}}if(!r){l.warn(`ChatSocketHandler::Event ${t} is not recognized`);return}c(this,vt).on(t,({payload:i})=>{let a=n;try{a=r(i)}catch(o){l.error("chatSocketHandler::on::binary_decode_error",{error:o})}return e(a)})}}vt=new WeakMap,lr([g.trace("SocketService.getChatMessages")],Qt.prototype,"getChatMessages",1),lr([g.trace("SocketService.getChatMessagesPaginated")],Qt.prototype,"getChatMessagesPaginated",1),lr([g.trace("SocketService.sendMessageToRoom")],Qt.prototype,"sendMessageToRoom",1),lr([g.trace("SocketService.sendMessageToPeers")],Qt.prototype,"sendMessageToPeers",1),lr([g.trace("SocketService.sendMessageToChannel")],Qt.prototype,"sendMessageToChannel",1),lr([g.trace("SocketService.sendMessage")],Qt.prototype,"sendMessage",1),lr([g.trace("SocketService.editMessage")],Qt.prototype,"editMessage",1),lr([g.trace("SocketService.deleteMessage")],Qt.prototype,"deleteMessage",1),lr([g.trace("SocketService.searchMessages")],Qt.prototype,"searchMessages",1),lr([g.trace("SocketService.getAllChannels")],Qt.prototype,"getAllChannels",1),lr([g.trace("SocketService.markLastReadMessage")],Qt.prototype,"markLastReadMessage",1);function DM(s){return s.replace(/([-_]\w)/g,t=>t[1].toUpperCase())}function wr(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>wr(e));const t={};return Object.keys(s).forEach(e=>{const r=Vd(e)?e:DM(e);t[r]=wr(s[e])}),t}function OM(s){return s.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function ig(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>ig(e));const t={};return Object.keys(s).forEach(e=>{const r=Vd(e)?e:OM(e);t[r]=s[e]}),t}function Fc(s,t={}){return s==null?{}:(Object.getOwnPropertyNames(s).forEach(e=>{if(typeof s[e]!="function"){if(typeof s[e]=="object"){Fc(s[e],t[e]={});return}t[e]=s[e]}}),t)}const NM=3,LM=30,FM=8e3;class xM{constructor(t,e){m(this,"ipInfo");m(this,"axios");m(this,"requests");m(this,"roomName");m(this,"roomUUID");m(this,"authToken");m(this,"organizationId");m(this,"iceServers");m(this,"pluginInformation");m(this,"userDetails");m(this,"roomDetails");m(this,"context");this.context=t;const{timeout:r=FM,retry:n=NM,retryDelay:i=LM,baseURL:a="https://api.cluster.dyte.in",authToken:o,cachedUserDetails:d}=e||{};this.iceServers=d==null?void 0:d.iceServers,this.pluginInformation=d==null?void 0:d.pluginInformation,this.userDetails=d==null?void 0:d.userDetails,this.roomDetails=d==null?void 0:d.roomDetails,this.requests=rc.create({baseURL:a,responseType:"json",timeout:r,retry:n,retryDelay:i}),this.axios=rc,this.setAuthToken(o,{bearer:!0}),this.requests.interceptors.request.use(u=>(g.injectContext(this.requests.defaults.headers.common),u),async u=>{l.error("xhr::axios",{debuggingHint:"otelRequestInterceptor failed.",error:u})}),this.requests.interceptors.response.use(u=>{try{u.config.url!==g.logsEndpoint&&l.debug("xhr::axios",{networkCall:{status:u.status,statusText:u.statusText,baseURL:u.config.baseURL,url:u.config.url,method:u.config.method}})}catch(h){console.error("xhr::dyte",{error:"responseInterceptorFailed",err:h,response:u})}return u},async u=>{var h;try{if(!u)return Promise.reject(new b("Unknown network error occurred","0011"));u&&u.config&&((h=u.config)==null?void 0:h.url)!==g.logsEndpoint&&l.error("xhr::axios",{error:u,networkCall:{status:u.status,statusText:u.statusText,baseURL:u.config.baseURL,url:u.config.url,retries:u.config.retry,method:u.config.method,isOnline:navigator.onLine?"online":"offline"}});const{config:p,message:f}=u;return p&&f&&p.retry!==void 0&&p.retry>0&&(f.includes("timeout")||f.includes("Network Error"))?(p.retry-=1,this.requests(p)):Promise.reject(new b(f,"0011"))}catch(p){return console.error("xhr::dyte",{error:"responseInterceptorFailed",err:p,responseError:u}),Promise.reject(new b(p.message,"0011"))}})}get peerId(){return this.context.getValue("peerId")}setAuthToken(t,e){const{bearer:r}=e||{};this.authToken=t,this.requests.defaults.headers.common.Authorization=r?`Bearer ${t}`:t}setHeader(t,e){this.requests.defaults.headers.common[t]=e}setRoomName(t){this.roomName=t}setRoomUUID(t){this.roomUUID=t}setOrganizationId(t){this.organizationId=t}}var UM=Object.defineProperty,VM=Object.getOwnPropertyDescriptor,au=(s,t,e,r)=>{for(var n=r>1?void 0:r?VM(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&UM(t,e,n),n};class xc extends xM{constructor(t,e){super(t,e),this.setHeader("x-dyte-web-core-version",t.getValue("sdkVersion"))}async getIPDetails(){var e;const{peerId:t}=this;try{const r=await Ud.getIPDetails({peerId:t,apiHostnames:Lm(this.context)});if(l.log("ipInfo",{ipInfo:r}),((e=r.loc)==null?void 0:e.length)>5)return r;throw Error("Insufficient data")}catch(r){l.warn("ApiClient.getRoomNodeLinkAndTitleV1 Failed to get ip details",{error:{name:r.name,message:r.message}});return}}async getICEServers(){if(this.iceServers)return this.iceServers;const{success:t,iceServers:e}=(await this.requests.get("/iceservers")).data;if(t)return(e==null?void 0:e.length)>0&&(this.iceServers=e),e}async getPlugins(){var n,i,a,o,d,u,h;if(this.pluginInformation)return this.pluginInformation;let{plugins:t}=(await this.requests.get("/v2/plugins/user")).data.data;const e=((i=(n=J.getValue(X.V1_PLUGINS))==null?void 0:n.toString())==null?void 0:i.split(","))||[];return t=t.reduce((p,f)=>(p[e.includes(f.id)?"v1":"v2"].push(f),p),{v1:[],v2:[]}).v2,(d=(o=(a=this.context.getValue("modules"))==null?void 0:a.devTools)==null?void 0:o.plugins)!=null&&d.length&&((h=(u=this.context.getValue("modules"))==null?void 0:u.devTools)==null||h.plugins.forEach(p=>{var v,T,P;const f={...ha,tags:[...ha.tags]};f.baseURL=`http://localhost:${p.port}`,f.name=p.name,f.picture=(v=p.picture)!=null?v:ha.picture,f.description=(T=p.description)!=null?T:ha.description,f.staggered=(P=p.staggered)!=null?P:ha.staggered,f.createdAt=new Date().toISOString(),f.updatedAt=new Date().toISOString(),f.id=p.id,f.organizationId=this.organizationId,t.push(f)})),t}async getPluginDetails(t){const{plugin:e}=(await this.requests.get(`/v2/plugins/view/${t}`)).data.data;return e}async getPluginConfig(t){return(await this.axios.get(`${t}/dyte-config.json`)).data}async authorizePlugin(t){const e={peerId:this.peerId},{token:r}=(await this.requests.post(`/v2/plugins/authorize/${t}`,e)).data.data;return r}async getPresignedUrls(t,e){const r=Nl(this.context,"chat_upload_expiry"),n={roomUUID:this.roomUUID,filename:t,expiry:typeof r=="number"?r:void 0};J.hasFeature(X.FEAT_CHAT_SDK)&&(n.viewType=e);const{getLocation:i,putLocation:a}=(await this.requests.post("/v1/meetings/genPreSignedUploadUrl",n)).data.data;return{getLocation:i,putLocation:a}}async uploadFile(t,e){if(navigator.isReactNative&&"uri"in t)try{await fetch(e,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:{uri:t.uri,name:t.name}})}catch(r){l.error(`sendFileMessage::${r}`)}else await this.axios.put(e,t,{headers:{"Content-Type":t.type}})}}au([g.trace("APIClient.getIPDetails")],xc.prototype,"getIPDetails",1),au([g.trace("APIClient.getICEServers")],xc.prototype,"getICEServers",1),au([g.trace("APIClient.getPlugins")],xc.prototype,"getPlugins",1);var $M=Object.defineProperty,BM=Object.getOwnPropertyDescriptor,jr=(s,t,e,r)=>{for(var n=r>1?void 0:r?BM(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&$M(t,e,n),n};class Cr extends xc{async startLivestreaming(){var e,r;return(r=(e=(await this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/livestreams`)).data)==null?void 0:e.data)==null?void 0:r.playback_url}async stopLivestreaming(){return this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/active-livestream/stop`)}async getActiveLivestream(){const{playbackUrl:t,status:e}=wr((await this.requests.get(`/v2/meetings/${this.context.getValue("meetingId")}/active-livestream`)).data.data);return{status:e,playbackUrl:t}}async getUserDetails(){if(this.userDetails)return this.userDetails;const t=(await this.requests.get("v2/internals/participant-details")).data.data;return wr(t)}async startRecording(t,e){return(await this.requests.post("/v2/recordings",{...ig(t),meeting_id:this.context.getValue("meetingId"),allow_multiple_recordings:!!e})).data.data.id}async updateRecording(t,e){return this.requests.put(`v2/recordings/${t}`,{action:e})}async getActiveRecording(){const{status:t,id:e}=(await this.requests.get(`v2/recordings/active-recording/${this.context.getValue("meetingId")}`)).data.data;return{status:t,id:e}}async getActiveTranscript(){const{transcript_download_url:t}=(await this.requests.get(`v2/meetings/${this.context.getValue("meetingId")}/active-transcript`)).data.data;try{return{transcript:(await this.axios.get(t)).data}}catch(e){throw new b("Cant fetch transcript s3 url")}}async getRoomNodeData(){const t=await this.getIPDetails();if(this.ipInfo=t,this.roomDetails)return this.roomDetails;const{roomNodeLink:e,title:r,useHiveMedia:n,sfu:i}=wr((await this.requests.post("v2/internals/rooms",{ip_information:t})).data.data);return{roomNodeUrl:e,meetingTitle:r,useHiveMedia:n!=null?n:!1,sfu:i}}}jr([g.trace("APIClient.startLivestreaming")],Cr.prototype,"startLivestreaming",1),jr([g.trace("APIClient.stopLivestreaming")],Cr.prototype,"stopLivestreaming",1),jr([g.trace("APIClient.getActiveLivestream")],Cr.prototype,"getActiveLivestream",1),jr([g.trace("APIClient.getUserDetails")],Cr.prototype,"getUserDetails",1),jr([g.trace("APIClient.startRecording")],Cr.prototype,"startRecording",1),jr([g.trace("APIClient.stopRecording")],Cr.prototype,"updateRecording",1),jr([g.trace("APIClient.getActiveRecording")],Cr.prototype,"getActiveRecording",1),jr([g.trace("APIClient.getActiveTranscript")],Cr.prototype,"getActiveTranscript",1),jr([g.trace("APIClient.getRoomNodeData")],Cr.prototype,"getRoomNodeData",1);let ou;function HM(s,t){return ou=new Cr(s,t),ou}function We(){return ou}function qM(s,t){return`
${t.replace(/
[.\s\S]*<\/blockquote>\n\n/m,"")}
+${this.message}`;try{let i=n;r&&r.endsWith("00")&&(i=!0),i&&l.error("DyteError",{error:{message:this.message,name:this.name,code:r}})}catch(i){}}}function vc(s,t,e,r){if(r instanceof b)throw r;if(r instanceof t){const n=new b(r.message,e);throw n.stack=r.stack,n}else throw r}function Fm(s,t,e){if(!s.value){const n=s.get,i=s.set;return n&&(s.get=function(){try{return n.apply(this)}catch(a){vc(this,t,e,a)}}),i&&(s.set=function(a){try{return i.apply(this,[a])}catch(o){vc(this,t,e,o)}}),s}const r=s.value;return s.value=function(...n){try{const i=r.apply(this,n);return i&&i instanceof Promise?i.catch(a=>{vc(this,t,e,a)}):i}catch(i){vc(this,t,e,i)}},s}function mb(s,t){return(e,r,n)=>{if(n)return Fm(n,s,t);for(const i of Reflect.ownKeys(e.prototype).filter(a=>a!=="constructor")){const a=Object.getOwnPropertyDescriptor(e.prototype,i);(a.value instanceof Function||a.get instanceof Function||a.set instanceof Function)&&Object.defineProperty(e.prototype,i,Fm(a,s,t))}}}const pt=s=>mb(Error,s);function fb(s){let t=0,e,r;if(!s)return t;for(e=0;enew Promise(i=>{c(this,Yr).get(e).push(i)}));super.emit(e,...r),await Promise.race([Promise.all(n),new Promise((i,a)=>setTimeout(()=>a(new Error(`emitAsync failed to resolve for event ${e}.`)),this.asyncPromiseTimeout))]),c(this,Yr).delete(e)}onAsync(e,r){const n=c(this,Yr),i=async(...a)=>{var d;try{await r(...a)}catch(u){l.error("[onAsync]",{error:u})}const o=(d=n.get(e))==null?void 0:d.shift();o==null||o()};return c(this,Qr).get(e)||c(this,Qr).set(e,[]),c(this,Qr).get(e).push(i),super.on(e,i)}reset(){y(this,Yr,new Map),y(this,Qr,new Map),super.removeAllListeners()}}Yr=new WeakMap,Qr=new WeakMap;const w=new gb;function vb(){Se.isElectron()&&window.dyteElectronGetDisplayMediaSource&&(navigator.mediaDevices.getDisplayMedia=async()=>{const s=await window.dyteElectronGetDisplayMediaSource({types:["window","screen"]});let t=[];if(s&&(Array.isArray(s)?t=s:t=[s]),!(t!=null&&t.length))throw new Error("Couldn't find any media source for screen share.");let e=t.find(i=>{var a;return(a=i.id)==null?void 0:a.includes("screen")});e=e!=null?e:t[0];const r={audio:!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e.id}}};return await navigator.mediaDevices.getUserMedia(r)})}var C=(s=>(s.NEW_PRODUCER="NEW_PRODUCER",s.PRODUCER_TRACK_ENDED="PRODUCER_TRACK_ENDED",s.ROOM_NODE_CONNECTION_ERROR="ROOM_NODE_CONNECTION_ERROR",s.SOCKET_SERVICE_ROOM_JOINED="SOCKET_SERVICE_ROOM_JOINED",s.SOCKET_SERVICE_RECONNECTED="SOCKET_SERVICE_RECONNECTED",s.SOCKET_SERVICE_DISCONNECTED="SOCKET_SERVICE_DISCONNECTED",s.SOCKET_SERVICE_FAILED="SOCKET_SERVICE_FAILED",s.SOCKET_STATE_UPDATE="SOCKET_STATE_UPDATE",s.ROOM_NODE_RECONNECTED="ROOM_NODE_RECONNECTED",s.ROOM_NODE_DISCONNECTED="ROOM_NODE_DISCONNECTED",s.ROOM_NODE_FAILED="ROOM_NODE_FAILED",s.TRANSPORT_STATE_UPDATE="TRANSPORT_STATE_UPDATE",s.PRODUCER_SCORE_UPDATE="PRODUCER_SCORE_UPDATE",s.CONSUMER_SCORE_UPDATE="CONSUMER_SCORE_UPDATE",s.PRODUCER_STATUS_UPDATE="PRODUCER_STATUS_UPDATE",s.CONSUMER_STATUS_UPDATE="CONSUMER_STATUS_UPDATE",s.LOW_PRODUCER_SCORE="LOW_PRODUCER_SCORE",s.LOW_CONSUMER_SCORE="LOW_CONSUMER_SCORE",s.MEDIA_PERMISSION_ERROR="MEDIA_PERMISSION_ERROR",s.MEDIA_PERMISSION_UPDATE="MEDIA_PERMISSION_UPDATE",s.WAITLISTED="WAIT_LISTED",s.MESSAGE="websocket/message",s.ROOM_MESSAGE="websocket/room-message",s.PEER_JOINED_INTERNAL="peer/joined-internal",s.PEER_CLOSED="websocket/peer-closed",s.CONSUMER_CLOSED="websocket/consumer-closed",s.CONSUMER_PAUSED="websocket/consumer-paused",s.CONSUMER_RESUMED="websocket/consumer-resumed",s.PRODUCER_CLOSED="websocket/producer-closed",s.NEW_CONSUMER="websocket/new-consumer",s.PRODUCER_SCORE="websocket/producer-score",s.CONSUMER_SCORE="websocket/consumer-score",s.PRODUCER_TOGGLE="hive/producer-toggle",s.CONSUMER_TOGGLE="hive/consumer-toggle",s.SELECTED_PEERS_DIFF="hive/selected-peers-diff",s.UPDATE_ACTIVE="media/update-active",s.RESET_PRODUCER_STATE="hive/reset-producer-state",s.CF_TRANSPORT_STATE_CHANGED="cf/transport-state-changed",s.CF_ROOM_REJOINING="cf/room-rejoining",s.CF_ROOM_REJOIN_FAILED="cf/room-rejoining-failed",s.CF_ROOM_REJOINED="cf/room-rejoined",s.CF_TRANPSORT_RECONNECTING="cf/transport-reconnecting",s.ROOM_STATE="sockethub/room-state",s.PEER_DISPLAY_NAME_CHANGED="hive/display-name-changed",s.GET_STAGE_REQUESTS="GET_STAGE_REQUESTS",s.UPDATE_STAGE_REQUESTS="UPDATE_STAGE_REQUESTS",s.KICK_PEER="KICK_PEER",s.UPDATE_PEER_STAGE_STATUS="UPDATE_PEER_STAGE_STATUS",s.JOIN_MEDIA_ROOM="JOIN_MEDIA_ROOM",s.LEAVE_MEDIA_ROOM="LEAVE_MEDIA_ROOM",s.PIP_HANGUP="PIP_HANGUP",s.E2EE_ACTIVE_PRODUCER="E2EE_ACTIVE_PRODUCER",s.E2EE_INACTIVE_PRODUCER="E2EE_INACTIVE_PRODUCER",s.E2EE_ACTIVE_CONSUMER="E2EE_ACTIVE_CONSUMER",s.E2EE_INACTIVE_CONSUMER="E2EE_INACTIVE_CONSUMER",s.SOCKET_PEERS="SOCKET_PEERS",s.UPDATE_PERMISSIONS="UPDATE_PERMISSIONS",s.MAX_SPATIAL_LAYER_CHANGE="MAX_SPATIAL_LAYER_CHANGE",s.MUTE_SELF="MUTE_SELF",s.MUTE_SELF_VIDEO="MUTE_SELF_VIDEO",s))(C||{});class Zn extends de.EventEmitter{constructor(){super(),super.setMaxListeners(25)}emit(t,...e){return super.emit("*",t,...e),super.emit(t,...e)}on(t,e){try{const r=this.listenerCount(t);r>25&&r%25===0&&l.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:t.toString(),listenerCount:this.listenerCount(t)}})}catch(r){}return super.on(t,e)}addListener(t,e){try{const r=this.listenerCount(t);r>25&&r%25===0&&l.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:t.toString(),listenerCount:this.listenerCount(t)}})}catch(r){}return super.addListener(t,e)}off(t,e){return super.off(t,e)}once(t,e){return super.once(t,e)}prependListener(t,e){return super.prependListener(t,e)}prependOnceListener(t,e){return super.prependOnceListener(t,e)}removeListener(t,e){return super.removeListener(t,e)}removeAllListeners(t){return super.removeAllListeners(t)}listeners(t){return super.listeners(t)}listenerCount(t){return super.listenerCount(t)}}class Ht extends de.EventEmitter{constructor(){super(),super.setMaxListeners(25)}emit(t,...e){return super.emit("*",t,...e),super.emit(t,...e)}on(t,e){try{const r=this.listenerCount(t);r>25&&r%25===0&&l.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:t.toString(),listenerCount:this.listenerCount(t)}})}catch(r){}return super.on(t,e)}addListener(t,e){try{const r=this.listenerCount(t);r>25&&r%25===0&&l.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:t.toString(),listenerCount:this.listenerCount(t)}})}catch(r){}return super.addListener(t,e)}off(t,e){return super.off(t,e)}once(t,e){return super.once(t,e)}prependListener(t,e){return super.prependListener(t,e)}prependOnceListener(t,e){return super.prependOnceListener(t,e)}removeListener(t,e){return super.removeListener(t,e)}removeAllListeners(t){return super.removeAllListeners(t)}listeners(t){return super.listeners(t)}listenerCount(t){return super.listenerCount(t)}}function yb(s,t=2){return s.replace(/[^\u00BF-\u1FFF\u2C00-\uD7FF\w\s]/g,"").trim().split(/\s+/).slice(0,t).map(n=>n.charAt(0)).join("").toUpperCase()}const xm=1080,Um=1920,Tb=(s,t,e,r,n,i)=>{let a=.5,o=.5;const d=n,u=i,h=Math.min(e/d,r/u);let p=d*h,f=u*h,v,T,P,k,I=1;return pd&&(P=d),k>u&&(k=u),[v,T,P,k,s,t,e,r]},ju=class extends Ht{constructor(e,r,n,i){super();S(this,Zt,void 0);S(this,fi,void 0);S(this,gt,void 0);S(this,er,void 0);S(this,qe,{height:xm,width:Um});S(this,mr,{brand:"#2160FD",background:"#141414",text:"#000000",videoBackground:"#191919",textOnBrand:"#EEEEEE"});S(this,Xr,void 0);S(this,It,{});S(this,Ze,void 0);S(this,gi,void 0);S(this,vi,void 0);S(this,Zr,void 0);S(this,yi,!1);m(this,"cleanupEventListeners",()=>{c(this,fi).unsubscribe("stageStatus",this.handlePipMediaControls),c(this,Ze).removeListener("videoUpdate",this.onSelfVideoUpdateListener),c(this,Ze).removeListener("audioUpdate",this.onSelfAudioUpdateListener),c(this,Ze).removeListener("roomLeft",()=>this.disable())});m(this,"enablePipMediaControls",()=>{this.mountAudioEvents(),this.mountVideoEvents()});m(this,"onSelfVideoUpdateListener",({videoEnabled:e})=>{this.updateMediaSession("CAMERA",e)});m(this,"onSelfAudioUpdateListener",({audioEnabled:e})=>{this.updateMediaSession("MIC",e)});m(this,"handlePipMediaControls",e=>{e==="ON_STAGE"?this.enablePipMediaControls():this.unmountEvents()});m(this,"eventCallback",e=>{e==="CAMERA"&&(c(this,Ze).videoEnabled?c(this,Ze).disableVideo():c(this,Ze).enableVideo(),this.emit("cameraToggled")),e==="MIC"&&(c(this,Ze).audioEnabled?c(this,Ze).disableAudio():c(this,Ze).enableAudio(),this.emit("micToggled")),e==="END"&&(w.emit(C.PIP_HANGUP),this.cleanupEventListeners(),this.emit("hangup"),this.cleanup())});m(this,"unmountEvents",()=>{navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||(navigator.mediaSession.setActionHandler("togglemicrophone",void 0),navigator.mediaSession.setActionHandler("togglecamera",void 0))});m(this,"animate",()=>{if(!this.isActive&&c(this,Zr)==="active"){this.disable(!0);return}c(this,It)!==void 0&&this.paintCanvas(),c(this,Xr)!==void 0&&y(this,Xr,requestAnimationFrame(()=>this.animate()))});m(this,"disable",(e=!1)=>{y(this,Zr,"idle"),this.cleanupEventListeners(),cancelAnimationFrame(c(this,Xr)),e!==!0&&document.body.removeChild(c(this,gt)),y(this,Xr,void 0),document.pictureInPictureElement&&document.exitPictureInPicture()});y(this,fi,e),y(this,Zr,"idle"),y(this,Ze,r),y(this,mr,{brand:r.config.designTokens.colors.brand[500],background:r.config.designTokens.colors.background[1e3],text:r.config.designTokens.colors.text,videoBackground:r.config.designTokens.colors.videoBg,textOnBrand:r.config.designTokens.colors.textOnBrand}),n&&this.setupIcon("pin",n),i&&this.setupIcon("handRaise",i)}static async _init(e,r){let n,i;try{n=await fc(cb),i=await fc(db)}catch(a){}return new ju(e,r,n,i)}async setupIcon(e,r){switch(e){case"handRaise":y(this,vi,r);break;case"pin":y(this,gi,r);break}}async overrideIcon(e,r){switch(e){case"handRaise":y(this,vi,await fc(r));break;case"pin":y(this,gi,await fc(r));break}}constructImage(e){const r=new Image,n=new Blob([e],{type:"image/svg+xml"}),i=window.URL.createObjectURL(n);return new Promise(a=>{r.onload=()=>{a(r),window.URL.revokeObjectURL(i)},r.src=i})}createVideoContainer(){y(this,gt,document.createElement("div")),c(this,gt).style.width="0.1px",c(this,gt).style.height="0.1px",c(this,gt).style.overflow="hidden",c(this,gt).style.position="absolute",c(this,gt).style.bottom="0",c(this,gt).style.right="0",c(this,gt).style.opacity="0",c(this,gt).appendChild(c(this,er))}setupEventListeners(){c(this,fi).subscribe("stageStatus",this.handlePipMediaControls),c(this,Ze).addListener("videoUpdate",this.onSelfVideoUpdateListener),c(this,Ze).addListener("audioUpdate",this.onSelfAudioUpdateListener),c(this,Ze).addListener("roomLeft",()=>this.disable())}createCanvas(){const e=document.createElement("canvas");e.height=c(this,qe).height,e.width=c(this,qe).width,y(this,Zt,e)}setupMediaSessionEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||(navigator.mediaSession.setActionHandler("hangup",()=>{this.eventCallback("END")}),this.mountAudioEvents(),this.mountVideoEvents())}mountAudioEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setMicrophoneActive===void 0||c(this,Ze).permissions.canProduceAudio&&navigator.mediaSession.setActionHandler("togglemicrophone",()=>{this.eventCallback("MIC")})}mountVideoEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||c(this,Ze).permissions.canProduceVideo&&navigator.mediaSession.setActionHandler("togglecamera",()=>{this.eventCallback("CAMERA")})}getSources(){const r=Object.values(c(this,It)).reduce((n,i)=>(n[i.pinned?"pinned":"regular"].push(i),n),{pinned:[],regular:[]});return[...r.pinned,...r.regular]}drawEmptyTile(e,r,n,i){if(c(this,Zt)===void 0)return;const a=c(this,Zt).getContext("2d"),o=c(this,Zt).width,d=0,u=0,h=r-d*2,p=n-d*2,f=Math.floor(o/h),v=Math.floor(e/f),P=e%f*(h+d)+d,k=v*(p+d)+d,{displayText:I,image:x}=i!=null?i:{};a.fillStyle=I||x?c(this,mr).videoBackground:c(this,mr).background,a.strokeStyle=c(this,mr).brand,a.beginPath(),a.moveTo(P+u,k),a.arcTo(P+h,k,P+h,k+u,u),a.arcTo(P+h,k+p,P+h-u,k+p,u),a.arcTo(P,k+p,P,k+p-u,u),a.arcTo(P,k,P+u,k,u),a.closePath(),a.fill(),a.stroke();const V=h/6,O=h/2+P,W=p/2+k;a.save(),(I||x)&&(a.beginPath(),a.arc(O,W,V,0,Math.PI*2),a.fillStyle=c(this,mr).brand,a.fill(),x?(a.clip(),a.drawImage(x,O-V,W-V,V*2,V*2),a.restore()):I&&(a.fillStyle=c(this,mr).textOnBrand,a.font=`${V/2}px sans-serif`,a.textAlign="center",a.textBaseline="middle",a.fillText(I,O,W)),this.drawIcons(i,P,k,Math.max(h,p)))}drawIcons(e,r,n,i){const a=Math.min(Math.max(i*.15,100),200),o=a*.2,d=a*.2;let u=r+o;const h=n+o,p=f=>{const v=c(this,Zt).getContext("2d");v.save(),v.fillStyle=c(this,mr).background,v.beginPath(),v.moveTo(u+d,h),v.arcTo(u+a,h,u+a,h+d,d),v.arcTo(u+a,h+a,u+a-d,h+a,d),v.arcTo(u,h+a,u,h+a-d,d),v.arcTo(u,h,u+d,h,d),v.closePath(),v.fill(),typeof f=="string"?(v.font=`${a/1.5}px sans-serif`,v.fillStyle=c(this,mr).text,v.textAlign="center",v.textBaseline="top",v.fillText(f,a/2+u,h+o)):v.drawImage(f,u+o,h+o,a-o*2,a-o*2),u+=a+o,v.restore()};e.pinned&&p(c(this,gi)),e.handRaised&&p(c(this,vi))}drawTile(e,r,n){var u,h;if(c(this,Zt)===void 0)return;const i=c(this,Zt).getContext("2d"),a=this.getSources();let o=0,d=0;for(;o0?e+1:e);const[r,n]=this.calcGridElemSize(e);this.drawTile(r,n,e)}isSupported(){return!!window.chrome&&document.pictureInPictureEnabled}get isActive(){return document.pictureInPictureElement!==null}cleanup(){if(y(this,yi,!1),this.isSupported()&&document.exitPictureInPicture!==void 0&&document.pictureInPictureElement!==null&&document.exitPictureInPicture(),c(this,gt))try{document.body.removeChild(c(this,gt))}catch(e){}this.removeAllSources(),y(this,Zt,void 0),y(this,er,void 0),y(this,Xr,void 0)}init({height:e,width:r}={}){if(c(this,yi))return;y(this,yi,!0),this.createCanvas(),this.setupMediaSessionEvents();const n=document.createElement("video");y(this,qe,{height:e!=null?e:xm,width:r!=null?r:Um}),n.height=c(this,qe).height,n.width=c(this,qe).width,n.autoplay=!0,n.muted=!0,n.srcObject=c(this,Zt).captureStream(24),y(this,er,n),c(this,er).onloadedmetadata=()=>{try{this.emit("pipStarted"),c(this,er).onleavepictureinpicture=()=>{this.emit("pipEnded")}}catch(i){this.emit("pipEnded")}},this.createVideoContainer(),this.paintCanvas()}updateMediaSession(e,r){navigator.mediaSession!==void 0&&(e==="CAMERA"&&navigator.mediaSession.setCameraActive!==void 0&&navigator.mediaSession.setCameraActive(r),e==="MIC"&&navigator.mediaSession.setMicrophoneActive!==void 0&&navigator.mediaSession.setMicrophoneActive(r))}enableSource(e){c(this,It)[e]!==void 0&&(c(this,It)[e].enabled=!0)}disableSource(e){c(this,It)[e]!==void 0&&(c(this,It)[e].enabled=!1)}async generateAvatar(e,r){const n=new Image,i=await fetch(r).then(o=>o.blob()),a=window.URL.createObjectURL(i);n.onload=()=>{this.updateSource(e,{image:n}),window.URL.revokeObjectURL(a)},n.src=a}addSource(e,r,n,i=!1,a=void 0,o=void 0,d=!1){l.info("DytePIP::AddSource",{pip:{id:e,handRaised:d}}),c(this,It)[e]={id:e,element:r,enabled:n,pinned:i,displayText:a?yb(a):void 0,imageUrl:o,handRaised:d},o&&this.generateAvatar(e,o)}updateSource(e,r){l.info("DytePIP::UpdateSource",{pip:{id:e,handRaised:r.handRaised}});const n=c(this,It)[e];n&&(c(this,It)[e]={...n,...r})}removeSource(e){delete c(this,It)[e]}removePinnedSource(){Object.values(c(this,It)).forEach(r=>{r.pinned&&this.removeSource(r.id)})}removeAllSources(){y(this,It,{})}enable(){y(this,Zr,"activating"),this.setupEventListeners(),this.updateMediaSession("CAMERA",c(this,Ze).videoEnabled),this.updateMediaSession("MIC",c(this,Ze).audioEnabled),document.body.appendChild(c(this,gt)),y(this,Xr,requestAnimationFrame(()=>this.animate())),c(this,er).onloadedmetadata=()=>{c(this,er).requestPictureInPicture().then(()=>{y(this,Zr,"active")})},c(this,er).readyState===4&&c(this,er).requestPictureInPicture().then(()=>{y(this,Zr,"active")})}};let Ll=ju;Zt=new WeakMap,fi=new WeakMap,gt=new WeakMap,er=new WeakMap,qe=new WeakMap,mr=new WeakMap,Xr=new WeakMap,It=new WeakMap,Ze=new WeakMap,gi=new WeakMap,vi=new WeakMap,Zr=new WeakMap,yi=new WeakMap;function Fl(s){let t=typeof s;if(t=="object"){if(Array.isArray(s))return"array";if(s===null)return"null"}return t}function _b(s){return s!==null&&typeof s=="object"&&!Array.isArray(s)}let $r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),yc=[];for(let s=0;s<$r.length;s++)yc[$r[s].charCodeAt(0)]=s;yc["-".charCodeAt(0)]=$r.indexOf("+"),yc["_".charCodeAt(0)]=$r.indexOf("/");function Sb(s){let t=s.length*3/4;s[s.length-2]=="="?t-=2:s[s.length-1]=="="&&(t-=1);let e=new Uint8Array(t),r=0,n=0,i,a=0;for(let o=0;o>4,a=i,n=2;break;case 2:e[r++]=(a&15)<<4|(i&60)>>2,a=i,n=3;break;case 3:e[r++]=(a&3)<<6|i,n=0;break}}if(n==1)throw Error("invalid base64 string.");return e.subarray(0,r)}function Eb(s){let t="",e=0,r,n=0;for(let i=0;i>2],n=(r&3)<<4,e=1;break;case 1:t+=$r[n|r>>4],n=(r&15)<<2,e=2;break;case 2:t+=$r[n|r>>6],t+=$r[r&63],e=0;break}return e&&(t+=$r[n],t+="=",e==1&&(t+="=")),t}var Tc;(function(s){s.symbol=Symbol.for("protobuf-ts/unknown"),s.onRead=(e,r,n,i,a)=>{(t(r)?r[s.symbol]:r[s.symbol]=[]).push({no:n,wireType:i,data:a})},s.onWrite=(e,r,n)=>{for(let{no:i,wireType:a,data:o}of s.list(r))n.tag(i,a).raw(o)},s.list=(e,r)=>{if(t(e)){let n=e[s.symbol];return r?n.filter(i=>i.no==r):n}return[]},s.last=(e,r)=>s.list(e,r).slice(-1)[0];const t=e=>e&&Array.isArray(e[s.symbol])})(Tc||(Tc={}));var Je;(function(s){s[s.Varint=0]="Varint",s[s.Bit64=1]="Bit64",s[s.LengthDelimited=2]="LengthDelimited",s[s.StartGroup=3]="StartGroup",s[s.EndGroup=4]="EndGroup",s[s.Bit32=5]="Bit32"})(Je||(Je={}));function wb(){let s=0,t=0;for(let r=0;r<28;r+=7){let n=this.buf[this.pos++];if(s|=(n&127)<>4,!(e&128))return this.assertBounds(),[s,t];for(let r=3;r<=31;r+=7){let n=this.buf[this.pos++];if(t|=(n&127)<>>i,o=!(!(a>>>7)&&t==0),d=(o?a|128:a)&255;if(e.push(d),!o)return}const r=s>>>28&15|(t&7)<<4,n=!!(t>>3);if(e.push((n?r|128:r)&255),!!n){for(let i=3;i<31;i=i+7){const a=t>>>i,o=!!(a>>>7),d=(o?a|128:a)&255;if(e.push(d),!o)return}e.push(t>>>31&1)}}const _c=(1<<16)*(1<<16);function Vm(s){let t=s[0]=="-";t&&(s=s.slice(1));const e=1e6;let r=0,n=0;function i(a,o){const d=Number(s.slice(a,o));n*=e,r=r*e+d,r>=_c&&(n=n+(r/_c|0),r=r%_c)}return i(-24,-18),i(-18,-12),i(-12,-6),i(-6),[t,r,n]}function Ul(s,t){if(t>>>0<=2097151)return""+(_c*t+(s>>>0));let e=s&16777215,r=(s>>>24|t<<8)>>>0&16777215,n=t>>16&65535,i=e+r*6777216+n*6710656,a=r+n*8147497,o=n*2,d=1e7;i>=d&&(a+=Math.floor(i/d),i%=d),a>=d&&(o+=Math.floor(a/d),a%=d);function u(h,p){let f=h?String(h):"";return p?"0000000".slice(f.length)+f:f}return u(o,0)+u(a,o)+u(i,1)}function $m(s,t){if(s>=0){for(;s>127;)t.push(s&127|128),s=s>>>7;t.push(s)}else{for(let e=0;e<9;e++)t.push(s&127|128),s=s>>7;t.push(1)}}function Cb(){let s=this.buf[this.pos++],t=s&127;if(!(s&128))return this.assertBounds(),t;if(s=this.buf[this.pos++],t|=(s&127)<<7,!(s&128))return this.assertBounds(),t;if(s=this.buf[this.pos++],t|=(s&127)<<14,!(s&128))return this.assertBounds(),t;if(s=this.buf[this.pos++],t|=(s&127)<<21,!(s&128))return this.assertBounds(),t;s=this.buf[this.pos++],t|=(s&15)<<28;for(let e=5;s&128&&e<10;e++)s=this.buf[this.pos++];if(s&128)throw new Error("invalid varint");return this.assertBounds(),t>>>0}let Ee;function bb(){const s=new DataView(new ArrayBuffer(8));Ee=globalThis.BigInt!==void 0&&typeof s.getBigInt64=="function"&&typeof s.getBigUint64=="function"&&typeof s.setBigInt64=="function"&&typeof s.setBigUint64=="function"?{MIN:BigInt("-9223372036854775808"),MAX:BigInt("9223372036854775807"),UMIN:BigInt("0"),UMAX:BigInt("18446744073709551615"),C:BigInt,V:s}:void 0}bb();function Bm(s){if(!s)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}const Hm=/^-?[0-9]+$/,Sc=4294967296,Ec=2147483648;class qm{constructor(t,e){this.lo=t|0,this.hi=e|0}isZero(){return this.lo==0&&this.hi==0}toNumber(){let t=this.hi*Sc+(this.lo>>>0);if(!Number.isSafeInteger(t))throw new Error("cannot convert to safe number");return t}}class mt extends qm{static from(t){if(Ee)switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=="")throw new Error("string is no integer");t=Ee.C(t);case"number":if(t===0)return this.ZERO;t=Ee.C(t);case"bigint":if(!t)return this.ZERO;if(tEe.UMAX)throw new Error("ulong too large");return Ee.V.setBigUint64(0,t,!0),new mt(Ee.V.getInt32(0,!0),Ee.V.getInt32(4,!0))}else switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=t.trim(),!Hm.test(t))throw new Error("string is no integer");let[e,r,n]=Vm(t);if(e)throw new Error("signed value for ulong");return new mt(r,n);case"number":if(t==0)return this.ZERO;if(!Number.isSafeInteger(t))throw new Error("number is no integer");if(t<0)throw new Error("signed value for ulong");return new mt(t,t/Sc)}throw new Error("unknown value "+typeof t)}toString(){return Ee?this.toBigInt().toString():Ul(this.lo,this.hi)}toBigInt(){return Bm(Ee),Ee.V.setInt32(0,this.lo,!0),Ee.V.setInt32(4,this.hi,!0),Ee.V.getBigUint64(0,!0)}}mt.ZERO=new mt(0,0);class Pe extends qm{static from(t){if(Ee)switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=="")throw new Error("string is no integer");t=Ee.C(t);case"number":if(t===0)return this.ZERO;t=Ee.C(t);case"bigint":if(!t)return this.ZERO;if(tEe.MAX)throw new Error("signed long too large");return Ee.V.setBigInt64(0,t,!0),new Pe(Ee.V.getInt32(0,!0),Ee.V.getInt32(4,!0))}else switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=t.trim(),!Hm.test(t))throw new Error("string is no integer");let[e,r,n]=Vm(t);if(e){if(n>Ec||n==Ec&&r!=0)throw new Error("signed long too small")}else if(n>=Ec)throw new Error("signed long too large");let i=new Pe(r,n);return e?i.negate():i;case"number":if(t==0)return this.ZERO;if(!Number.isSafeInteger(t))throw new Error("number is no integer");return t>0?new Pe(t,t/Sc):new Pe(-t,-t/Sc).negate()}throw new Error("unknown value "+typeof t)}isNegative(){return(this.hi&Ec)!==0}negate(){let t=~this.hi,e=this.lo;return e?e=~e+1:t+=1,new Pe(e,t)}toString(){if(Ee)return this.toBigInt().toString();if(this.isNegative()){let t=this.negate();return"-"+Ul(t.lo,t.hi)}return Ul(this.lo,this.hi)}toBigInt(){return Bm(Ee),Ee.V.setInt32(0,this.lo,!0),Ee.V.setInt32(4,this.hi,!0),Ee.V.getBigInt64(0,!0)}}Pe.ZERO=new Pe(0,0);const jm={readUnknownField:!0,readerFactory:s=>new Rb(s)};function Pb(s){return s?Object.assign(Object.assign({},jm),s):jm}class Rb{constructor(t,e){this.varint64=wb,this.uint32=Cb,this.buf=t,this.len=t.length,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.textDecoder=e!=null?e:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0})}tag(){let t=this.uint32(),e=t>>>3,r=t&7;if(e<=0||r<0||r>5)throw new Error("illegal tag: field no "+e+" wire type "+r);return[e,r]}skip(t){let e=this.pos;switch(t){case Je.Varint:for(;this.buf[this.pos++]&128;);break;case Je.Bit64:this.pos+=4;case Je.Bit32:this.pos+=4;break;case Je.LengthDelimited:let r=this.uint32();this.pos+=r;break;case Je.StartGroup:let n;for(;(n=this.tag()[1])!==Je.EndGroup;)this.skip(n);break;default:throw new Error("cant skip wire type "+t)}return this.assertBounds(),this.buf.subarray(e,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)}int64(){return new Pe(...this.varint64())}uint64(){return new mt(...this.varint64())}sint64(){let[t,e]=this.varint64(),r=-(t&1);return t=(t>>>1|(e&1)<<31)^r,e=e>>>1^r,new Pe(t,e)}bool(){let[t,e]=this.varint64();return t!==0||e!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return new mt(this.sfixed32(),this.sfixed32())}sfixed64(){return new Pe(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let t=this.uint32(),e=this.pos;return this.pos+=t,this.assertBounds(),this.buf.subarray(e,e+t)}string(){return this.textDecoder.decode(this.bytes())}}function fe(s,t){if(!s)throw new Error(t)}const kb=34028234663852886e22,Ib=-34028234663852886e22,Ab=4294967295,Mb=2147483647,Db=-2147483648;function ma(s){if(typeof s!="number")throw new Error("invalid int 32: "+typeof s);if(!Number.isInteger(s)||s>Mb||sAb||s<0)throw new Error("invalid uint 32: "+s)}function Vl(s){if(typeof s!="number")throw new Error("invalid float 32: "+typeof s);if(Number.isFinite(s)&&(s>kb||snew Nb};function Ob(s){return s?Object.assign(Object.assign({},Gm),s):Gm}class Nb{constructor(t){this.stack=[],this.textEncoder=t!=null?t:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let t=0;for(let n=0;n>>0)}raw(t){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(t),this}uint32(t){for(wc(t);t>127;)this.buf.push(t&127|128),t=t>>>7;return this.buf.push(t),this}int32(t){return ma(t),$m(t,this.buf),this}bool(t){return this.buf.push(t?1:0),this}bytes(t){return this.uint32(t.byteLength),this.raw(t)}string(t){let e=this.textEncoder.encode(t);return this.uint32(e.byteLength),this.raw(e)}float(t){Vl(t);let e=new Uint8Array(4);return new DataView(e.buffer).setFloat32(0,t,!0),this.raw(e)}double(t){let e=new Uint8Array(8);return new DataView(e.buffer).setFloat64(0,t,!0),this.raw(e)}fixed32(t){wc(t);let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!0),this.raw(e)}sfixed32(t){ma(t);let e=new Uint8Array(4);return new DataView(e.buffer).setInt32(0,t,!0),this.raw(e)}sint32(t){return ma(t),t=(t<<1^t>>31)>>>0,$m(t,this.buf),this}sfixed64(t){let e=new Uint8Array(8),r=new DataView(e.buffer),n=Pe.from(t);return r.setInt32(0,n.lo,!0),r.setInt32(4,n.hi,!0),this.raw(e)}fixed64(t){let e=new Uint8Array(8),r=new DataView(e.buffer),n=mt.from(t);return r.setInt32(0,n.lo,!0),r.setInt32(4,n.hi,!0),this.raw(e)}int64(t){let e=Pe.from(t);return xl(e.lo,e.hi,this.buf),this}sint64(t){let e=Pe.from(t),r=e.hi>>31,n=e.lo<<1^r,i=(e.hi<<1|e.lo>>>31)^r;return xl(n,i,this.buf),this}uint64(t){let e=mt.from(t);return xl(e.lo,e.hi,this.buf),this}}const Jm={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},Wm={ignoreUnknownFields:!1};function Lb(s){return s?Object.assign(Object.assign({},Wm),s):Wm}function Fb(s){return s?Object.assign(Object.assign({},Jm),s):Jm}const Km=Symbol.for("protobuf-ts/message-type");function zm(s){let t=!1;const e=[];for(let r=0;r!n.includes(a))||!r&&n.some(a=>!i.known.includes(a)))return!1;if(e<1)return!0;for(const a of i.oneofs){const o=t[a];if(!Ub(o))return!1;if(o.oneofKind===void 0)continue;const d=this.fields.find(u=>u.localName===o.oneofKind);if(!d||!this.field(o[o.oneofKind],d,r,e))return!1}for(const a of this.fields)if(a.oneof===void 0&&!this.field(t[a.localName],a,r,e))return!1;return!0}field(t,e,r,n){let i=e.repeat;switch(e.kind){case"scalar":return t===void 0?e.opt:i?this.scalars(t,e.T,n,e.L):this.scalar(t,e.T,e.L);case"enum":return t===void 0?e.opt:i?this.scalars(t,D.INT32,n):this.scalar(t,D.INT32);case"message":return t===void 0?!0:i?this.messages(t,e.T(),r,n):this.message(t,e.T(),r,n);case"map":if(typeof t!="object"||t===null)return!1;if(n<2)return!0;if(!this.mapKeys(t,e.K,n))return!1;switch(e.V.kind){case"scalar":return this.scalars(Object.values(t),e.V.T,n,e.V.L);case"enum":return this.scalars(Object.values(t),D.INT32,n);case"message":return this.messages(Object.values(t),e.V.T(),r,n)}break}return!0}message(t,e,r,n){return r?e.isAssignable(t,n):e.is(t,n)}messages(t,e,r,n){if(!Array.isArray(t))return!1;if(n<2)return!0;if(r){for(let i=0;iparseInt(i)),e,r);case D.BOOL:return this.scalars(n.slice(0,r).map(i=>i=="true"?!0:i=="false"?!1:i),e,r);default:return this.scalars(n,e,r,Er.STRING)}}}function cr(s,t){switch(t){case Er.BIGINT:return s.toBigInt();case Er.NUMBER:return s.toNumber();default:return s.toString()}}class $b{constructor(t){this.info=t}prepare(){var t;if(this.fMap===void 0){this.fMap={};const e=(t=this.info.fields)!==null&&t!==void 0?t:[];for(const r of e)this.fMap[r.name]=r,this.fMap[r.jsonName]=r,this.fMap[r.localName]=r}}assert(t,e,r){if(!t){let n=Fl(r);throw(n=="number"||n=="boolean")&&(n=r.toString()),new Error(`Cannot parse JSON ${n} for ${this.info.typeName}#${e}`)}}read(t,e,r){this.prepare();const n=[];for(const[i,a]of Object.entries(t)){const o=this.fMap[i];if(!o){if(!r.ignoreUnknownFields)throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${i}`);continue}const d=o.localName;let u;if(o.oneof){if(a===null&&(o.kind!=="enum"||o.T()[0]!=="google.protobuf.NullValue"))continue;if(n.includes(o.oneof))throw new Error(`Multiple members of the oneof group "${o.oneof}" of ${this.info.typeName} are present in JSON.`);n.push(o.oneof),u=e[o.oneof]={oneofKind:d}}else u=e;if(o.kind=="map"){if(a===null)continue;this.assert(_b(a),o.name,a);const h=u[d];for(const[p,f]of Object.entries(a)){this.assert(f!==null,o.name+" map value",null);let v;switch(o.V.kind){case"message":v=o.V.T().internalJsonRead(f,r);break;case"enum":if(v=this.enum(o.V.T(),f,o.name,r.ignoreUnknownFields),v===!1)continue;break;case"scalar":v=this.scalar(f,o.V.T,o.V.L,o.name);break}this.assert(v!==void 0,o.name+" map value",f);let T=p;o.K==D.BOOL&&(T=T=="true"?!0:T=="false"?!1:T),T=this.scalar(T,o.K,Er.STRING,o.name).toString(),h[T]=v}}else if(o.repeat){if(a===null)continue;this.assert(Array.isArray(a),o.name,a);const h=u[d];for(const p of a){this.assert(p!==null,o.name,null);let f;switch(o.kind){case"message":f=o.T().internalJsonRead(p,r);break;case"enum":if(f=this.enum(o.T(),p,o.name,r.ignoreUnknownFields),f===!1)continue;break;case"scalar":f=this.scalar(p,o.T,o.L,o.name);break}this.assert(f!==void 0,o.name,a),h.push(f)}}else switch(o.kind){case"message":if(a===null&&o.T().typeName!="google.protobuf.Value"){this.assert(o.oneof===void 0,o.name+" (oneof member)",null);continue}u[d]=o.T().internalJsonRead(a,r,u[d]);break;case"enum":let h=this.enum(o.T(),a,o.name,r.ignoreUnknownFields);if(h===!1)continue;u[d]=h;break;case"scalar":u[d]=this.scalar(a,o.T,o.L,o.name);break}}}enum(t,e,r,n){if(t[0]=="google.protobuf.NullValue"&&fe(e===null||e==="NULL_VALUE",`Unable to parse field ${this.info.typeName}#${r}, enum ${t[0]} only accepts null.`),e===null)return 0;switch(typeof e){case"number":return fe(Number.isInteger(e),`Unable to parse field ${this.info.typeName}#${r}, enum can only be integral number, got ${e}.`),e;case"string":let i=e;t[2]&&e.substring(0,t[2].length)===t[2]&&(i=e.substring(t[2].length));let a=t[1][i];return typeof a=="undefined"&&n?!1:(fe(typeof a=="number",`Unable to parse field ${this.info.typeName}#${r}, enum ${t[0]} has no value for "${e}".`),a)}fe(!1,`Unable to parse field ${this.info.typeName}#${r}, cannot parse enum value from ${typeof e}".`)}scalar(t,e,r,n){let i;try{switch(e){case D.DOUBLE:case D.FLOAT:if(t===null)return 0;if(t==="NaN")return Number.NaN;if(t==="Infinity")return Number.POSITIVE_INFINITY;if(t==="-Infinity")return Number.NEGATIVE_INFINITY;if(t===""){i="empty string";break}if(typeof t=="string"&&t.trim().length!==t.length){i="extra whitespace";break}if(typeof t!="string"&&typeof t!="number")break;let a=Number(t);if(Number.isNaN(a)){i="not a number";break}if(!Number.isFinite(a)){i="too large or small";break}return e==D.FLOAT&&Vl(a),a;case D.INT32:case D.FIXED32:case D.SFIXED32:case D.SINT32:case D.UINT32:if(t===null)return 0;let o;if(typeof t=="number"?o=t:t===""?i="empty string":typeof t=="string"&&(t.trim().length!==t.length?i="extra whitespace":o=Number(t)),o===void 0)break;return e==D.UINT32?wc(o):ma(o),o;case D.INT64:case D.SFIXED64:case D.SINT64:if(t===null)return cr(Pe.ZERO,r);if(typeof t!="number"&&typeof t!="string")break;return cr(Pe.from(t),r);case D.FIXED64:case D.UINT64:if(t===null)return cr(mt.ZERO,r);if(typeof t!="number"&&typeof t!="string")break;return cr(mt.from(t),r);case D.BOOL:if(t===null)return!1;if(typeof t!="boolean")break;return t;case D.STRING:if(t===null)return"";if(typeof t!="string"){i="extra whitespace";break}try{encodeURIComponent(t)}catch(d){d="invalid UTF8";break}return t;case D.BYTES:if(t===null||t==="")return new Uint8Array(0);if(typeof t!="string")break;return Sb(t)}}catch(a){i=a.message}this.assert(!1,n+(i?" - "+i:""),t)}}class Bb{constructor(t){var e;this.fields=(e=t.fields)!==null&&e!==void 0?e:[]}write(t,e){const r={},n=t;for(const i of this.fields){if(!i.oneof){let u=this.field(i,n[i.localName],e);u!==void 0&&(r[e.useProtoFieldName?i.name:i.jsonName]=u);continue}const a=n[i.oneof];if(a.oneofKind!==i.localName)continue;const o=i.kind=="scalar"||i.kind=="enum"?Object.assign(Object.assign({},e),{emitDefaultValues:!0}):e;let d=this.field(i,a[i.localName],o);fe(d!==void 0),r[e.useProtoFieldName?i.name:i.jsonName]=d}return r}field(t,e,r){let n;if(t.kind=="map"){fe(typeof e=="object"&&e!==null);const i={};switch(t.V.kind){case"scalar":for(const[d,u]of Object.entries(e)){const h=this.scalar(t.V.T,u,t.name,!1,!0);fe(h!==void 0),i[d.toString()]=h}break;case"message":const a=t.V.T();for(const[d,u]of Object.entries(e)){const h=this.message(a,u,t.name,r);fe(h!==void 0),i[d.toString()]=h}break;case"enum":const o=t.V.T();for(const[d,u]of Object.entries(e)){fe(u===void 0||typeof u=="number");const h=this.enum(o,u,t.name,!1,!0,r.enumAsInteger);fe(h!==void 0),i[d.toString()]=h}break}(r.emitDefaultValues||Object.keys(i).length>0)&&(n=i)}else if(t.repeat){fe(Array.isArray(e));const i=[];switch(t.kind){case"scalar":for(let d=0;d0||r.emitDefaultValues)&&(n=i)}else switch(t.kind){case"scalar":n=this.scalar(t.T,e,t.name,t.opt,r.emitDefaultValues);break;case"enum":n=this.enum(t.T(),e,t.name,t.opt,r.emitDefaultValues,r.enumAsInteger);break;case"message":n=this.message(t.T(),e,t.name,r);break}return n}enum(t,e,r,n,i,a){if(t[0]=="google.protobuf.NullValue")return!i&&!n?void 0:null;if(e===void 0){fe(n);return}if(!(e===0&&!i&&!n))return fe(typeof e=="number"),fe(Number.isInteger(e)),a||!t[1].hasOwnProperty(e)?e:t[2]?t[2]+t[1][e]:t[1][e]}message(t,e,r,n){return e===void 0?n.emitDefaultValues?null:void 0:t.internalJsonWrite(e,n)}scalar(t,e,r,n,i){if(e===void 0){fe(n);return}const a=i||n;switch(t){case D.INT32:case D.SFIXED32:case D.SINT32:return e===0?a?0:void 0:(ma(e),e);case D.FIXED32:case D.UINT32:return e===0?a?0:void 0:(wc(e),e);case D.FLOAT:Vl(e);case D.DOUBLE:return e===0?a?0:void 0:(fe(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e);case D.STRING:return e===""?a?"":void 0:(fe(typeof e=="string"),e);case D.BOOL:return e===!1?a?!1:void 0:(fe(typeof e=="boolean"),e);case D.UINT64:case D.FIXED64:fe(typeof e=="number"||typeof e=="string"||typeof e=="bigint");let o=mt.from(e);return o.isZero()&&!a?void 0:o.toString();case D.INT64:case D.SFIXED64:case D.SINT64:fe(typeof e=="number"||typeof e=="string"||typeof e=="bigint");let d=Pe.from(e);return d.isZero()&&!a?void 0:d.toString();case D.BYTES:return fe(e instanceof Uint8Array),e.byteLength?Eb(e):a?"":void 0}}}function $l(s,t=Er.STRING){switch(s){case D.BOOL:return!1;case D.UINT64:case D.FIXED64:return cr(mt.ZERO,t);case D.INT64:case D.SFIXED64:case D.SINT64:return cr(Pe.ZERO,t);case D.DOUBLE:case D.FLOAT:return 0;case D.BYTES:return new Uint8Array(0);case D.STRING:return"";default:return 0}}class Hb{constructor(t){this.info=t}prepare(){var t;if(!this.fieldNoToField){const e=(t=this.info.fields)!==null&&t!==void 0?t:[];this.fieldNoToField=new Map(e.map(r=>[r.no,r]))}}read(t,e,r,n){this.prepare();const i=n===void 0?t.len:t.pos+n;for(;t.pose.no-r.no)}}write(t,e,r){this.prepare();for(const i of this.fields){let a,o,d=i.repeat,u=i.localName;if(i.oneof){const h=t[i.oneof];if(h.oneofKind!==u)continue;a=h[u],o=!0}else a=t[u],o=!1;switch(i.kind){case"scalar":case"enum":let h=i.kind=="enum"?D.INT32:i.T;if(d)if(fe(Array.isArray(a)),d==Cc.PACKED)this.packed(e,h,i.no,a);else for(const p of a)this.scalar(e,h,i.no,p,!0);else a===void 0?fe(i.opt):this.scalar(e,h,i.no,a,o||i.opt);break;case"message":if(d){fe(Array.isArray(a));for(const p of a)this.message(e,r,i.T(),i.no,p)}else this.message(e,r,i.T(),i.no,a);break;case"map":fe(typeof a=="object"&&a!==null);for(const[p,f]of Object.entries(a))this.mapEntry(e,r,i,p,f);break}}let n=r.writeUnknownFields;n!==!1&&(n===!0?Tc.onWrite:n)(this.info.typeName,t,e)}mapEntry(t,e,r,n,i){t.tag(r.no,Je.LengthDelimited),t.fork();let a=n;switch(r.K){case D.INT32:case D.FIXED32:case D.UINT32:case D.SFIXED32:case D.SINT32:a=Number.parseInt(n);break;case D.BOOL:fe(n=="true"||n=="false"),a=n=="true";break}switch(this.scalar(t,r.K,1,a,!0),r.V.kind){case"scalar":this.scalar(t,r.V.T,2,i,!0);break;case"enum":this.scalar(t,D.INT32,2,i,!0);break;case"message":this.message(t,e,r.V.T(),2,i);break}t.join()}message(t,e,r,n,i){i!==void 0&&(r.internalBinaryWrite(i,t.tag(n,Je.LengthDelimited).fork(),e),t.join())}scalar(t,e,r,n,i){let[a,o,d]=this.scalarInfo(e,n);(!d||i)&&(t.tag(r,a),t[o](n))}packed(t,e,r,n){if(!n.length)return;fe(e!==D.BYTES&&e!==D.STRING),t.tag(r,Je.LengthDelimited),t.fork();let[,i]=this.scalarInfo(e);for(let a=0;a["media.Target",qt]},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"sdp",kind:"scalar",T:9}])}}const dr=new Xb;class Zb extends _{constructor(){super("media.CreateTransportRequest",[{no:1,name:"consuming",kind:"scalar",T:8},{no:2,name:"force_tcp",kind:"scalar",opt:!0,T:8},{no:3,name:"description",kind:"message",T:()=>dr}])}}const Zm=new Zb;class eP extends _{constructor(){super("media.CreateTransportResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>dr},{no:3,name:"transcription_enabled",kind:"scalar",opt:!0,T:8}])}}const Hl=new eP;class tP extends _{constructor(){super("media.RenegotiateRequest",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>dr}])}}const ef=new tP;class rP extends _{constructor(){super("media.RenegotiateResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>dr}])}}new rP;class sP extends _{constructor(){super("media.NestedScore",[{no:1,name:"encoding_idx",kind:"scalar",T:5},{no:2,name:"rid",kind:"scalar",T:9},{no:3,name:"score",kind:"scalar",T:5},{no:4,name:"ssrc",kind:"scalar",T:3,L:0}])}}const nP=new sP;class iP extends _{constructor(){super("media.ProducerTrack",[{no:1,name:"track_id",kind:"scalar",T:9},{no:2,name:"producer_id",kind:"scalar",T:9},{no:3,name:"stream_id",kind:"scalar",T:9}])}}const aP=new iP;class oP extends _{constructor(){super("media.ProducerEntry",[{no:1,name:"producing_transport_id",kind:"scalar",T:9},{no:2,name:"producer_id",kind:"scalar",T:9}])}}new oP;class cP extends _{constructor(){super("media.ConsumerEntry",[{no:1,name:"consuming_transport_id",kind:"scalar",T:9},{no:2,name:"consumer_id",kind:"scalar",T:9}])}}new cP;class dP extends _{constructor(){super("media.ProducerState",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"kind",kind:"enum",T:()=>["media.ProducerKind",Nt]},{no:3,name:"pause",kind:"scalar",T:8},{no:4,name:"screen_share",kind:"scalar",T:8},{no:5,name:"app_data",kind:"scalar",opt:!0,T:9},{no:6,name:"producing_transport_id",kind:"scalar",opt:!0,T:9},{no:7,name:"mime_type",kind:"scalar",opt:!0,T:9}])}}const fa=new dP;class lP extends _{constructor(){super("media.ConsumerState",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>fa},{no:3,name:"producer_track",kind:"message",T:()=>aP}])}}const uP=new lP;class hP extends _{constructor(){super("media.ProducerIdToConsumerMap",[{no:1,name:"map",kind:"map",K:9,V:{kind:"message",T:()=>uP}}])}}const tf=new hP;class pP extends _{constructor(){super("media.PeerRtpCapabilitites",[{no:1,name:"sender",kind:"message",T:()=>nf},{no:2,name:"receiver",kind:"message",T:()=>nf}])}}const rf=new pP;class mP extends _{constructor(){super("media.RtpCapability",[{no:1,name:"codecs",kind:"message",repeat:1,T:()=>Kb},{no:2,name:"header_extensions",kind:"message",repeat:1,T:()=>Yb}])}}const sf=new mP;class fP extends _{constructor(){super("media.RtpCapabilitites",[{no:1,name:"audio",kind:"message",T:()=>sf},{no:2,name:"video",kind:"message",T:()=>sf}])}}const nf=new fP;class gP extends _{constructor(){super("media.PreferredCodec",[{no:1,name:"audio",kind:"scalar",opt:!0,T:9},{no:2,name:"video",kind:"scalar",opt:!0,T:9}])}}const vP=new gP;class yP extends _{constructor(){super("media.edge.GeoLocation",[{no:1,name:"latitude",kind:"scalar",T:2},{no:2,name:"longitude",kind:"scalar",T:2},{no:3,name:"region",kind:"scalar",opt:!0,T:9}])}}const TP=new yP;class _P extends _{constructor(){super("media.edge.PeerJoinRequest",[{no:1,name:"display_name",kind:"scalar",opt:!0,T:9},{no:2,name:"prejoined",kind:"scalar",T:8},{no:3,name:"room_uuid",kind:"scalar",T:9},{no:4,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:5,name:"preset",kind:"scalar",opt:!0,T:12},{no:6,name:"user_id",kind:"scalar",opt:!0,T:9},{no:7,name:"organization_id",kind:"scalar",opt:!0,T:9},{no:8,name:"location",kind:"message",T:()=>TP},{no:9,name:"capabilities",kind:"message",T:()=>rf}])}}const af=new _P;class SP extends _{constructor(){super("media.edge.PeerJoinCompleteRequest",[])}}const of=new SP;class EP extends _{constructor(){super("media.edge.PeerLeaveRequest",[{no:1,name:"close_room",kind:"scalar",T:8}])}}const cf=new EP;class wP extends _{constructor(){super("media.edge.ConsumeMultipleProducerRequest",[{no:1,name:"producer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"paused",kind:"scalar",opt:!0,T:8}])}}new wP;class CP extends _{constructor(){super("media.edge.ConsumePeerRequest",[{no:1,name:"producing_peer_id",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",opt:!0,T:8},{no:3,name:"producer_id",kind:"scalar",opt:!0,T:9},{no:4,name:"preferred_codec",kind:"message",T:()=>vP}])}}const df=new CP;class bP extends _{constructor(){super("media.edge.ProducerCreateRequest",[{no:1,name:"kind",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",T:8},{no:3,name:"screen_share",kind:"scalar",T:8},{no:4,name:"description",kind:"message",T:()=>dr},{no:5,name:"msid",kind:"scalar",T:9},{no:6,name:"app_data",kind:"scalar",opt:!0,T:9},{no:7,name:"mime_type",kind:"scalar",opt:!0,T:9}])}}const lf=new bP;class PP extends _{constructor(){super("media.edge.SelectedPeersRequest",[])}}new PP;class RP extends _{constructor(){super("media.edge.GlobalPeerPinningRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const uf=new RP;class kP extends _{constructor(){super("media.edge.ProducerToggleRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}const fs=new kP;class IP extends _{constructor(){super("media.edge.ConsumerToggleRequest",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}const Pc=new IP;class AP extends _{constructor(){super("media.edge.ProducerCloseRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>dr}])}}const hf=new AP;class MP extends _{constructor(){super("media.edge.ConsumerCloseRequest",[{no:1,name:"consumer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"description",kind:"message",T:()=>dr}])}}const pf=new MP;class DP extends _{constructor(){super("media.edge.KickPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const mf=new DP;class OP extends _{constructor(){super("media.edge.KickAllPeersRequest",[{no:1,name:"propagate_kick_across_rooms",kind:"scalar",T:8}])}}const ql=new OP;class NP extends _{constructor(){super("media.edge.PeerDisplayNameEditRequest",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}const ff=new NP;class LP extends _{constructor(){super("media.edge.HostMediaControlForPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"audio",kind:"scalar",T:8},{no:3,name:"video",kind:"scalar",T:8},{no:4,name:"scree_share",kind:"scalar",T:8}])}}const gf=new LP;class FP extends _{constructor(){super("media.edge.HostMediaControlForAllPeerRequest",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8},{no:3,name:"screen_share",kind:"scalar",T:8}])}}const vf=new FP;class xP extends _{constructor(){super("media.edge.GetRoomStateResponse",[{no:1,name:"display_title",kind:"scalar",T:9},{no:2,name:"locked_mode",kind:"scalar",T:8},{no:3,name:"room_uuid",kind:"scalar",T:9},{no:4,name:"room_name",kind:"scalar",T:9},{no:5,name:"current_peer_id",kind:"scalar",T:9},{no:6,name:"is_recording",kind:"scalar",opt:!0,T:8},{no:7,name:"recorder_participant_id",kind:"scalar",opt:!0,T:9},{no:8,name:"pinned_peer_ids",kind:"scalar",repeat:2,T:9}])}}const UP=new xP;class VP extends _{constructor(){super("media.edge.ErrorResponse",[{no:1,name:"error_message",kind:"scalar",T:9},{no:2,name:"event_id",kind:"scalar",T:5}])}}const $P=new VP;class BP extends _{constructor(){super("media.edge.EmptyResponse",[])}}new BP;class HP extends _{constructor(){super("media.edge.RoomParticipants",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"producer_states",kind:"message",repeat:1,T:()=>fa},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"user_id",kind:"scalar",opt:!0,T:9},{no:5,name:"capabilities",kind:"message",T:()=>rf}])}}const yf=new HP;class qP extends _{constructor(){super("media.edge.SelectedPeersResponse",[{no:1,name:"audio_peers",kind:"scalar",repeat:2,T:9},{no:2,name:"compulsory_peers",kind:"scalar",repeat:2,T:9}])}}const jl=new qP;class jP extends _{constructor(){super("media.edge.SelectedPeersDiffEntry",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"priority",kind:"scalar",T:5}])}}const GP=new jP;class JP extends _{constructor(){super("media.edge.SelectedPeersDiffResponse",[{no:1,name:"entries",kind:"message",repeat:1,T:()=>GP}])}}const Tf=new JP;class WP extends _{constructor(){super("media.edge.PeerJoinResponse",[])}}new WP;class KP extends _{constructor(){super("media.edge.PeerJoinCompleteResponse",[{no:1,name:"room_state",kind:"message",T:()=>UP},{no:2,name:"participants",kind:"message",repeat:1,T:()=>yf},{no:3,name:"selected_peers",kind:"message",T:()=>jl},{no:4,name:"max_preferred_streams",kind:"scalar",T:5}])}}const Rc=new KP;class zP extends _{constructor(){super("media.edge.PeerLeaveResponse",[{no:1,name:"closed",kind:"scalar",T:8}])}}const _f=new zP;class YP extends _{constructor(){super("media.edge.ConsumeMultipleProducerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>tf}])}}new YP;class QP extends _{constructor(){super("media.edge.ConsumePeerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>tf},{no:3,name:"description",kind:"message",T:()=>dr}])}}const Sf=new QP;class XP extends _{constructor(){super("media.edge.ProducerCreateResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"producer_id",kind:"scalar",T:9},{no:4,name:"description",kind:"message",T:()=>dr}])}}const Ef=new XP;class ZP extends _{constructor(){super("media.edge.ProducerScoreResponse",[{no:1,name:"responseid",kind:"scalar",T:9},{no:2,name:"score",kind:"message",T:()=>nP}])}}new ZP;class eR extends _{constructor(){super("media.edge.ActiveSpeakerResponse",[{no:1,name:"responsepeer_id",kind:"scalar",T:9},{no:2,name:"volume",kind:"scalar",T:5}])}}new eR;class tR extends _{constructor(){super("media.edge.NoActiveSpeakerResponse",[])}}new tR;class rR extends _{constructor(){super("media.edge.ProducerToggleResponse",[])}}new rR;class sR extends _{constructor(){super("media.edge.ConsumerToggleResponse",[])}}new sR;class nR extends _{constructor(){super("media.edge.ProducerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>dr}])}}const wf=new nR;class iR extends _{constructor(){super("media.edge.ConsumerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>dr}])}}new iR;class aR extends _{constructor(){super("media.edge.GlobalPeerPinningResponse",[])}}new aR;class oR extends _{constructor(){super("media.edge.KickPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Cf=new oR;class cR extends _{constructor(){super("media.edge.KickAllPeersResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const bf=new cR;class dR extends _{constructor(){super("media.edge.HostMediaControlForPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Pf=new dR;class lR extends _{constructor(){super("media.edge.HostMediaControlForAllPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Rf=new lR;class uR extends _{constructor(){super("media.edge.PeerDisplayNameEditResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const kf=new uR;class hR extends _{constructor(){super("media.edge.PeerJoinBroadcastResponse",[{no:1,name:"participant",kind:"message",T:()=>yf}])}}const If=new hR;class pR extends _{constructor(){super("media.edge.TrackSubscriptionKind",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8}])}}const Af=new pR;class mR extends _{constructor(){super("media.edge.TrackSubscription",[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"webcam",kind:"message",T:()=>Af},{no:3,name:"screenshare",kind:"message",T:()=>Af}])}}const fR=new mR;class gR extends _{constructor(){super("media.edge.PeerProducingTransportCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"transport_details",kind:"message",T:()=>Hl},{no:3,name:"track_subscriptions",kind:"message",repeat:1,T:()=>fR}])}}new gR;class vR extends _{constructor(){super("media.edge.PeerProducerCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>fa}])}}const Mf=new vR;class yR extends _{constructor(){super("media.edge.PeerProducerToggleBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>fa}])}}const Df=new yR;class TR extends _{constructor(){super("media.edge.PeerProducerCloseBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>fa}])}}const Of=new TR;class _R extends _{constructor(){super("media.edge.PeerLeaveBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const kc=new _R;class SR extends _{constructor(){super("media.edge.GlobalPeerPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Nf=new SR;class ER extends _{constructor(){super("media.edge.GlobalPeerUnPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new ER;class wR extends _{constructor(){super("media.edge.RecordingStartedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new wR;class CR extends _{constructor(){super("media.edge.RecordingStoppedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new CR;class bR extends _{constructor(){super("media.edge.PeerDisplayNameEditBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}new bR;class PR extends _{constructor(){super("media.edge.PeerPingRequestBroadcastResponse",[{no:1,name:"password",kind:"scalar",T:9}])}}new PR;class RR extends _{constructor(){super("media.edge.MediaRoomTerminationBroadcastResponse",[{no:1,name:"reason",kind:"scalar",T:9}])}}new RR;class kR extends _{constructor(){super("socket.ai.MeetingTranscript",[{no:1,name:"meeting_id",kind:"scalar",T:9},{no:2,name:"transcript",kind:"scalar",T:9},{no:3,name:"is_partial",kind:"scalar",T:8}])}}const Gl=new kR;class IR extends _{constructor(){super("socket.api.BaseSocketHubMessage",[{no:1,name:"event",kind:"scalar",T:5},{no:2,name:"id",kind:"scalar",T:9},{no:3,name:"peer_id",kind:"scalar",T:9},{no:4,name:"room_id",kind:"scalar",T:9},{no:5,name:"user_id",kind:"scalar",T:9},{no:6,name:"payload",kind:"scalar",T:12},{no:7,name:"error",kind:"scalar",opt:!0,T:8},{no:8,name:"sid",kind:"scalar",opt:!0,T:9}])}}new IR;class AR extends _{constructor(){super("socket.api.ErrorMessage",[{no:1,name:"code",kind:"scalar",opt:!0,T:5},{no:2,name:"message",kind:"scalar",T:9}])}}const MR=new AR;var an;(function(s){s[s.BROWSER=0]="BROWSER",s[s.TRACK=1]="TRACK",s[s.COMPOSITE=2]="COMPOSITE"})(an||(an={}));var Br;(function(s){s[s.UNSPECIFIED=0]="UNSPECIFIED",s[s.ON_STAGE=1]="ON_STAGE",s[s.APPROVED_STAGE=2]="APPROVED_STAGE",s[s.REQUESTED_STAGE=3]="REQUESTED_STAGE",s[s.OFF_STAGE=4]="OFF_STAGE"})(Br||(Br={}));var Jl;(function(s){s[s.NONE=0]="NONE",s[s.RECORDER=1]="RECORDER",s[s.LIVESTREAMER=2]="LIVESTREAMER"})(Jl||(Jl={}));var Ic;(function(s){s[s.HIVE=0]="HIVE",s[s.CHAT=1]="CHAT",s[s.PING=2]="PING"})(Ic||(Ic={}));class DR extends _{constructor(){super("socket.room.PeerFlags",[{no:1,name:"preset_name",kind:"scalar",T:9},{no:2,name:"recorder_type",kind:"scalar",T:9},{no:3,name:"hidden_participant",kind:"scalar",T:8}])}}const OR=new DR;class NR extends _{constructor(){super("socket.room.Peer",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"stage_type",kind:"enum",opt:!0,T:()=>["socket.room.StageType",Br,"STAGE_TYPE_"]},{no:5,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:6,name:"preset_id",kind:"scalar",opt:!0,T:9},{no:7,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:8,name:"waitlisted",kind:"scalar",T:8},{no:9,name:"flags",kind:"message",T:()=>OR}])}}const Ac=new NR;class LR extends _{constructor(){super("socket.room.PeerInfoResponse",[{no:1,name:"peer",kind:"message",T:()=>Ac}])}}const ei=new LR;class FR extends _{constructor(){super("socket.room.PeerStatusUpdate",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"stage_type",kind:"enum",opt:!0,T:()=>["socket.room.StageType",Br,"STAGE_TYPE_"]}])}}const Lf=new FR;class xR extends _{constructor(){super("socket.room.RoomPeersInfoRequest",[{no:1,name:"seach_query",kind:"scalar",T:9},{no:2,name:"limit",kind:"scalar",T:5},{no:3,name:"offset",kind:"scalar",T:5}])}}const UR=new xR;class VR extends _{constructor(){super("socket.room.RoomPeersInfoResponse",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>Ac}])}}const Wl=new VR;class $R extends _{constructor(){super("socket.room.RoomPeerCountResponse",[{no:1,name:"count",kind:"scalar",T:4,L:2}])}}const Ff=new $R;class BR extends _{constructor(){super("socket.room.Room",[{no:1,name:"room_id",kind:"scalar",T:9},{no:2,name:"title",kind:"scalar",T:9},{no:4,name:"created_at",kind:"scalar",T:4,L:2},{no:5,name:"active_recordings",kind:"message",repeat:1,T:()=>qR},{no:6,name:"room_uuid",kind:"scalar",opt:!0,T:9}])}}const xf=new BR;class HR extends _{constructor(){super("socket.room.ActiveRecording",[{no:1,name:"recording_id",kind:"scalar",T:9},{no:2,name:"recording_type",kind:"enum",T:()=>["common.RecordingType",an]},{no:3,name:"recording_status",kind:"scalar",T:9}])}}const qR=new HR;class jR extends _{constructor(){super("socket.room.RoomInfoResponse",[{no:1,name:"room",kind:"message",T:()=>xf}])}}const Uf=new jR;class GR extends _{constructor(){super("socket.room.GetPeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9}])}}const Vf=new GR;class JR extends _{constructor(){super("socket.room.UpdatePeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",opt:!0,T:9}])}}new JR;class WR extends _{constructor(){super("socket.room.JoinRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>Ac},{no:3,name:"room_uuid",kind:"scalar",T:9},{no:4,name:"organization_id",kind:"scalar",opt:!0,T:9},{no:5,name:"use_hive",kind:"scalar",opt:!0,T:8},{no:6,name:"preset",kind:"scalar",opt:!0,T:12},{no:7,name:"capabilities",kind:"enum",repeat:1,T:()=>["socket.room.Capabilities",Ic,"CAPABILITIES_"]},{no:8,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const KR=new WR;class zR extends _{constructor(){super("socket.room.LeaveRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>Ac},{no:2,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const YR=new zR;class QR extends _{constructor(){super("socket.room.UpdateRoomInfoRequest",[{no:1,name:"room",kind:"message",T:()=>xf}])}}new QR;class XR extends _{constructor(){super("socket.room.GetConnectedRoomsDumpRequest",[])}}new XR;class ZR extends _{constructor(){super("socket.room.ServiceError",[{no:1,name:"message",kind:"scalar",opt:!0,T:9},{no:2,name:"code",kind:"scalar",opt:!0,T:9}])}}const Kl=new ZR;class ek extends _{constructor(){super("socket.room.ConnectedMeetingPeer",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"display_name",kind:"scalar",opt:!0,T:9},{no:3,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:4,name:"preset_id",kind:"scalar",opt:!0,T:9},{no:5,name:"display_picture_url",kind:"scalar",opt:!0,T:9}])}}const tk=new ek;class rk extends _{constructor(){super("socket.room.ConnectedMeetingDump",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"title",kind:"scalar",opt:!0,T:9},{no:3,name:"participants",kind:"message",repeat:1,T:()=>tk}])}}const $f=new rk;class sk extends _{constructor(){super("socket.room.GetConnectedRoomsDumpResponse",[{no:1,name:"parent_meeting",kind:"message",T:()=>$f},{no:2,name:"meetings",kind:"message",repeat:1,T:()=>$f}])}}const nk=new sk;class ik extends _{constructor(){super("socket.room.CreateRoomRequestPayload",[{no:1,name:"title",kind:"scalar",opt:!0,T:9}])}}const ak=new ik;class ok extends _{constructor(){super("socket.room.CreateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>ak}])}}const ck=new ok;class dk extends _{constructor(){super("socket.room.CreateRoomResponsePayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"title",kind:"scalar",opt:!0,T:9},{no:3,name:"error",kind:"message",T:()=>Kl}])}}const lk=new dk;class uk extends _{constructor(){super("socket.room.CreateConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>lk}])}}const Bf=new uk;class hk extends _{constructor(){super("socket.room.UpdateRoomRequestPayload",[{no:1,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"title",kind:"scalar",opt:!0,T:9}])}}const pk=new hk;class mk extends _{constructor(){super("socket.room.UpdateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>pk}])}}new mk;class fk extends _{constructor(){super("socket.room.DisableRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9}])}}const gk=new fk;class vk extends _{constructor(){super("socket.room.DisableConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>gk}])}}const yk=new vk;class Tk extends _{constructor(){super("socket.room.DisableConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Ek}])}}const _k=new Tk;class Sk extends _{constructor(){super("socket.room.DisableConnectedRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"status",kind:"scalar",opt:!0,T:9},{no:3,name:"title",kind:"scalar",opt:!0,T:9},{no:4,name:"error",kind:"message",T:()=>Kl}])}}const Ek=new Sk;class wk extends _{constructor(){super("socket.room.MovePeerPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"preset_id",kind:"scalar",opt:!0,T:9}])}}const Ck=new wk;class bk extends _{constructor(){super("socket.room.MovePeersBetweenRoomsRequest",[{no:1,name:"source_meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"destination_meeting_id",kind:"scalar",opt:!0,T:9},{no:3,name:"participants",kind:"message",repeat:1,T:()=>Ck}])}}const Pk=new bk;class Rk extends _{constructor(){super("socket.room.MovedPeer",[{no:1,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:3,name:"error",kind:"message",T:()=>Kl}])}}const Hf=new Rk;class kk extends _{constructor(){super("socket.room.MovePeersBetweenRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Hf}])}}new kk;class Ik extends _{constructor(){super("socket.room.TransferPeer",[{no:1,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"auth_token",kind:"scalar",opt:!0,T:9}])}}const Ak=new Ik;class Mk extends _{constructor(){super("socket.room.GetAllAddedParticipantsResponse",[{no:1,name:"participants",kind:"message",repeat:1,T:()=>Nk}])}}const Dk=new Mk;class Ok extends _{constructor(){super("socket.room.AddedParticipant",[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",opt:!0,T:9},{no:3,name:"picture",kind:"scalar",opt:!0,T:9},{no:4,name:"custom_participant_id",kind:"scalar",T:9}])}}const Nk=new Ok;class Lk extends _{constructor(){super("socket.room.RemoveParticipantsRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const Fk=new Lk;class xk extends _{constructor(){super("socket.room.BroadcastMessage",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"timestamp",kind:"scalar",T:4,L:2},{no:4,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const Mc=new xk;class Uk extends _{constructor(){super("socket.room.AcceptWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const Vk=new Uk;class $k extends _{constructor(){super("socket.room.DenyWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const Bk=new $k;class Hk extends _{constructor(){super("socket.room.WaitingRoomRequest",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"picture",kind:"scalar",opt:!0,T:9},{no:5,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:6,name:"preset_name",kind:"scalar",opt:!0,T:9}])}}const qk=new Hk;class jk extends _{constructor(){super("socket.room.GetWaitingRoomRequests",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>qk}])}}const qf=new jk;class Gk extends _{constructor(){super("socket.room.GetRoomStageStateResponse",[{no:1,name:"on_stage_peers",kind:"scalar",repeat:2,T:9},{no:2,name:"approved_stage_peers",kind:"scalar",repeat:2,T:9},{no:3,name:"requested_stage_peers",kind:"scalar",repeat:2,T:9}])}}const jf=new Gk;var zl;(function(s){s[s.NONE=0]="NONE",s[s.SKIP=1]="SKIP",s[s.ON_PRIVILEGED_USER_ENTRY=2]="ON_PRIVILEGED_USER_ENTRY",s[s.SKIP_ON_ACCEPT=3]="SKIP_ON_ACCEPT"})(zl||(zl={}));var gs;(function(s){s[s.NONE=0]="NONE",s[s.ALLOWED=1]="ALLOWED",s[s.NOT_ALLOWED=2]="NOT_ALLOWED",s[s.CAN_REQUEST=3]="CAN_REQUEST"})(gs||(gs={}));class Jk extends _{constructor(){super("socket.preset.PollsPermissionUpdate",[{no:1,name:"can_create",kind:"scalar",opt:!0,T:8},{no:2,name:"can_vote",kind:"scalar",opt:!0,T:8},{no:3,name:"can_view",kind:"scalar",opt:!0,T:8}])}}const Wk=new Jk;class Kk extends _{constructor(){super("socket.preset.PluginsPermissionsUpdate",[{no:1,name:"can_close",kind:"scalar",opt:!0,T:8},{no:2,name:"can_start",kind:"scalar",opt:!0,T:8}])}}const zk=new Kk;class Yk extends _{constructor(){super("socket.preset.PublicChatPermission",[{no:1,name:"can_send",kind:"scalar",opt:!0,T:8},{no:2,name:"text",kind:"scalar",opt:!0,T:8},{no:3,name:"files",kind:"scalar",opt:!0,T:8}])}}const Qk=new Yk;class Xk extends _{constructor(){super("socket.preset.PrivateChatPermission",[{no:1,name:"can_send",kind:"scalar",opt:!0,T:8},{no:2,name:"can_receive",kind:"scalar",opt:!0,T:8},{no:3,name:"text",kind:"scalar",opt:!0,T:8},{no:4,name:"files",kind:"scalar",opt:!0,T:8}])}}const Zk=new Xk;class eI extends _{constructor(){super("socket.preset.ChatPermissionUpdate",[{no:1,name:"public",kind:"message",T:()=>Qk},{no:2,name:"private",kind:"message",T:()=>Zk}])}}const tI=new eI;class rI extends _{constructor(){super("socket.preset.ConnectedMeetingPermissionUpdate",[{no:1,name:"can_alter_connected_meetings",kind:"scalar",opt:!0,T:8},{no:2,name:"can_switch_to_parent_meeting",kind:"scalar",opt:!0,T:8},{no:3,name:"can_switch_connected_meetings",kind:"scalar",opt:!0,T:8}])}}const sI=new rI;class nI extends _{constructor(){super("socket.preset.StreamPermission",[{no:1,name:"can_produce",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",gs,"STREAM_PERMISSION_TYPE_"]},{no:2,name:"can_consume",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",gs,"STREAM_PERMISSION_TYPE_"]}])}}const Yl=new nI;class iI extends _{constructor(){super("socket.preset.MediaPermissionUpdate",[{no:1,name:"video",kind:"message",T:()=>Yl},{no:2,name:"audio",kind:"message",T:()=>Yl},{no:3,name:"screenshare",kind:"message",T:()=>Yl}])}}const aI=new iI;class oI extends _{constructor(){super("socket.preset.PresetUpdates",[{no:1,name:"polls",kind:"message",T:()=>Wk},{no:2,name:"plugins",kind:"message",T:()=>zk},{no:3,name:"chat",kind:"message",T:()=>tI},{no:4,name:"accept_waiting_requests",kind:"scalar",opt:!0,T:8},{no:5,name:"can_accept_production_requests",kind:"scalar",opt:!0,T:8},{no:6,name:"can_edit_display_name",kind:"scalar",opt:!0,T:8},{no:7,name:"can_record",kind:"scalar",opt:!0,T:8},{no:8,name:"can_livestream",kind:"scalar",opt:!0,T:8},{no:9,name:"can_spotlight",kind:"scalar",opt:!0,T:8},{no:10,name:"disable_participant_audio",kind:"scalar",opt:!0,T:8},{no:11,name:"disable_participant_screensharing",kind:"scalar",opt:!0,T:8},{no:12,name:"disable_participant_video",kind:"scalar",opt:!0,T:8},{no:13,name:"kick_participant",kind:"scalar",opt:!0,T:8},{no:14,name:"pin_participant",kind:"scalar",opt:!0,T:8},{no:15,name:"transcription_enabled",kind:"scalar",opt:!0,T:8},{no:16,name:"waiting_room_type",kind:"enum",opt:!0,T:()=>["socket.preset.WaitingRoomType",zl,"WAITING_ROOM_TYPE_"]},{no:17,name:"is_recorder",kind:"scalar",opt:!0,T:8},{no:18,name:"recorder_type",kind:"enum",opt:!0,T:()=>["socket.room.RecorderType",Jl,"RECORDER_TYPE_"]},{no:19,name:"hidden_participant",kind:"scalar",opt:!0,T:8},{no:20,name:"show_participant_list",kind:"scalar",opt:!0,T:8},{no:21,name:"can_change_participant_permissions",kind:"scalar",opt:!0,T:8},{no:22,name:"connected_meetings",kind:"message",T:()=>sI},{no:23,name:"media",kind:"message",T:()=>aI}])}}const Ql=new oI;class cI extends _{constructor(){super("socket.preset.ReadPeersPresetRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const dI=new cI;class lI extends _{constructor(){super("socket.preset.PeerPreset",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"preset",kind:"scalar",T:12}])}}const uI=new lI;class hI extends _{constructor(){super("socket.preset.ReadPeersPresetResponse",[{no:1,name:"peer_presets",kind:"message",repeat:1,T:()=>uI}])}}const pI=new hI;class mI extends _{constructor(){super("socket.preset.UpdatePeerPreset",[{no:1,name:"user_ids",kind:"scalar",T:9},{no:2,name:"patch",kind:"message",T:()=>Ql}])}}const Gf=new mI;class fI extends _{constructor(){super("socket.preset.UpdatePeersPresetRequest",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>Gf}])}}const gI=new fI;class vI extends _{constructor(){super("socket.preset.UpdatePeersPresetResponse",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>Gf}])}}const Jf=new vI;class yI extends _{constructor(){super("socket.preset.PeerUserIDMap",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9}])}}const TI=new yI;class _I extends _{constructor(){super("socket.preset.BulkUpdatePeerPresetRequest",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>TI},{no:2,name:"patch",kind:"message",T:()=>Ql}])}}new _I;class SI extends _{constructor(){super("socket.preset.BulkUpdatePeerPresetResponse",[{no:2,name:"patch",kind:"message",T:()=>Ql}])}}new SI;class EI extends _{constructor(){super("socket.chat.ChatMessage",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"user_id",kind:"scalar",T:9},{no:4,name:"display_name",kind:"scalar",T:9},{no:5,name:"pinned",kind:"scalar",T:8},{no:6,name:"is_edited",kind:"scalar",T:8},{no:7,name:"payload_type",kind:"scalar",T:5},{no:8,name:"payload",kind:"scalar",T:9},{no:10,name:"target_user_ids",kind:"scalar",repeat:2,T:9},{no:11,name:"created_at",kind:"scalar",T:4,L:2},{no:12,name:"created_at_ms",kind:"scalar",opt:!0,T:4,L:2},{no:13,name:"channel_id",kind:"scalar",opt:!0,T:9},{no:14,name:"channel_index",kind:"scalar",opt:!0,T:9}])}}const on=new EI;class wI extends _{constructor(){super("socket.chat.GetPaginatedChatMessageRoomRequest",[{no:1,name:"time_stamp",kind:"scalar",T:4,L:2},{no:2,name:"size",kind:"scalar",T:5},{no:3,name:"from",kind:"scalar",T:5},{no:4,name:"reversed",kind:"scalar",T:8},{no:5,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const CI=new wI;class bI extends _{constructor(){super("socket.chat.GetPaginatedChatMessageRoomResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>on},{no:2,name:"next",kind:"scalar",T:8}])}}const PI=new bI;class RI extends _{constructor(){super("socket.chat.GetChatMessagesResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>on}])}}const Wf=new RI;class kI extends _{constructor(){super("socket.chat.SendChatMessageToRoomRequest",[{no:1,name:"payload_type",kind:"scalar",T:5},{no:2,name:"payload",kind:"scalar",T:9}])}}const II=new kI;class AI extends _{constructor(){super("socket.chat.SendChatMessageToRoomResponse",[{no:1,name:"message",kind:"message",T:()=>on}])}}const Xl=new AI;class MI extends _{constructor(){super("socket.chat.SendChatMessageToPeersRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"payload_type",kind:"scalar",T:5},{no:3,name:"payload",kind:"scalar",T:9}])}}const DI=new MI;class OI extends _{constructor(){super("socket.chat.SendChatMessageToPeersResponse",[{no:1,name:"message",kind:"message",T:()=>on}])}}const Zl=new OI;class NI extends _{constructor(){super("socket.chat.SendChatMessageToChannelRequest",[{no:1,name:"channel_id",kind:"scalar",T:9},{no:2,name:"payload_type",kind:"scalar",T:5},{no:3,name:"payload",kind:"scalar",T:9}])}}const LI=new NI;class FI extends _{constructor(){super("socket.chat.SendChatMessageToChannelResponse",[{no:1,name:"message",kind:"message",T:()=>on}])}}new FI;class xI extends _{constructor(){super("socket.chat.EditChatMessageRequest",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"payload_type",kind:"scalar",opt:!0,T:5},{no:3,name:"payload",kind:"scalar",opt:!0,T:9},{no:4,name:"pinned",kind:"scalar",opt:!0,T:8},{no:5,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const UI=new xI;class VI extends _{constructor(){super("socket.chat.PinChatMessageRequest",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"pinned",kind:"scalar",T:8},{no:3,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const $I=new VI;class BI extends _{constructor(){super("socket.chat.PinChatMessageResponse",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"pinned",kind:"scalar",T:8},{no:3,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const Dc=new BI;class HI extends _{constructor(){super("socket.chat.EditChatMessageResponse",[{no:1,name:"message",kind:"message",T:()=>on}])}}const Oc=new HI;class qI extends _{constructor(){super("socket.chat.DeleteChatMessageRequest",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const jI=new qI;class GI extends _{constructor(){super("socket.chat.DeleteChatMessageResponse",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const Nc=new GI;class JI extends _{constructor(){super("socket.chat.SearchChatMessagesRequest",[{no:1,name:"time_stamp",kind:"scalar",T:4,L:2},{no:2,name:"size",kind:"scalar",T:5},{no:3,name:"from",kind:"scalar",T:5},{no:4,name:"reversed",kind:"scalar",T:8},{no:5,name:"channel_id",kind:"scalar",opt:!0,T:9},{no:6,name:"search_term",kind:"scalar",T:9}])}}const WI=new JI;class KI extends _{constructor(){super("socket.chat.MarkChannelIndexAsReadRequest",[{no:1,name:"channel_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"channel_index",kind:"scalar",T:9}])}}const zI=new KI;class YI extends _{constructor(){super("socket.chat.MarkChannelIndexAsReadResponse",[{no:1,name:"channel_index",kind:"scalar",T:9}])}}const QI=new YI;class XI extends _{constructor(){super("socket.chat.CreateChatChannelRequest",[{no:1,name:"display_name",kind:"scalar",T:9},{no:2,name:"target_user_ids",kind:"scalar",repeat:2,T:9},{no:3,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:4,name:"visibility",kind:"scalar",T:9},{no:5,name:"is_direct_message",kind:"scalar",T:8}])}}const ZI=new XI;class eA extends _{constructor(){super("socket.chat.UpdateChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",opt:!0,T:9},{no:3,name:"target_user_ids",kind:"scalar",repeat:2,T:9},{no:4,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:5,name:"visibility",kind:"scalar",opt:!0,T:9},{no:6,name:"is_direct_message",kind:"scalar",opt:!0,T:8}])}}const tA=new eA;class rA extends _{constructor(){super("socket.chat.CreateChatChannelResponse",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new rA;class sA extends _{constructor(){super("socket.chat.GetChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}const nA=new sA;class iA extends _{constructor(){super("socket.chat.LatestMessageAndUnreadCount",[{no:1,name:"message",kind:"message",T:()=>on},{no:2,name:"unread_count",kind:"scalar",T:4,L:2}])}}const aA=new iA;class oA extends _{constructor(){super("socket.chat.ChatChannel",[{no:1,name:"chat_channel_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9},{no:3,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:4,name:"visibility",kind:"scalar",T:9},{no:5,name:"is_direct_message",kind:"scalar",T:8},{no:6,name:"latest_message_and_unread_count",kind:"message",T:()=>aA},{no:7,name:"target_user_ids",kind:"scalar",repeat:2,T:9}])}}const cA=new oA;class dA extends _{constructor(){super("socket.chat.GetChatChannelResponse",[{no:1,name:"chat_channels",kind:"message",repeat:1,T:()=>cA}])}}const Hr=new dA;class lA extends _{constructor(){super("socket.chat.ChannelMember",[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",opt:!0,T:9},{no:3,name:"picture",kind:"scalar",opt:!0,T:9},{no:4,name:"custom_participant_id",kind:"scalar",T:9}])}}const uA=new lA;class hA extends _{constructor(){super("socket.chat.GetChatChannelMembersResponse",[{no:1,name:"channel_members",kind:"message",repeat:1,T:()=>uA}])}}const pA=new hA;class mA extends _{constructor(){super("socket.plugin.AddPluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const fA=new mA;class gA extends _{constructor(){super("socket.plugin.RemovePluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const vA=new gA;class yA extends _{constructor(){super("socket.plugin.EnablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const TA=new yA;class _A extends _{constructor(){super("socket.plugin.DisablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const SA=new _A;class EA extends _{constructor(){super("socket.plugin.EnablePluginForPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const wA=new EA;class CA extends _{constructor(){super("socket.plugin.DisablePluginForPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const bA=new CA;class PA extends _{constructor(){super("socket.plugin.PluginEventToRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}const RA=new PA;class kA extends _{constructor(){super("socket.plugin.PluginEventToPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9},{no:3,name:"plugin_data",kind:"scalar",T:12}])}}const IA=new kA;class AA extends _{constructor(){super("socket.plugin.StoreKeys",[{no:1,name:"store_key",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",opt:!0,T:12}])}}const eu=new AA;class MA extends _{constructor(){super("socket.plugin.PluginStoreInsertKeysRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"insert_keys",kind:"message",repeat:1,T:()=>eu}])}}const Kf=new MA;class DA extends _{constructor(){super("socket.plugin.PluginStoreGetKeysRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"get_keys",kind:"message",repeat:1,T:()=>eu}])}}const OA=new DA;class NA extends _{constructor(){super("socket.plugin.PluginStoreDeleteKeysRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"delete_keys",kind:"message",repeat:1,T:()=>eu}])}}const LA=new NA;class FA extends _{constructor(){super("socket.plugin.PluginStoreDeleteRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9}])}}const xA=new FA;class UA extends _{constructor(){super("socket.plugin.EnablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"enabled_by",kind:"scalar",T:9}])}}const tu=new UA;class VA extends _{constructor(){super("socket.plugin.EnablePluginsResponse",[{no:1,name:"plugins",kind:"message",repeat:1,T:()=>tu}])}}const $A=new VA;class BA extends _{constructor(){super("socket.plugin.DisablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"disabled_by",kind:"scalar",T:9}])}}const zf=new BA;class HA extends _{constructor(){super("socket.plugin.PluginStoreItem",[{no:1,name:"timestamp",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"store_key",kind:"scalar",T:9},{no:4,name:"payload",kind:"scalar",T:12}])}}const qA=new HA;class jA extends _{constructor(){super("socket.plugin.PluginStoreResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"store_items",kind:"message",repeat:1,T:()=>qA}])}}const Yf=new jA;class GA extends _{constructor(){super("socket.plugin.PluginEventResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}const Qf=new GA;class JA extends _{constructor(){super("socket.livestreaming.LiveStreamingEvent",[{no:1,name:"livestream_id",kind:"scalar",T:9},{no:2,name:"err_message",kind:"scalar",T:9},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"meeting_id",kind:"scalar",T:9},{no:5,name:"playback_url",kind:"scalar",T:9},{no:6,name:"org_id",kind:"scalar",T:9},{no:7,name:"room_name",kind:"scalar",T:9},{no:8,name:"room_uuid",kind:"scalar",T:9},{no:9,name:"status",kind:"scalar",T:9}])}}const Xf=new JA;class WA extends _{constructor(){super("socket.livestreaming.GetStagePeersResponse",[{no:1,name:"stage_peers",kind:"scalar",repeat:2,T:9}])}}const Zf=new WA;class KA extends _{constructor(){super("socket.livestreaming.StageRequest",[{no:1,name:"display_name",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"peer_id",kind:"scalar",T:9}])}}const zA=new KA;class YA extends _{constructor(){super("socket.livestreaming.GetStageRequestsResponse",[{no:1,name:"stage_requests",kind:"message",repeat:1,T:()=>zA}])}}const ru=new YA;class QA extends _{constructor(){super("socket.livestreaming.GrantStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const XA=new QA;class ZA extends _{constructor(){super("socket.livestreaming.DenyStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const eM=new ZA;class tM extends _{constructor(){super("socket.livestreaming.LeaveStageRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const eg=new tM;class rM extends _{constructor(){super("socket.polls.Poll",[{no:1,name:"poll_id",kind:"scalar",T:9},{no:2,name:"created_by",kind:"scalar",T:9},{no:3,name:"created_by_user_id",kind:"scalar",T:9},{no:4,name:"question",kind:"scalar",T:9},{no:5,name:"options",kind:"message",repeat:1,T:()=>nM},{no:6,name:"hide_votes",kind:"scalar",T:8},{no:7,name:"anonymous",kind:"scalar",T:8},{no:8,name:"votes",kind:"scalar",repeat:2,T:9}])}}const tg=new rM;class sM extends _{constructor(){super("socket.polls.PollOption",[{no:1,name:"text",kind:"scalar",T:9},{no:2,name:"count",kind:"scalar",opt:!0,T:4,L:2},{no:3,name:"votes",kind:"message",repeat:1,T:()=>aM}])}}const nM=new sM;class iM extends _{constructor(){super("socket.polls.PollVote",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9}])}}const aM=new iM;class oM extends _{constructor(){super("socket.polls.NewPollRequest",[{no:1,name:"question",kind:"scalar",T:9},{no:2,name:"options",kind:"scalar",repeat:2,T:9},{no:3,name:"anonymous",kind:"scalar",T:8},{no:4,name:"hide_votes",kind:"scalar",T:8},{no:5,name:"created_by",kind:"scalar",opt:!0,T:9},{no:6,name:"created_by_user_id",kind:"scalar",opt:!0,T:9}])}}const cM=new oM;class dM extends _{constructor(){super("socket.polls.VotePollRequest",[{no:1,name:"poll_id",kind:"scalar",T:9},{no:2,name:"index",kind:"scalar",T:4,L:2}])}}const lM=new dM;class uM extends _{constructor(){super("socket.polls.UpdatePollResponse",[{no:1,name:"poll",kind:"message",T:()=>tg}])}}const su=new uM;class hM extends _{constructor(){super("socket.polls.GetPollsResponse",[{no:1,name:"polls",kind:"message",repeat:1,T:()=>tg}])}}const pM=new hM;class mM extends _{constructor(){super("socket.recording.RecordingEvent",[{no:1,name:"recording_id",kind:"scalar",T:9},{no:2,name:"err_message",kind:"scalar",T:9},{no:3,name:"recording_type",kind:"enum",T:()=>["common.RecordingType",an]}])}}const rg=new mM;class fM extends _{constructor(){super("google.protobuf.Timestamp",[{no:1,name:"seconds",kind:"scalar",T:3,L:0},{no:2,name:"nanos",kind:"scalar",T:5}])}now(){const t=this.create(),e=Date.now();return t.seconds=Pe.from(Math.floor(e/1e3)).toBigInt(),t.nanos=e%1e3*1e6,t}toDate(t){return new Date(Pe.from(t.seconds).toNumber()*1e3+Math.ceil(t.nanos/1e6))}fromDate(t){const e=this.create(),r=t.getTime();return e.seconds=Pe.from(Math.floor(r/1e3)).toBigInt(),e.nanos=r%1e3*1e6,e}internalJsonWrite(t,e){let r=Pe.from(t.seconds).toNumber()*1e3;if(rDate.parse("9999-12-31T23:59:59Z"))throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");if(t.nanos<0)throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative.");let n="Z";if(t.nanos>0){let i=(t.nanos+1e9).toString().substring(1);i.substring(3)==="000000"?n="."+i.substring(0,3)+"Z":i.substring(6)==="000"?n="."+i.substring(0,6)+"Z":n="."+i+"Z"}return new Date(r).toISOString().replace(".000Z",n)}internalJsonRead(t,e,r){if(typeof t!="string")throw new Error("Unable to parse Timestamp from JSON "+Fl(t)+".");let n=t.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw new Error("Unable to parse Timestamp from JSON. Invalid format.");let i=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[8]:"Z"));if(Number.isNaN(i))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(iDate.parse("9999-12-31T23:59:59Z"))throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");return r||(r=this.create()),r.seconds=Pe.from(i/1e3).toBigInt(),r.nanos=0,n[7]&&(r.nanos=parseInt("1"+n[7]+"0".repeat(9-n[7].length))-1e9),r}}new fM;const gM=0,vM=1,yM=2,TM=3,_M=4,SM=5,EM={getPeerInfo:0,updatePeerInfo:1,getRoomPeersInfo:2,joinRoom:3,leaveRoom:4,getRoomInfo:5,updateRoomInfo:6,closeRoom:7,startedLivestream:8,stoppedLivestream:9,erroredLivestream:10,getStagePeers:11,getStageRequests:12,requestStageAccess:13,cancelStageRequest:14,grantStageAccess:15,denyStageAccess:16,roomPeerCount:17,joinStage:18,leaveStage:19,getConnectedRoomsDump:20,createConnectedRooms:21,deleteConnectedRooms:22,movePeers:23,transferPeer:24,movedPeer:25,connectedRoomsUpdated:26,connectedRoomsDeleted:27,getAllAddedParticipants:28,broadcastMessage:29,kick:30,kickAll:31,transcript:32,getWaitingRoomRequests:33,acceptWaitingRoomRequests:34,waitingRoomRequestAccepted:35,denyWaitingRoomRequests:36,waitingRoomRequestDenied:37,peerStageStatusUpdate:38,broadcastToPeers:39,recordingStarted:40,recordingStopped:41,recordingPaused:42,getRoomStageState:43},wM={getMessages:0,sendMessageToRoom:1,sendMessageToPeers:2,editMessage:3,deleteMessage:4,getPaginatedMessages:5,sendMessageToChannel:6,searchChannelMessages:7,getAllChatChannels:8,markChannelIndexAsRead:9,pinMessage:10},CM={getPlugins:0,addPlugin:1,enablePluginForRoom:2,disablePluginForPeers:3,enablePluginForPeers:4,disablePluginForRoom:5,removePlugin:6,customPluginEventToRoom:7,customPluginEventToPeers:8,storeInsertKeys:9,storeGetKeys:10,storeDeleteKeys:11,storeDelete:12},bM={createPoll:0,getPolls:1,votePoll:2,updatePoll:3},sg={unknown:0,createWebRTCTransport:1,produce:2,consume:3,toggleProducer:4,toggleConsumer:5,closeProducer:6,closeConsumer:7,joinRoom:16,leaveRoom:17,selectedPeer:18,globalPinPeer:19,selfJoinComplete:20,peerJoinedBroadcast:25,peerLeaveBroadcast:26,peerProducerCreateBroadcast:27,peerProducerToggleBroadcast:28,peerProducerCloseBroadcast:29,globalPeerPinBroadcast:30,recordingStartedBroadcast:31,recordingStoppedBroadcast:32,peerDisplayNameEditBroadcast:33,mediaRoomTerminationBroadcastResponse:36,selectedPeerDiff:40,renegotiateSessionDescription:50,errorResponse:60,kickPeer:90,kickAll:91,changeDisplayName:92,hostControlPeer:93,hostControlAllPeers:94},PM={createChatChannel:0,getChatChannel:1,deprecatedGetAllChatChannels:2,getChannelMembers:3,updateChatChannel:4},RM={getUserPresets:0,updateUserPreset:1};function ti(s,t){return Object.keys(t).reduce((e,r)=>(e[r]=(s<<16)+t[r],e),{})}function ng(s,t){return Object.keys(s).reduce((e,r)=>(e[r]=t|s[r],e),{})}const $=ti(gM,EM),Ue=ti(vM,wM),j=ti(yM,CM),qr=ti(TM,bM),cn=ti(_M,PM),se=ng(sg,16777216),ne=ng(sg,50331648),Lc=ti(SM,RM);var kM=Object.defineProperty,IM=Object.getOwnPropertyDescriptor,nu=(s,t,e,r)=>{for(var n=r>1?void 0:r?IM(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&kM(t,e,n),n};const iu=(wv=class{constructor(s){S(this,ks,void 0);y(this,ks,s)}async createChannel(s,t,e,r="public",n=!1){const i={displayName:s,targetUserIds:t,displayPictureUrl:e,visibility:r,isDirectMessage:n};n&&(i.visibility="private");const a=await c(this,ks).sendMessagePromise(cn.createChatChannel,ZI.toBinary(i)),o=Hr.fromBinary(a.payload).chatChannels;return iu.formatChannel(o[0])}async updateChannel(s,t){const e=await c(this,ks).sendMessagePromise(cn.updateChatChannel,tA.toBinary({chatChannelId:s,targetUserIds:t.memberIds,displayName:t.displayName,displayPictureUrl:t.displayPictureUrl,visibility:t.visibility})),r=Hr.fromBinary(e.payload).chatChannels;return iu.formatChannel(r[0])}static formatChannel(s){var r;const{latestMessageAndUnreadCount:t}=s,e={...s,id:s.chatChannelId,memberIds:s.targetUserIds,unreadCount:(r=t==null?void 0:t.unreadCount)!=null?r:0};return t!=null&&t.message&&(e.latestMessage=ur.formatSocketServiceMessage(t.message)),delete e.chatChannelId,delete e.targetUserIds,delete e.latestMessageAndUnreadCount,e}async getChannelMembers(s){try{const t=await c(this,ks).sendMessagePromise(cn.getChannelMembers,nA.toBinary({chatChannelId:s}));return pA.fromBinary(t.payload).channelMembers.map(({id:e,...r})=>({...r,userId:e}))}catch(t){return[]}}on(s,t){let e,r;switch(s){case cn.createChatChannel:{e=Hr.fromBinary.bind(Hr),r=Hr.create();break}case cn.updateChatChannel:{e=Hr.fromBinary.bind(Hr),r=Hr.create();break}}if(!e){l.warn(`ChatChannelSocketHandler::Event ${s} is not recognized`);return}c(this,ks).on(s,({payload:n})=>{let i=r;try{i=e(n)}catch(a){l.error("ChatChannelSocketHandler::on::binary_decode_error",{error:a})}return t(i)})}},ks=new WeakMap,wv);let dn=iu;nu([g.trace("ChatChannelHandler.createChannel")],dn.prototype,"createChannel",1),nu([g.trace("ChatChannelHandler.updateChannel")],dn.prototype,"updateChannel",1),nu([g.trace("ChatChannelHandler.getChannelMembers")],dn.prototype,"getChannelMembers",1);var AM=Object.defineProperty,MM=Object.getOwnPropertyDescriptor,lr=(s,t,e,r)=>{for(var n=r>1?void 0:r?MM(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&AM(t,e,n),n},Pt=(s=>(s[s.TEXT=0]="TEXT",s[s.IMAGE=1]="IMAGE",s[s.FILE=2]="FILE",s[s.CUSTOM=3]="CUSTOM",s))(Pt||{});class Xt{constructor(t){S(this,vt,void 0);y(this,vt,t)}getChatMessages(){return c(this,vt).sendMessagePromise(Ue.getMessages)}async getChatMessagesPaginated(t,e,r,n=0,i=""){const a={timeStamp:t,size:e,from:n,reversed:r,channelId:i},o=await c(this,vt).sendMessagePromise(Ue.getPaginatedMessages,CI.toBinary(a));return o.payload?PI.fromBinary(o.payload):{messages:[],next:!1}}sendMessageToRoom(t,e){const r={payloadType:e,payload:t};c(this,vt).sendMessage(Ue.sendMessageToRoom,II.toBinary(r))}sendMessageToPeers(t,e,r){const n={payloadType:e,peerIds:r,payload:t};c(this,vt).sendMessage(Ue.sendMessageToPeers,DI.toBinary(n))}sendMessageToChannel(t,e,r){const n={payloadType:e,channelId:r,payload:t};c(this,vt).sendMessage(Ue.sendMessageToChannel,LI.toBinary(n))}sendMessage(t,e,r,n){if(n&&this.sendMessageToChannel(t,e,n),r&&r.length>0){this.sendMessageToPeers(t,e,r);return}this.sendMessageToRoom(t,e)}async editMessage(t,e,r,n,i){const a={chatId:t,payloadType:r,payload:e};n&&(a.channelId=n),i!==void 0&&(a.pinned=i);const o=await c(this,vt).sendMessagePromise(Ue.editMessage,UI.toBinary(a));return Oc.fromBinary(o.payload).message}async deleteMessage(t,e){const r={chatId:t};e&&(r.channelId=e);const n=await c(this,vt).sendMessagePromise(Ue.deleteMessage,jI.toBinary(r)),i=Nc.fromBinary(n.payload);return{id:i.chatId,...i.channelId?{channelId:i.channelId}:{}}}async searchMessages(t,e){var n,i,a;const r={searchTerm:t,timeStamp:(n=e.timestamp)!=null?n:Date.now(),size:(i=e.size)!=null?i:75,from:0,reversed:(a=e.reversed)!=null?a:!0};e.channelId&&(r.channelId=e.channelId);try{const o=await c(this,vt).sendMessagePromise(Ue.searchChannelMessages,WI.toBinary(r));return Wf.fromBinary(o.payload).messages}catch(o){return[]}}async getAllChannels(){try{const t=await c(this,vt).sendMessagePromise(Ue.getAllChatChannels);return Hr.fromBinary(t.payload).chatChannels.map(dn.formatChannel)}catch(t){return[]}}async markLastReadMessage(t,e){const r=await c(this,vt).sendMessagePromise(Ue.markChannelIndexAsRead,zI.toBinary({channelId:t,userId:e.userId,channelIndex:e.channelIndex}));return QI.fromBinary(r.payload).channelIndex}async setPinState(t,e){const r={chatId:t.id,pinned:e,channelId:t.channelId},n=await c(this,vt).sendMessagePromise(Ue.pinMessage,$I.toBinary(r));return Dc.fromBinary(n.payload)}on(t,e){let r,n;switch(t){case Ue.sendMessageToRoom:{r=Xl.fromBinary.bind(Xl),n=Xl.create();break}case Ue.sendMessageToPeers:{r=Zl.fromBinary.bind(Zl),n=Zl.create();break}case Ue.editMessage:{r=Oc.fromBinary.bind(Oc),n=Oc.create();break}case Ue.pinMessage:{r=Dc.fromBinary.bind(Dc),n=Dc.create();break}case Ue.deleteMessage:{r=Nc.fromBinary.bind(Nc),n=Nc.create();break}}if(!r){l.warn(`ChatSocketHandler::Event ${t} is not recognized`);return}c(this,vt).on(t,({payload:i})=>{let a=n;try{a=r(i)}catch(o){l.error("chatSocketHandler::on::binary_decode_error",{error:o})}return e(a)})}}vt=new WeakMap,lr([g.trace("SocketService.getChatMessages")],Xt.prototype,"getChatMessages",1),lr([g.trace("SocketService.getChatMessagesPaginated")],Xt.prototype,"getChatMessagesPaginated",1),lr([g.trace("SocketService.sendMessageToRoom")],Xt.prototype,"sendMessageToRoom",1),lr([g.trace("SocketService.sendMessageToPeers")],Xt.prototype,"sendMessageToPeers",1),lr([g.trace("SocketService.sendMessageToChannel")],Xt.prototype,"sendMessageToChannel",1),lr([g.trace("SocketService.sendMessage")],Xt.prototype,"sendMessage",1),lr([g.trace("SocketService.editMessage")],Xt.prototype,"editMessage",1),lr([g.trace("SocketService.deleteMessage")],Xt.prototype,"deleteMessage",1),lr([g.trace("SocketService.searchMessages")],Xt.prototype,"searchMessages",1),lr([g.trace("SocketService.getAllChannels")],Xt.prototype,"getAllChannels",1),lr([g.trace("SocketService.markLastReadMessage")],Xt.prototype,"markLastReadMessage",1);function DM(s){return s.replace(/([-_]\w)/g,t=>t[1].toUpperCase())}function wr(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>wr(e));const t={};return Object.keys(s).forEach(e=>{const r=Vd(e)?e:DM(e);t[r]=wr(s[e])}),t}function OM(s){return s.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function ig(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>ig(e));const t={};return Object.keys(s).forEach(e=>{const r=Vd(e)?e:OM(e);t[r]=s[e]}),t}function Fc(s,t={}){return s==null?{}:(Object.getOwnPropertyNames(s).forEach(e=>{if(typeof s[e]!="function"){if(typeof s[e]=="object"){Fc(s[e],t[e]={});return}t[e]=s[e]}}),t)}const NM=3,LM=30,FM=8e3;class xM{constructor(t,e){m(this,"ipInfo");m(this,"axios");m(this,"requests");m(this,"roomName");m(this,"roomUUID");m(this,"authToken");m(this,"organizationId");m(this,"iceServers");m(this,"pluginInformation");m(this,"userDetails");m(this,"roomDetails");m(this,"context");this.context=t;const{timeout:r=FM,retry:n=NM,retryDelay:i=LM,baseURL:a="https://api.cluster.dyte.in",authToken:o,cachedUserDetails:d}=e||{};this.iceServers=d==null?void 0:d.iceServers,this.pluginInformation=d==null?void 0:d.pluginInformation,this.userDetails=d==null?void 0:d.userDetails,this.roomDetails=d==null?void 0:d.roomDetails,this.requests=rc.create({baseURL:a,responseType:"json",timeout:r,retry:n,retryDelay:i}),this.axios=rc,this.setAuthToken(o,{bearer:!0}),this.requests.interceptors.request.use(u=>(g.injectContext(this.requests.defaults.headers.common),u),async u=>{l.error("xhr::axios",{debuggingHint:"otelRequestInterceptor failed.",error:u})}),this.requests.interceptors.response.use(u=>{try{u.config.url!==g.logsEndpoint&&l.debug("xhr::axios",{networkCall:{status:u.status,statusText:u.statusText,baseURL:u.config.baseURL,url:u.config.url,method:u.config.method}})}catch(h){console.error("xhr::dyte",{error:"responseInterceptorFailed",err:h,response:u})}return u},async u=>{var h;try{if(!u)return Promise.reject(new b("Unknown network error occurred","0011"));u&&u.config&&((h=u.config)==null?void 0:h.url)!==g.logsEndpoint&&l.error("xhr::axios",{error:u,networkCall:{status:u.status,statusText:u.statusText,baseURL:u.config.baseURL,url:u.config.url,retries:u.config.retry,method:u.config.method,isOnline:navigator.onLine?"online":"offline"}});const{config:p,message:f}=u;return p&&f&&p.retry!==void 0&&p.retry>0&&(f.includes("timeout")||f.includes("Network Error"))?(p.retry-=1,this.requests(p)):Promise.reject(new b(f,"0011"))}catch(p){return console.error("xhr::dyte",{error:"responseInterceptorFailed",err:p,responseError:u}),Promise.reject(new b(p.message,"0011"))}})}get peerId(){return this.context.getValue("peerId")}setAuthToken(t,e){const{bearer:r}=e||{};this.authToken=t,this.requests.defaults.headers.common.Authorization=r?`Bearer ${t}`:t}setHeader(t,e){this.requests.defaults.headers.common[t]=e}setRoomName(t){this.roomName=t}setRoomUUID(t){this.roomUUID=t}setOrganizationId(t){this.organizationId=t}}var UM=Object.defineProperty,VM=Object.getOwnPropertyDescriptor,au=(s,t,e,r)=>{for(var n=r>1?void 0:r?VM(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&UM(t,e,n),n};class xc extends xM{constructor(t,e){super(t,e),this.setHeader("x-dyte-web-core-version",t.getValue("sdkVersion"))}async getIPDetails(){var e;const{peerId:t}=this;try{const r=await Ud.getIPDetails({peerId:t,apiHostnames:Lm(this.context)});if(l.log("ipInfo",{ipInfo:r}),((e=r.loc)==null?void 0:e.length)>5)return r;throw Error("Insufficient data")}catch(r){l.warn("ApiClient.getRoomNodeLinkAndTitleV1 Failed to get ip details",{error:{name:r.name,message:r.message}});return}}async getICEServers(){if(this.iceServers)return this.iceServers;const{success:t,iceServers:e}=(await this.requests.get("/iceservers")).data;if(t)return(e==null?void 0:e.length)>0&&(this.iceServers=e),e}async getPlugins(){var n,i,a,o,d,u,h;if(this.pluginInformation)return this.pluginInformation;let{plugins:t}=(await this.requests.get("/v2/plugins/user")).data.data;const e=((i=(n=J.getValue(X.V1_PLUGINS))==null?void 0:n.toString())==null?void 0:i.split(","))||[];return t=t.reduce((p,f)=>(p[e.includes(f.id)?"v1":"v2"].push(f),p),{v1:[],v2:[]}).v2,(d=(o=(a=this.context.getValue("modules"))==null?void 0:a.devTools)==null?void 0:o.plugins)!=null&&d.length&&((h=(u=this.context.getValue("modules"))==null?void 0:u.devTools)==null||h.plugins.forEach(p=>{var v,T,P;const f={...ha,tags:[...ha.tags]};f.baseURL=`http://localhost:${p.port}`,f.name=p.name,f.picture=(v=p.picture)!=null?v:ha.picture,f.description=(T=p.description)!=null?T:ha.description,f.staggered=(P=p.staggered)!=null?P:ha.staggered,f.createdAt=new Date().toISOString(),f.updatedAt=new Date().toISOString(),f.id=p.id,f.organizationId=this.organizationId,t.push(f)})),t}async getPluginDetails(t){const{plugin:e}=(await this.requests.get(`/v2/plugins/view/${t}`)).data.data;return e}async getPluginConfig(t){return(await this.axios.get(`${t}/dyte-config.json`)).data}async authorizePlugin(t){const e={peerId:this.peerId},{token:r}=(await this.requests.post(`/v2/plugins/authorize/${t}`,e)).data.data;return r}async getPresignedUrls(t,e){const r=Nl(this.context,"chat_upload_expiry"),n={roomUUID:this.roomUUID,filename:t,expiry:typeof r=="number"?r:void 0};J.hasFeature(X.FEAT_CHAT_SDK)&&(n.viewType=e);const{getLocation:i,putLocation:a}=(await this.requests.post("/v1/meetings/genPreSignedUploadUrl",n)).data.data;return{getLocation:i,putLocation:a}}async uploadFile(t,e){if(navigator.isReactNative&&"uri"in t)try{await fetch(e,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:{uri:t.uri,name:t.name}})}catch(r){l.error(`sendFileMessage::${r}`)}else await this.axios.put(e,t,{headers:{"Content-Type":t.type}})}}au([g.trace("APIClient.getIPDetails")],xc.prototype,"getIPDetails",1),au([g.trace("APIClient.getICEServers")],xc.prototype,"getICEServers",1),au([g.trace("APIClient.getPlugins")],xc.prototype,"getPlugins",1);var $M=Object.defineProperty,BM=Object.getOwnPropertyDescriptor,jr=(s,t,e,r)=>{for(var n=r>1?void 0:r?BM(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&$M(t,e,n),n};class Cr extends xc{async startLivestreaming(){var e,r;return(r=(e=(await this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/livestreams`)).data)==null?void 0:e.data)==null?void 0:r.playback_url}async stopLivestreaming(){return this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/active-livestream/stop`)}async getActiveLivestream(){const{playbackUrl:t,status:e}=wr((await this.requests.get(`/v2/meetings/${this.context.getValue("meetingId")}/active-livestream`)).data.data);return{status:e,playbackUrl:t}}async getUserDetails(){if(this.userDetails)return this.userDetails;const t=(await this.requests.get("v2/internals/participant-details")).data.data;return wr(t)}async startRecording(t,e){return(await this.requests.post("/v2/recordings",{...ig(t),meeting_id:this.context.getValue("meetingId"),allow_multiple_recordings:!!e})).data.data.id}async updateRecording(t,e){return this.requests.put(`v2/recordings/${t}`,{action:e})}async getActiveRecording(){const{status:t,id:e}=(await this.requests.get(`v2/recordings/active-recording/${this.context.getValue("meetingId")}`)).data.data;return{status:t,id:e}}async getActiveTranscript(){const{transcript_download_url:t}=(await this.requests.get(`v2/meetings/${this.context.getValue("meetingId")}/active-transcript`)).data.data;try{return{transcript:(await this.axios.get(t)).data}}catch(e){throw new b("Cant fetch transcript s3 url")}}async getRoomNodeData(){const t=await this.getIPDetails();if(this.ipInfo=t,this.roomDetails)return this.roomDetails;const{roomNodeLink:e,title:r,useHiveMedia:n,sfu:i}=wr((await this.requests.post("v2/internals/rooms",{ip_information:t})).data.data);return{roomNodeUrl:e,meetingTitle:r,useHiveMedia:n!=null?n:!1,sfu:i}}}jr([g.trace("APIClient.startLivestreaming")],Cr.prototype,"startLivestreaming",1),jr([g.trace("APIClient.stopLivestreaming")],Cr.prototype,"stopLivestreaming",1),jr([g.trace("APIClient.getActiveLivestream")],Cr.prototype,"getActiveLivestream",1),jr([g.trace("APIClient.getUserDetails")],Cr.prototype,"getUserDetails",1),jr([g.trace("APIClient.startRecording")],Cr.prototype,"startRecording",1),jr([g.trace("APIClient.stopRecording")],Cr.prototype,"updateRecording",1),jr([g.trace("APIClient.getActiveRecording")],Cr.prototype,"getActiveRecording",1),jr([g.trace("APIClient.getActiveTranscript")],Cr.prototype,"getActiveTranscript",1),jr([g.trace("APIClient.getRoomNodeData")],Cr.prototype,"getRoomNodeData",1);let ou;function HM(s,t){return ou=new Cr(s,t),ou}function We(){return ou}function qM(s,t){return`
${t.replace(/
[.\s\S]*<\/blockquote>\n\n/m,"")}
${s}`}function Lt(s,t){return function(e,r,n){const i=n.value;let a=0,o=Date.now();return n.value=function(...d){const u=Date.now(),h=t?this[t]:s;if(u-o>h.period*1e3&&(o=u,a=0),a>=h.maxInvocations)throw new b(`Method rate limit ${h.maxInvocations} invocations/${h.period}sec exceeded`);return a+=1,i.apply(this,d)},n}}var jM=Object.defineProperty,GM=Object.getOwnPropertyDescriptor,ft=(s,t,e,r)=>{for(var n=r>1?void 0:r?GM(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&jM(t,e,n),n};const JM=["text","image","file","custom","poll"],Uc={maxInvocations:180,period:60};let at=(Cv=class extends Ht{constructor(t,e,r,n,i){super();S(this,gd);m(this,"messages");m(this,"channels",[]);S(this,re,void 0);S(this,bn,void 0);S(this,et,void 0);S(this,Pn,void 0);S(this,Ma,void 0);m(this,"maxTextLimit",2e3);y(this,Ma,t),y(this,et,e),y(this,Pn,r),y(this,re,n),y(this,bn,i),this.messages=[]}setMaxTextLimit(t){this.maxTextLimit=t}get roomJoined(){var t;return((t=c(this,gd,Hv))==null?void 0:t.roomJoined)===!0}async sendMessageInternal(t,e,r,n={}){switch(t.type){case"text":{const i=n.replyTo&&n.replyTo.type==="text"?qM(t.message,n.replyTo.message):t.message;await this.sendTextMessageInternal(i,e,r);break}case"image":await this.sendImageMessageInternal(t.image,e,r);break;case"file":await this.sendFileMessageInternal(t.file,e,r);break;default:l.error("sendMessage::message_type_not_supported",{dyteChat:{messageType:t.type}});break}}async sendTextMessageInternal(t,e,r){var i,a,o,d,u,h;if(t.length>this.maxTextLimit)throw new b("Max character limit breached");if(e&&e.length>0){if(!((i=c(this,re).permissions)!=null&&i.chatPrivate.canSend)||!((a=c(this,re).permissions)!=null&&a.chatPrivate.text))throw l.error("sendTextMessage::private_chat_permission_denied"),new b("Could not send message to private chat.","0501")}else if(!((d=(o=c(this,re).permissions)==null?void 0:o.chatPublic)!=null&&d.canSend)||!((h=(u=c(this,re).permissions)==null?void 0:u.chatPublic)!=null&&h.text))throw l.error("sendTextMessage::public_chat_permission_denied"),new b("Could not send message to public chat.","0501");if(!t)throw l.error("sendTextMessage::message_can_not_be_empty"),new b("Message can not be empty.","0502");if(r){c(this,et).sendMessageToChannel(t,Pt.TEXT,r);return}let n=[];e&&e.length>0&&(e.push(c(this,re).id),n=c(this,bn).joined.toArray().filter(p=>e.includes(p.id)).map(p=>p.userId),n.push(c(this,re).userId)),c(this,et).sendMessage(t,Pt.TEXT,e)}async sendImageMessageInternal(t,e,r){var i,a,o,d,u,h;if(e&&e.length>0){if(!((i=c(this,re).permissions)!=null&&i.chatPrivate.canSend)||!((a=c(this,re).permissions)!=null&&a.chatPrivate.files)){l.error("sendImageMessage::private_chat_permission_denied");return}}else if(!((d=(o=c(this,re).permissions)==null?void 0:o.chatPublic)!=null&&d.canSend)||!((h=(u=c(this,re).permissions)==null?void 0:u.chatPublic)!=null&&h.files)){l.error("sendImageMessage::permission_denied");return}if(!t){l.error("sendImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(t.type)){l.error("sendImageMessage::image_type_not_supported",{dyteChat:{imageType:t.type}});return}try{const p=We(),{getLocation:f,putLocation:v}=await p.getPresignedUrls(t.name,c(this,re).config.viewType);if(await p.uploadFile(t,v),r){c(this,et).sendMessageToChannel(f,Pt.IMAGE,r);return}let T=[];e&&e.length>0&&(e.push(c(this,re).id),T=c(this,bn).joined.toArray().filter(P=>e.includes(P.id)).map(P=>P.userId),T.push(c(this,re).userId)),c(this,et).sendMessage(f,Pt.IMAGE,e)}catch(p){throw new b("Error sending image message.")}}async sendFileMessageInternal(t,e,r){var n,i,a,o,d,u;if(e&&e.length>0){if(!((n=c(this,re).permissions)!=null&&n.chatPrivate.canSend)||!((i=c(this,re).permissions)!=null&&i.chatPrivate.files)){l.error("sendFileMessage::private_chat_permission_denied");return}}else if(!((o=(a=c(this,re).permissions)==null?void 0:a.chatPublic)!=null&&o.canSend)||!((u=(d=c(this,re).permissions)==null?void 0:d.chatPublic)!=null&&u.files)){l.error("sendFileMessage::permission_denied");return}if(!t){l.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const h=We(),{getLocation:p,putLocation:f}=await h.getPresignedUrls(t.name,c(this,re).config.viewType);if(await h.uploadFile(t,f),r){c(this,et).sendMessageToChannel(JSON.stringify({link:p,name:t.name,size:"size"in t?t.size:0}),Pt.FILE,r);return}let v=[];e&&e.length>0&&(e.push(c(this,re).id),v=c(this,bn).joined.toArray().filter(P=>e.includes(P.id)).map(P=>P.userId),v.push(c(this,re).userId));const T=JSON.stringify({link:p,name:t.name,size:"size"in t?t.size:0});c(this,et).sendMessage(T,Pt.FILE,e)}catch(h){throw new b("Error sending file message.")}}get rateLimits(){return Uc}updateRateLimits(t,e){Uc.maxInvocations=t,Uc.period=e}async sendTextMessage(t,e){return this.sendTextMessageInternal(t,e)}async sendCustomMessage(t,e){var i,a,o,d,u,h,p,f,v,T,P,k,I,x,V;if(e&&e.length>0){if(!((i=c(this,re).permissions)!=null&&i.chatPrivate.canSend)||!((a=c(this,re).permissions)!=null&&a.chatPrivate.files)||!((o=c(this,re).permissions)!=null&&o.chatPrivate.text)){l.error("sendCustomMessage::private_chat_permission_denied");return}}else if(!((u=(d=c(this,re).permissions)==null?void 0:d.chatPublic)!=null&&u.canSend)||!((p=(h=c(this,re).permissions)==null?void 0:h.chatPublic)!=null&&p.files)||!((v=(f=c(this,re).permissions)==null?void 0:f.chatPublic)!=null&&v.text)){l.error("sendCustomMessage::permission_denied");return}const r=async O=>{try{if(typeof O=="string")return{link:O};const W=We(),{getLocation:Q,putLocation:oe}=await W.getPresignedUrls(O.name,c(this,re).config.viewType);return await W.uploadFile(O,oe),{link:Q,type:O.type,name:O.name,size:O.size}}catch(W){throw new b("Error sending image message.")}},n={...t,files:await Promise.all((P=(T=t.files)!=null?T:[])==null?void 0:P.map(async O=>r(O))),images:await Promise.all((I=(k=t.images)!=null?k:[])==null?void 0:I.map(async O=>r(O))),videos:await Promise.all((V=(x=t.videos)!=null?x:[])==null?void 0:V.map(async O=>r(O)))};c(this,et).sendMessage(JSON.stringify(n),Pt.CUSTOM,e)}async sendImageMessage(t,e){return this.sendImageMessageInternal(t,e)}async sendFileMessage(t,e){return this.sendFileMessageInternal(t,e)}async sendMessage(t,e){return this.sendMessageInternal(t,e)}async editTextMessage(t,e,r){var n,i,a,o,d,u;if(((i=(n=c(this,re).permissions)==null?void 0:n.chatMessage)==null?void 0:i.canEdit)==="NONE")throw new b("Not permitted to edit messages","0501");if(!((o=(a=c(this,re).permissions)==null?void 0:a.chatPublic)!=null&&o.canSend)||!((u=(d=c(this,re).permissions)==null?void 0:d.chatPublic)!=null&&u.text)){l.error("editTextMessage::permission_denied");return}if(!e){l.error("editTextMessage::message_can_not_be_empty");return}c(this,et).editMessage(t,e,Pt.TEXT,r)}async editImageMessage(t,e,r){var i,a,o,d;if(!((a=(i=c(this,re).permissions)==null?void 0:i.chatPublic)!=null&&a.canSend)||!((d=(o=c(this,re).permissions)==null?void 0:o.chatPublic)!=null&&d.files)){l.error("editImageMessage::permission_denied");return}if(!e){l.error("editImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(e.type)){l.error("sendImageMessage::image_type_not_supported",{dyteChat:{imageType:e.type}});return}try{const u=We(),{getLocation:h,putLocation:p}=await u.getPresignedUrls(e.name,c(this,re).config.viewType);await u.uploadFile(e,p),c(this,et).editMessage(t,h,Pt.IMAGE,r)}catch(u){throw new b("Error editing image message.")}}async editFileMessage(t,e,r){var n,i,a,o;if(!((i=(n=c(this,re).permissions)==null?void 0:n.chatPublic)!=null&&i.canSend)||!((o=(a=c(this,re).permissions)==null?void 0:a.chatPublic)!=null&&o.files)){l.error("sendFileMessage::permission_denied");return}if(!e){l.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const d=We(),{getLocation:u,putLocation:h}=await d.getPresignedUrls(e.name,c(this,re).config.viewType);await d.uploadFile(e,h),c(this,et).editMessage(t,JSON.stringify({link:u,name:e.name,size:"size"in e?e.size:0}),Pt.FILE,r)}catch(d){throw new b("Error editing file message.")}}async editMessage(t,e,r){switch(e.type){case"text":{this.editTextMessage(t,e.message,r);break}case"image":{this.editImageMessage(t,e.image,r);break}case"file":{this.editFileMessage(t,e.file,r);break}default:{l.error("editMessage::message_type_not_supported",{dyteChat:{messageType:e.type}});break}}}async deleteMessage(t,e){var r,n;if(((n=(r=c(this,re).permissions)==null?void 0:r.chatMessage)==null?void 0:n.canDelete)==="NONE")throw new b("Not permitted to delete messages","0501");c(this,et).deleteMessage(t,e)}getMessagesByUser(t){return this.messages.filter(e=>e.userId===t)}getMessagesByType(t){return this.messages.filter(e=>e.type===t)}async pin(t){if(!this.roomJoined)throw new b("Can`t pin message without joining room");if(!c(this,re).permissions.pinParticipant)throw new b("You do not have permission to pin messages.");const e=this.messages.find(r=>r.id===t);if(e){c(this,et).setPinState(e,!0);return}throw new b(`No message found with id: ${t}`)}async unpin(t){if(!this.roomJoined)throw new b("Can`t unpin message without joining room");if(!c(this,re).permissions.pinParticipant)throw new b("You do not have permission to unpin messages.");const e=this.messages.find(r=>r.id===t);if(e){c(this,et).setPinState(e,!1);return}throw new b(`No message found with id: ${t}`)}async getMessages(t,e,r,n=0,i=void 0){const a=await c(this,et).getChatMessagesPaginated(t,e,r,n,i);return{messages:a.messages.map(o=>ur.formatSocketServiceMessage(o)),next:a.next}}async createChannel(t,e,r={}){var o;const n=(o=c(this,re).permissions)==null?void 0:o.chatChannel;if(n){if(n.canCreate==="NONE")throw new b("Not permitted to create channels","0501");if(r.visibility==="public"&&!(n.canCreate==="PUBLIC"||n.canCreate==="ALL"))throw new b("Not permitted to create public channels","0501");if(r.visibility==="private"&&!(n.canCreate==="PRIVATE"||n.canCreate==="ALL"))throw new b("Not permitted to create private channels","0501")}if(!t||t.trim().length===0)throw new b("channel name cannot be empty.","0510");const i=[...new Set([...e,c(this,re).userId])];return await c(this,Pn).createChannel(t.trim(),i,r.displayPictureUrl,r.visibility,r.isDirectMessage)}updateChannel(t,e){var a,o,d,u,h;const r=this.channels.find(p=>p.id===t),n=(a=c(this,re).permissions)==null?void 0:a.chatChannel;if(n){if(n.canUpdate==="NONE")throw new b("Not permitted to update channels","0501");if(r.visibility==="public"&&!(n.canUpdate==="PUBLIC"||n.canUpdate==="ALL"))throw new b("Not permitted to update public channels","0501");if(r.visibility==="private"&&!(n.canUpdate==="PRIVATE"||n.canUpdate==="ALL"))throw new b("Not permitted to update private channels","0501")}const i={memberIds:(o=e.memberIds)!=null?o:r.memberIds,displayName:(d=e.displayName)!=null?d:r.displayName,displayPictureUrl:(u=e.displayPictureUrl)!=null?u:r.displayPictureUrl,visibility:(h=e.visibility)!=null?h:r.visibility};return c(this,Pn).updateChannel(t,i)}async sendMessageToChannel(t,e,r={}){return this.sendMessageInternal(t,null,e,r)}async getChannelMembers(t){return c(this,Pn).getChannelMembers(t)}async searchMessages(t,e={}){if(!J.hasFeature(X.FEAT_CHAT_SDK_SEARCH))throw new b("searchMessages is temporarily disabled!");return(await c(this,et).searchMessages(t,e)).map(ur.formatSocketServiceMessage)}async markLastReadMessage(t,e){await c(this,et).markLastReadMessage(t,e);const r=this.channels.find(n=>n.id===t);if(r){const n={...r,unreadCount:0};this.channels=this.channels.map(i=>i.id===t?n:i),this.emit("channelMessageUpdate",n)}}get pinned(){return this.messages.filter(t=>t.pinned)}},re=new WeakMap,bn=new WeakMap,et=new WeakMap,Pn=new WeakMap,Ma=new WeakMap,gd=new WeakSet,Hv=function(){return c(this,Ma).getValue("roomNodeClient")},Cv);ft([g.trace("DyteChat.sendTextMessage"),Lt(Uc)],at.prototype,"sendTextMessage",1),ft([g.trace("DyteChat.sendImageMessage"),Lt({maxInvocations:20,period:60})],at.prototype,"sendImageMessage",1),ft([g.trace("DyteChat.sendFileMessage"),Lt({maxInvocations:20,period:60})],at.prototype,"sendFileMessage",1),ft([g.trace("DyteChat.sendMessage"),Lt({maxInvocations:180,period:60})],at.prototype,"sendMessage",1),ft([g.trace("DyteChat.editTextMessage")],at.prototype,"editTextMessage",1),ft([g.trace("DyteChat.editImageMessage")],at.prototype,"editImageMessage",1),ft([g.trace("DyteChat.editFileMessage")],at.prototype,"editFileMessage",1),ft([g.trace("DyteChat.editMessage")],at.prototype,"editMessage",1),ft([g.trace("DyteChat.deleteMessage")],at.prototype,"deleteMessage",1),ft([g.trace("DyteChat.createChannel")],at.prototype,"createChannel",1),ft([g.trace("DyteChat.updateChannel")],at.prototype,"updateChannel",1),ft([g.trace("DyteChat.sendMessageToChannel")],at.prototype,"sendMessageToChannel",1),ft([g.trace("DyteChat.getChannelMembers")],at.prototype,"getChannelMembers",1),ft([g.trace("DyteChat.searchMessages")],at.prototype,"searchMessages",1),ft([g.trace("DyteChat.markLastReadMessage")],at.prototype,"markLastReadMessage",1),at=ft([pt("0500")],at);var WM=Object.defineProperty,KM=Object.getOwnPropertyDescriptor,zM=(s,t,e,r)=>{for(var n=r>1?void 0:r?KM(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&WM(t,e,n),n};const ln=(bv=class{constructor(s,t,e,r,n){m(this,"chat");m(this,"chatSocketHandler");m(this,"chatChannelSocketHandler");m(this,"self");S(this,vd,void 0);y(this,vd,s),this.chatSocketHandler=t,this.chatChannelSocketHandler=e,this.chat=new at(s,t,e,r,n),this.self=r,this.setupEvents()}static async init(s,t,e,r,n){return new ln(s,t,e,r,n)}static formatMessage(s){return{...s,time:new Date(s.time),type:JM[s.type]}}static formatSocketServiceMessage(s){const t=s.createdAt*1e3,e={displayName:s.displayName,id:s.chatId,time:t,timeMs:s.createdAtMs,type:s.payloadType,isEdited:s.isEdited,userId:s.userId,targetUserIds:s.targetUserIds,channelId:s.channelId,channelIndex:s.channelIndex,message:"",link:"",name:"",html:"",images:[],videos:[],files:[],size:0,pinned:s.pinned};switch(e.type){case Pt.TEXT:{e.message=s.payload;break}case Pt.IMAGE:{e.link=s.payload;break}case Pt.FILE:{const{link:r,name:n,size:i}=JSON.parse(s.payload);e.link=r,e.name=n,e.size=i;break}case Pt.CUSTOM:{const{html:r,images:n,message:i,videos:a,files:o}=JSON.parse(s.payload);e.message=i,e.html=r,e.images=n,e.videos=a,e.files=o;break}}return ln.formatMessage(e)}async getChatMessages(){if(this.self.config.viewType==="LIVESTREAM"||this.self.config.viewType==="CHAT"||J.hasFeature(X.FEAT_PAGINATED_CHAT))return;const s=await this.chatSocketHandler.getChatMessages();if(!(s!=null&&s.payload))return;const t=Wf.fromBinary(s.payload).messages;this.chat.messages=t.map(e=>ln.formatSocketServiceMessage(e))}setupEvents(){w.on(C.SOCKET_SERVICE_ROOM_JOINED,async()=>{this.getChatMessages()}),this.chatSocketHandler.on(Ue.sendMessageToRoom,s=>{const t=ln.formatSocketServiceMessage(s.message);if(!t.channelId)this.chat.messages=[...this.chat.messages,t];else{const e=this.chat.channels.find(r=>r.id===t.channelId);e&&(e.latestMessage=t,e.unreadCount+=1,this.chat.emit("channelMessageUpdate",e))}this.chat.emit("chatUpdate",{action:"add",message:t,messages:this.chat.messages})}),this.chatSocketHandler.on(Ue.sendMessageToPeers,s=>{const t=ln.formatSocketServiceMessage(s.message);this.chat.messages=[...this.chat.messages,t],this.chat.emit("chatUpdate",{action:"add",message:t,messages:this.chat.messages})}),this.chatSocketHandler.on(Ue.editMessage,s=>{const t=ln.formatSocketServiceMessage(s.message);if(t.channelId){this.chat.emit("chatUpdate",{action:"edit",message:t,messages:this.chat.messages});return}const e=this.chat.messages.findIndex(r=>r.id===t.id);e!==-1&&(this.chat.messages[e]=t,this.chat.emit("chatUpdate",{action:"edit",message:t,messages:this.chat.messages}))}),this.chatSocketHandler.on(Ue.deleteMessage,s=>{if(s.channelId){this.chat.emit("chatUpdate",{action:"delete",message:{id:s.chatId,channelId:s.channelId},messages:this.chat.messages});return}const t=this.chat.messages.findIndex(r=>r.id===s.chatId);if(t===-1)return;const[e]=this.chat.messages.splice(t,1);this.chat.emit("chatUpdate",{action:"delete",message:e,messages:this.chat.messages})}),this.chatChannelSocketHandler.on(cn.createChatChannel,s=>{const[t]=s.chatChannels,e=dn.formatChannel(t);this.chat.channels.push(e),this.chat.emit("channelCreate",e)}),this.chatSocketHandler.on(Ue.pinMessage,s=>{const t=this.chat.messages.findIndex(r=>r.id===s.chatId);if(t===-1)return;const e=this.chat.messages[t];e.pinned=s.pinned,this.chat.messages[t]=e,this.chat.emit("chatUpdate",{action:"edit",message:e,messages:this.chat.messages})}),this.chatChannelSocketHandler.on(cn.updateChatChannel,s=>{const[t]=s.chatChannels,e=dn.formatChannel(t);this.chat.channels=this.chat.channels.map(r=>r.id===e.id?e:r),this.chat.emit("channelUpdate",e)})}},vd=new WeakMap,bv);let ur=ln;zM([g.trace("ChatController.setupEvents")],ur.prototype,"setupEvents",1);var YM=Object.defineProperty,QM=Object.getOwnPropertyDescriptor,XM=(s,t,e,r)=>{for(var n=r>1?void 0:r?QM(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&YM(t,e,n),n};let cu=(Pv=class extends Ht{constructor(t,e,r){super();S(this,yd);m(this,"items");S(this,Rn,void 0);S(this,Ti,void 0);S(this,Da,void 0);y(this,Da,t),y(this,Rn,e),y(this,Ti,r),this.items=[]}get roomJoined(){var t;return((t=c(this,yd,qv))==null?void 0:t.roomJoined)===!0}async create(t,e,r=!1,n=!1){if(c(this,Rn).config.viewType!=="LIVESTREAM"&&!this.roomJoined)throw new b("Can't create polls without joining room");if(!c(this,Rn).permissions.polls.canCreate){l.error("DytePolls::create::permission_denied");return}if(!t||!e){l.error("DytePolls::question_and_options_can_not_be_empty",{dytePolls:{hasQuestion:!!t,optionsLength:e==null?void 0:e.length}});return}if(e.length<2){l.error("DytePolls::there_must_be_at_least_two_options",{dytePolls:{hasQuestion:!!t,optionsLength:e.length}});return}await c(this,Ti).createPoll(t,e,r,n)}async vote(t,e){if(!c(this,Rn).permissions.polls.canVote){l.error("DytePolls::vote::permission_denied");return}await c(this,Ti).votePoll(t,e)}},yd=new WeakSet,qv=function(){return c(this,Da).getValue("roomNodeClient")},Rn=new WeakMap,Ti=new WeakMap,Da=new WeakMap,Pv);cu=XM([pt("0700")],cu);var ZM=Object.defineProperty,e0=Object.getOwnPropertyDescriptor,t0=(s,t,e,r)=>{for(var n=r>1?void 0:r?e0(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&ZM(t,e,n),n};const ri=(Rv=class{constructor(s,t,e){m(this,"polls");S(this,_i,void 0);S(this,kn,void 0);this.polls=new cu(s,t,e),y(this,_i,t),y(this,kn,e),this.setupEvents()}static async init(s,t,e){return new ri(s,t,e)}canViewPolls(){return c(this,_i).permissions.polls.canView}setupEvents(){const s={[qr.createPoll]:r=>{r.poll&&this.updatePoll(ri.formatSocketServicePoll(r.poll))},[qr.updatePoll]:r=>{r.poll&&this.updatePoll(ri.formatSocketServicePoll(r.poll))},[qr.votePoll]:r=>{r.poll&&this.updatePoll(ri.formatSocketServicePoll(r.poll))}},t=()=>{w.on(C.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{c(this,kn).on(r,s[r])})},e=()=>{w.on(C.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{c(this,kn).removeListeners(r)})};c(this,_i).permissions.on("permissionsUpdate",async r=>{var n;(n=r==null?void 0:r.polls)!=null&&n.canView?(await this.getPolls(),t()):(this.polls.items=[],e())}),this.canViewPolls()&&t()}updatePoll(s){if(!this.canViewPolls())return;const t=this.polls.items.findIndex(e=>e.id===s.id);if(t>-1){const e=JSON.stringify(this.polls.items[t]);this.polls.items[t]=s,e!==JSON.stringify(s)&&this.polls.emit("pollsUpdate",{polls:this.polls.items,newPoll:!1});return}this.polls.items=[...this.polls.items,s],this.polls.emit("pollsUpdate",{polls:this.polls.items,newPoll:!0})}async getPolls(){const s=await c(this,kn).getPolls();if(!(s!=null&&s.payload))return;const{polls:t}=pM.fromBinary(s.payload);this.polls.items=t.map(e=>ri.formatSocketServicePoll(e))}static formatSocketServicePoll(s){const t=s.options.map(e=>({count:e.count,text:e.text,votes:e.votes.map(r=>({id:r.userId,name:r.name}))}));return{anonymous:s.anonymous,createdBy:s.createdBy,createdByUserId:s.createdByUserId,hideVotes:s.hideVotes,id:s.pollId,options:t,question:s.question,voted:s.votes}}},_i=new WeakMap,kn=new WeakMap,Rv);let ag=ri;t0([g.trace("PollController.setupEvents")],ag.prototype,"setupEvents",1);var r0=Object.defineProperty,s0=Object.getOwnPropertyDescriptor,n0=(s,t,e,r)=>{for(var n=r>1?void 0:r?s0(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&r0(t,e,n),n},og=(s=>(s[s.User=0]="User",s[s.Meeting=1]="Meeting",s))(og||{});let du=(kv=class extends Ht{constructor(t,e,r,n,i){super();S(this,Td);S(this,Oa);m(this,"selfActiveTab");m(this,"broadcastTabChanges");S(this,Si,void 0);S(this,In,void 0);S(this,Na,void 0);m(this,"viewType");m(this,"meetingStartedTimestamp");m(this,"meetingTitle");m(this,"sessionId");y(this,Si,t),y(this,In,e),this.viewType=r,y(this,Na,n),this.meetingTitle=i,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){return c(this,Oa,zu).socketState}get mediaState(){return c(this,Oa,zu).mediaState}get meetingId(){var t;return(t=c(this,Td,jv))==null?void 0:t.roomName}setBroadcastTabChanges(t){if(!c(this,In).permissions.canSpotlight)throw l.error("DyteSpotlight::setSpotlighted::permission_denied"),new b("User does not have permission to toggle spotlight");this.broadcastTabChanges=t,this.emit("broadcastTabChangesUpdate",this.broadcastTabChanges),this.broadcastTabChanges&&this.assertActiveTabToRoom()}setSelfActiveTab(t,e){var r;l.info("DyteSpotlight::setActiveTab",{spotlight:{currentTab:{id:t.id,type:t.type}}}),this.selfActiveTab=t,e===0&&this.emit("selfTabUpdate",t),(r=c(this,In).permissions)!=null&&r.canSpotlight&&this.broadcastTabChanges&&e===0&&this.assertActiveTabToRoom()}assertActiveTabToRoom(){c(this,Na).broadcastMessage("spotlight",{userId:c(this,In).userId,currentTab:this.selfActiveTab})}},Si=new WeakMap,Td=new WeakSet,jv=function(){return c(this,Si).getValue("roomNodeClient")},Oa=new WeakSet,zu=function(){return c(this,Si).getValue("connectionHandler")},In=new WeakMap,Na=new WeakMap,kv);du=n0([pt("0800")],du);function i0(s){let t="",e=[""];const r=[e];let n=0,i=0,a=!0,o;for(o of s)o==='"'?(a&&o===t&&(e[n]+=o),a=!a):o===","&&a?o=e[++n]="":o===` `&&a?(t==="\r"&&(e[n]=e[n].slice(0,-1)),e=r[++i]=[o=""],n=0):e[n]+=o,t=o;return r}var a0=Object.defineProperty,o0=Object.getOwnPropertyDescriptor,cg=(s,t,e,r)=>{for(var n=r>1?void 0:r?o0(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&a0(t,e,n),n};let vs=class extends Ht{constructor(){super();m(this,"transcripts");this.transcripts=[]}static async init(t){const e=new vs;try{t&&e.getActiveTranscript()}catch(r){l.error("Error fetching active transcriptions ",r)}return e}static parseTranscript(t,e=!1){try{if(!t)return;const[[r,n,i,a,o,d]]=i0(t);return{id:Xs(),name:o,peerId:n,userId:i,customParticipantId:a,transcript:d,isPartialTranscript:e,date:new Date(parseInt(r,10)*1e3)}}catch(r){l.error(`Failed to parse transcript: ${t}`,r);return}}static parseTranscripts(t){return t?t.split(` -`).map(e=>vs.parseTranscript(e,!1)).filter(Boolean):[]}async getActiveTranscript(){try{const t=We(),{transcript:e}=await t.getActiveTranscript();this.transcripts=vs.parseTranscripts(e)}catch(t){}}async onTranscript(t){var r;const e=this.transcripts.filter(({peerId:n})=>n===t.peerId);if((r=e==null?void 0:e.at(-1))!=null&&r.isPartialTranscript){const n=e.at(-1);n.transcript=t.transcript,n.isPartialTranscript=t.isPartialTranscript,this.emit("transcript",n);return}this.transcripts.push(t),this.emit("transcript",t)}};cg([g.trace("DyteAi.getActiveTranscript")],vs.prototype,"getActiveTranscript",1),vs=cg([pt("0000")],vs);var c0=Object.defineProperty,d0=Object.getOwnPropertyDescriptor,l0=(s,t,e,r)=>{for(var n=r>1?void 0:r?d0(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&c0(t,e,n),n};const dg=(Iv=class{constructor(s,t,e,r,n,i){m(this,"meta");m(this,"ai");S(this,Is,void 0);S(this,Ei,void 0);m(this,"aiSocketHandler");S(this,_d,void 0);y(this,_d,s),this.meta=new du(s,t,t.config.viewType,e,i),this.ai=r,y(this,Is,t),y(this,Ei,e),this.aiSocketHandler=n,t.config.viewType!==Xe.Chat&&this.setupEvents()}static async init(s,t,e,r,n){const i=await vs.init(t.permissions.transcriptionEnabled);return new dg(s,t,e,i,r,n)}conditionallySetActiveTab(s){var t;s!=null&&s.currentTab&&((t=this.meta.selfActiveTab)==null?void 0:t.id)!==s.currentTab.id&&(this.meta.setSelfActiveTab(s.currentTab,og.Meeting),this.meta.emit("activeTabUpdate",s.currentTab))}setupEvents(){w.on(C.TRANSPORT_STATE_UPDATE,s=>{this.meta.emit("mediaConnectionUpdate",s)}),w.on(C.SOCKET_STATE_UPDATE,s=>{this.meta.emit("socketConnectionUpdate",s)}),w.on(C.ROOM_STATE,({createdAt:s,roomUuid:t})=>{const e=this.meta.meetingStartedTimestamp;if(t&&(this.meta.sessionId=t),s&&!e){const r=new Date(s*1e3);this.meta.meetingStartedTimestamp=r,this.meta.emit("meetingStartTimeUpdate",{meetingStartedTimestamp:this.meta.meetingStartedTimestamp})}}),w.on(C.PRODUCER_SCORE_UPDATE,({score:s})=>{s<5&&this.meta.emit("poorConnection",{score:s})}),c(this,Is).permissions.canSpotlight&&(l.info("DyteMetaController::Asserting Spotlight"),this.meta.selfActiveTab&&c(this,Ei).broadcastMessage("spotlight",{userId:c(this,Is).userId,currentTab:this.meta.selfActiveTab})),w.on(C.PEER_JOINED_INTERNAL,async s=>{c(this,Is).permissions.canSpotlight&&this.meta.selfActiveTab&&c(this,Ei).broadcastToPeers("spotlight",[s.id],{userId:c(this,Is).userId,currentTab:this.meta.selfActiveTab})}),w.on(C.ROOM_MESSAGE,s=>{var e,r;let t;if("type"in s){if(s.type!=="spotlight")return;t={...s,...s.payload}}else if("roomMessageType"in s){if(s.roomMessageType!=="spotlight")return;t=s}else return;l.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:t.userId},currentTab:{id:(e=t.currentTab)==null?void 0:e.id,type:(r=t.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(t)}),w.on(C.MESSAGE,s=>{var e,r;let t;if("type"in s){if(s.type!=="spotlight")return;t={...s,...s.payload}}else if("roomMessageType"in s){if(s.roomMessageType!=="spotlight")return;t=s}else return;l.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:t.userId},currentTab:{id:(e=t.currentTab)==null?void 0:e.id,type:(r=t.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(t)}),this.aiSocketHandler.on($.transcript,s=>{const{meetingId:t,transcript:e,isPartial:r}=s,n=vs.parseTranscript(e,r);if(!n){l.warn("Received empty transcript data");return}this.ai.onTranscript(n),this.meta.emit("transcript",n);const{peerId:i,name:a,transcript:o}=n;l.debug(`${t} Received transcript for peer ${i} - ${a}: ${o}`)})}},Is=new WeakMap,Ei=new WeakMap,_d=new WeakMap,Iv);let lg=dg;l0([g.trace("MetaController.setupEvents")],lg.prototype,"setupEvents",1);var u0=Object.defineProperty,h0=Object.getOwnPropertyDescriptor,un=(s,t,e,r)=>{for(var n=r>1?void 0:r?h0(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&u0(t,e,n),n};class ys extends Ht{constructor(e,r,n,i,a){super();S(this,Ci);S(this,er,void 0);S(this,wi,void 0);S(this,Re,void 0);S(this,La,void 0);S(this,Pr,void 0);S(this,fr,void 0);y(this,fr,e),y(this,er,i),y(this,wi,a),y(this,Re,r),y(this,La,n),y(this,Pr,[]),this.setupEvents()}get status(){return c(this,fr).getValue("stageStatus")}setupEvents(){const e={[C.GET_STAGE_REQUESTS]:async i=>{y(this,Pr,i)},[C.UPDATE_STAGE_REQUESTS]:async({add:i})=>{const a=c(this,Pr).length,{stageRequests:o}=this.getAccessRequests();(i||o.length>a)&&this.emit("newStageRequest",{count:o.length}),this.emit("stageAccessRequestUpdate",o)}},r=()=>{Object.entries(e).forEach(([i,a])=>{w.onAsync(i,a)})},n=()=>{Object.entries(e).forEach(([i,a])=>{w.removeListener(i,a)})};c(this,Re).permissions.on("permissionsUpdate",i=>{const{canAcceptProductionRequests:a}=i;a!==void 0&&(c(this,Re).permissions.acceptStageRequests?(r(),c(this,er).getStageRequests()):(n(),y(this,Pr,[]),this.emit("stageAccessRequestUpdate",c(this,Pr))))}),c(this,Re).permissions.acceptStageRequests&&r()}getAccessRequests(){if(!c(this,Re).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new b("Stage is disabled");if(!c(this,Re).permissions.acceptStageRequests)throw l.error("DyteStage::get_access_request::permission_denied"),new b("You do not have permission to perform this action/");const e=c(this,La).joined.toArray().filter(r=>r.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(r=>({displayName:r.name,userId:r.userId,peerId:r.id}));return y(this,Pr,e),{stageRequests:c(this,Pr)}}async requestAccess(){if(!c(this,Re).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new b("Stage is disabled");if(this.status!=="OFF_STAGE")throw new b(`Unable to request access you are currently ${this.status}`);if(c(this,Re).permissions.stageAccess===H.Allowed){je(this,Ci,Nd).call(this,"ACCEPTED_TO_JOIN_STAGE");return}c(this,er).requestAccess(),je(this,Ci,Nd).call(this,"REQUESTED_TO_JOIN_STAGE")}async cancelRequestAccess(){if(!c(this,Re).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new b("Stage is disabled");c(this,er).cancelRequestAccess(),je(this,Ci,Nd).call(this,"OFF_STAGE")}grantAccess(e){if(!c(this,Re).roomJoined)throw new b("Can`t rejectRequestToJoinStage for participant without joining room");if(!c(this,Re).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new b("Stage is disabled");if(!c(this,Re).permissions.acceptStageRequests)throw l.error("DyteStage::grant_access::permission_denied"),new b("You do not have permission to perform this action/");return c(this,er).grantAccess(e)}denyAccess(e){if(!c(this,Re).roomJoined)throw new b("Can`t rejectRequestToJoinStage for participant without joining room");if(!c(this,Re).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new b("Stage is disabled");if(!c(this,Re).permissions.acceptStageRequests)throw l.error("DyteStage::deny_access::permission_denied"),new b("You do not have permission to perform this action/");return c(this,er).denyAccess(e)}async join(){const e=c(this,fr).getValue("viewType");if(this.status==="ON_STAGE")throw new b("You are already on stage.");if(this.status!=="ACCEPTED_TO_JOIN_STAGE"||c(this,Re).permissions.stageAccess===H.NotAllowed)throw new b(`Unable to join stage you are currently ${this.status}`);if(await c(this,er).joinStage(),e===Xe.Livestream&&await c(this,wi).joinRoom(c(this,Re),e),c(this,fr).setValue("stageStatus","ON_STAGE",!1),await w.emitAsync(C.JOIN_MEDIA_ROOM),c(this,fr).notify("stageStatus"),e===Xe.Livestream){const{peers:r}=await c(this,wi).getStagePeers();w.emit(C.SOCKET_PEERS,r)}}async leave(){if(!c(this,Re).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new b("Stage is disabled");if(!(this.status==="ON_STAGE"||this.status==="ACCEPTED_TO_JOIN_STAGE"))throw new b(`Unable to leave stage you are currently ${this.status}`);c(this,Re).setIsPinned(!1),await c(this,er).leaveStage(c(this,Re).userId),c(this,fr).setValue("stageStatus","OFF_STAGE",!1),await w.emitAsync(C.LEAVE_MEDIA_ROOM,"stageLeft"),c(this,fr).notify("stageStatus")}async kick(e){if(!c(this,Re).roomJoined)throw new b("Can`t kick participant without joining room");if(!c(this,Re).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new b("Stage is disabled");if(!c(this,Re).permissions.acceptStageRequests)throw l.error("DyteStage::kick::permission_denied"),new b("You do not have permissions for kick");return c(this,er).kick(e)}}er=new WeakMap,wi=new WeakMap,Re=new WeakMap,La=new WeakMap,Pr=new WeakMap,fr=new WeakMap,Ci=new WeakSet,Nd=async function(e){this.status!==e&&c(this,fr).setValue("stageStatus",e)},un([g.trace("DyteStage.getStageRequests")],ys.prototype,"getAccessRequests",1),un([g.trace("DyteStage.requestAccess")],ys.prototype,"requestAccess",1),un([g.trace("DyteStage.cancelRequestAccess")],ys.prototype,"cancelRequestAccess",1),un([g.trace("DyteStage.grantAccess")],ys.prototype,"grantAccess",1),un([g.trace("DyteStage.denyAccess")],ys.prototype,"denyAccess",1),un([g.trace("DyteStage.joinStage")],ys.prototype,"join",1),un([g.trace("DyteStage.leaveStage")],ys.prototype,"leave",1);function p0(s){return!(s.viewType==="LIVESTREAM"||s.viewType==="CHAT")}function lu(s){switch(s){case Br.UNSPECIFIED:return"OFF_STAGE";case Br.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case Br.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case Br.OFF_STAGE:return"OFF_STAGE";case Br.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var m0=Object.defineProperty,f0=Object.getOwnPropertyDescriptor,g0=(s,t,e,r)=>{for(var n=r>1?void 0:r?f0(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&m0(t,e,n),n};class ug{constructor(t,e,r,n,i){m(this,"stage");S(this,As,void 0);S(this,An,void 0);S(this,Ms,void 0);S(this,Fa,0);S(this,es,void 0);y(this,es,t),this.stage=new ys(t,n,i,e,r),y(this,Ms,e),y(this,As,n),y(this,An,i),this.setupEvents()}setupEvents(){c(this,es).subscribe("stageStatus",t=>{this.stage.emit("stageStatusUpdate",t)}),c(this,Ms).on($.grantStageAccess,()=>{c(this,As).permissions.stageAccess!==H.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),c(this,Ms).on($.peerStageStatusUpdate,t=>{t!==void 0&&(t.peerId===c(this,As).id?this.selfStageStatusHandler(t):this.peerStageStatusHandler(t))}),c(this,Ms).on($.denyStageAccess,()=>{c(this,As).permissions.stageAccess!==H.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),c(this,Ms).on($.getStageRequests,async t=>{var r;if(c(this,As).permissions.stageAccess!==H.Allowed)return;const e=(r=t==null?void 0:t.stageRequests)!=null?r:[];await w.emitAsync(C.GET_STAGE_REQUESTS,e),c(this,Fa)0&&this.stage.emit("newStageRequest",{count:e.length}),y(this,Fa,e.length),this.stage.emit("stageAccessRequestUpdate",e)})}getCurrentStageRequests(){return c(this,An).joined.toArray().filter(e=>e.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(e=>({displayName:e.name,userId:e.userId,peerId:e.id}))}async setStageStatus(t){this.stage.status!==t&&c(this,es).setValue("stageStatus",t)}selfStageStatusHandler(t){const e=lu(t.stageType),r=c(this,es).getValue("stageStatus");if(r!==e)switch(t.stageType){case 1:c(this,es).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.join();break;case 2:case 3:this.setStageStatus(r);break;case 0:case 4:default:c(this,es).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}async peerStageStatusHandler(t){const e=c(this,An).joined.get(t.peerId),r=c(this,An).viewMode==="ACTIVE_GRID";if(!e){l.warn("err::peerStageStatusUpdate: participant not found");return}switch(t.stageType){case 1:e.setStageStatus("ON_STAGE"),r&&w.emit(C.UPDATE_ACTIVE);break;case 2:e.setStageStatus("ACCEPTED_TO_JOIN_STAGE");break;case 3:e.setStageStatus("REQUESTED_TO_JOIN_STAGE");break;case 0:case 4:default:e.setStageStatus("OFF_STAGE"),r&&w.emit(C.UPDATE_ACTIVE);break}w.emit(C.UPDATE_PEER_STAGE_STATUS,{id:e.id,status:e.stageStatus})}}As=new WeakMap,An=new WeakMap,Ms=new WeakMap,Fa=new WeakMap,es=new WeakMap,g0([g.trace("DyteStage.setupEvents")],ug.prototype,"setupEvents",1);var v0=Object.defineProperty,y0=Object.getOwnPropertyDescriptor,Vc=(s,t,e,r)=>{for(var n=r>1?void 0:r?y0(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&v0(t,e,n),n};const Be={getPeer:14,getPeers:15,chatMessage:16,getRoomName:17,getDisplayTitle:18,getPluginInitiator:19,customPluginEventToParent:20,peerJoined:22,peerLeft:23,sendData:24,stageStatusUpdate:25,peerStageStatusUpdate:26};let si=(Av=class extends Zn{constructor(t,{baseURL:e,createdAt:r,description:n,id:i,name:a,organizationId:o,picture:d,private:u,published:h,staggered:p,tags:f,type:v,updatedAt:T},P,k,I,x){super();S(this,Mn);S(this,yt,void 0);m(this,"baseURL");m(this,"createdAt");m(this,"description");m(this,"id");m(this,"name");S(this,tr,void 0);S(this,bi,void 0);S(this,Pi,void 0);m(this,"organizationId");m(this,"picture");m(this,"private");m(this,"published");m(this,"staggered");m(this,"tags");m(this,"type");m(this,"updatedAt");S(this,ts,void 0);m(this,"config");S(this,Ri,void 0);m(this,"active");m(this,"iframes");m(this,"enabledBy");S(this,ki,void 0);y(this,ki,t),this.baseURL=e,this.createdAt=new Date(r),this.description=n,this.id=i,this.name=a,y(this,tr,k),this.organizationId=o,this.picture=d,this.private=u,this.published=h,this.staggered=p,this.tags=f,this.type=v,this.updatedAt=new Date(T),this.active=!1,this.iframes=new Map,y(this,yt,P),y(this,bi,I),y(this,Pi,x),this.enabledBy=""}sendIframeEvent(t){this.iframes.size&&this.iframes.forEach(e=>{const{iframe:r}=e;r&&(navigator.isReactNative?r.postMessage(JSON.stringify(t)):r.contentWindow.postMessage(t,"*"))})}async handleIframeMessage(t){var a;if(!this.active)return;const e=t,{payload:r,uuid:n,type:i}=e;switch(i){case j.customPluginEventToRoom:{c(this,yt).customPluginEventToRoom(this.id,r,n);break}case j.customPluginEventToPeers:{c(this,yt).customPluginEventToPeers(this.id,r.peerIds,r,n);break}case j.enablePluginForRoom:{c(this,yt).enablePluginForRoom(this.id,n);break}case j.enablePluginForPeers:{c(this,yt).enablePluginForPeers(this.id,r.peerIds,n);break}case j.disablePluginForRoom:{c(this,yt).disablePluginForRoom(this.id,n);break}case j.disablePluginForPeers:{c(this,yt).disablePluginForPeers(this.id,r.peerIds,n);break}case j.storeInsertKeys:{c(this,yt).storeInsertKeys(this.id,r.store,r.insertKeys,n);break}case j.storeGetKeys:{c(this,yt).storeGetKeys(this.id,r.store,r.getKeys,n);break}case j.storeDeleteKeys:{c(this,yt).storeDeleteKeys(this.id,r.store,r.deleteKeys,n);break}case j.storeDelete:{c(this,yt).storeDelete(this.id,r.store,n);break}case Be.chatMessage:{const{messagePayload:o,peerIds:d}=r;if(!c(this,Pi)){this.sendIframeEvent({type:Be.chatMessage,uuid:e.uuid,payload:{error:"Chat is disabled for this room."}});return}try{await c(this,Pi).sendMessage(o,d),this.sendIframeEvent({type:Be.chatMessage,uuid:e.uuid,payload:{success:!0}})}catch(u){this.sendIframeEvent({type:Be.chatMessage,uuid:e.uuid,payload:{error:u}})}break}case Be.getPeer:{let o;const{peerId:d}=r,u={...c(this,tr),isRecorder:(a=c(this,tr).permissions)==null?void 0:a.isRecorder,isHidden:c(this,tr).permissions.hiddenParticipant,stageStatus:c(this,tr).stageStatus};d?(o=c(this,bi).joined.get(r.peerId),c(this,tr).id===d&&(o=u)):o=u,this.sendIframeEvent({type:Be.getPeer,payload:{peer:o&&Fc(o)},uuid:e.uuid});break}case Be.getPeers:{const o=c(this,bi).joined.toArray().map(d=>Fc(d));this.sendIframeEvent({type:Be.getPeers,payload:{peers:o},uuid:e.uuid});break}case Be.getPluginInitiator:{this.sendIframeEvent({type:Be.getPluginInitiator,payload:{enabledBy:this.enabledBy},uuid:e.uuid});break}case Be.getDisplayTitle:{this.sendIframeEvent({type:Be.getDisplayTitle,payload:{displayTitle:c(this,Mn,Oo).meetingTitle},uuid:e.uuid});break}case Be.getRoomName:{this.sendIframeEvent({type:Be.getRoomName,payload:{roomName:c(this,Mn,Oo).roomName},uuid:e.uuid});break}case Be.customPluginEventToParent:{this.emit(e.payload.eventName,e.payload.data);break}}}sendData(t){this.active&&(l.info("DytePlugin::SendData",{plugin:{id:this.id,name:this.name,data:{eventName:t.eventName}}}),this.sendIframeEvent({type:Be.sendData,uuid:"",payload:t}))}removePluginView(t="default"){var n;const{iframe:e,listener:r}=(n=this.iframes.get(t))!=null?n:{};(e||r)&&(navigator.isReactNative?e.props.onMessage=void 0:window.removeEventListener("message",r),this.iframes.delete(t))}addPluginView(t,e="default"){var a;if(!c(this,Ri))throw l.error("DytePlugin::addPluginView::no_auth_token_set_for_plugin"),new b("No auth token set for plugin.");if(!t)throw l.error("DytePlugin::addPluginView::iframe_was_not_provided"),new b("Iframe was not provided.");this.removePluginView(e);const r=t,n=new URL(this.baseURL),i={auth:c(this,Ri),parent:navigator.isReactNative?this.baseURL:window.location.origin,backend:c(this,ki).getValue("apiBase"),pluginId:this.id,roomName:(a=c(this,Mn,Oo).roomName)!=null?a:"",displayTitle:c(this,Mn,Oo).meetingTitle};if(Object.keys(i).forEach(o=>{n.searchParams.set(o,i[o])}),r.src=n.href,r.allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",r.title=e,navigator.isReactNative)r.props.onMessage=o=>{this.handleIframeMessage(JSON.parse(o.nativeEvent.data))},this.iframes.set(e,{iframe:r});else{const o=async d=>{d.source===t.contentWindow&&await this.handleIframeMessage(d.data)};window.addEventListener("message",o),this.iframes.set(e,{iframe:r,listener:o})}}setActive(t){var e,r;if(this.active=t,t){this.emit("stateUpdate",{active:this.active,pluginId:this.id,bind:this.addPluginView.bind(this),views:(e=this.config)==null?void 0:e.views});return}this.active=!1,this.emit("stateUpdate",{active:this.active,pluginId:this.id,views:(r=this.config)==null?void 0:r.views})}async activateForSelf(){const t=We(),e=await t.authorizePlugin(this.id);y(this,Ri,e),y(this,ts,new Date);try{const r=await t.getPluginConfig(this.baseURL);this.config=r}catch(r){l.error("DytePlugin::activateForSelf",{error:r})}this.setActive(!0),this.emit("enabled")}deactivateForSelf(){Array.from(this.iframes.keys()).forEach(t=>{this.removePluginView(t)}),y(this,ts,void 0),this.iframes.clear(),this.setActive(!1),this.emit("closed")}async enable(){return this.activateForSelf()}disable(){return this.deactivateForSelf()}async activate(){var t,e;this.active||(e=(t=c(this,tr).permissions)==null?void 0:t.plugins)!=null&&e.canStart&&(c(this,yt).addPlugin(this.id,this.staggered),y(this,ts,new Date),l.info("plugin::activated",{plugin:{id:this.id,enabledBy:this.enabledBy,name:this.name}}))}async deactivate(){var t,e;this.active&&(!((e=(t=c(this,tr).permissions)==null?void 0:t.plugins)!=null&&e.canClose)&&this.enabledBy!==c(this,tr).id||(c(this,yt).removePlugin(this.id),l.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:c(this,ts)?new Date().getTime()-c(this,ts).getTime():0}}),y(this,ts,void 0)))}},yt=new WeakMap,tr=new WeakMap,bi=new WeakMap,Pi=new WeakMap,ts=new WeakMap,Ri=new WeakMap,ki=new WeakMap,Mn=new WeakSet,Oo=function(){return c(this,ki).getValue("roomNodeClient")},Av);Vc([Lt({maxInvocations:5,period:1})],si.prototype,"sendData",1),Vc([g.trace("DytePlugin.activatePlugin")],si.prototype,"activate",1),Vc([g.trace("DytePlugin.deactivatePlugin")],si.prototype,"deactivate",1),si=Vc([pt("0600")],si);class hg extends Map{constructor(e){const{onAddEvent:r,onDeleteEvent:n,onClearEvent:i}=e;super();S(this,ze,void 0);S(this,Dn,void 0);m(this,"onAddEvent");m(this,"onDeleteEvent");m(this,"onClearEvent");y(this,ze,new Zn),this.onAddEvent=r,this.onDeleteEvent=n,this.onClearEvent=i,y(this,Dn,new Map)}emit(e,...r){return c(this,ze).emit(e,...r)}on(e,r){return c(this,ze).on(e,r)}addListener(e,r){return c(this,ze).addListener(e,r)}off(e,r){return c(this,ze).off(e,r)}once(e,r){return c(this,ze).once(e,r)}prependListener(e,r){return c(this,ze).prependListener(e,r)}prependOnceListener(e,r){return c(this,ze).prependOnceListener(e,r)}removeListener(e,r){return c(this,ze).removeListener(e,r)}removeAllListeners(e){return c(this,ze).removeAllListeners(e)}listeners(e){return c(this,ze).listeners(e)}listenerCount(e){return c(this,ze).listenerCount(e)}getMaxListeners(){return c(this,ze).getMaxListeners()}setMaxListeners(e){return c(this,ze).setMaxListeners(e)}eventNames(){return c(this,ze).eventNames()}add(e,r=!0){return this.set(e.id,e,r)}set(e,r,n=!0){const i=super.set(e,r),a=(o,...d)=>{this.emit(o,r,...d)};return c(this,Dn).set(e,a),r.on("*",a),n&&c(this,ze).emit(this.onAddEvent,r),i}delete(e,r=!0,n=!1){const i=this.get(e);if(!i)return!1;i.removeListener("*",c(this,Dn).get(e));const a=super.delete(e);return n&&i.removeAllListeners(),r&&c(this,ze).emit(this.onDeleteEvent,i),a}clear(e=!0,r=!1){this.forEach(i=>{i.removeListener("*",c(this,Dn).get(i.id)),r&&i.removeAllListeners()});const n=super.clear();return e&&c(this,ze).emit(this.onClearEvent),n}toArray(){return Array.from(this.values())}}ze=new WeakMap,Dn=new WeakMap;class pg extends hg{constructor(){super({onAddEvent:"pluginAdded",onDeleteEvent:"pluginDeleted"})}add(t,e=!0){return super.add(t,e)}delete(t,e=!0,r=!1){return super.delete(t,e,r)}}var T0=Object.defineProperty,_0=Object.getOwnPropertyDescriptor,S0=(s,t,e,r)=>{for(var n=r>1?void 0:r?_0(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&T0(t,e,n),n};let uu=class{constructor(){m(this,"all");m(this,"active");this.all=new pg,this.active=new pg}};uu=S0([pt("0600")],uu);var E0=Object.defineProperty,w0=Object.getOwnPropertyDescriptor,$c=(s,t,e,r)=>{for(var n=r>1?void 0:r?w0(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&E0(t,e,n),n};const mg=(Mv=class{constructor(s,t,e,r){m(this,"plugins");S(this,rr,void 0);S(this,Ii,void 0);S(this,xa,void 0);y(this,rr,t),y(this,Ii,e),y(this,xa,s),this.plugins=r,this.setupEvents()}static async init(s,t,e,r,n,i,a){const o=new uu;return t.forEach(d=>{const u=new si(s,d,e,i,a,n);o.all.add(u)}),new mg(s,e,r,o)}async getRoomPlugins(){var t;const{plugins:s}=await c(this,rr).getActivePlugins();(t=this.plugins.active)==null||t.toArray().forEach(e=>{this.disablePlugin({id:e.id})}),await Promise.all(s.map(e=>this.enablePlugin({id:e.pluginId,enabledBy:e.enabledBy})))}async enablePlugin({id:s,enabledBy:t}){const e=this.plugins.all.get(s);e&&(await e.activateForSelf(),e.enabledBy=t)}async disablePlugin({id:s}){const t=this.plugins.all.get(s);t&&t.deactivateForSelf()}sendIframeEvent(s,t,e,r){const n=this.plugins.all.get(t);n&&n.sendIframeEvent({type:s,uuid:e,payload:r})}broadcastIframeEvent(s,t){this.plugins.active.forEach(e=>{this.sendIframeEvent(s,e.id,"",t)})}setupEvents(){this.plugins.all.on("stateUpdate",({active:s,id:t})=>{if(s){this.plugins.active.add(this.plugins.all.get(t));return}this.plugins.active.delete(t)}),w.onAsync(C.SOCKET_SERVICE_ROOM_JOINED,async()=>{await this.getRoomPlugins(),l.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to fetch plugins.")}),c(this,rr).on(j.addPlugin,async s=>{var e;const t=s.pluginId;(e=this.plugins.all.get(t))!=null&&e.active||await this.enablePlugin({id:t,enabledBy:s.enabledBy})}),c(this,rr).on(j.removePlugin,async s=>{var e;const t=s.pluginId;(e=this.plugins.all.get(t))!=null&&e.active&&await this.disablePlugin({id:t})}),[j.enablePluginForPeers,j.enablePluginForRoom].forEach(s=>{c(this,rr).on(s,async(t,e)=>{this.sendIframeEvent(s,t.pluginId,e,{enabledBy:t.enabledBy})})}),[j.disablePluginForPeers,j.disablePluginForRoom].forEach(s=>{c(this,rr).on(s,async(t,e)=>{this.sendIframeEvent(s,t.pluginId,e,{disabledBy:t.disabledBy})})}),[j.customPluginEventToPeers,j.customPluginEventToRoom].forEach(s=>{c(this,rr).on(s,async(t,e)=>{this.sendIframeEvent(s,t.pluginId,e,{data:JSON.parse(new TextDecoder().decode(t.pluginData))})})}),[j.storeInsertKeys,j.storeGetKeys,j.storeDeleteKeys].forEach(s=>{c(this,rr).on(s,async(t,e)=>{var n;const r=(n=t.storeItems)==null?void 0:n.map(i=>{var a;return{timestamp:i.timestamp,peerId:i.peerId,payload:JSON.parse((a=i.payload)!=null&&a.length?new TextDecoder().decode(i.payload):"{}"),key:i.storeKey}});this.sendIframeEvent(s,t.pluginId,e,{storeName:t.storeName,storeItems:r})})}),c(this,rr).on(j.storeDelete,async(s,t)=>{this.sendIframeEvent(j.storeDelete,s.pluginId,t,{storeName:s.storeName})}),c(this,Ii).on(Ue.sendMessageToPeers,s=>{const t=ur==null?void 0:ur.formatSocketServiceMessage(s.message);this.broadcastIframeEvent(Be.chatMessage,{message:t})}),c(this,Ii).on(Ue.sendMessageToRoom,s=>{const t=ur==null?void 0:ur.formatSocketServiceMessage(s.message);this.broadcastIframeEvent(Be.chatMessage,{message:t})}),w.on(C.PEER_JOINED_INTERNAL,s=>{const t=Fc(s);this.broadcastIframeEvent(Be.peerJoined,t)}),w.on(C.PEER_CLOSED,s=>{this.broadcastIframeEvent(Be.peerLeft,s)}),w.on(C.UPDATE_PEER_STAGE_STATUS,s=>{this.broadcastIframeEvent(Be.peerStageStatusUpdate,s)}),c(this,xa).subscribe("stageStatus",s=>{this.broadcastIframeEvent(Be.stageStatusUpdate,s)})}},rr=new WeakMap,Ii=new WeakMap,xa=new WeakMap,Mv);let ga=mg;$c([g.trace("PluginController.getRoomPlugins")],ga.prototype,"getRoomPlugins",1),$c([g.trace("PluginController.enableForSelf")],ga.prototype,"enablePlugin",1),$c([g.trace("PluginController.disableForSelf")],ga.prototype,"disablePlugin",1),$c([g.trace("PluginController.setupEvents")],ga.prototype,"setupEvents",1);class C0{constructor(){m(this,"roomJoined");m(this,"socketJoinAttempted");m(this,"mediaJoinAttempted");m(this,"socketState");m(this,"mediaState");this.roomJoined=!1,this.socketJoinAttempted=!1,this.mediaJoinAttempted=!1,this.socketState={state:void 0,reconnected:!1,reconnectionAttempt:void 0},this.mediaState={consuming:void 0,producing:void 0}}get joinAttempted(){return this.mediaJoinAttempted||this.socketJoinAttempted}updateSocketConnectionState(t,e){let r;const{reconnected:n}=this.socketState;switch(t){case"connected":r={state:"connected",reconnected:n,reconnectionAttempt:void 0};break;case"disconnected":r={state:"disconnected",reconnected:!1,reconnectionAttempt:0};break;case"reconnected":r={state:"connected",reconnected:!0,reconnectionAttempt:void 0};break;case"reconnecting":r={state:"reconnecting",reconnected:n,reconnectionAttempt:0};break;case"reconnectAttempt":r={state:"reconnecting",reconnected:n,reconnectionAttempt:e};break;case"failed":r={state:"failed",reconnected:n,reconnectionAttempt:void 0};break}r&&(w.emit(C.SOCKET_STATE_UPDATE,r),this.socketState=r)}}var b0=Object.defineProperty,P0=Object.getOwnPropertyDescriptor,va=(s,t,e,r)=>{for(var n=r>1?void 0:r?P0(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&b0(t,e,n),n};let hn=(Dv=class extends Ht{constructor(t,e){super();S(this,Mi);S(this,Ai,void 0);S(this,Ua,void 0);m(this,"recordingPeerIds",[]);m(this,"recordings",[]);y(this,Ua,t),y(this,Ai,e)}get recordingState(){return this.recordings.some(t=>t.state==="RECORDING")?"RECORDING":this.recordings.some(t=>t.state==="PAUSED")?"PAUSED":this.recordings.some(t=>t.state==="STARTING")?"STARTING":this.recordings.some(t=>t.state==="STOPPING")?"STOPPING":"IDLE"}updateRecordings(t){this.recordings=t,this.emit("recordingUpdate",this.recordingState)}async start(t){if(!c(this,Ai).permissions.canRecord)throw l.error("DyteRecording::start::permission_denied"),new b("User does not have permission to start recording");if((t==null?void 0:t.allowMultiple)!==!0&&(this.recordingState==="STARTING"||this.recordingState==="RECORDING"||this.recordingState==="STOPPING"))throw l.error("DyteRecording::start::recording_in_progress",{recording:{state:this.recordingState}}),new b(`Cant start recording, recordingState irregular: ${this.recordingState}`);try{const e=We(),{recording:r={}}=c(this,Ua).getValue("defaults"),n=await e.startRecording(r,t==null?void 0:t.allowMultiple);this.updateRecordings([...this.recordings,{id:n,state:"STARTING",type:"BROWSER"}])}catch(e){throw l.error("DyteRecording::stop::recording_failed_to_start",{error:e}),new b("Error while starting recording")}}async stop(t){await je(this,Mi,Ld).call(this,"stop",["RECORDING","PAUSED"],t)}async pause(t){await je(this,Mi,Ld).call(this,"pause",["RECORDING"],t)}async resume(t){await je(this,Mi,Ld).call(this,"resume",["PAUSED"],t)}},Ai=new WeakMap,Ua=new WeakMap,Mi=new WeakSet,Ld=async function(t,e,r){if(!c(this,Ai).permissions.canRecord)throw l.error("DyteRecording::stop::permission_denied"),new b("User does not have permission to stop recording");let n=[];if(r!==void 0){const i=this.recordings.find(a=>a.id===r);if(i===void 0)throw new b("Could not find the specified recording");if(e.includes(i.state)){l.error("DyteRecording::stop::recording_not_in_expected_state",{recording:{state:i.state}});return}n.push(i)}else n=this.recordings.filter(i=>e.includes(i.state));n.forEach(async i=>{const a=i.state;t==="stop"&&(i.state="STOPPING",this.emit("recordingUpdate","STOPPING"));try{await We().updateRecording(i.id,t)}catch(o){throw l.error("DyteRecording::stop::recording_failed_to_stop",{error:o}),i.state!==a&&(i.state=a,this.emit("recordingUpdate",a)),new b("Error while stopping recording")}})},Dv);va([g.trace("DyteRecording.start")],hn.prototype,"start",1),va([g.trace("DyteRecording.stop")],hn.prototype,"stop",1),va([g.trace("DyteRecording.stop")],hn.prototype,"pause",1),va([g.trace("DyteRecording.stop")],hn.prototype,"resume",1),hn=va([pt("1000")],hn);var R0=Object.defineProperty,k0=Object.getOwnPropertyDescriptor,I0=(s,t,e,r)=>{for(var n=r>1?void 0:r?k0(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&R0(t,e,n),n};class fg{constructor(t,e,r){m(this,"recording");m(this,"room");S(this,Sd,void 0);y(this,Sd,t),this.recording=new hn(t,e),this.room=r,this.setupEvents()}getRecordingTypeFromProtoType(t){let e;switch(t){case an.BROWSER:e="BROWSER";break;case an.COMPOSITE:e="COMPOSITE";break;case an.TRACK:e="TRACK";break;default:e="BROWSER"}return e}setupEvents(){w.on(C.ROOM_STATE,t=>{t.activeRecordings.length!==0?this.recording.updateRecordings(t.activeRecordings.map(e=>{const r=this.getRecordingTypeFromProtoType(e.recordingType);return{id:e.recordingId,state:e.recordingStatus,type:r}})):this.recording.recordings.length&&this.recording.updateRecordings([])}),this.room.on($.recordingStarted,t=>{let e=!1;const r=[...this.recording.recordings];if(r.forEach(n=>{n.id===t.recordingId&&(e=!0,n.state="RECORDING")}),e===!1){const n=this.getRecordingTypeFromProtoType(t.recordingType);r.push({id:t.recordingId,state:"RECORDING",type:n})}this.recording.updateRecordings(r)}),this.room.on($.recordingPaused,t=>{const e=[...this.recording.recordings];e.forEach(r=>{r.id===t.recordingId&&(r.state="PAUSED")}),this.recording.updateRecordings(e)}),this.room.on($.recordingStopped,t=>{const e=[...this.recording.recordings.filter(r=>r.id!==t.recordingId)];this.recording.updateRecordings(e)})}}Sd=new WeakMap,I0([g.trace("RecordingController.setupEvents")],fg.prototype,"setupEvents",1);class A0{static hasFeature(t){var e;return(e=J.hasFeature(t))!=null?e:!1}static getFeatureValue(t){return J.getValue(t)}static getAllFeatures(){return J.getAllFlags()}}class hu{constructor(t,e,r){m(this,"logger");m(this,"features");m(this,"browserSpecs");m(this,"callStats");this.logger=t,this.features=e,this.browserSpecs=Se,this.callStats=r}static init(t){return new hu(l,A0,t)}}class pu{constructor(t){m(this,"internals");this.internals=t}static async init(){const t=hu.init(U);return new pu(t)}}var M0=Object.defineProperty,D0=Object.getOwnPropertyDescriptor,jt=(s,t,e,r)=>{for(var n=r>1?void 0:r?D0(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&M0(t,e,n),n};class Ft extends Zn{constructor(e,r,n=Hc,i=!0){super();S(this,st,void 0);S(this,ht,void 0);S(this,tt,void 0);S(this,Rr,void 0);S(this,sr,void 0);S(this,Va,void 0);S(this,Ed,void 0);m(this,"audioUpdateInProgress");m(this,"videoUpdateInProgress");y(this,Ed,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,y(this,st,new bg(e,r)),y(this,ht,new oD(c(this,st),void 0,n)),y(this,tt,new mD(c(this,st),void 0,n)),y(this,sr,new uD(c(this,st))),y(this,Rr,new dD(c(this,st))),y(this,Va,i),c(this,ht).on("trackMuted",this.onAudioTrackMuted.bind(this)),c(this,ht).on("trackChanged",this.onAudioTrackChanged.bind(this)),c(this,tt).on("trackChanged",this.onVideoTrackChanged.bind(this)),c(this,tt).on("trackEnded",this.onVideoTrackEnded.bind(this)),c(this,sr).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}async onVisibilityChange(){U.tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?U.browserBackgrounded():(U.browserForegrounded(),await this.setupSpeaker())}async repopulateAvailableDevices(){return!0}async setupStreams({audio:e,video:r}){var a;let n,i;if(e&&r)try{const o=await c(this,st).getAudioAndVideoTrack();n=o.audioTrack,i=o.videoTrack}catch(o){l.error("LocalMediaHandler::init::Failed to get audio video tracks",{error:o})}if(!n&&e)try{n=await c(this,st).getAudioTrack(!1)}catch(o){l.error("LocalMediaHandler::init::Failed to get audio track",{error:o})}if(!i&&r)try{i=await c(this,st).getVideoTrack()}catch(o){l.error("LocalMediaHandler::init::Failed to get video track",{error:o})}await c(this,ht).setMediaTrack(n),await c(this,tt).setMediaTrack(i);try{await c(this,Rr).setupSpeaker()}catch(o){}if(i){const o=await this.getDeviceById(i.getSettings().deviceId);U.onSafeInitialization(()=>{U.selectedDevice("VIDEO",o)})}if(n){const o=await this.getDeviceById(n.getSettings().deviceId);U.onSafeInitialization(()=>{U.selectedDevice("AUDIO",o)})}(a=c(this,Rr).currentDevice)!=null&&a.deviceId&&U.onSafeInitialization(()=>{U.selectedDevice("SPEAKER",c(this,Rr).currentDevice)}),c(this,st).onDeviceChange((o,d,u)=>{this.onDeviceChange(d,u)})}getCurrentDevices(){return{audio:c(this,ht).currentDevice,video:c(this,tt).currentDevice,speaker:c(this,Rr).currentDevice}}get permissions(){return c(this,st).permissions}getAllDevices(){return c(this,st).getAvailableDevices()}getDeviceById(e,r){return c(this,st).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return c(this,ht).mediaTrack}get audioTrack(){return c(this,ht).transformedMediaTrack}get audioEnabled(){return c(this,ht).trackEnabled}async enableAudio(){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{await c(this,ht).unmuteTrack()}catch(e){}finally{this.audioUpdateInProgress=!1}}}disableAudio(){c(this,ht).muteTrack()}getAudioDevices(e){return c(this,st).getAudioInputDevices(e)}async setAudioDevice(e){await c(this,ht).setDevice(e),e!=null&&e.deviceId&&U.onSafeInitialization(()=>{U.selectedDevice("AUDIO",e)}),this.emit("AUDIO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}setupSpeaker(){return c(this,Rr).setupSpeaker()}async setSpeakerDevice(e){await c(this,Rr).setupSpeaker(e),e!=null&&e.deviceId&&U.onSafeInitialization(()=>{U.selectedDevice("SPEAKER",e)}),this.emit("DEVICE_CHANGE",{device:e})}onVideoTrackChanged(){this.emit("VIDEO_TRACK_CHANGE")}onVideoTrackEnded(){this.emit("VIDEO_TRACK_CHANGE")}get rawVideoTrack(){return c(this,tt).mediaTrack}get videoTrack(){return c(this,tt).transformedMediaTrack}get videoEnabled(){return c(this,tt).trackEnabled}async enableVideo(){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{await c(this,tt).unmuteTrack()}catch(e){}finally{this.videoUpdateInProgress=!1}}}disableVideo(){c(this,tt).disableTrack()}getVideoDevices(e){return c(this,st).getVideoInputDevices(e)}async setVideoDevice(e){await c(this,tt).setDevice(e),e!=null&&e.deviceId&&U.onSafeInitialization(()=>{U.selectedDevice("VIDEO",e)}),this.emit("VIDEO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async updateVideoConstraints(e){await c(this,tt).updateConstraints(e)}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:c(this,sr).audioMediaTrack,video:c(this,sr).videoMediaTrack}}get screenShareEnabled(){return c(this,sr).trackEnabled}async enableScreenShare(){await c(this,sr).enableScreenShare()}async disableScreenShare(){c(this,sr).disableScreenShare()}async updateScreenshareConstraints(e){await c(this,sr).updateConstraints(e)}getSpeakerDevices(e){return c(this,st).getAudioOutputDevices(e)}addAudioMiddleware(e){return c(this,ht).addMiddleware(e)}removeAudioMiddleware(e){return c(this,ht).removeMiddleware(e)}addVideoMiddleware(e){return c(this,tt).addMiddleware(e)}removeVideoMiddleware(e){return c(this,tt).removeMiddleware(e)}setVideoMiddlewareGlobalConfig(e){return c(this,tt).setVideoMiddlewareGlobalConfig(e)}destruct(){c(this,ht).disableTrack(),c(this,tt).disableTrack(),c(this,tt).terminateMiddlewareWebWorker(),c(this,sr).disableScreenShare(),c(this,st).destruct()}async onDeviceChange(e,r){var n,i;this.emit("DEVICE_LIST_UPDATED",e),!(r||!c(this,Va))&&((n=e==null?void 0:e.added)==null||n.forEach(async a=>{var o;a&&!Hc(a)&&(a.kind==="audioinput"&&((o=this.audioTrack)==null?void 0:o.enabled)===!0?await this.setAudioDevice(a):a.kind==="audiooutput"&&await this.setSpeakerDevice(a))}),(i=e==null?void 0:e.removed)==null||i.forEach(async a=>{var o;if(a.kind==="audiooutput"&&((o=this.getCurrentDevices().speaker)==null?void 0:o.deviceId)===a.deviceId){const d=(await this.getSpeakerDevices()).find(u=>u.deviceId!==a.deviceId);d&&await this.setSpeakerDevice(d)}}))}removeAllTracks(){this.destruct()}async removeDocumentEventListeners(){document.removeEventListener("visibilitychange",this.onVisibilityChange)}}st=new WeakMap,ht=new WeakMap,tt=new WeakMap,Rr=new WeakMap,sr=new WeakMap,Va=new WeakMap,Ed=new WeakMap,jt([g.trace("MediaHandler.setupStreams")],Ft.prototype,"setupStreams",1),jt([g.trace("MediaHandler.enableAudio")],Ft.prototype,"enableAudio",1),jt([g.trace("MediaHandler.disableAudio")],Ft.prototype,"disableAudio",1),jt([g.trace("MediaHandler.setAudioDevice")],Ft.prototype,"setAudioDevice",1),jt([g.trace("MediaHandler.enableVideo")],Ft.prototype,"enableVideo",1),jt([g.trace("MediaHandler.disableVideo")],Ft.prototype,"disableVideo",1),jt([g.trace("MediaHandler.setVideoDevice")],Ft.prototype,"setVideoDevice",1),jt([g.trace("MediaHandler.updateVideoConstraints")],Ft.prototype,"updateVideoConstraints",1),jt([g.trace("MediaHandler.enableScreenShare")],Ft.prototype,"enableScreenShare",1),jt([g.trace("MediaHandler.disableScreenShare")],Ft.prototype,"disableScreenShare",1),jt([g.trace("MediaHandler.updateScreenshareConstraints")],Ft.prototype,"updateScreenshareConstraints",1),jt([g.trace("MediaHandler.destruct")],Ft.prototype,"destruct",1),jt([g.trace("MediaHandler.onDeviceChange")],Ft.prototype,"onDeviceChange",1);function Bc(s,t,e){switch(!0){case Se.isChromiumBased():switch(t){case"NotAllowedError":return e.includes("by system")?"SYSTEM_DENIED":s==="screenshare"?"CANCELED":"DENIED";case"NotReadableError":default:return"COULD_NOT_START"}case Se.isSafari():switch(t){case"NotAllowedError":return"DENIED";default:return"COULD_NOT_START"}case Se.isFirefox():switch(t){case"NotFoundError":case"NotReadableError":return"SYSTEM_DENIED";case"NotAllowedError":return"DENIED";case"AbortError":default:return"COULD_NOT_START"}default:return"COULD_NOT_START"}}const O0=["virtual","emulator","krisp","solstice conference","teams","manycam","blackHole"];function Hc(s){const t=s.label.toLowerCase();return Se._bowser.getOSName()==="macOS"&&t.includes("iphone")?(l.log("isVirtualDevice::ignore_macos_continuity"),!0):O0.some(e=>t.includes(e))}async function N0(s,t){if(!(s!=null&&s.length))return t;const e=new AudioContext,r=await Promise.all(s==null?void 0:s.map(a=>a(e))),n=e.createMediaStreamSource(new MediaStream([t])),i=e.createMediaStreamDestination();try{let a=n;for(let o=0;o(t,e)=>(s.set(t,e),e),gg=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,vg=536870912,yg=vg*2,F0=(s,t)=>e=>{const r=t.get(e);let n=r===void 0?e.size:rgg)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;e.has(n);)n=Math.floor(Math.random()*gg);return s(e,n)},Tg=new WeakMap,x0=L0(Tg),qc=F0(x0,Tg),U0=s=>s.method!==void 0&&s.method==="call",V0=s=>s.error===null&&typeof s.id=="number",jc=((s,t)=>{let e=null;return()=>{if(e!==null)return e;const r=new Blob([t],{type:"application/javascript; charset=utf-8"}),n=URL.createObjectURL(r);return e=s(n),setTimeout(()=>URL.revokeObjectURL(n)),e}})(s=>{const t=new Map([[0,()=>{}]]),e=new Map([[0,()=>{}]]),r=new Map,n=new Worker(s);return n.addEventListener("message",({data:u})=>{if(U0(u)){const{params:{timerId:h,timerType:p}}=u;if(p==="interval"){const f=t.get(h);if(typeof f=="number"){const v=r.get(f);if(v===void 0||v.timerId!==h||v.timerType!==p)throw new Error("The timer is in an undefined state.")}else if(typeof f!="undefined")f();else throw new Error("The timer is in an undefined state.")}else if(p==="timeout"){const f=e.get(h);if(typeof f=="number"){const v=r.get(f);if(v===void 0||v.timerId!==h||v.timerType!==p)throw new Error("The timer is in an undefined state.")}else if(typeof f!="undefined")f(),e.delete(h);else throw new Error("The timer is in an undefined state.")}}else if(V0(u)){const{id:h}=u,p=r.get(h);if(p===void 0)throw new Error("The timer is in an undefined state.");const{timerId:f,timerType:v}=p;r.delete(h),v==="interval"?t.delete(f):e.delete(f)}else{const{error:{message:h}}=u;throw new Error(h)}}),{clearInterval:u=>{const h=qc(r);r.set(h,{timerId:u,timerType:"interval"}),t.set(u,h),n.postMessage({id:h,method:"clear",params:{timerId:u,timerType:"interval"}})},clearTimeout:u=>{const h=qc(r);r.set(h,{timerId:u,timerType:"timeout"}),e.set(u,h),n.postMessage({id:h,method:"clear",params:{timerId:u,timerType:"timeout"}})},setInterval:(u,h=0)=>{const p=qc(t);return t.set(p,()=>{u(),typeof t.get(p)=="function"&&n.postMessage({id:null,method:"set",params:{delay:h,now:performance.now(),timerId:p,timerType:"interval"}})}),n.postMessage({id:null,method:"set",params:{delay:h,now:performance.now(),timerId:p,timerType:"interval"}}),p},setTimeout:(u,h=0)=>{const p=qc(e);return e.set(p,u),n.postMessage({id:null,method:"set",params:{delay:h,now:performance.now(),timerId:p,timerType:"timeout"}}),p}}},`(()=>{"use strict";const e=new Map,t=new Map,r=(e,t)=>{let r,o;const i=performance.now();r=i,o=e-Math.max(0,i-t);return{expected:r+o,remainingDelay:o}},o=(e,t,r,i)=>{const s=performance.now();s>r?postMessage({id:null,method:"call",params:{timerId:t,timerType:i}}):e.set(t,setTimeout(o,r-s,e,t,r,i))};addEventListener("message",(i=>{let{data:s}=i;try{if("clear"===s.method){const{id:r,params:{timerId:o,timerType:i}}=s;if("interval"===i)(t=>{const r=e.get(t);if(void 0===r)throw new Error('There is no interval scheduled with the given id "'.concat(t,'".'));clearTimeout(r),e.delete(t)})(o),postMessage({error:null,id:r});else{if("timeout"!==i)throw new Error('The given type "'.concat(i,'" is not supported'));(e=>{const r=t.get(e);if(void 0===r)throw new Error('There is no timeout scheduled with the given id "'.concat(e,'".'));clearTimeout(r),t.delete(e)})(o),postMessage({error:null,id:r})}}else{if("set"!==s.method)throw new Error('The given method "'.concat(s.method,'" is not supported'));{const{params:{delay:i,now:n,timerId:a,timerType:d}}=s;if("interval"===d)((t,i,s)=>{const{expected:n,remainingDelay:a}=r(t,s);e.set(i,setTimeout(o,a,e,i,n,"interval"))})(i,a,n);else{if("timeout"!==d)throw new Error('The given type "'.concat(d,'" is not supported'));((e,i,s)=>{const{expected:n,remainingDelay:a}=r(e,s);t.set(i,setTimeout(o,a,t,i,n,"timeout"))})(i,a,n)}}}}catch(e){postMessage({error:{message:e.message},id:s.id,result:null})}}))})();`),_g=s=>jc().clearInterval(s),$0=s=>jc().clearTimeout(s),Sg=(s,t)=>jc().setInterval(s,t),B0=Object.freeze(Object.defineProperty({__proto__:null,clearInterval:_g,clearTimeout:$0,setInterval:Sg,setTimeout:(s,t)=>jc().setTimeout(s,t)},Symbol.toStringTag,{value:"Module"}));class H0{constructor(){S(this,On,void 0)}terminateMiddlewareWebWorker(){if(c(this,On))try{_g(c(this,On)),y(this,On,void 0)}catch(t){l.debug("WorkerTimers::terminateMiddlewareWebWorker::failed")}}async getTransformedVideoTrack(t,e,r){if(!(t!=null&&t.length))return e;const n=document.createElement("canvas"),i=await Promise.all(t==null?void 0:t.map(p=>p({canvas:n,WorkerTimers:B0})));if(r.disablePerFrameCanvasRendering)return n.captureStream().getVideoTracks()[0];const a=document.createElement("video"),o=new MediaStream;o.addTrack(e);const d=n.getContext("2d");a.srcObject=o,a.autoplay=!0,this.terminateMiddlewareWebWorker();const u=async()=>{if(e.enabled===!1||e.readyState==="ended"){this.terminateMiddlewareWebWorker(),a.remove(),n.remove();return}try{d.drawImage(a,0,0);for(let p=0;p{n.width=a.width||e.getSettings().width,n.height=a.width||e.getSettings().height,y(this,On,Sg(u,50))},!1),n.captureStream().getVideoTracks()[0]}}On=new WeakMap;const Eg={gross:{width:{ideal:192},height:{ideal:144}},qvga:{width:{ideal:384},height:{ideal:288}},pvga:{width:{ideal:480},height:{ideal:360}},vga:{width:{ideal:640},height:{ideal:480}},hd:{width:{ideal:1280},height:{ideal:720}},hd_cropped:{width:{ideal:900},height:{ideal:720}},fhd:{width:{ideal:1920},height:{ideal:1080}}},wg={320:[{rid:"q",maxBitrate:25e4,maxFramerate:24,scalabilityMode:"L1T1"}],640:[{rid:"q",scaleResolutionDownBy:2,maxBitrate:25e4,maxFramerate:24,scalabilityMode:"L1T1"},{rid:"h",maxBitrate:7e5,maxFramerate:30,scalabilityMode:"L1T1"}],1280:[{rid:"q",scaleResolutionDownBy:2,maxBitrate:5e5,maxFramerate:24,scalabilityMode:"L1T1"},{rid:"h",maxBitrate:13e5,maxFramerate:30,scalabilityMode:"L1T1"}]},q0={320:[{rid:"q",maxBitrate:25e4,maxFramerate:24,scalabilityMode:"L1T1"}],640:[{rid:"h",maxBitrate:7e5,maxFramerate:30,scalabilityMode:"L1T1"}],1280:[{rid:"h",maxBitrate:14e5,maxFramerate:30,scalabilityMode:"L1T1"}]},Cg={320:[{rid:"q",maxBitrate:25e4,maxFramerate:24,scalabilityMode:"L1T1"}],640:[{rid:"q",scaleResolutionDownBy:2,maxBitrate:25e4,maxFramerate:24,scalabilityMode:"L1T1"},{rid:"h",maxBitrate:7e5,maxFramerate:30,scalabilityMode:"L1T1"}],1280:[{rid:"q",scaleResolutionDownBy:2,maxBitrate:5e5,maxFramerate:24,scalabilityMode:"L1T1"},{rid:"h",maxBitrate:13e5,maxFramerate:30,scalabilityMode:"L1T1"}]};var Y=(s=>(s.WEBCAM="webcam",s.MIC="mic",s.SCREENSHARE_VIDEO="screenshare_video",s.SCREENSHARE_AUDIO="screenshare_audio",s))(Y||{});const j0=Cw(),ni=wr(j0.config.media);function G0(s){var e,r;const t={};return s.audio&&(t.audio={enableStereo:(e=s.audio.enableStereo)!=null?e:!1,enableHighBitrate:(r=s.audio.enableHighBitrate)!=null?r:!1}),t.video=s.video.quality,t}class J0{constructor(t,e){S(this,Nn,void 0);S(this,wd,void 0);m(this,"getScreenShareConstraints",()=>{var u,h,p,f,v,T,P,k,I;const t=(u=c(this,Nn))==null?void 0:u.screenshare,e=(p=(h=t==null?void 0:t.width)==null?void 0:h.max)!=null?p:1920,r=(v=(f=t==null?void 0:t.height)==null?void 0:f.max)!=null?v:1080,n=(P=(T=t==null?void 0:t.frameRate)==null?void 0:T.max)!=null?P:5;let i=(I=(k=t==null?void 0:t.frameRate)==null?void 0:k.ideal)!=null?I:5;const a=t==null?void 0:t.displaySurface,o=t==null?void 0:t.selfBrowserSurface;J.getValue(X.VAL_MIN_FRAMERATE)&&(i=parseInt(J.getValue(X.VAL_MIN_FRAMERATE),10));let d={width:{max:e},height:{max:r},frameRate:{ideal:i,max:n}};if(J.hasFeature(X.SCREENSHARE_CONSTRAINTS)){const x=J.getValue(X.SCREENSHARE_CONSTRAINTS);d=JSON.parse(x)}return a!==void 0&&["monitor","browser","window"].includes(a)&&(d={...d,displaySurface:a}),o!==void 0&&(d={...d,selfBrowserSurface:o}),{audio:!0,video:d}});m(this,"getAudioConstraints",t=>{var i,a,o,d,u,h,p,f;const e={},r=(i=c(this,Nn))==null?void 0:i.audio,n=r!=null&&r.enableStereo?2:1;return Se.isFirefox()||Se.isWebKitBased()?(e.audio={deviceId:t,autoGainControl:(a=r==null?void 0:r.autoGainControl)!=null?a:!0,echoCancellation:(o=r==null?void 0:r.echoCancellation)!=null?o:!0,noiseSuppression:(d=r==null?void 0:r.noiseSupression)!=null?d:!0,channelCount:n},e):(e.audio={},e.audio.optional=[t?{sourceId:t}:{sourceId:"default"},{channelCount:n},{echoCancellation:(u=r==null?void 0:r.echoCancellation)!=null?u:!0},{googEchoCancellation:(h=r==null?void 0:r.echoCancellation)!=null?h:!0},{googAutoGainControl:(p=r==null?void 0:r.autoGainControl)!=null?p:!0},{googNoiseSuppression:(f=r==null?void 0:r.noiseSupression)!=null?f:!0},{googHighpassFilter:!0}],e)});m(this,"getVideoConstraints",t=>{var i,a,o;const e={},r=(i=c(this,Nn))==null?void 0:i.video;let n=Eg.vga;if(typeof r=="string"?n=Eg[r]:r!==void 0&&(n.height.ideal=r.height.ideal,n.width.ideal=r.width.ideal),n.frameRate={ideal:(o=(a=n.frameRate)==null?void 0:a.ideal)!=null?o:24},Se.isChromiumBased()&&(n.frameRate.max=30),J.hasFeature(X.VIDEO_CONSTRAINTS)){const d=J.getValue(X.VIDEO_CONSTRAINTS);n=JSON.parse(d)}return e.video=n,typeof e.video=="boolean"||(t?e.video.deviceId={exact:t}:e.video.facingMode="user"),e});y(this,wd,t),y(this,Nn,e)}getUpdatedVideoConstraints(t){return t}}Nn=new WeakMap,wd=new WeakMap;class mu extends Error{constructor(e,r,n){super(r);m(this,"constraints");m(this,"name");this.name=e,this.constraints=n}}class W0{constructor(){m(this,"permissions");this.permissions={audio:"NOT_REQUESTED",video:"NOT_REQUESTED",screenshare:"NOT_REQUESTED"}}async getAudioInputDevices(t){let e=t;return t||(e=await this.getAvailableDevices()),e.filter(r=>r.kind==="audioinput")}async getVideoInputDevices(t){let e=t;return t||(e=await this.getAvailableDevices()),e.filter(r=>r.kind==="videoinput")}async getAudioOutputDevices(t){let e=t;return t||(e=await this.getAvailableDevices()),e.filter(r=>r.kind==="audiooutput")}}var K0=Object.defineProperty,z0=Object.getOwnPropertyDescriptor,hr=(s,t,e,r)=>{for(var n=r>1?void 0:r?z0(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&K0(t,e,n),n};let Gt=(Ov=class extends W0{constructor(t,e){super();m(this,"availableDevices");S(this,Di,void 0);S(this,kr,void 0);S(this,Cd,void 0);y(this,Cd,t),y(this,kr,new J0(t,e)),y(this,Di,new AbortController),this.availableDevices=[],this.getAvailableDevices()}get constraintsBuilder(){return c(this,kr)}async destruct(){var t;(t=c(this,Di))==null||t.abort()}handlePermissionErrors(t,e){const r=Bc(t,e.name,e.message);return this.permissions[t]=r,w.emit(C.MEDIA_PERMISSION_ERROR,{message:r,constraints:e.constraints,kind:t}),r}async getAudioAndVideoTrack(){const t={audio:c(this,kr).getAudioConstraints().audio,video:c(this,kr).getVideoConstraints().video};try{l.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(t)});const e=await navigator.mediaDevices.getUserMedia(t);l.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(t)});const r=e.getAudioTracks()[0];let n=e.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",J.hasFeature(X.OBS_QUALITY)&&n.label.includes("OBS Virtual")){const o=(await this.getVideoInputDevices()).find(d=>d.label.includes("OBS Virtual"));n=await this.getVideoTrack(o.deviceId)}return w.emit(C.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),w.emit(C.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:r,videoTrack:n}}catch(e){throw l.error("WebMediaInterface.getAudioAndVideoTrack",{error:e}),new b("Couldnt fetch audio and video track")}}async getAudioTrack(t,e){let r=await this.getAudioInputDevices();if(r.length===0)throw this.permissions.audio="NO_DEVICES_AVAILABLE",w.emit(C.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),new b("No audio devices available");const n=async i=>{let a;try{r=r.filter(d=>d.deviceId!==i),a=c(this,kr).getAudioConstraints(i),l.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(a)});const[o]=(await navigator.mediaDevices.getUserMedia(a)).getAudioTracks();return l.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(a)}),o}catch(o){const d=Bc("audio",o.name,o.message),u=new mu(o.name,o.message,a);if(d==="COULD_NOT_START"){const h=r.shift();if(!h)throw u;return n(h.deviceId)}throw u}};try{const i=await n(e);return i.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",w.emit(C.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"})),i}catch(i){throw i.constraints&&this.handlePermissionErrors("audio",i),new b(i.message,"1601")}}async getVideoTrack(t){var o;const e=J.hasFeature(X.OBS_QUALITY),r=(o=await this.getCurrentDeviceLabel(t))==null?void 0:o.includes("OBS Virtual"),n=e&&r,i=await this.getVideoInputDevices();if(i.length===0)throw this.permissions.video="NO_DEVICES_AVAILABLE",w.emit(C.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),new b("No video devices available");const a=async d=>{try{let u=d;const{video:h}=u;n&&typeof h!="boolean"&&(u={video:{deviceId:h.deviceId}}),l.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(u)});const[p]=(await navigator.mediaDevices.getUserMedia(u)).getVideoTracks();if(n&&typeof h!="boolean"&&typeof h.width=="object"){const{width:f,height:v}=p.getSettings(),{ideal:T}=h.width;p.applyConstraints({width:{ideal:T},height:{ideal:Math.floor(v*T/f)},frameRate:h.frameRate})}return l.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(u)}),p}catch(u){const h=Bc("video",u.name,u.message),p=new mu(u.name,u.message,d);if(h==="COULD_NOT_START"){if(!i.shift())throw p;return a({video:d.video})}throw p}};try{const d=c(this,kr).getVideoConstraints(t),u=await a(d);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",w.emit(C.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"})),u}catch(d){throw d.constraints&&this.handlePermissionErrors("video",d),new b(d.message,"1601")}}async getScreenShareTracks(){const t=async e=>{try{l.info("getDisplayMediaWithoutTimeout::requesting_display_media",{constraints:JSON.stringify(e)}),U.screenShareRequested();const r=await navigator.mediaDevices.getDisplayMedia(e);return l.info("getDisplayMediaWithoutTimeout::received_display_media",{constraints:JSON.stringify(e)}),r}catch(r){const n=Bc("video",r.name,r.message),i=new mu(r.name,r.message,e),a={video:!0};if(jC(e,a)||!J.hasFeature(X.SCREEENSHARE_CONSTRAINTS_RETRY))throw i;if(n==="COULD_NOT_START")return t(a);throw i}};try{const e=c(this,kr).getScreenShareConstraints(),r=await t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",w.emit(C.MEDIA_PERMISSION_UPDATE,{message:this.permissions.screenshare,kind:"screenshare"})),{audioTrack:r.getAudioTracks()[0],videoTrack:r.getVideoTracks()[0]}}catch(e){throw e.constraints&&this.handlePermissionErrors("screenshare",e),new b(e.message,"1601")}}async getCurrentDeviceLabel(t){const e=await this.getDevice(t||"default");return e==null?void 0:e.label}async getAvailableDevices(){try{const t=await navigator.mediaDevices.enumerateDevices();return this.availableDevices=t,t}catch(t){throw l.error("enumerate_devices_failed",{error:t}),new b("Failed to get available devices")}}async getAvailableDevicesByKind(t){try{return(await navigator.mediaDevices.enumerateDevices()).filter(({kind:e})=>t===e)}catch(e){throw l.error("enumerate_devices_failed",{error:e}),new b("Failed to get available devices by kind")}}async getDevice(t){try{return(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.deviceId===t)[0]}catch(e){throw l.error("enumerate_devices_failed",{error:e}),new b("Failed to get device")}}async onDeviceChange(t){Se.supportsDeviceChangeEvent()&&navigator.mediaDevices.addEventListener("devicechange",async e=>{var u,h;const r=p=>`${p.kind}-${p.deviceId}`,n=this.availableDevices,i=new Set(n.map(p=>r(p))),a=await this.getAvailableDevices(),o=new Set(a.map(p=>r(p))),d={added:a.filter(p=>!i.has(r(p))),removed:n.filter(p=>!o.has(r(p))),devices:a};if((u=d.added)!=null&&u.length||(h=d.removed)!=null&&h.length){l.info("repopulated_full_device_list",{devices:JSON.stringify(a)});const p=[...d.added,...d.removed];U.onSafeInitialization(async()=>{p.some(f=>f.kind==="audioinput")&&U.devices("AUDIO",a==null?void 0:a.filter(f=>f.kind==="audioinput")),p.some(f=>f.kind==="videoinput")&&U.devices("VIDEO",a==null?void 0:a.filter(f=>f.kind==="videoinput")),p.some(f=>f.kind==="audiooutput")&&U.devices("SPEAKER",a==null?void 0:a.filter(f=>f.kind==="audiooutput"))}),t(e,d,!1)}},{signal:c(this,Di).signal})}},Di=new WeakMap,kr=new WeakMap,Cd=new WeakMap,Ov);hr([g.trace("WebMediaInterface.destruct")],Gt.prototype,"destruct",1),hr([g.trace("WebMediaInterface.handlePermissionErrors")],Gt.prototype,"handlePermissionErrors",1),hr([g.trace("WebMediaInterface.getAudioAndVideoTrack")],Gt.prototype,"getAudioAndVideoTrack",1),hr([g.trace("WebMediaInterface.getAudioTrack")],Gt.prototype,"getAudioTrack",1),hr([g.trace("WebMediaInterface.getVideoTrack")],Gt.prototype,"getVideoTrack",1),hr([g.trace("WebMediaInterface.getScreenShareTracks")],Gt.prototype,"getScreenShareTracks",1),hr([g.trace("WebMediaInterface.getAvailableDevices")],Gt.prototype,"getAvailableDevices",1),hr([g.trace("WebMediaInterface.getAvailableDevicesByKind")],Gt.prototype,"getAvailableDevicesByKind",1),hr([g.trace("WebMediaInterface.getDevice")],Gt.prototype,"getDevice",1),hr([g.trace("WebMediaInterface.onDeviceChange")],Gt.prototype,"onDeviceChange",1),Gt=hr([pt("1600")],Gt);const bg=Gt,fu={setItem:(s,t)=>{try{localStorage.setItem(s,t)}catch(e){l.error("LocalStorage::setItem::crashed",{error:e,localStorage:{key:s,value:t}})}},getItem:s=>{try{return localStorage.getItem(s)}catch(t){l.error("LocalStorage::getItem::crashed",{error:t,localStorage:{key:s}})}return null}},Y0=(s=0)=>new Promise(t=>setTimeout(t,s)),Q0=(s,t,e)=>{const r=typeof e=="number"?e:250,n=s.createMediaStreamSource(t),i=s.createAnalyser();i.fftSize=2048,n.connect(i);const a=new Uint8Array(i.fftSize);let o=!1;setTimeout(()=>{o=!0},r);function d(){return o?Promise.resolve(!0):(i.getByteTimeDomainData(a),a.some(u=>u!==128&&u!==0)?Promise.resolve(!1):Y0().then(d))}return d().then(u=>(n.disconnect(),u),u=>{throw n.disconnect(),u})},X0=typeof AudioContext!="undefined"?AudioContext:null;class gu{constructor(t){m(this,"_AudioContext");m(this,"audioContext");m(this,"_audioContextRefContainers");const e={AudioContext:X0,...t};Object.defineProperties(this,{_AudioContext:{value:e.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:gu}})}getOrCreate(t){if(!this._audioContextRefContainers.has(t)&&(this._audioContextRefContainers.add(t),this._AudioContext&&!this.audioContext))try{this.audioContext=new this._AudioContext}catch(e){}return this.audioContext}release(t){this._audioContextRefContainers.has(t)&&(this._audioContextRefContainers.delete(t),!this._audioContextRefContainers.size&&this.audioContext&&(this.audioContext.close(),this.audioContext=null))}}const Pg=new gu,Z0=3,eD=250;function tD(s){const t={},e=Pg.getOrCreate(t);let r=Z0;function n(){return r-=1,Q0(e,s.srcObject,eD).then(i=>i?r>0?n():!0:!1).catch(()=>!0)}return n().finally(()=>{Pg.release(t)})}async function Rg(s){const t=new Audio,e=new MediaStream;e.addTrack(s),t.srcObject=e;let r=!1;try{const n=t.play();n&&await n,r=await tD(t),r&&l.info("checkIfAudioTrackIsSilent::silence_detected")}catch(n){l.error("checkIfAudioTrackIsSilent::failed_to_detect_silence",{error:n})}finally{t.pause(),t.remove()}return r}var rD=Object.defineProperty,sD=Object.getOwnPropertyDescriptor,nD=(s,t,e,r)=>{for(var n=r>1?void 0:r?sD(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&rD(t,e,n),n};let vu=class extends Zn{constructor(t,e,r){super();m(this,"constructorName",this.constructor.name);m(this,"userSelectedDevice");m(this,"mediaInterface");m(this,"isNonPreferredDevice");m(this,"_mediaTrack");m(this,"transformedMediaTrack");m(this,"middlewares",[]);m(this,"currentDevice");this.mediaInterface=t,e&&this.setMediaTrack(e),this.userSelectedDevice=void 0,this.isNonPreferredDevice=r,this.onTrackEnded=this.onTrackEnded.bind(this),this.onTrackMuted=this.onTrackMuted.bind(this)}disableTrack(){var t,e;this.removeMediaTrackListeners(),(t=this._mediaTrack)==null||t.stop(),this._mediaTrack=void 0,(e=this.transformedMediaTrack)==null||e.stop(),this.transformedMediaTrack=void 0}get mediaTrack(){return this._mediaTrack}async setMediaTrack(t){const e=r=>{l.error(`${this.constructorName}.setMediaTrack.error`,{error:r})};try{this.disableTrack()}catch(r){e(r)}this._mediaTrack=await this.conditionallyChangeTrack(t),await this.setTransformedTrack();try{this.addMediaTrackListeners(),await this.setCurrentDevice()}catch(r){e(r)}}get trackEnabled(){return!!this.mediaTrack&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled}muteTrack(){if(!this.mediaTrack){l.warn("BaseMediaHandler.muteTrack Tried muting with no track present");return}this.transformedMediaTrack&&(this.transformedMediaTrack.enabled=!1),this.mediaTrack.enabled=!1}async unmuteTrack(){try{this.mediaTrack?this.mediaTrack.enabled=!0:await this.enableTrack(!1)}catch(t){throw l.error(`${this.constructorName}.unmuteTrack.error`,{error:t}),this.disableTrack(),new b("Failed to unmute track")}}async setCurrentDevice(){var t;if(!this.mediaTrack){this.currentDevice=void 0;return}((t=this.currentDevice)==null?void 0:t.deviceId)!==this.mediaTrack.getSettings().deviceId&&(this.currentDevice=await this.mediaInterface.getDevice(this.mediaTrack.getSettings().deviceId))}async addMiddleware(t){if(Se.isWebKitBased()&&!J.hasFeature(X.ALLOW_SAFARI_MEDIA_MIDDLEWARES))return{success:!1,message:"Middlewares are not supported in this WebKit engine based browser."};if(this.middlewares.includes(t))return{success:!1,message:"This middleware has been applied, already. Skipping."};try{return this.middlewares.push(t),this.trackEnabled&&await this.setTransformedTrack(),{success:!0,message:"Successfully added the middleware."}}catch(e){return l.error("While adding middleware",{error:e}),this.removeMiddleware(t),{success:!1,message:e==null?void 0:e.message}}}async removeMiddleware(t){const e=this.middlewares.indexOf(t,0);if(e>-1)try{return this.middlewares.splice(e,1),await this.setTransformedTrack(!0),{success:!0,message:"Successfully removed the middleware."}}catch(r){return l.error("While removing middleware",{error:r}),{success:!1,message:r==null?void 0:r.message}}return{success:!1,message:"No such middleware was found. Skipping."}}addMediaTrackListeners(){var t,e,r;this.mediaTrack&&(l.info(`${this.constructorName}.addMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(r=this.mediaTrack)==null?void 0:r.kind}`),this.mediaTrack.addEventListener("ended",this.onTrackEnded),this.mediaTrack.addEventListener("mute",this.onTrackMuted))}removeMediaTrackListeners(){var t,e,r;this.mediaTrack&&(l.info(`${this.constructorName}.removeMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(r=this.mediaTrack)==null?void 0:r.kind}`),l.info(`${this.constructorName}.removeMediaTrackListeners`),this.mediaTrack.removeEventListener("ended",this.onTrackEnded),this.mediaTrack.removeEventListener("mute",this.onTrackMuted))}};vu=nD([pt("1600")],vu);const kg=vu;var iD=Object.defineProperty,aD=Object.getOwnPropertyDescriptor,yu=(s,t,e,r)=>{for(var n=r>1?void 0:r?aD(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&iD(t,e,n),n};const Tu="[Dyte]nonSilentDeviceLabels";class Gc extends kg{async setDevice(t){if(!t)throw l.warn("AudioMediaHandler.setDevice No device received"),new b("No device received!","1603");if(t.kind!=="audioinput")throw l.warn("AudioMediaHandler.setDevice Received non audio device"),new b("Non audio device received while setting device!","1603");try{const e=this.trackEnabled;this.userSelectedDevice=t.deviceId,await this.setMediaTrack(await this.mediaInterface.getAudioTrack(!e,t.deviceId))}catch(e){throw l.error("AudioMediaHandler.setDevice.error",{error:e}),this.disableTrack(),new b(e.message,"1604")}}async enableTrack(t){if(this.trackEnabled){l.warn("AudioMediaHandler.enableTrack Track already enabled!");return}const e=await this.mediaInterface.getAudioTrack(t,this.userSelectedDevice);await this.setMediaTrack(e)}async setTransformedTrack(t){var e;if(!t&&!((e=this.middlewares)!=null&&e.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=await N0(this.middlewares,this.mediaTrack),this.emit("trackChanged")}catch(r){l.error("AudioMediaHandler.setTransformedTrack",{error:r}),this.transformedMediaTrack=this.mediaTrack}}async onTrackEnded(){l.info("AudioMediaHandler.TrackEnded"),this.emit("trackEnded");const t=this.mediaTrack.enabled;this.disableTrack(),await this.enableTrack(!t),await this.setTransformedTrack(),this.emit("trackChanged")}onTrackMuted(){l.info("AudioMediaHandler.TrackMuted"),this.emit("trackMuted")}async conditionallyChangeTrack(t){var o;if(!t||this.userSelectedDevice)return t;let e=t;const r=await this.mediaInterface.getAudioInputDevices(),n=this.isNonPreferredDevice?r.filter(d=>d&&!this.isNonPreferredDevice(d)):r;if(!(n!=null&&n.length))return e;n.find(d=>d.deviceId===t.getSettings().deviceId)||(e.stop(),l.info("localmediahandler::setupstreams::found_audio_non_preferred"),e=await this.mediaInterface.getAudioTrack(!1,n[0].deviceId));const i=JSON.parse(fu.getItem(Tu));if(i!=null&&i.devices.some(d=>d.label===e.label))return e;if(!await Rg(e)){const d=(o=i==null?void 0:i.devices.concat({label:e.label}))!=null?o:[{label:e.label}];return fu.setItem(Tu,JSON.stringify({devices:d})),e}l.info("AudioMediaHandler.conditionallyChangeTrack.DetectedSilentTrack");const a=e.getSettings().deviceId;return n.filter(d=>d.deviceId!==a).some(async d=>{if(e=await this.mediaInterface.getAudioTrack(!1,d.deviceId),!await Rg(e)){const u=i.devices.concat({label:e.label});return fu.setItem(Tu,JSON.stringify({devices:u})),l.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return l.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1}),e}}yu([g.trace("AudioMediaHandler.setTransformedTrack")],Gc.prototype,"setTransformedTrack",1),yu([g.trace("AudioMediaHandler.onTrackEnded")],Gc.prototype,"onTrackEnded",1),yu([g.trace("AudioMediaHandler.conditionallyChangeTrack")],Gc.prototype,"conditionallyChangeTrack",1);const oD=Gc;class cD{constructor(t){S(this,Oi,void 0);m(this,"currentDevice");y(this,Oi,t)}async setupSpeaker(t){var r;if(!(c(this,Oi)instanceof bg))return;let e=t;if(t||([e]=(await c(this,Oi).getAvailableDevicesByKind("audiooutput")).sort((i,a)=>(Hc(i)?0:1)-(Hc(a)?0:1))),!e)throw new b("No speaker found");((r=this.currentDevice)==null?void 0:r.deviceId)!==e.deviceId&&(this.currentDevice=e,document.querySelectorAll("audio").forEach(async n=>{if(typeof n.sinkId!="undefined"&&this.currentDevice.deviceId&&n.sinkId!==this.currentDevice.deviceId)try{await n.setSinkId(this.currentDevice.deviceId)}catch(i){}}))}}Oi=new WeakMap;const dD=cD;class lD extends Zn{constructor(e){super();m(this,"mediaInterface");m(this,"audioMediaTrack");m(this,"videoMediaTrack");this.mediaInterface=e}get trackEnabled(){return!!this.videoMediaTrack}async enableScreenShare(){var e,r;try{const{audioTrack:n,videoTrack:i}=await this.mediaInterface.getScreenShareTracks();if(this.audioMediaTrack=n,this.videoMediaTrack=i,this.addMediaTrackListeners(),((r=(e=this.mediaInterface)==null?void 0:e.permissions)==null?void 0:r.screenshare)==="ACCEPTED")return;this.mediaInterface.permissions&&(this.mediaInterface.permissions.screenshare="ACCEPTED",w.emit(C.MEDIA_PERMISSION_UPDATE,{message:this.mediaInterface.permissions.screenshare,kind:"screenshare"}))}catch(n){}}disableScreenShare(){var e,r;this.removeMediaTrackListeners(),(e=this.audioMediaTrack)==null||e.stop(),(r=this.videoMediaTrack)==null||r.stop(),this.videoMediaTrack=void 0,this.audioMediaTrack=void 0}async updateConstraints(e){if(!this.videoMediaTrack)throw new b("No media track enabled!");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new b("update constraints not supported for non web clients","1100");try{this.videoMediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),this.addMediaTrackListeners()}catch(n){l.error("ScreenShareHandler.updateConstraints.error",{error:n})}}addMediaTrackListeners(){var e,r;(e=this.videoMediaTrack)==null||e.addEventListener("ended",this.onTrackEnded.bind(this)),Se.isWebKitBased()&&((r=this.videoMediaTrack)==null||r.addEventListener("mute",this.onTrackEnded.bind(this)))}removeMediaTrackListeners(){var e,r;(e=this.videoMediaTrack)==null||e.removeEventListener("ended",this.onTrackEnded),(r=this.videoMediaTrack)==null||r.removeEventListener("mute",this.onTrackEnded)}onTrackEnded(){this.emit("trackEnded")}}const uD=lD;var hD=Object.defineProperty,pD=Object.getOwnPropertyDescriptor,Jc=(s,t,e,r)=>{for(var n=r>1?void 0:r?pD(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&hD(t,e,n),n};class ya extends kg{constructor(e,r,n){super(e,r,n);S(this,Ni,void 0);S(this,$a,{disablePerFrameCanvasRendering:!1});y(this,Ni,new H0)}async setDevice(e){if(!e)throw l.warn("VideoMediaHandler.setDevice No device received"),new b("No device received!");if(e.kind!=="videoinput")throw l.warn("VideoMediaHandler.setDevice Received non video device",{devices:[e]}),new b("Non video device received while setting video device!");if(this.userSelectedDevice=e.deviceId,!(this.mediaTrack&&this.mediaTrack.enabled)){l.warn("VideoMediaHandler.setDevice Tried switching device with video disabled",{devices:[e]}),this.currentDevice=e;return}try{await this.setMediaTrack(await this.mediaInterface.getVideoTrack(this.userSelectedDevice))}catch(r){throw l.error("VideoMediaHandler.setDevice.error",{error:r}),this.disableTrack(),new b("Failed to change device")}}async enableTrack(){if(this.trackEnabled){l.warn("VideoMediaHandler.enableTrack Track already enabled!");return}await this.setMediaTrack(await this.mediaInterface.getVideoTrack(this.userSelectedDevice))}async setTransformedTrack(e){var r;if(!e&&!((r=this.middlewares)!=null&&r.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=await c(this,Ni).getTransformedVideoTrack(this.middlewares,this.mediaTrack,c(this,$a)),this.emit("trackChanged")}catch(n){l.error("VideoMediaHandler.setTransformedTrack",{error:n}),this.transformedMediaTrack=this.mediaTrack}}async setVideoMiddlewareGlobalConfig(e){y(this,$a,e)}async updateConstraints(e){if(!this._mediaTrack)throw new b("No media track enabled!");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new b("update constraints not supported for non web clients","1100");try{this._mediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),await this.setTransformedTrack(),this.addMediaTrackListeners(),await this.setCurrentDevice()}catch(n){l.error("VideoMediaHandler.updateConstraints.error",{error:n})}}terminateMiddlewareWebWorker(){c(this,Ni).terminateMiddlewareWebWorker()}async onTrackEnded(){l.info("VideoMediaHandler.TrackEnded"),this.disableTrack(),this.emit("trackEnded")}onTrackMuted(){l.info("VideoMediaHandler.TrackMuted"),this.emit("trackMuted")}async conditionallyChangeTrack(e){if(!e||this.userSelectedDevice)return e;let r=e;const n=await this.mediaInterface.getVideoInputDevices(),i=this.isNonPreferredDevice?n.filter(a=>!this.isNonPreferredDevice(a)):n;return!(i!=null&&i.length)||window.FAST_DYTE||i.find(a=>a.deviceId===e.getSettings().deviceId)||(r.stop(),l.info("localmediahandler::setupstreams::found_video_non_preferred"),r=await this.mediaInterface.getVideoTrack(i[0].deviceId)),r}}Ni=new WeakMap,$a=new WeakMap,Jc([g.trace("VideoMediaHandler.setTransformedTrack")],ya.prototype,"setTransformedTrack",1),Jc([g.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],ya.prototype,"setVideoMiddlewareGlobalConfig",1),Jc([g.trace("VideoMediaHandler.onTrackEnded")],ya.prototype,"onTrackEnded",1),Jc([g.trace("VideoMediaHandler.conditionallyChangeTrack")],ya.prototype,"conditionallyChangeTrack",1);const mD=ya,Ig=wr(Rl()),Fi=class{constructor(t){S(this,Wt,void 0);S(this,Ln,void 0);S(this,Ba,void 0);S(this,Li,void 0);if(!t)throw new b("Could not load preset.");y(this,Wt,t.config),y(this,Ba,t.name),y(this,Ln,t.ui||wr(Rl().ui)),y(this,Li,t.permissions.plugins.config)}static fromResponse(t){return new Fi(t)}static default(){return new Fi(Ig)}static init(t,e=!0){return!t||e?new Fi(Ig):new Fi(t)}get setupScreen(){return{isEnabled:!0}}get waitingRoom(){return{isEnabled:!0}}get controlBar(){return{isEnabled:!0,elements:{chat:!0,fullscreen:!0,invite:!1,layout:!1,participants:!0,plugins:!0,polls:!0,reactions:!1,screenshare:!0}}}get header(){return{isEnabled:!0,elements:{logo:c(this,Ln).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return c(this,Wt).viewType}get maxVideoStreams(){return c(this,Wt).maxVideoStreams}get maxScreenShareCount(){return c(this,Wt).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(c(this,Li)).filter(t=>c(this,Li)[t].disabled)}get designTokens(){return c(this,Ln).designTokens}get configDiff(){return c(this,Ln).configDiff}get mediaConstraints(){var t,e,r,n,i,a,o,d,u,h,p,f,v,T,P,k,I,x,V,O,W,Q,oe,ve;return{audio:{enableStereo:(n=(r=(e=(t=c(this,Wt))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.enableStereo)!=null?n:ni.audio.enableStereo,enableHighBitrate:(d=(o=(a=(i=c(this,Wt))==null?void 0:i.media)==null?void 0:a.audio)==null?void 0:o.enableHighBitrate)!=null?d:ni.audio.enableHighBitrate},video:{quality:(f=(p=(h=(u=c(this,Wt))==null?void 0:u.media)==null?void 0:h.video)==null?void 0:p.quality)!=null?f:ni.video.quality,frameRate:(k=(P=(T=(v=c(this,Wt))==null?void 0:v.media)==null?void 0:T.video)==null?void 0:P.frameRate)!=null?k:ni.video.frameRate},screenshare:{quality:(O=(V=(x=(I=c(this,Wt))==null?void 0:I.media)==null?void 0:x.screenshare)==null?void 0:V.quality)!=null?O:ni.screenshare.quality,frameRate:(ve=(oe=(Q=(W=c(this,Wt))==null?void 0:W.media)==null?void 0:Q.screenshare)==null?void 0:oe.frameRate)!=null?ve:ni.screenshare.frameRate}}}get name(){return c(this,Ba)}};let _u=Fi;Wt=new WeakMap,Ln=new WeakMap,Ba=new WeakMap,Li=new WeakMap;var fD=Object.defineProperty,gD=Object.getOwnPropertyDescriptor,Ag=(s,t,e,r)=>{for(var n=r>1?void 0:r?gD(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&fD(t,e,n),n};class Su extends Ht{constructor(e){super();S(this,xi,void 0);m(this,"state","IDLE");m(this,"playbackUrl");m(this,"viewerCount");y(this,xi,e),this.viewerCount=0}setLivestreamState(e){const r=this.state;this.state=e,r!==e&&this.emitCurrentLivestreamState()}emitCurrentLivestreamState(){this.emit("livestreamUpdate",this.state)}async start(){if(!c(this,xi).permissions.canLivestream)throw l.error("DyteLivestream::start::permission_denied"),new b("User does not have permission to start livestreaming");this.setLivestreamState("STARTING");try{const r=await We().startLivestreaming();this.playbackUrl=r}catch(e){throw l.error("DyteRecording::stop::livestream_failed_to_start",{error:e}),this.setLivestreamState("IDLE"),new b("Error while starting livestream")}}async stop(){if(!c(this,xi).permissions.canLivestream)throw l.error("DyteLivestream::stop::permission_denied"),new b("User does not have permission to stop livestreaming");if(this.state!=="LIVESTREAMING")throw l.error("DyteLivestream::stop::inconsistent_state"),new b("Livestream not started yet");try{this.setLivestreamState("STOPPING"),await We().stopLivestreaming()}catch(e){throw l.error("DyteLivestream::stop::livestream_failed_to_stop",{error:e}),this.setLivestreamState("STOPPING"),new b("Error while stopping livestream")}}}xi=new WeakMap,Ag([g.trace("livestream.start")],Su.prototype,"start",1),Ag([g.trace("livestream.stop")],Su.prototype,"stop",1);var vD=Object.defineProperty,yD=Object.getOwnPropertyDescriptor,TD=(s,t,e,r)=>{for(var n=r>1?void 0:r?yD(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&vD(t,e,n),n};class Mg{constructor(t,e){m(this,"livestream");S(this,Ui,void 0);S(this,Ds,void 0);this.livestream=new Su(t),y(this,Ds,e),this.setupEvents()}async fetchInitialLivestreamingState(){const t=We(),{status:e,playbackUrl:r}=await t.getActiveLivestream();this.livestream.playbackUrl=r,e==="LIVE"&&this.livestream.setLivestreamState("LIVESTREAMING")}setupEvents(){c(this,Ds).on($.startedLivestream,t=>{this.livestream.playbackUrl=t.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING")}),c(this,Ds).on($.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),c(this,Ds).on($.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),c(this,Ds).on($.roomPeerCount,t=>{this.livestream.viewerCount=t.count,this.livestream.emit("viewerCountUpdate",t.count)}),w.on(C.PEER_JOINED_INTERNAL,async t=>{var e;((e=t.flags)==null?void 0:e.hiddenParticipant)===!0&&t.recorderType==="LIVESTREAMER"&&(y(this,Ui,t.id),this.livestream.setLivestreamState("LIVESTREAMING"))}),w.on(C.PEER_CLOSED,t=>{t.id===c(this,Ui)&&(y(this,Ui,void 0),this.livestream.setLivestreamState("IDLE"))}),w.onAsync(C.LEAVE_MEDIA_ROOM,async()=>{this.livestream.playbackUrl||(l.info("Fetching livestreaming state on leave stage"),await this.fetchInitialLivestreamingState())}),w.on(C.SOCKET_SERVICE_ROOM_JOINED,async()=>{try{await this.fetchInitialLivestreamingState()}catch(t){l.error("Error: LivestreamController.fetchLivestream")}})}}Ui=new WeakMap,Ds=new WeakMap,TD([g.trace("LivestreamController.setupEvents")],Mg.prototype,"setupEvents",1);var _D=Object.defineProperty,SD=Object.getOwnPropertyDescriptor,Ta=(s,t,e,r)=>{for(var n=r>1?void 0:r?SD(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&_D(t,e,n),n};const _a={maxInvocations:5,period:1};class ii{constructor({name:t,socketHandler:e,meetingId:r}){S(this,bd);m(this,"name","");S(this,Tt,{});S(this,Os,"");S(this,Ns,void 0);m(this,"volatile");m(this,"rateLimitConfig",{maxInvocations:5,period:1});m(this,"bulkRateLimitConfig",{maxInvocations:5,period:1});m(this,"listeners",{});this.name=t,y(this,Ns,e),y(this,Os,r)}async set(t,e,r=!0,n=!1){c(this,Tt)[t]=e,r&&c(this,Ns).storeInsertKeys(c(this,Os),this.name,[{key:t,payload:e}]),n&&(this.listeners[t]&&this.listeners[t].forEach(i=>i({[t]:c(this,Tt)[t]})),this.listeners["*"]&&this.listeners["*"].forEach(i=>i({[t]:c(this,Tt)[t]})))}async bulkSet(t){t.forEach(({key:e,payload:r})=>{c(this,Tt)[e]=r}),c(this,Ns).storeInsertKeys(c(this,Os),this.name,t)}async update(t,e,r=!0){je(this,bd,Gv).call(this,t,e,r)}async delete(t,e=!0,r=!1){if(c(this,Tt)[t]&&delete c(this,Tt)[t],e)return c(this,Ns).storeDeleteKeys(c(this,Os),this.name,[{key:t}]);r&&(this.listeners[t]&&(this.listeners[t].forEach(n=>n({[t]:void 0})),delete this.listeners[t]),this.listeners["*"]&&this.listeners["*"].forEach(n=>n({[t]:void 0})))}async bulkDelete(t){return t.forEach(({key:e})=>{c(this,Tt)[e]&&delete c(this,Tt)[e]}),c(this,Ns).storeDeleteKeys(c(this,Os),this.name,t)}get(t){if(c(this,Tt)[t])return c(this,Tt)[t]}getAll(){return c(this,Tt)}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get bulkRateLimits(){return this.bulkRateLimitConfig}updateBulkRateLimits(t,e){this.bulkRateLimitConfig.maxInvocations=t,this.bulkRateLimitConfig.period=e}subscribe(t,e){if(this.listeners[t]){this.listeners[t].push(e);return}this.listeners[t]=[e]}unsubscribe(t,e){var r;if(e){this.listeners[t]=((r=this.listeners[t])==null?void 0:r.filter(n=>n!==e))||[];return}this.listeners[t]&&delete this.listeners[t]}populate(t){y(this,Tt,t)}}Tt=new WeakMap,Os=new WeakMap,Ns=new WeakMap,bd=new WeakSet,Gv=function(t,e,r=!0){let n;const i=c(this,Tt)[t],a=Object.prototype.toString.call(e),o=Object.prototype.toString.call(i);if(a!==o){this.set(t,e);return}switch(o){case"[object Array]":n=[...i,...e];break;case"[object Object]":n={...i,...e};break;case"[object Map]":n=new Map([...i,...e]);break;case"[object Set]":n=new Set([...i,...e]);break;default:n=e;break}this.set(t,n,r)},Ta([Lt(_a,"rateLimitConfig")],ii.prototype,"set",1),Ta([Lt(_a,"bulkRateLimitConfig")],ii.prototype,"bulkSet",1),Ta([Lt(_a,"rateLimitConfig")],ii.prototype,"update",1),Ta([Lt(_a,"rateLimitConfig")],ii.prototype,"delete",1),Ta([Lt(_a,"bulkRateLimitConfig")],ii.prototype,"bulkDelete",1);class ED{constructor(t,e){S(this,Ha);S(this,Pd);m(this,"stores",new Map);S(this,Fn,void 0);S(this,xn,"");S(this,qa,void 0);S(this,Ls,new Map);y(this,Fn,e),y(this,xn,t.getValue("meetingId")),y(this,qa,t),je(this,Pd,Jv).call(this)}create(t){const e=new ii({name:t,socketHandler:c(this,Fn),meetingId:c(this,xn)});return c(this,Fn).storeGetKeys(c(this,xn),t,[]),new Promise((n,i)=>{const a=setTimeout(()=>i(Error("Failed")),3e3);c(this,Ls).set(t,{rejectTimeout:a,resolve:n,store:e})})}}Fn=new WeakMap,xn=new WeakMap,Ha=new WeakSet,Yu=function(){return c(this,qa).getValue("peerId")},qa=new WeakMap,Ls=new WeakMap,Pd=new WeakSet,Jv=function(){[j.storeInsertKeys,j.storeGetKeys,j.storeDeleteKeys].forEach(t=>{c(this,Fn).on(t,async e=>{var i,a;if(e.pluginId!==c(this,xn))return;const r=(i=e.storeItems)==null?void 0:i.map(o=>{var d;return{timestamp:o.timestamp,peerId:o.peerId,payload:JSON.parse((d=o.payload)!=null&&d.length?new TextDecoder().decode(o.payload):"{}"),key:o.storeKey}});if(t===j.storeGetKeys){const o=c(this,Ls).get(e.storeName),d=this.stores.get(e.storeName)||(o==null?void 0:o.store);c(this,Ls).get(e.storeName)&&(this.stores.set(e.storeName,o.store),o.resolve(d),clearTimeout(o.rejectTimeout),c(this,Ls).delete(e.storeName)),r.forEach(u=>{d.set(u.key,u.payload,!1,!1)});return}const n=this.stores.get(e.storeName)||((a=c(this,Ls).get(e.storeName))==null?void 0:a.store);n!==void 0&&(t===j.storeInsertKeys&&r.forEach(({key:o,peerId:d,payload:u})=>{d===c(this,Ha,Yu)&&t!==j.storeGetKeys||n.set(o,u,!1,!0)}),t===j.storeDeleteKeys&&r.forEach(({key:o,peerId:d})=>{d!==c(this,Ha,Yu)&&n.delete(o,!1,!0)}))})})};function pn(s){var t,e,r,n,i,a,o,d,u,h,p,f,v;return s?{media:{audio:{enabled:s.audioEnabled,trackId:(t=s.audioTrack)==null?void 0:t.id,permission:"mediaPermissions"in s?(e=s.mediaPermissions)==null?void 0:e.audio:null},video:{enabled:s.videoEnabled,trackId:(r=s.videoTrack)==null?void 0:r.id,permission:"mediaPermissions"in s?(n=s.mediaPermissions)==null?void 0:n.video:null},screenshare:{enabled:s.screenShareEnabled,permission:"mediaPermissions"in s?(i=s.mediaPermissions)==null?void 0:i.screenshare:null,audio:{enabled:(o=(a=s.screenShareTracks)==null?void 0:a.audio)==null?void 0:o.enabled,trackId:(u=(d=s.screenShareTracks)==null?void 0:d.audio)==null?void 0:u.id},video:{enabled:(p=(h=s.screenShareTracks)==null?void 0:h.video)==null?void 0:p.enabled,trackId:(v=(f=s.screenShareTracks)==null?void 0:f.video)==null?void 0:v.id}}}}:{}}var wD=Object.defineProperty,CD=Object.getOwnPropertyDescriptor,ai=(s,t,e,r)=>{for(var n=r>1?void 0:r?CD(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&wD(t,e,n),n};const bD=.8,PD=1.2;let Gr=(Nv=class extends Ht{constructor(t,e,r,n){super();S(this,Fs);S(this,Hi);S(this,Ga);m(this,"id");m(this,"userId");m(this,"name");m(this,"picture");m(this,"isHost");m(this,"customParticipantId");m(this,"flags");m(this,"device");m(this,"videoTrack");m(this,"audioTrack");m(this,"screenShareTracks");m(this,"videoEnabled");m(this,"audioEnabled");m(this,"screenShareEnabled");m(this,"producers");m(this,"manualProducerConfig");S(this,Vi,void 0);m(this,"supportsRemoteControl",!1);S(this,$i,void 0);m(this,"presetName");S(this,Bi,void 0);S(this,rs,void 0);S(this,ja,void 0);S(this,xs,new Map);S(this,ss,1);S(this,Rd,Vr(t=>{if(!this.videoTrack)return;const{clientWidth:e,clientHeight:r}=t,{width:n,height:i}=this.videoTrack.getSettings();if(!n||!i)return;const a=i/r,o=n/e,d=Math.max(a,o);d>PD&&c(this,ss)===1?(y(this,ss,0),w.emit(C.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:c(this,ss)})):dc(this,Rd).call(this,t)),e.observe(t)),c(this,xs).set(t,{observer:e}),this.updateVideo(t),(a=c(this,Hi,Fd))==null||a.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(i=this.raised)!=null?i:!1)}deregisterVideoElement(t){var e,r,n;t.srcObject=void 0,(r=(e=c(this,xs).get(t))==null?void 0:e.observer)==null||r.disconnect(),c(this,xs).delete(t),(n=c(this,Hi,Fd))==null||n.removeSource(this.id)}updateVideo(t){var e;if(this.videoEnabled){if(this.videoTrack==null)return;const r=(e=t.srcObject)==null?void 0:e.getTracks()[0];if((r==null?void 0:r.id)===this.videoTrack.id)return;const n=new MediaStream;n.addTrack(this.videoTrack),t.srcObject=n}else t.srcObject=void 0;t.style.display=this.videoEnabled?"block":"none"}},Vi=new WeakMap,$i=new WeakMap,Bi=new WeakMap,Fs=new WeakSet,Zi=function(){return c(this,Bi).getValue("roomNodeClient")},rs=new WeakMap,ja=new WeakMap,xs=new WeakMap,Hi=new WeakSet,Fd=function(){return c(this,Bi).getValue("pip")},ss=new WeakMap,Rd=new WeakMap,Ga=new WeakSet,Qu=function(){Array.from(c(this,xs).keys()).forEach(this.updateVideo)},Nv);ai([g.trace("DyteParticipant.disableAudio")],Gr.prototype,"disableAudio",1),ai([g.trace("DyteParticipant.kick")],Gr.prototype,"kick",1),ai([g.trace("DyteParticipant.disableVideo")],Gr.prototype,"disableVideo",1),ai([g.trace("DyteParticipant.getPermissions")],Gr.prototype,"getPermissions",1),ai([g.trace("DyteParticipant.setStageStatus")],Gr.prototype,"setStageStatus",1),Gr=ai([pt("1200")],Gr);class Sa extends hg{constructor(t){const{onAddEvent:e="participantJoined",onDeleteEvent:r="participantLeft",onClearEvent:n="participantsCleared"}=t!=null?t:{};super({onAddEvent:e,onDeleteEvent:r,onClearEvent:n})}add(t,e=!0){return this.has(t.id)&&Object.is(this.get(t.id),t)===!1&&this.delete(t.id),super.add(t,e)}clear(t=!0,e=!1){return super.clear(t,e)}delete(t,e=!0,r=!1){return super.delete(t,e,r)}}class RD extends Zn{constructor(){super();S(this,Us,void 0);y(this,Us,new Map)}__set(e,r){return c(this,Us).set(e,r)}__clear(){return c(this,Us).clear()}get(e){return c(this,Us).get(e)}toArray(){return Array.from(c(this,Us).values())}}Us=new WeakMap;var mn={},Wc={},Kc={},kD={get exports(){return Kc},set exports(s){Kc=s}},Eu,Dg;function ID(){if(Dg)return Eu;Dg=1;var s=1e3,t=s*60,e=t*60,r=e*24,n=r*7,i=r*365.25;Eu=function(h,p){p=p||{};var f=typeof h;if(f==="string"&&h.length>0)return a(h);if(f==="number"&&isFinite(h))return p.long?d(h):o(h);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(h))};function a(h){if(h=String(h),!(h.length>100)){var p=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(h);if(p){var f=parseFloat(p[1]),v=(p[2]||"ms").toLowerCase();switch(v){case"years":case"year":case"yrs":case"yr":case"y":return f*i;case"weeks":case"week":case"w":return f*n;case"days":case"day":case"d":return f*r;case"hours":case"hour":case"hrs":case"hr":case"h":return f*e;case"minutes":case"minute":case"mins":case"min":case"m":return f*t;case"seconds":case"second":case"secs":case"sec":case"s":return f*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return f;default:return}}}}function o(h){var p=Math.abs(h);return p>=r?Math.round(h/r)+"d":p>=e?Math.round(h/e)+"h":p>=t?Math.round(h/t)+"m":p>=s?Math.round(h/s)+"s":h+"ms"}function d(h){var p=Math.abs(h);return p>=r?u(h,p,r,"day"):p>=e?u(h,p,e,"hour"):p>=t?u(h,p,t,"minute"):p>=s?u(h,p,s,"second"):h+" ms"}function u(h,p,f,v){var T=p>=f*1.5;return Math.round(h/f)+" "+v+(T?"s":"")}return Eu}function AD(s){e.debug=e,e.default=e,e.coerce=d,e.disable=i,e.enable=n,e.enabled=a,e.humanize=ID(),e.destroy=u,Object.keys(s).forEach(h=>{e[h]=s[h]}),e.names=[],e.skips=[],e.formatters={};function t(h){let p=0;for(let f=0;f{if(Q==="%%")return"%";O++;const ve=e.formatters[oe];if(typeof ve=="function"){const Mt=k[O];Q=ve.call(I,Mt),k.splice(O,1),O--}return Q}),e.formatArgs.call(I,k),(I.log||e.log).apply(I,k)}return P.namespace=h,P.useColors=e.useColors(),P.color=e.selectColor(h),P.extend=r,P.destroy=e.destroy,Object.defineProperty(P,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(v!==e.namespaces&&(v=e.namespaces,T=e.enabled(h)),T),set:k=>{f=k}}),typeof e.init=="function"&&e.init(P),P}function r(h,p){const f=e(this.namespace+(typeof p=="undefined"?":":p)+h);return f.log=this.log,f}function n(h){e.save(h),e.namespaces=h,e.names=[],e.skips=[];let p;const f=(typeof h=="string"?h:"").split(/[\s,]+/),v=f.length;for(p=0;p"-"+p)].join(",");return e.enable(""),h}function a(h){if(h[h.length-1]==="*")return!0;let p,f;for(p=0,f=e.skips.length;p{let d=!1;return()=>{d||(d=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function e(){return typeof window!="undefined"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document!="undefined"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window!="undefined"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(d){if(d[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+d[0]+(this.useColors?"%c ":" ")+"+"+s.exports.humanize(this.diff),!this.useColors)return;const u="color: "+this.color;d.splice(1,0,u,"color: inherit");let h=0,p=0;d[0].replace(/%[a-zA-Z%]/g,f=>{f!=="%%"&&(h++,f==="%c"&&(p=h))}),d.splice(p,0,u)}t.log=console.debug||console.log||(()=>{});function n(d){try{d?t.storage.setItem("debug",d):t.storage.removeItem("debug")}catch(u){}}function i(){let d;try{d=t.storage.getItem("debug")}catch(u){}return!d&&typeof process!="undefined"&&"env"in process&&(d=process.env.DEBUG),d}function a(){try{return localStorage}catch(d){}}s.exports=MD(t);const{formatters:o}=s.exports;o.j=function(d){try{return JSON.stringify(d)}catch(u){return"[UnexpectedJSONParseError]: "+u.message}}})(kD,Kc);var DD=De&&De.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Wc,"__esModule",{value:!0}),Wc.Logger=void 0;const oi=DD(Kc),ci="awaitqueue";class OD{constructor(t){t?(this._debug=(0,oi.default)(`${ci}:${t}`),this._warn=(0,oi.default)(`${ci}:WARN:${t}`),this._error=(0,oi.default)(`${ci}:ERROR:${t}`)):(this._debug=(0,oi.default)(ci),this._warn=(0,oi.default)(`${ci}:WARN`),this._error=(0,oi.default)(`${ci}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}}Wc.Logger=OD,Object.defineProperty(mn,"__esModule",{value:!0});var di=mn.AwaitQueue=mn.AwaitQueueRemovedTaskError=mn.AwaitQueueStoppedError=void 0;const ND=Wc,Ts=new ND.Logger;class wu extends Error{constructor(t){super(t!=null?t:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,wu)}}mn.AwaitQueueStoppedError=wu;class zc extends Error{constructor(t){super(t!=null?t:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,zc)}}mn.AwaitQueueRemovedTaskError=zc;class LD{constructor(){this.pendingTasks=new Map,this.nextTaskId=0,this.stopping=!1}get size(){return this.pendingTasks.size}async push(t,e){if(e=e!=null?e:t.name,Ts.debug(`push() [name:${e}]`),typeof t!="function")throw new TypeError("given task is not a function");if(e)try{Object.defineProperty(t,"name",{value:e})}catch(r){}return new Promise((r,n)=>{const i={id:this.nextTaskId++,task:t,name:e,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:a=>{if(i.completed)return;i.completed=!0,this.pendingTasks.delete(i.id),Ts.debug(`resolving task [name:${i.name}]`),r(a);const[o]=this.pendingTasks.values();o&&!o.executedAt&&this.execute(o)},reject:a=>{if(!i.completed&&(i.completed=!0,this.pendingTasks.delete(i.id),Ts.debug(`rejecting task [name:${i.name}]: %s`,String(a)),n(a),!this.stopping)){const[o]=this.pendingTasks.values();o&&!o.executedAt&&this.execute(o)}}};this.pendingTasks.set(i.id,i),this.pendingTasks.size===1&&this.execute(i)})}stop(){Ts.debug("stop()"),this.stopping=!0;for(const t of this.pendingTasks.values())Ts.debug(`stop() | stopping task [name:${t.name}]`);this.stopping=!1}remove(t){Ts.debug(`remove() [taskIdx:${t}]`);const e=Array.from(this.pendingTasks.values())[t];if(!e){Ts.debug(`stop() | no task with given idx [taskIdx:${t}]`);return}e.reject(new zc)}dump(){const t=Date.now();let e=0;return Array.from(this.pendingTasks.values()).map(r=>({idx:e++,task:r.task,name:r.name,enqueuedTime:r.executedAt?r.executedAt-r.enqueuedAt:t-r.enqueuedAt,executionTime:r.executedAt?t-r.executedAt:0}))}async execute(t){if(Ts.debug(`execute() [name:${t.name}]`),t.executedAt)throw new Error("task already being executed");t.executedAt=Date.now();try{const e=await t.task();t.resolve(e)}catch(e){t.reject(e)}}}di=mn.AwaitQueue=LD;class Og{constructor(){m(this,"meetingTitle");m(this,"roomName");m(this,"roomUUID");S(this,Ja,void 0);m(this,"context");m(this,"authToken");m(this,"maxPreferredStreams")}get peerId(){return this.context.getValue("peerId")}get roomJoined(){return!1}set roomJoined(t){throw new b("Method not implemented.")}get sfuHandler(){return c(this,Ja)}get mediaState(){return c(this,Ja).transportState}reconnect(){throw new b("Method not implemented.")}async partialJoinRoom(t,e,r=!1,n=void 0){throw new b("Method not implemented.")}async joinRoom(t,e,r={},n=!1,i=!1){throw new b("Method not implemented.")}async leaveRoom(){throw new b("Method not implemented.")}reset(t=!0){throw new b("Method not implemented")}async handleSocketCallbacks(t){throw new b("Method not implemented.")}async handleSockets(t,e){throw new b("Method not implemented.")}async shareMic(t){throw new b("Method not implemented.")}async shareWebcam(t){throw new b("Method not implemented.")}async shareScreen(t){throw new b("Method not implemented.")}async unmuteSelf(){throw new b("Method not implemented.")}async muteSelf(){throw new b("Method not implemented.")}async pauseWebcam(){throw new b("Method not implemented.")}async disableScreenShare(){throw new b("Method not implemented.")}async acceptWaitingRequest(t){throw new b("Method not implemented.")}async rejectWaitingRequest(t){throw new b("Method not implemented.")}async muteAll(t){throw new b("Method not implemented.")}async muteAllVideo(){throw new b("Method not implemented.")}async disableAudio(t){throw new b("Method not implemented.")}async disableVideo(t){throw new b("Method not implemented.")}async kickAll(){throw new b("Method not implemented.")}async kick(t){throw new b("Method not implemented.")}async pinPeer(t){throw new b("Method not implemented.")}getConsumers(){throw new b("Method not implemented.")}stopAllProducers(){throw new b("Method not implemented.")}async activatePeers(t){throw new b("Method not implemented.")}async deactivatePeers(t,e="default"){throw new b("Method not implemented.")}async createConsumers(t){throw new b("Method not implemented.")}async closeConsumers(t){throw new b("Method not implemented.")}async switchConsumersToLayer(t,e){throw new b("Method not implemented.")}}Ja=new WeakMap;var Ng={},Yc={},FD={get exports(){return Yc},set exports(s){Yc=s}},Lg=FD.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(s){return s.encoding?"rtpmap:%d %s/%s/%s":s.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(s){return s.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(s){return s.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(s){return"extmap:%d"+(s.direction?"/%s":"%v")+(s["encrypt-uri"]?" %s":"%v")+" %s"+(s.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(s){return s.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(s){var t="candidate:%s %d %s %d %s %d typ %s";return t+=s.raddr!=null?" raddr %s rport %d":"%v%v",t+=s.tcptype!=null?" tcptype %s":"%v",s.generation!=null&&(t+=" generation %d"),t+=s["network-id"]!=null?" network-id %d":"%v",t+=s["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(s){var t="ssrc:%d";return s.attribute!=null&&(t+=" %s",s.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(s){return s.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(s){return s.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(s){return"imageattr:%s %s %s"+(s.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(s){return"simulcast:%s %s"+(s.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(s){return"ts-refclk:%s"+(s.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(s){var t="mediaclk:";return t+=s.id!=null?"id=%s %s":"%v%s",t+=s.mediaClockValue!=null?"=%s":"",t+=s.rateNumerator!=null?" rate=%s":"",t+=s.rateDenominator!=null?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(Lg).forEach(function(s){var t=Lg[s];t.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})}),function(s){var t=function(o){return String(Number(o))===o?Number(o):o},e=function(o,d,u,h){if(h&&!u)d[h]=t(o[1]);else for(var p=0;p1&&(o[u[0]]=void 0),o};s.parseParams=function(o){return o.split(/;\s?/).reduce(a,{})},s.parseFmtpConfig=s.parseParams,s.parsePayloads=function(o){return o.toString().split(" ").map(Number)},s.parseRemoteCandidates=function(o){for(var d=[],u=o.split(" ").map(t),h=0;h=r)return n;var i=e[t];switch(t+=1,n){case"%%":return"%";case"%s":return String(i);case"%d":return Number(i);case"%v":return""}})},Ea=function(s,t,e){var r=t.format instanceof Function?t.format(t.push?e:e[t.name]):t.format,n=[s+"="+r];if(t.names)for(var i=0;ivs.parseTranscript(e,!1)).filter(Boolean):[]}async getActiveTranscript(){try{const t=We(),{transcript:e}=await t.getActiveTranscript();this.transcripts=vs.parseTranscripts(e)}catch(t){}}async onTranscript(t){var r;const e=this.transcripts.filter(({peerId:n})=>n===t.peerId);if((r=e==null?void 0:e.at(-1))!=null&&r.isPartialTranscript){const n=e.at(-1);n.transcript=t.transcript,n.isPartialTranscript=t.isPartialTranscript,this.emit("transcript",n);return}this.transcripts.push(t),this.emit("transcript",t)}};cg([g.trace("DyteAi.getActiveTranscript")],vs.prototype,"getActiveTranscript",1),vs=cg([pt("0000")],vs);var c0=Object.defineProperty,d0=Object.getOwnPropertyDescriptor,l0=(s,t,e,r)=>{for(var n=r>1?void 0:r?d0(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&c0(t,e,n),n};const dg=(Iv=class{constructor(s,t,e,r,n,i){m(this,"meta");m(this,"ai");S(this,Is,void 0);S(this,Ei,void 0);m(this,"aiSocketHandler");S(this,_d,void 0);y(this,_d,s),this.meta=new du(s,t,t.config.viewType,e,i),this.ai=r,y(this,Is,t),y(this,Ei,e),this.aiSocketHandler=n,t.config.viewType!==Xe.Chat&&this.setupEvents()}static async init(s,t,e,r,n){const i=await vs.init(t.permissions.transcriptionEnabled);return new dg(s,t,e,i,r,n)}conditionallySetActiveTab(s){var t;s!=null&&s.currentTab&&((t=this.meta.selfActiveTab)==null?void 0:t.id)!==s.currentTab.id&&(this.meta.setSelfActiveTab(s.currentTab,og.Meeting),this.meta.emit("activeTabUpdate",s.currentTab))}setupEvents(){w.on(C.TRANSPORT_STATE_UPDATE,s=>{this.meta.emit("mediaConnectionUpdate",s)}),w.on(C.SOCKET_STATE_UPDATE,s=>{this.meta.emit("socketConnectionUpdate",s)}),w.on(C.ROOM_STATE,({createdAt:s,roomUuid:t})=>{const e=this.meta.meetingStartedTimestamp;if(t&&(this.meta.sessionId=t),s&&!e){const r=new Date(s*1e3);this.meta.meetingStartedTimestamp=r,this.meta.emit("meetingStartTimeUpdate",{meetingStartedTimestamp:this.meta.meetingStartedTimestamp})}}),w.on(C.PRODUCER_SCORE_UPDATE,({score:s})=>{s<5&&this.meta.emit("poorConnection",{score:s})}),c(this,Is).permissions.canSpotlight&&(l.info("DyteMetaController::Asserting Spotlight"),this.meta.selfActiveTab&&c(this,Ei).broadcastMessage("spotlight",{userId:c(this,Is).userId,currentTab:this.meta.selfActiveTab})),w.on(C.PEER_JOINED_INTERNAL,async s=>{c(this,Is).permissions.canSpotlight&&this.meta.selfActiveTab&&c(this,Ei).broadcastToPeers("spotlight",[s.id],{userId:c(this,Is).userId,currentTab:this.meta.selfActiveTab})}),w.on(C.ROOM_MESSAGE,s=>{var e,r;let t;if("type"in s){if(s.type!=="spotlight")return;t={...s,...s.payload}}else if("roomMessageType"in s){if(s.roomMessageType!=="spotlight")return;t=s}else return;l.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:t.userId},currentTab:{id:(e=t.currentTab)==null?void 0:e.id,type:(r=t.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(t)}),w.on(C.MESSAGE,s=>{var e,r;let t;if("type"in s){if(s.type!=="spotlight")return;t={...s,...s.payload}}else if("roomMessageType"in s){if(s.roomMessageType!=="spotlight")return;t=s}else return;l.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:t.userId},currentTab:{id:(e=t.currentTab)==null?void 0:e.id,type:(r=t.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(t)}),this.aiSocketHandler.on($.transcript,s=>{const{meetingId:t,transcript:e,isPartial:r}=s,n=vs.parseTranscript(e,r);if(!n){l.warn("Received empty transcript data");return}this.ai.onTranscript(n),this.meta.emit("transcript",n);const{peerId:i,name:a,transcript:o}=n;l.debug(`${t} Received transcript for peer ${i} - ${a}: ${o}`)})}},Is=new WeakMap,Ei=new WeakMap,_d=new WeakMap,Iv);let lg=dg;l0([g.trace("MetaController.setupEvents")],lg.prototype,"setupEvents",1);var u0=Object.defineProperty,h0=Object.getOwnPropertyDescriptor,un=(s,t,e,r)=>{for(var n=r>1?void 0:r?h0(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&u0(t,e,n),n};class ys extends Ht{constructor(e,r,n,i,a){super();S(this,Ci);S(this,tr,void 0);S(this,wi,void 0);S(this,Re,void 0);S(this,La,void 0);S(this,Pr,void 0);S(this,fr,void 0);y(this,fr,e),y(this,tr,i),y(this,wi,a),y(this,Re,r),y(this,La,n),y(this,Pr,[]),this.setupEvents()}get status(){return c(this,fr).getValue("stageStatus")}setupEvents(){const e={[C.GET_STAGE_REQUESTS]:async i=>{y(this,Pr,i)},[C.UPDATE_STAGE_REQUESTS]:async({add:i})=>{const a=c(this,Pr).length,{stageRequests:o}=this.getAccessRequests();(i||o.length>a)&&this.emit("newStageRequest",{count:o.length}),this.emit("stageAccessRequestUpdate",o)}},r=()=>{Object.entries(e).forEach(([i,a])=>{w.onAsync(i,a)})},n=()=>{Object.entries(e).forEach(([i,a])=>{w.removeListener(i,a)})};c(this,Re).permissions.on("permissionsUpdate",i=>{const{canAcceptProductionRequests:a}=i;a!==void 0&&(c(this,Re).permissions.acceptStageRequests?(r(),c(this,tr).getStageRequests()):(n(),y(this,Pr,[]),this.emit("stageAccessRequestUpdate",c(this,Pr))))}),c(this,Re).permissions.acceptStageRequests&&r()}getAccessRequests(){if(!c(this,Re).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new b("Stage is disabled");if(!c(this,Re).permissions.acceptStageRequests)throw l.error("DyteStage::get_access_request::permission_denied"),new b("You do not have permission to perform this action/");const e=c(this,La).joined.toArray().filter(r=>r.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(r=>({displayName:r.name,userId:r.userId,peerId:r.id}));return y(this,Pr,e),{stageRequests:c(this,Pr)}}async requestAccess(){if(!c(this,Re).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new b("Stage is disabled");if(this.status!=="OFF_STAGE")throw new b(`Unable to request access you are currently ${this.status}`);if(c(this,Re).permissions.stageAccess===H.Allowed){je(this,Ci,Nd).call(this,"ACCEPTED_TO_JOIN_STAGE");return}c(this,tr).requestAccess(),je(this,Ci,Nd).call(this,"REQUESTED_TO_JOIN_STAGE")}async cancelRequestAccess(){if(!c(this,Re).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new b("Stage is disabled");c(this,tr).cancelRequestAccess(),je(this,Ci,Nd).call(this,"OFF_STAGE")}grantAccess(e){if(!c(this,Re).roomJoined)throw new b("Can`t rejectRequestToJoinStage for participant without joining room");if(!c(this,Re).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new b("Stage is disabled");if(!c(this,Re).permissions.acceptStageRequests)throw l.error("DyteStage::grant_access::permission_denied"),new b("You do not have permission to perform this action/");return c(this,tr).grantAccess(e)}denyAccess(e){if(!c(this,Re).roomJoined)throw new b("Can`t rejectRequestToJoinStage for participant without joining room");if(!c(this,Re).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new b("Stage is disabled");if(!c(this,Re).permissions.acceptStageRequests)throw l.error("DyteStage::deny_access::permission_denied"),new b("You do not have permission to perform this action/");return c(this,tr).denyAccess(e)}async join(){const e=c(this,fr).getValue("viewType");if(this.status==="ON_STAGE")throw new b("You are already on stage.");if(this.status!=="ACCEPTED_TO_JOIN_STAGE"||c(this,Re).permissions.stageAccess===H.NotAllowed)throw new b(`Unable to join stage you are currently ${this.status}`);if(await c(this,tr).joinStage(),e===Xe.Livestream&&await c(this,wi).joinRoom(c(this,Re),e),c(this,fr).setValue("stageStatus","ON_STAGE",!1),await w.emitAsync(C.JOIN_MEDIA_ROOM),c(this,fr).notify("stageStatus"),e===Xe.Livestream){const{peers:r}=await c(this,wi).getStagePeers();w.emit(C.SOCKET_PEERS,r)}}async leave(){if(!c(this,Re).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new b("Stage is disabled");if(!(this.status==="ON_STAGE"||this.status==="ACCEPTED_TO_JOIN_STAGE"))throw new b(`Unable to leave stage you are currently ${this.status}`);c(this,Re).setIsPinned(!1),await c(this,tr).leaveStage(c(this,Re).userId),c(this,fr).setValue("stageStatus","OFF_STAGE",!1),await w.emitAsync(C.LEAVE_MEDIA_ROOM,"stageLeft"),c(this,fr).notify("stageStatus")}async kick(e){if(!c(this,Re).roomJoined)throw new b("Can`t kick participant without joining room");if(!c(this,Re).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new b("Stage is disabled");if(!c(this,Re).permissions.acceptStageRequests)throw l.error("DyteStage::kick::permission_denied"),new b("You do not have permissions for kick");return c(this,tr).kick(e)}}tr=new WeakMap,wi=new WeakMap,Re=new WeakMap,La=new WeakMap,Pr=new WeakMap,fr=new WeakMap,Ci=new WeakSet,Nd=async function(e){this.status!==e&&c(this,fr).setValue("stageStatus",e)},un([g.trace("DyteStage.getStageRequests")],ys.prototype,"getAccessRequests",1),un([g.trace("DyteStage.requestAccess")],ys.prototype,"requestAccess",1),un([g.trace("DyteStage.cancelRequestAccess")],ys.prototype,"cancelRequestAccess",1),un([g.trace("DyteStage.grantAccess")],ys.prototype,"grantAccess",1),un([g.trace("DyteStage.denyAccess")],ys.prototype,"denyAccess",1),un([g.trace("DyteStage.joinStage")],ys.prototype,"join",1),un([g.trace("DyteStage.leaveStage")],ys.prototype,"leave",1);function p0(s){return!(s.viewType==="LIVESTREAM"||s.viewType==="CHAT")}function lu(s){switch(s){case Br.UNSPECIFIED:return"OFF_STAGE";case Br.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case Br.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case Br.OFF_STAGE:return"OFF_STAGE";case Br.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var m0=Object.defineProperty,f0=Object.getOwnPropertyDescriptor,g0=(s,t,e,r)=>{for(var n=r>1?void 0:r?f0(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&m0(t,e,n),n};class ug{constructor(t,e,r,n,i){m(this,"stage");S(this,As,void 0);S(this,An,void 0);S(this,Ms,void 0);S(this,Fa,0);S(this,es,void 0);y(this,es,t),this.stage=new ys(t,n,i,e,r),y(this,Ms,e),y(this,As,n),y(this,An,i),this.setupEvents()}setupEvents(){c(this,es).subscribe("stageStatus",t=>{this.stage.emit("stageStatusUpdate",t)}),c(this,Ms).on($.grantStageAccess,()=>{c(this,As).permissions.stageAccess!==H.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),c(this,Ms).on($.peerStageStatusUpdate,t=>{t!==void 0&&(t.peerId===c(this,As).id?this.selfStageStatusHandler(t):this.peerStageStatusHandler(t))}),c(this,Ms).on($.denyStageAccess,()=>{c(this,As).permissions.stageAccess!==H.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),c(this,Ms).on($.getStageRequests,async t=>{var r;if(c(this,As).permissions.stageAccess!==H.Allowed)return;const e=(r=t==null?void 0:t.stageRequests)!=null?r:[];await w.emitAsync(C.GET_STAGE_REQUESTS,e),c(this,Fa)0&&this.stage.emit("newStageRequest",{count:e.length}),y(this,Fa,e.length),this.stage.emit("stageAccessRequestUpdate",e)})}getCurrentStageRequests(){return c(this,An).joined.toArray().filter(e=>e.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(e=>({displayName:e.name,userId:e.userId,peerId:e.id}))}async setStageStatus(t){this.stage.status!==t&&c(this,es).setValue("stageStatus",t)}selfStageStatusHandler(t){const e=lu(t.stageType),r=c(this,es).getValue("stageStatus");if(r!==e)switch(t.stageType){case 1:c(this,es).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.join();break;case 2:case 3:this.setStageStatus(r);break;case 0:case 4:default:c(this,es).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}async peerStageStatusHandler(t){const e=c(this,An).joined.get(t.peerId),r=c(this,An).viewMode==="ACTIVE_GRID";if(!e){l.warn("err::peerStageStatusUpdate: participant not found");return}switch(t.stageType){case 1:e.setStageStatus("ON_STAGE"),r&&w.emit(C.UPDATE_ACTIVE);break;case 2:e.setStageStatus("ACCEPTED_TO_JOIN_STAGE");break;case 3:e.setStageStatus("REQUESTED_TO_JOIN_STAGE");break;case 0:case 4:default:e.setStageStatus("OFF_STAGE"),r&&w.emit(C.UPDATE_ACTIVE);break}w.emit(C.UPDATE_PEER_STAGE_STATUS,{id:e.id,status:e.stageStatus})}}As=new WeakMap,An=new WeakMap,Ms=new WeakMap,Fa=new WeakMap,es=new WeakMap,g0([g.trace("DyteStage.setupEvents")],ug.prototype,"setupEvents",1);var v0=Object.defineProperty,y0=Object.getOwnPropertyDescriptor,Vc=(s,t,e,r)=>{for(var n=r>1?void 0:r?y0(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&v0(t,e,n),n};const Be={getPeer:14,getPeers:15,chatMessage:16,getRoomName:17,getDisplayTitle:18,getPluginInitiator:19,customPluginEventToParent:20,peerJoined:22,peerLeft:23,sendData:24,stageStatusUpdate:25,peerStageStatusUpdate:26};let si=(Av=class extends Zn{constructor(t,{baseURL:e,createdAt:r,description:n,id:i,name:a,organizationId:o,picture:d,private:u,published:h,staggered:p,tags:f,type:v,updatedAt:T},P,k,I,x){super();S(this,Mn);S(this,yt,void 0);m(this,"baseURL");m(this,"createdAt");m(this,"description");m(this,"id");m(this,"name");S(this,Wt,void 0);S(this,bi,void 0);S(this,Pi,void 0);m(this,"organizationId");m(this,"picture");m(this,"private");m(this,"published");m(this,"staggered");m(this,"tags");m(this,"type");m(this,"updatedAt");S(this,ts,void 0);m(this,"config");S(this,Ri,void 0);m(this,"active");m(this,"iframes");m(this,"enabledBy");S(this,ki,void 0);y(this,ki,t),this.baseURL=e,this.createdAt=new Date(r),this.description=n,this.id=i,this.name=a,y(this,Wt,k),this.organizationId=o,this.picture=d,this.private=u,this.published=h,this.staggered=p,this.tags=f,this.type=v,this.updatedAt=new Date(T),this.active=!1,this.iframes=new Map,y(this,yt,P),y(this,bi,I),y(this,Pi,x),this.enabledBy=""}sendIframeEvent(t){this.iframes.size&&this.iframes.forEach(e=>{const{iframe:r}=e;r&&(navigator.isReactNative?r.postMessage(JSON.stringify(t)):r.contentWindow.postMessage(t,"*"))})}async handleIframeMessage(t){var a;if(!this.active)return;const e=t,{payload:r,uuid:n,type:i}=e;switch(i){case j.customPluginEventToRoom:{c(this,yt).customPluginEventToRoom(this.id,r,n);break}case j.customPluginEventToPeers:{c(this,yt).customPluginEventToPeers(this.id,r.peerIds,r,n);break}case j.enablePluginForRoom:{c(this,yt).enablePluginForRoom(this.id,n);break}case j.enablePluginForPeers:{c(this,yt).enablePluginForPeers(this.id,r.peerIds,n);break}case j.disablePluginForRoom:{c(this,yt).disablePluginForRoom(this.id,n);break}case j.disablePluginForPeers:{c(this,yt).disablePluginForPeers(this.id,r.peerIds,n);break}case j.storeInsertKeys:{c(this,yt).storeInsertKeys(this.id,r.store,r.insertKeys,n);break}case j.storeGetKeys:{c(this,yt).storeGetKeys(this.id,r.store,r.getKeys,n);break}case j.storeDeleteKeys:{c(this,yt).storeDeleteKeys(this.id,r.store,r.deleteKeys,n);break}case j.storeDelete:{c(this,yt).storeDelete(this.id,r.store,n);break}case Be.chatMessage:{const{messagePayload:o,peerIds:d}=r;if(!c(this,Pi)){this.sendIframeEvent({type:Be.chatMessage,uuid:e.uuid,payload:{error:"Chat is disabled for this room."}});return}try{await c(this,Pi).sendMessage(o,d),this.sendIframeEvent({type:Be.chatMessage,uuid:e.uuid,payload:{success:!0}})}catch(u){this.sendIframeEvent({type:Be.chatMessage,uuid:e.uuid,payload:{error:u}})}break}case Be.getPeer:{let o;const{peerId:d}=r,u={...c(this,Wt),id:c(this,Wt).id,isRecorder:(a=c(this,Wt).permissions)==null?void 0:a.isRecorder,isHidden:c(this,Wt).permissions.hiddenParticipant,stageStatus:c(this,Wt).stageStatus};d?(o=c(this,bi).joined.get(r.peerId),c(this,Wt).id===d&&(o=u)):o=u,this.sendIframeEvent({type:Be.getPeer,payload:{peer:o&&Fc(o)},uuid:e.uuid});break}case Be.getPeers:{const o=c(this,bi).joined.toArray().map(d=>Fc(d));this.sendIframeEvent({type:Be.getPeers,payload:{peers:o},uuid:e.uuid});break}case Be.getPluginInitiator:{this.sendIframeEvent({type:Be.getPluginInitiator,payload:{enabledBy:this.enabledBy},uuid:e.uuid});break}case Be.getDisplayTitle:{this.sendIframeEvent({type:Be.getDisplayTitle,payload:{displayTitle:c(this,Mn,Oo).meetingTitle},uuid:e.uuid});break}case Be.getRoomName:{this.sendIframeEvent({type:Be.getRoomName,payload:{roomName:c(this,Mn,Oo).roomName},uuid:e.uuid});break}case Be.customPluginEventToParent:{this.emit(e.payload.eventName,e.payload.data);break}}}sendData(t){this.active&&(l.info("DytePlugin::SendData",{plugin:{id:this.id,name:this.name,data:{eventName:t.eventName}}}),this.sendIframeEvent({type:Be.sendData,uuid:"",payload:t}))}removePluginView(t="default"){var n;const{iframe:e,listener:r}=(n=this.iframes.get(t))!=null?n:{};(e||r)&&(navigator.isReactNative?e.props.onMessage=void 0:window.removeEventListener("message",r),this.iframes.delete(t))}addPluginView(t,e="default"){var a;if(!c(this,Ri))throw l.error("DytePlugin::addPluginView::no_auth_token_set_for_plugin"),new b("No auth token set for plugin.");if(!t)throw l.error("DytePlugin::addPluginView::iframe_was_not_provided"),new b("Iframe was not provided.");this.removePluginView(e);const r=t,n=new URL(this.baseURL),i={auth:c(this,Ri),parent:navigator.isReactNative?this.baseURL:window.location.origin,backend:c(this,ki).getValue("apiBase"),pluginId:this.id,roomName:(a=c(this,Mn,Oo).roomName)!=null?a:"",displayTitle:c(this,Mn,Oo).meetingTitle};if(Object.keys(i).forEach(o=>{n.searchParams.set(o,i[o])}),r.src=n.href,r.allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",r.title=e,navigator.isReactNative)r.props.onMessage=o=>{this.handleIframeMessage(JSON.parse(o.nativeEvent.data))},this.iframes.set(e,{iframe:r});else{const o=async d=>{d.source===t.contentWindow&&await this.handleIframeMessage(d.data)};window.addEventListener("message",o),this.iframes.set(e,{iframe:r,listener:o})}}setActive(t){var e,r;if(this.active=t,t){this.emit("stateUpdate",{active:this.active,pluginId:this.id,bind:this.addPluginView.bind(this),views:(e=this.config)==null?void 0:e.views});return}this.active=!1,this.emit("stateUpdate",{active:this.active,pluginId:this.id,views:(r=this.config)==null?void 0:r.views})}async activateForSelf(){const t=We(),e=await t.authorizePlugin(this.id);y(this,Ri,e),y(this,ts,new Date);try{const r=await t.getPluginConfig(this.baseURL);this.config=r}catch(r){l.error("DytePlugin::activateForSelf",{error:r})}this.setActive(!0),this.emit("enabled")}deactivateForSelf(){Array.from(this.iframes.keys()).forEach(t=>{this.removePluginView(t)}),y(this,ts,void 0),this.iframes.clear(),this.setActive(!1),this.emit("closed")}async enable(){return this.activateForSelf()}disable(){return this.deactivateForSelf()}async activate(){var t,e;this.active||(e=(t=c(this,Wt).permissions)==null?void 0:t.plugins)!=null&&e.canStart&&(c(this,yt).addPlugin(this.id,this.staggered),y(this,ts,new Date),l.info("plugin::activated",{plugin:{id:this.id,enabledBy:this.enabledBy,name:this.name}}))}async deactivate(){var t,e;this.active&&(!((e=(t=c(this,Wt).permissions)==null?void 0:t.plugins)!=null&&e.canClose)&&this.enabledBy!==c(this,Wt).id||(c(this,yt).removePlugin(this.id),l.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:c(this,ts)?new Date().getTime()-c(this,ts).getTime():0}}),y(this,ts,void 0)))}},yt=new WeakMap,Wt=new WeakMap,bi=new WeakMap,Pi=new WeakMap,ts=new WeakMap,Ri=new WeakMap,ki=new WeakMap,Mn=new WeakSet,Oo=function(){return c(this,ki).getValue("roomNodeClient")},Av);Vc([Lt({maxInvocations:5,period:1})],si.prototype,"sendData",1),Vc([g.trace("DytePlugin.activatePlugin")],si.prototype,"activate",1),Vc([g.trace("DytePlugin.deactivatePlugin")],si.prototype,"deactivate",1),si=Vc([pt("0600")],si);class hg extends Map{constructor(e){const{onAddEvent:r,onDeleteEvent:n,onClearEvent:i}=e;super();S(this,ze,void 0);S(this,Dn,void 0);m(this,"onAddEvent");m(this,"onDeleteEvent");m(this,"onClearEvent");y(this,ze,new Zn),this.onAddEvent=r,this.onDeleteEvent=n,this.onClearEvent=i,y(this,Dn,new Map)}emit(e,...r){return c(this,ze).emit(e,...r)}on(e,r){return c(this,ze).on(e,r)}addListener(e,r){return c(this,ze).addListener(e,r)}off(e,r){return c(this,ze).off(e,r)}once(e,r){return c(this,ze).once(e,r)}prependListener(e,r){return c(this,ze).prependListener(e,r)}prependOnceListener(e,r){return c(this,ze).prependOnceListener(e,r)}removeListener(e,r){return c(this,ze).removeListener(e,r)}removeAllListeners(e){return c(this,ze).removeAllListeners(e)}listeners(e){return c(this,ze).listeners(e)}listenerCount(e){return c(this,ze).listenerCount(e)}getMaxListeners(){return c(this,ze).getMaxListeners()}setMaxListeners(e){return c(this,ze).setMaxListeners(e)}eventNames(){return c(this,ze).eventNames()}add(e,r=!0){return this.set(e.id,e,r)}set(e,r,n=!0){const i=super.set(e,r),a=(o,...d)=>{this.emit(o,r,...d)};return c(this,Dn).set(e,a),r.on("*",a),n&&c(this,ze).emit(this.onAddEvent,r),i}delete(e,r=!0,n=!1){const i=this.get(e);if(!i)return!1;i.removeListener("*",c(this,Dn).get(e));const a=super.delete(e);return n&&i.removeAllListeners(),r&&c(this,ze).emit(this.onDeleteEvent,i),a}clear(e=!0,r=!1){this.forEach(i=>{i.removeListener("*",c(this,Dn).get(i.id)),r&&i.removeAllListeners()});const n=super.clear();return e&&c(this,ze).emit(this.onClearEvent),n}toArray(){return Array.from(this.values())}}ze=new WeakMap,Dn=new WeakMap;class pg extends hg{constructor(){super({onAddEvent:"pluginAdded",onDeleteEvent:"pluginDeleted"})}add(t,e=!0){return super.add(t,e)}delete(t,e=!0,r=!1){return super.delete(t,e,r)}}var T0=Object.defineProperty,_0=Object.getOwnPropertyDescriptor,S0=(s,t,e,r)=>{for(var n=r>1?void 0:r?_0(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&T0(t,e,n),n};let uu=class{constructor(){m(this,"all");m(this,"active");this.all=new pg,this.active=new pg}};uu=S0([pt("0600")],uu);var E0=Object.defineProperty,w0=Object.getOwnPropertyDescriptor,$c=(s,t,e,r)=>{for(var n=r>1?void 0:r?w0(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&E0(t,e,n),n};const mg=(Mv=class{constructor(s,t,e,r){m(this,"plugins");S(this,rr,void 0);S(this,Ii,void 0);S(this,xa,void 0);y(this,rr,t),y(this,Ii,e),y(this,xa,s),this.plugins=r,this.setupEvents()}static async init(s,t,e,r,n,i,a){const o=new uu;return t.forEach(d=>{const u=new si(s,d,e,i,a,n);o.all.add(u)}),new mg(s,e,r,o)}async getRoomPlugins(){var t;const{plugins:s}=await c(this,rr).getActivePlugins();(t=this.plugins.active)==null||t.toArray().forEach(e=>{this.disablePlugin({id:e.id})}),await Promise.all(s.map(e=>this.enablePlugin({id:e.pluginId,enabledBy:e.enabledBy})))}async enablePlugin({id:s,enabledBy:t}){const e=this.plugins.all.get(s);e&&(await e.activateForSelf(),e.enabledBy=t)}async disablePlugin({id:s}){const t=this.plugins.all.get(s);t&&t.deactivateForSelf()}sendIframeEvent(s,t,e,r){const n=this.plugins.all.get(t);n&&n.sendIframeEvent({type:s,uuid:e,payload:r})}broadcastIframeEvent(s,t){this.plugins.active.forEach(e=>{this.sendIframeEvent(s,e.id,"",t)})}setupEvents(){this.plugins.all.on("stateUpdate",({active:s,id:t})=>{if(s){this.plugins.active.add(this.plugins.all.get(t));return}this.plugins.active.delete(t)}),w.onAsync(C.SOCKET_SERVICE_ROOM_JOINED,async()=>{await this.getRoomPlugins(),l.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to fetch plugins.")}),c(this,rr).on(j.addPlugin,async s=>{var e;const t=s.pluginId;(e=this.plugins.all.get(t))!=null&&e.active||await this.enablePlugin({id:t,enabledBy:s.enabledBy})}),c(this,rr).on(j.removePlugin,async s=>{var e;const t=s.pluginId;(e=this.plugins.all.get(t))!=null&&e.active&&await this.disablePlugin({id:t})}),[j.enablePluginForPeers,j.enablePluginForRoom].forEach(s=>{c(this,rr).on(s,async(t,e)=>{this.sendIframeEvent(s,t.pluginId,e,{enabledBy:t.enabledBy})})}),[j.disablePluginForPeers,j.disablePluginForRoom].forEach(s=>{c(this,rr).on(s,async(t,e)=>{this.sendIframeEvent(s,t.pluginId,e,{disabledBy:t.disabledBy})})}),[j.customPluginEventToPeers,j.customPluginEventToRoom].forEach(s=>{c(this,rr).on(s,async(t,e)=>{this.sendIframeEvent(s,t.pluginId,e,{data:JSON.parse(new TextDecoder().decode(t.pluginData))})})}),[j.storeInsertKeys,j.storeGetKeys,j.storeDeleteKeys].forEach(s=>{c(this,rr).on(s,async(t,e)=>{var n;const r=(n=t.storeItems)==null?void 0:n.map(i=>{var a;return{timestamp:i.timestamp,peerId:i.peerId,payload:JSON.parse((a=i.payload)!=null&&a.length?new TextDecoder().decode(i.payload):"{}"),key:i.storeKey}});this.sendIframeEvent(s,t.pluginId,e,{storeName:t.storeName,storeItems:r})})}),c(this,rr).on(j.storeDelete,async(s,t)=>{this.sendIframeEvent(j.storeDelete,s.pluginId,t,{storeName:s.storeName})}),c(this,Ii).on(Ue.sendMessageToPeers,s=>{const t=ur==null?void 0:ur.formatSocketServiceMessage(s.message);this.broadcastIframeEvent(Be.chatMessage,{message:t})}),c(this,Ii).on(Ue.sendMessageToRoom,s=>{const t=ur==null?void 0:ur.formatSocketServiceMessage(s.message);this.broadcastIframeEvent(Be.chatMessage,{message:t})}),w.on(C.PEER_JOINED_INTERNAL,s=>{const t=Fc(s);this.broadcastIframeEvent(Be.peerJoined,t)}),w.on(C.PEER_CLOSED,s=>{this.broadcastIframeEvent(Be.peerLeft,s)}),w.on(C.UPDATE_PEER_STAGE_STATUS,s=>{this.broadcastIframeEvent(Be.peerStageStatusUpdate,s)}),c(this,xa).subscribe("stageStatus",s=>{this.broadcastIframeEvent(Be.stageStatusUpdate,s)})}},rr=new WeakMap,Ii=new WeakMap,xa=new WeakMap,Mv);let ga=mg;$c([g.trace("PluginController.getRoomPlugins")],ga.prototype,"getRoomPlugins",1),$c([g.trace("PluginController.enableForSelf")],ga.prototype,"enablePlugin",1),$c([g.trace("PluginController.disableForSelf")],ga.prototype,"disablePlugin",1),$c([g.trace("PluginController.setupEvents")],ga.prototype,"setupEvents",1);class C0{constructor(){m(this,"roomJoined");m(this,"socketJoinAttempted");m(this,"mediaJoinAttempted");m(this,"socketState");m(this,"mediaState");this.roomJoined=!1,this.socketJoinAttempted=!1,this.mediaJoinAttempted=!1,this.socketState={state:void 0,reconnected:!1,reconnectionAttempt:void 0},this.mediaState={consuming:void 0,producing:void 0}}get joinAttempted(){return this.mediaJoinAttempted||this.socketJoinAttempted}updateSocketConnectionState(t,e){let r;const{reconnected:n}=this.socketState;switch(t){case"connected":r={state:"connected",reconnected:n,reconnectionAttempt:void 0};break;case"disconnected":r={state:"disconnected",reconnected:!1,reconnectionAttempt:0};break;case"reconnected":r={state:"connected",reconnected:!0,reconnectionAttempt:void 0};break;case"reconnecting":r={state:"reconnecting",reconnected:n,reconnectionAttempt:0};break;case"reconnectAttempt":r={state:"reconnecting",reconnected:n,reconnectionAttempt:e};break;case"failed":r={state:"failed",reconnected:n,reconnectionAttempt:void 0};break}r&&(w.emit(C.SOCKET_STATE_UPDATE,r),this.socketState=r)}}var b0=Object.defineProperty,P0=Object.getOwnPropertyDescriptor,va=(s,t,e,r)=>{for(var n=r>1?void 0:r?P0(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&b0(t,e,n),n};let hn=(Dv=class extends Ht{constructor(t,e){super();S(this,Mi);S(this,Ai,void 0);S(this,Ua,void 0);m(this,"recordingPeerIds",[]);m(this,"recordings",[]);y(this,Ua,t),y(this,Ai,e)}get recordingState(){return this.recordings.some(t=>t.state==="RECORDING")?"RECORDING":this.recordings.some(t=>t.state==="PAUSED")?"PAUSED":this.recordings.some(t=>t.state==="STARTING")?"STARTING":this.recordings.some(t=>t.state==="STOPPING")?"STOPPING":"IDLE"}updateRecordings(t){this.recordings=t,this.emit("recordingUpdate",this.recordingState)}async start(t){if(!c(this,Ai).permissions.canRecord)throw l.error("DyteRecording::start::permission_denied"),new b("User does not have permission to start recording");if((t==null?void 0:t.allowMultiple)!==!0&&(this.recordingState==="STARTING"||this.recordingState==="RECORDING"||this.recordingState==="STOPPING"))throw l.error("DyteRecording::start::recording_in_progress",{recording:{state:this.recordingState}}),new b(`Cant start recording, recordingState irregular: ${this.recordingState}`);try{const e=We(),{recording:r={}}=c(this,Ua).getValue("defaults"),n=await e.startRecording(r,t==null?void 0:t.allowMultiple);this.updateRecordings([...this.recordings,{id:n,state:"STARTING",type:"BROWSER"}])}catch(e){throw l.error("DyteRecording::stop::recording_failed_to_start",{error:e}),new b("Error while starting recording")}}async stop(t){await je(this,Mi,Ld).call(this,"stop",["RECORDING","PAUSED"],t)}async pause(t){await je(this,Mi,Ld).call(this,"pause",["RECORDING"],t)}async resume(t){await je(this,Mi,Ld).call(this,"resume",["PAUSED"],t)}},Ai=new WeakMap,Ua=new WeakMap,Mi=new WeakSet,Ld=async function(t,e,r){if(!c(this,Ai).permissions.canRecord)throw l.error("DyteRecording::stop::permission_denied"),new b("User does not have permission to stop recording");let n=[];if(r!==void 0){const i=this.recordings.find(a=>a.id===r);if(i===void 0)throw new b("Could not find the specified recording");if(e.includes(i.state)){l.error("DyteRecording::stop::recording_not_in_expected_state",{recording:{state:i.state}});return}n.push(i)}else n=this.recordings.filter(i=>e.includes(i.state));n.forEach(async i=>{const a=i.state;t==="stop"&&(i.state="STOPPING",this.emit("recordingUpdate","STOPPING"));try{await We().updateRecording(i.id,t)}catch(o){throw l.error("DyteRecording::stop::recording_failed_to_stop",{error:o}),i.state!==a&&(i.state=a,this.emit("recordingUpdate",a)),new b("Error while stopping recording")}})},Dv);va([g.trace("DyteRecording.start")],hn.prototype,"start",1),va([g.trace("DyteRecording.stop")],hn.prototype,"stop",1),va([g.trace("DyteRecording.stop")],hn.prototype,"pause",1),va([g.trace("DyteRecording.stop")],hn.prototype,"resume",1),hn=va([pt("1000")],hn);var R0=Object.defineProperty,k0=Object.getOwnPropertyDescriptor,I0=(s,t,e,r)=>{for(var n=r>1?void 0:r?k0(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&R0(t,e,n),n};class fg{constructor(t,e,r){m(this,"recording");m(this,"room");S(this,Sd,void 0);y(this,Sd,t),this.recording=new hn(t,e),this.room=r,this.setupEvents()}getRecordingTypeFromProtoType(t){let e;switch(t){case an.BROWSER:e="BROWSER";break;case an.COMPOSITE:e="COMPOSITE";break;case an.TRACK:e="TRACK";break;default:e="BROWSER"}return e}setupEvents(){w.on(C.ROOM_STATE,t=>{t.activeRecordings.length!==0?this.recording.updateRecordings(t.activeRecordings.map(e=>{const r=this.getRecordingTypeFromProtoType(e.recordingType);return{id:e.recordingId,state:e.recordingStatus,type:r}})):this.recording.recordings.length&&this.recording.updateRecordings([])}),this.room.on($.recordingStarted,t=>{let e=!1;const r=[...this.recording.recordings];if(r.forEach(n=>{n.id===t.recordingId&&(e=!0,n.state="RECORDING")}),e===!1){const n=this.getRecordingTypeFromProtoType(t.recordingType);r.push({id:t.recordingId,state:"RECORDING",type:n})}this.recording.updateRecordings(r)}),this.room.on($.recordingPaused,t=>{const e=[...this.recording.recordings];e.forEach(r=>{r.id===t.recordingId&&(r.state="PAUSED")}),this.recording.updateRecordings(e)}),this.room.on($.recordingStopped,t=>{const e=[...this.recording.recordings.filter(r=>r.id!==t.recordingId)];this.recording.updateRecordings(e)})}}Sd=new WeakMap,I0([g.trace("RecordingController.setupEvents")],fg.prototype,"setupEvents",1);class A0{static hasFeature(t){var e;return(e=J.hasFeature(t))!=null?e:!1}static getFeatureValue(t){return J.getValue(t)}static getAllFeatures(){return J.getAllFlags()}}class hu{constructor(t,e,r){m(this,"logger");m(this,"features");m(this,"browserSpecs");m(this,"callStats");this.logger=t,this.features=e,this.browserSpecs=Se,this.callStats=r}static init(t){return new hu(l,A0,t)}}class pu{constructor(t){m(this,"internals");this.internals=t}static async init(){const t=hu.init(U);return new pu(t)}}var M0=Object.defineProperty,D0=Object.getOwnPropertyDescriptor,jt=(s,t,e,r)=>{for(var n=r>1?void 0:r?D0(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&M0(t,e,n),n};class Ft extends Zn{constructor(e,r,n=Hc,i=!0){super();S(this,st,void 0);S(this,ht,void 0);S(this,tt,void 0);S(this,Rr,void 0);S(this,sr,void 0);S(this,Va,void 0);S(this,Ed,void 0);m(this,"audioUpdateInProgress");m(this,"videoUpdateInProgress");y(this,Ed,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,y(this,st,new bg(e,r)),y(this,ht,new oD(c(this,st),void 0,n)),y(this,tt,new mD(c(this,st),void 0,n)),y(this,sr,new uD(c(this,st))),y(this,Rr,new dD(c(this,st))),y(this,Va,i),c(this,ht).on("trackMuted",this.onAudioTrackMuted.bind(this)),c(this,ht).on("trackChanged",this.onAudioTrackChanged.bind(this)),c(this,tt).on("trackChanged",this.onVideoTrackChanged.bind(this)),c(this,tt).on("trackEnded",this.onVideoTrackEnded.bind(this)),c(this,sr).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}async onVisibilityChange(){U.tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?U.browserBackgrounded():(U.browserForegrounded(),await this.setupSpeaker())}async repopulateAvailableDevices(){return!0}async setupStreams({audio:e,video:r}){var a;let n,i;if(e&&r)try{const o=await c(this,st).getAudioAndVideoTrack();n=o.audioTrack,i=o.videoTrack}catch(o){l.error("LocalMediaHandler::init::Failed to get audio video tracks",{error:o})}if(!n&&e)try{n=await c(this,st).getAudioTrack(!1)}catch(o){l.error("LocalMediaHandler::init::Failed to get audio track",{error:o})}if(!i&&r)try{i=await c(this,st).getVideoTrack()}catch(o){l.error("LocalMediaHandler::init::Failed to get video track",{error:o})}await c(this,ht).setMediaTrack(n),await c(this,tt).setMediaTrack(i);try{await c(this,Rr).setupSpeaker()}catch(o){}if(i){const o=await this.getDeviceById(i.getSettings().deviceId);U.onSafeInitialization(()=>{U.selectedDevice("VIDEO",o)})}if(n){const o=await this.getDeviceById(n.getSettings().deviceId);U.onSafeInitialization(()=>{U.selectedDevice("AUDIO",o)})}(a=c(this,Rr).currentDevice)!=null&&a.deviceId&&U.onSafeInitialization(()=>{U.selectedDevice("SPEAKER",c(this,Rr).currentDevice)}),c(this,st).onDeviceChange((o,d,u)=>{this.onDeviceChange(d,u)})}getCurrentDevices(){return{audio:c(this,ht).currentDevice,video:c(this,tt).currentDevice,speaker:c(this,Rr).currentDevice}}get permissions(){return c(this,st).permissions}getAllDevices(){return c(this,st).getAvailableDevices()}getDeviceById(e,r){return c(this,st).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return c(this,ht).mediaTrack}get audioTrack(){return c(this,ht).transformedMediaTrack}get audioEnabled(){return c(this,ht).trackEnabled}async enableAudio(){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{await c(this,ht).unmuteTrack()}catch(e){}finally{this.audioUpdateInProgress=!1}}}disableAudio(){c(this,ht).muteTrack()}getAudioDevices(e){return c(this,st).getAudioInputDevices(e)}async setAudioDevice(e){await c(this,ht).setDevice(e),e!=null&&e.deviceId&&U.onSafeInitialization(()=>{U.selectedDevice("AUDIO",e)}),this.emit("AUDIO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}setupSpeaker(){return c(this,Rr).setupSpeaker()}async setSpeakerDevice(e){await c(this,Rr).setupSpeaker(e),e!=null&&e.deviceId&&U.onSafeInitialization(()=>{U.selectedDevice("SPEAKER",e)}),this.emit("DEVICE_CHANGE",{device:e})}onVideoTrackChanged(){this.emit("VIDEO_TRACK_CHANGE")}onVideoTrackEnded(){this.emit("VIDEO_TRACK_CHANGE")}get rawVideoTrack(){return c(this,tt).mediaTrack}get videoTrack(){return c(this,tt).transformedMediaTrack}get videoEnabled(){return c(this,tt).trackEnabled}async enableVideo(){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{await c(this,tt).unmuteTrack()}catch(e){}finally{this.videoUpdateInProgress=!1}}}disableVideo(){c(this,tt).disableTrack()}getVideoDevices(e){return c(this,st).getVideoInputDevices(e)}async setVideoDevice(e){await c(this,tt).setDevice(e),e!=null&&e.deviceId&&U.onSafeInitialization(()=>{U.selectedDevice("VIDEO",e)}),this.emit("VIDEO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async updateVideoConstraints(e){await c(this,tt).updateConstraints(e)}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:c(this,sr).audioMediaTrack,video:c(this,sr).videoMediaTrack}}get screenShareEnabled(){return c(this,sr).trackEnabled}async enableScreenShare(){await c(this,sr).enableScreenShare()}async disableScreenShare(){c(this,sr).disableScreenShare()}async updateScreenshareConstraints(e){await c(this,sr).updateConstraints(e)}getSpeakerDevices(e){return c(this,st).getAudioOutputDevices(e)}addAudioMiddleware(e){return c(this,ht).addMiddleware(e)}removeAudioMiddleware(e){return c(this,ht).removeMiddleware(e)}addVideoMiddleware(e){return c(this,tt).addMiddleware(e)}removeVideoMiddleware(e){return c(this,tt).removeMiddleware(e)}setVideoMiddlewareGlobalConfig(e){return c(this,tt).setVideoMiddlewareGlobalConfig(e)}destruct(){c(this,ht).disableTrack(),c(this,tt).disableTrack(),c(this,tt).terminateMiddlewareWebWorker(),c(this,sr).disableScreenShare(),c(this,st).destruct()}async onDeviceChange(e,r){var n,i;this.emit("DEVICE_LIST_UPDATED",e),!(r||!c(this,Va))&&((n=e==null?void 0:e.added)==null||n.forEach(async a=>{var o;a&&!Hc(a)&&(a.kind==="audioinput"&&((o=this.audioTrack)==null?void 0:o.enabled)===!0?await this.setAudioDevice(a):a.kind==="audiooutput"&&await this.setSpeakerDevice(a))}),(i=e==null?void 0:e.removed)==null||i.forEach(async a=>{var o;if(a.kind==="audiooutput"&&((o=this.getCurrentDevices().speaker)==null?void 0:o.deviceId)===a.deviceId){const d=(await this.getSpeakerDevices()).find(u=>u.deviceId!==a.deviceId);d&&await this.setSpeakerDevice(d)}}))}removeAllTracks(){this.destruct()}async removeDocumentEventListeners(){document.removeEventListener("visibilitychange",this.onVisibilityChange)}}st=new WeakMap,ht=new WeakMap,tt=new WeakMap,Rr=new WeakMap,sr=new WeakMap,Va=new WeakMap,Ed=new WeakMap,jt([g.trace("MediaHandler.setupStreams")],Ft.prototype,"setupStreams",1),jt([g.trace("MediaHandler.enableAudio")],Ft.prototype,"enableAudio",1),jt([g.trace("MediaHandler.disableAudio")],Ft.prototype,"disableAudio",1),jt([g.trace("MediaHandler.setAudioDevice")],Ft.prototype,"setAudioDevice",1),jt([g.trace("MediaHandler.enableVideo")],Ft.prototype,"enableVideo",1),jt([g.trace("MediaHandler.disableVideo")],Ft.prototype,"disableVideo",1),jt([g.trace("MediaHandler.setVideoDevice")],Ft.prototype,"setVideoDevice",1),jt([g.trace("MediaHandler.updateVideoConstraints")],Ft.prototype,"updateVideoConstraints",1),jt([g.trace("MediaHandler.enableScreenShare")],Ft.prototype,"enableScreenShare",1),jt([g.trace("MediaHandler.disableScreenShare")],Ft.prototype,"disableScreenShare",1),jt([g.trace("MediaHandler.updateScreenshareConstraints")],Ft.prototype,"updateScreenshareConstraints",1),jt([g.trace("MediaHandler.destruct")],Ft.prototype,"destruct",1),jt([g.trace("MediaHandler.onDeviceChange")],Ft.prototype,"onDeviceChange",1);function Bc(s,t,e){switch(!0){case Se.isChromiumBased():switch(t){case"NotAllowedError":return e.includes("by system")?"SYSTEM_DENIED":s==="screenshare"?"CANCELED":"DENIED";case"NotReadableError":default:return"COULD_NOT_START"}case Se.isSafari():switch(t){case"NotAllowedError":return"DENIED";default:return"COULD_NOT_START"}case Se.isFirefox():switch(t){case"NotFoundError":case"NotReadableError":return"SYSTEM_DENIED";case"NotAllowedError":return"DENIED";case"AbortError":default:return"COULD_NOT_START"}default:return"COULD_NOT_START"}}const O0=["virtual","emulator","krisp","solstice conference","teams","manycam","blackHole"];function Hc(s){const t=s.label.toLowerCase();return Se._bowser.getOSName()==="macOS"&&t.includes("iphone")?(l.log("isVirtualDevice::ignore_macos_continuity"),!0):O0.some(e=>t.includes(e))}async function N0(s,t){if(!(s!=null&&s.length))return t;const e=new AudioContext,r=await Promise.all(s==null?void 0:s.map(a=>a(e))),n=e.createMediaStreamSource(new MediaStream([t])),i=e.createMediaStreamDestination();try{let a=n;for(let o=0;o(t,e)=>(s.set(t,e),e),gg=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,vg=536870912,yg=vg*2,F0=(s,t)=>e=>{const r=t.get(e);let n=r===void 0?e.size:rgg)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;e.has(n);)n=Math.floor(Math.random()*gg);return s(e,n)},Tg=new WeakMap,x0=L0(Tg),qc=F0(x0,Tg),U0=s=>s.method!==void 0&&s.method==="call",V0=s=>s.error===null&&typeof s.id=="number",jc=((s,t)=>{let e=null;return()=>{if(e!==null)return e;const r=new Blob([t],{type:"application/javascript; charset=utf-8"}),n=URL.createObjectURL(r);return e=s(n),setTimeout(()=>URL.revokeObjectURL(n)),e}})(s=>{const t=new Map([[0,()=>{}]]),e=new Map([[0,()=>{}]]),r=new Map,n=new Worker(s);return n.addEventListener("message",({data:u})=>{if(U0(u)){const{params:{timerId:h,timerType:p}}=u;if(p==="interval"){const f=t.get(h);if(typeof f=="number"){const v=r.get(f);if(v===void 0||v.timerId!==h||v.timerType!==p)throw new Error("The timer is in an undefined state.")}else if(typeof f!="undefined")f();else throw new Error("The timer is in an undefined state.")}else if(p==="timeout"){const f=e.get(h);if(typeof f=="number"){const v=r.get(f);if(v===void 0||v.timerId!==h||v.timerType!==p)throw new Error("The timer is in an undefined state.")}else if(typeof f!="undefined")f(),e.delete(h);else throw new Error("The timer is in an undefined state.")}}else if(V0(u)){const{id:h}=u,p=r.get(h);if(p===void 0)throw new Error("The timer is in an undefined state.");const{timerId:f,timerType:v}=p;r.delete(h),v==="interval"?t.delete(f):e.delete(f)}else{const{error:{message:h}}=u;throw new Error(h)}}),{clearInterval:u=>{const h=qc(r);r.set(h,{timerId:u,timerType:"interval"}),t.set(u,h),n.postMessage({id:h,method:"clear",params:{timerId:u,timerType:"interval"}})},clearTimeout:u=>{const h=qc(r);r.set(h,{timerId:u,timerType:"timeout"}),e.set(u,h),n.postMessage({id:h,method:"clear",params:{timerId:u,timerType:"timeout"}})},setInterval:(u,h=0)=>{const p=qc(t);return t.set(p,()=>{u(),typeof t.get(p)=="function"&&n.postMessage({id:null,method:"set",params:{delay:h,now:performance.now(),timerId:p,timerType:"interval"}})}),n.postMessage({id:null,method:"set",params:{delay:h,now:performance.now(),timerId:p,timerType:"interval"}}),p},setTimeout:(u,h=0)=>{const p=qc(e);return e.set(p,u),n.postMessage({id:null,method:"set",params:{delay:h,now:performance.now(),timerId:p,timerType:"timeout"}}),p}}},`(()=>{"use strict";const e=new Map,t=new Map,r=(e,t)=>{let r,o;const i=performance.now();r=i,o=e-Math.max(0,i-t);return{expected:r+o,remainingDelay:o}},o=(e,t,r,i)=>{const s=performance.now();s>r?postMessage({id:null,method:"call",params:{timerId:t,timerType:i}}):e.set(t,setTimeout(o,r-s,e,t,r,i))};addEventListener("message",(i=>{let{data:s}=i;try{if("clear"===s.method){const{id:r,params:{timerId:o,timerType:i}}=s;if("interval"===i)(t=>{const r=e.get(t);if(void 0===r)throw new Error('There is no interval scheduled with the given id "'.concat(t,'".'));clearTimeout(r),e.delete(t)})(o),postMessage({error:null,id:r});else{if("timeout"!==i)throw new Error('The given type "'.concat(i,'" is not supported'));(e=>{const r=t.get(e);if(void 0===r)throw new Error('There is no timeout scheduled with the given id "'.concat(e,'".'));clearTimeout(r),t.delete(e)})(o),postMessage({error:null,id:r})}}else{if("set"!==s.method)throw new Error('The given method "'.concat(s.method,'" is not supported'));{const{params:{delay:i,now:n,timerId:a,timerType:d}}=s;if("interval"===d)((t,i,s)=>{const{expected:n,remainingDelay:a}=r(t,s);e.set(i,setTimeout(o,a,e,i,n,"interval"))})(i,a,n);else{if("timeout"!==d)throw new Error('The given type "'.concat(d,'" is not supported'));((e,i,s)=>{const{expected:n,remainingDelay:a}=r(e,s);t.set(i,setTimeout(o,a,t,i,n,"timeout"))})(i,a,n)}}}}catch(e){postMessage({error:{message:e.message},id:s.id,result:null})}}))})();`),_g=s=>jc().clearInterval(s),$0=s=>jc().clearTimeout(s),Sg=(s,t)=>jc().setInterval(s,t),B0=Object.freeze(Object.defineProperty({__proto__:null,clearInterval:_g,clearTimeout:$0,setInterval:Sg,setTimeout:(s,t)=>jc().setTimeout(s,t)},Symbol.toStringTag,{value:"Module"}));class H0{constructor(){S(this,On,void 0)}terminateMiddlewareWebWorker(){if(c(this,On))try{_g(c(this,On)),y(this,On,void 0)}catch(t){l.debug("WorkerTimers::terminateMiddlewareWebWorker::failed")}}async getTransformedVideoTrack(t,e,r){if(!(t!=null&&t.length))return e;const n=document.createElement("canvas"),i=await Promise.all(t==null?void 0:t.map(p=>p({canvas:n,WorkerTimers:B0})));if(r.disablePerFrameCanvasRendering)return n.captureStream().getVideoTracks()[0];const a=document.createElement("video"),o=new MediaStream;o.addTrack(e);const d=n.getContext("2d");a.srcObject=o,a.autoplay=!0,this.terminateMiddlewareWebWorker();const u=async()=>{if(e.enabled===!1||e.readyState==="ended"){this.terminateMiddlewareWebWorker(),a.remove(),n.remove();return}try{d.drawImage(a,0,0);for(let p=0;p{n.width=a.width||e.getSettings().width,n.height=a.width||e.getSettings().height,y(this,On,Sg(u,50))},!1),n.captureStream().getVideoTracks()[0]}}On=new WeakMap;const Eg={gross:{width:{ideal:192},height:{ideal:144}},qvga:{width:{ideal:384},height:{ideal:288}},pvga:{width:{ideal:480},height:{ideal:360}},vga:{width:{ideal:640},height:{ideal:480}},hd:{width:{ideal:1280},height:{ideal:720}},hd_cropped:{width:{ideal:900},height:{ideal:720}},fhd:{width:{ideal:1920},height:{ideal:1080}}},wg={320:[{rid:"q",maxBitrate:25e4,maxFramerate:24,scalabilityMode:"L1T1"}],640:[{rid:"q",scaleResolutionDownBy:2,maxBitrate:25e4,maxFramerate:24,scalabilityMode:"L1T1"},{rid:"h",maxBitrate:7e5,maxFramerate:30,scalabilityMode:"L1T1"}],1280:[{rid:"q",scaleResolutionDownBy:2,maxBitrate:5e5,maxFramerate:24,scalabilityMode:"L1T1"},{rid:"h",maxBitrate:13e5,maxFramerate:30,scalabilityMode:"L1T1"}]},q0={320:[{rid:"q",maxBitrate:25e4,maxFramerate:24,scalabilityMode:"L1T1"}],640:[{rid:"h",maxBitrate:7e5,maxFramerate:30,scalabilityMode:"L1T1"}],1280:[{rid:"h",maxBitrate:14e5,maxFramerate:30,scalabilityMode:"L1T1"}]},Cg={320:[{rid:"q",maxBitrate:25e4,maxFramerate:24,scalabilityMode:"L1T1"}],640:[{rid:"q",scaleResolutionDownBy:2,maxBitrate:25e4,maxFramerate:24,scalabilityMode:"L1T1"},{rid:"h",maxBitrate:7e5,maxFramerate:30,scalabilityMode:"L1T1"}],1280:[{rid:"q",scaleResolutionDownBy:2,maxBitrate:5e5,maxFramerate:24,scalabilityMode:"L1T1"},{rid:"h",maxBitrate:13e5,maxFramerate:30,scalabilityMode:"L1T1"}]};var Y=(s=>(s.WEBCAM="webcam",s.MIC="mic",s.SCREENSHARE_VIDEO="screenshare_video",s.SCREENSHARE_AUDIO="screenshare_audio",s))(Y||{});const j0=Cw(),ni=wr(j0.config.media);function G0(s){var e,r;const t={};return s.audio&&(t.audio={enableStereo:(e=s.audio.enableStereo)!=null?e:!1,enableHighBitrate:(r=s.audio.enableHighBitrate)!=null?r:!1}),t.video=s.video.quality,t}class J0{constructor(t,e){S(this,Nn,void 0);S(this,wd,void 0);m(this,"getScreenShareConstraints",()=>{var u,h,p,f,v,T,P,k,I;const t=(u=c(this,Nn))==null?void 0:u.screenshare,e=(p=(h=t==null?void 0:t.width)==null?void 0:h.max)!=null?p:1920,r=(v=(f=t==null?void 0:t.height)==null?void 0:f.max)!=null?v:1080,n=(P=(T=t==null?void 0:t.frameRate)==null?void 0:T.max)!=null?P:5;let i=(I=(k=t==null?void 0:t.frameRate)==null?void 0:k.ideal)!=null?I:5;const a=t==null?void 0:t.displaySurface,o=t==null?void 0:t.selfBrowserSurface;J.getValue(X.VAL_MIN_FRAMERATE)&&(i=parseInt(J.getValue(X.VAL_MIN_FRAMERATE),10));let d={width:{max:e},height:{max:r},frameRate:{ideal:i,max:n}};if(J.hasFeature(X.SCREENSHARE_CONSTRAINTS)){const x=J.getValue(X.SCREENSHARE_CONSTRAINTS);d=JSON.parse(x)}return a!==void 0&&["monitor","browser","window"].includes(a)&&(d={...d,displaySurface:a}),o!==void 0&&(d={...d,selfBrowserSurface:o}),{audio:!0,video:d}});m(this,"getAudioConstraints",t=>{var i,a,o,d,u,h,p,f;const e={},r=(i=c(this,Nn))==null?void 0:i.audio,n=r!=null&&r.enableStereo?2:1;return Se.isFirefox()||Se.isWebKitBased()?(e.audio={deviceId:t,autoGainControl:(a=r==null?void 0:r.autoGainControl)!=null?a:!0,echoCancellation:(o=r==null?void 0:r.echoCancellation)!=null?o:!0,noiseSuppression:(d=r==null?void 0:r.noiseSupression)!=null?d:!0,channelCount:n},e):(e.audio={},e.audio.optional=[t?{sourceId:t}:{sourceId:"default"},{channelCount:n},{echoCancellation:(u=r==null?void 0:r.echoCancellation)!=null?u:!0},{googEchoCancellation:(h=r==null?void 0:r.echoCancellation)!=null?h:!0},{googAutoGainControl:(p=r==null?void 0:r.autoGainControl)!=null?p:!0},{googNoiseSuppression:(f=r==null?void 0:r.noiseSupression)!=null?f:!0},{googHighpassFilter:!0}],e)});m(this,"getVideoConstraints",t=>{var i,a,o;const e={},r=(i=c(this,Nn))==null?void 0:i.video;let n=Eg.vga;if(typeof r=="string"?n=Eg[r]:r!==void 0&&(n.height.ideal=r.height.ideal,n.width.ideal=r.width.ideal),n.frameRate={ideal:(o=(a=n.frameRate)==null?void 0:a.ideal)!=null?o:24},Se.isChromiumBased()&&(n.frameRate.max=30),J.hasFeature(X.VIDEO_CONSTRAINTS)){const d=J.getValue(X.VIDEO_CONSTRAINTS);n=JSON.parse(d)}return e.video=n,typeof e.video=="boolean"||(t?e.video.deviceId={exact:t}:e.video.facingMode="user"),e});y(this,wd,t),y(this,Nn,e)}getUpdatedVideoConstraints(t){return t}}Nn=new WeakMap,wd=new WeakMap;class mu extends Error{constructor(e,r,n){super(r);m(this,"constraints");m(this,"name");this.name=e,this.constraints=n}}class W0{constructor(){m(this,"permissions");this.permissions={audio:"NOT_REQUESTED",video:"NOT_REQUESTED",screenshare:"NOT_REQUESTED"}}async getAudioInputDevices(t){let e=t;return t||(e=await this.getAvailableDevices()),e.filter(r=>r.kind==="audioinput")}async getVideoInputDevices(t){let e=t;return t||(e=await this.getAvailableDevices()),e.filter(r=>r.kind==="videoinput")}async getAudioOutputDevices(t){let e=t;return t||(e=await this.getAvailableDevices()),e.filter(r=>r.kind==="audiooutput")}}var K0=Object.defineProperty,z0=Object.getOwnPropertyDescriptor,hr=(s,t,e,r)=>{for(var n=r>1?void 0:r?z0(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&K0(t,e,n),n};let Gt=(Ov=class extends W0{constructor(t,e){super();m(this,"availableDevices");S(this,Di,void 0);S(this,kr,void 0);S(this,Cd,void 0);y(this,Cd,t),y(this,kr,new J0(t,e)),y(this,Di,new AbortController),this.availableDevices=[],this.getAvailableDevices()}get constraintsBuilder(){return c(this,kr)}async destruct(){var t;(t=c(this,Di))==null||t.abort()}handlePermissionErrors(t,e){const r=Bc(t,e.name,e.message);return this.permissions[t]=r,w.emit(C.MEDIA_PERMISSION_ERROR,{message:r,constraints:e.constraints,kind:t}),r}async getAudioAndVideoTrack(){const t={audio:c(this,kr).getAudioConstraints().audio,video:c(this,kr).getVideoConstraints().video};try{l.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(t)});const e=await navigator.mediaDevices.getUserMedia(t);l.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(t)});const r=e.getAudioTracks()[0];let n=e.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",J.hasFeature(X.OBS_QUALITY)&&n.label.includes("OBS Virtual")){const o=(await this.getVideoInputDevices()).find(d=>d.label.includes("OBS Virtual"));n=await this.getVideoTrack(o.deviceId)}return w.emit(C.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),w.emit(C.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:r,videoTrack:n}}catch(e){throw l.error("WebMediaInterface.getAudioAndVideoTrack",{error:e}),new b("Couldnt fetch audio and video track")}}async getAudioTrack(t,e){let r=await this.getAudioInputDevices();if(r.length===0)throw this.permissions.audio="NO_DEVICES_AVAILABLE",w.emit(C.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),new b("No audio devices available");const n=async i=>{let a;try{r=r.filter(d=>d.deviceId!==i),a=c(this,kr).getAudioConstraints(i),l.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(a)});const[o]=(await navigator.mediaDevices.getUserMedia(a)).getAudioTracks();return l.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(a)}),o}catch(o){const d=Bc("audio",o.name,o.message),u=new mu(o.name,o.message,a);if(d==="COULD_NOT_START"){const h=r.shift();if(!h)throw u;return n(h.deviceId)}throw u}};try{const i=await n(e);return i.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",w.emit(C.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"})),i}catch(i){throw i.constraints&&this.handlePermissionErrors("audio",i),new b(i.message,"1601")}}async getVideoTrack(t){var o;const e=J.hasFeature(X.OBS_QUALITY),r=(o=await this.getCurrentDeviceLabel(t))==null?void 0:o.includes("OBS Virtual"),n=e&&r,i=await this.getVideoInputDevices();if(i.length===0)throw this.permissions.video="NO_DEVICES_AVAILABLE",w.emit(C.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),new b("No video devices available");const a=async d=>{try{let u=d;const{video:h}=u;n&&typeof h!="boolean"&&(u={video:{deviceId:h.deviceId}}),l.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(u)});const[p]=(await navigator.mediaDevices.getUserMedia(u)).getVideoTracks();if(n&&typeof h!="boolean"&&typeof h.width=="object"){const{width:f,height:v}=p.getSettings(),{ideal:T}=h.width;p.applyConstraints({width:{ideal:T},height:{ideal:Math.floor(v*T/f)},frameRate:h.frameRate})}return l.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(u)}),p}catch(u){const h=Bc("video",u.name,u.message),p=new mu(u.name,u.message,d);if(h==="COULD_NOT_START"){if(!i.shift())throw p;return a({video:d.video})}throw p}};try{const d=c(this,kr).getVideoConstraints(t),u=await a(d);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",w.emit(C.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"})),u}catch(d){throw d.constraints&&this.handlePermissionErrors("video",d),new b(d.message,"1601")}}async getScreenShareTracks(){const t=async e=>{try{l.info("getDisplayMediaWithoutTimeout::requesting_display_media",{constraints:JSON.stringify(e)}),U.screenShareRequested();const r=await navigator.mediaDevices.getDisplayMedia(e);return l.info("getDisplayMediaWithoutTimeout::received_display_media",{constraints:JSON.stringify(e)}),r}catch(r){const n=Bc("video",r.name,r.message),i=new mu(r.name,r.message,e),a={video:!0};if(jC(e,a)||!J.hasFeature(X.SCREEENSHARE_CONSTRAINTS_RETRY))throw i;if(n==="COULD_NOT_START")return t(a);throw i}};try{const e=c(this,kr).getScreenShareConstraints(),r=await t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",w.emit(C.MEDIA_PERMISSION_UPDATE,{message:this.permissions.screenshare,kind:"screenshare"})),{audioTrack:r.getAudioTracks()[0],videoTrack:r.getVideoTracks()[0]}}catch(e){throw e.constraints&&this.handlePermissionErrors("screenshare",e),new b(e.message,"1601")}}async getCurrentDeviceLabel(t){const e=await this.getDevice(t||"default");return e==null?void 0:e.label}async getAvailableDevices(){try{const t=await navigator.mediaDevices.enumerateDevices();return this.availableDevices=t,t}catch(t){throw l.error("enumerate_devices_failed",{error:t}),new b("Failed to get available devices")}}async getAvailableDevicesByKind(t){try{return(await navigator.mediaDevices.enumerateDevices()).filter(({kind:e})=>t===e)}catch(e){throw l.error("enumerate_devices_failed",{error:e}),new b("Failed to get available devices by kind")}}async getDevice(t){try{return(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.deviceId===t)[0]}catch(e){throw l.error("enumerate_devices_failed",{error:e}),new b("Failed to get device")}}async onDeviceChange(t){Se.supportsDeviceChangeEvent()&&navigator.mediaDevices.addEventListener("devicechange",async e=>{var u,h;const r=p=>`${p.kind}-${p.deviceId}`,n=this.availableDevices,i=new Set(n.map(p=>r(p))),a=await this.getAvailableDevices(),o=new Set(a.map(p=>r(p))),d={added:a.filter(p=>!i.has(r(p))),removed:n.filter(p=>!o.has(r(p))),devices:a};if((u=d.added)!=null&&u.length||(h=d.removed)!=null&&h.length){l.info("repopulated_full_device_list",{devices:JSON.stringify(a)});const p=[...d.added,...d.removed];U.onSafeInitialization(async()=>{p.some(f=>f.kind==="audioinput")&&U.devices("AUDIO",a==null?void 0:a.filter(f=>f.kind==="audioinput")),p.some(f=>f.kind==="videoinput")&&U.devices("VIDEO",a==null?void 0:a.filter(f=>f.kind==="videoinput")),p.some(f=>f.kind==="audiooutput")&&U.devices("SPEAKER",a==null?void 0:a.filter(f=>f.kind==="audiooutput"))}),t(e,d,!1)}},{signal:c(this,Di).signal})}},Di=new WeakMap,kr=new WeakMap,Cd=new WeakMap,Ov);hr([g.trace("WebMediaInterface.destruct")],Gt.prototype,"destruct",1),hr([g.trace("WebMediaInterface.handlePermissionErrors")],Gt.prototype,"handlePermissionErrors",1),hr([g.trace("WebMediaInterface.getAudioAndVideoTrack")],Gt.prototype,"getAudioAndVideoTrack",1),hr([g.trace("WebMediaInterface.getAudioTrack")],Gt.prototype,"getAudioTrack",1),hr([g.trace("WebMediaInterface.getVideoTrack")],Gt.prototype,"getVideoTrack",1),hr([g.trace("WebMediaInterface.getScreenShareTracks")],Gt.prototype,"getScreenShareTracks",1),hr([g.trace("WebMediaInterface.getAvailableDevices")],Gt.prototype,"getAvailableDevices",1),hr([g.trace("WebMediaInterface.getAvailableDevicesByKind")],Gt.prototype,"getAvailableDevicesByKind",1),hr([g.trace("WebMediaInterface.getDevice")],Gt.prototype,"getDevice",1),hr([g.trace("WebMediaInterface.onDeviceChange")],Gt.prototype,"onDeviceChange",1),Gt=hr([pt("1600")],Gt);const bg=Gt,fu={setItem:(s,t)=>{try{localStorage.setItem(s,t)}catch(e){l.error("LocalStorage::setItem::crashed",{error:e,localStorage:{key:s,value:t}})}},getItem:s=>{try{return localStorage.getItem(s)}catch(t){l.error("LocalStorage::getItem::crashed",{error:t,localStorage:{key:s}})}return null}},Y0=(s=0)=>new Promise(t=>setTimeout(t,s)),Q0=(s,t,e)=>{const r=typeof e=="number"?e:250,n=s.createMediaStreamSource(t),i=s.createAnalyser();i.fftSize=2048,n.connect(i);const a=new Uint8Array(i.fftSize);let o=!1;setTimeout(()=>{o=!0},r);function d(){return o?Promise.resolve(!0):(i.getByteTimeDomainData(a),a.some(u=>u!==128&&u!==0)?Promise.resolve(!1):Y0().then(d))}return d().then(u=>(n.disconnect(),u),u=>{throw n.disconnect(),u})},X0=typeof AudioContext!="undefined"?AudioContext:null;class gu{constructor(t){m(this,"_AudioContext");m(this,"audioContext");m(this,"_audioContextRefContainers");const e={AudioContext:X0,...t};Object.defineProperties(this,{_AudioContext:{value:e.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:gu}})}getOrCreate(t){if(!this._audioContextRefContainers.has(t)&&(this._audioContextRefContainers.add(t),this._AudioContext&&!this.audioContext))try{this.audioContext=new this._AudioContext}catch(e){}return this.audioContext}release(t){this._audioContextRefContainers.has(t)&&(this._audioContextRefContainers.delete(t),!this._audioContextRefContainers.size&&this.audioContext&&(this.audioContext.close(),this.audioContext=null))}}const Pg=new gu,Z0=3,eD=250;function tD(s){const t={},e=Pg.getOrCreate(t);let r=Z0;function n(){return r-=1,Q0(e,s.srcObject,eD).then(i=>i?r>0?n():!0:!1).catch(()=>!0)}return n().finally(()=>{Pg.release(t)})}async function Rg(s){const t=new Audio,e=new MediaStream;e.addTrack(s),t.srcObject=e;let r=!1;try{const n=t.play();n&&await n,r=await tD(t),r&&l.info("checkIfAudioTrackIsSilent::silence_detected")}catch(n){l.error("checkIfAudioTrackIsSilent::failed_to_detect_silence",{error:n})}finally{t.pause(),t.remove()}return r}var rD=Object.defineProperty,sD=Object.getOwnPropertyDescriptor,nD=(s,t,e,r)=>{for(var n=r>1?void 0:r?sD(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&rD(t,e,n),n};let vu=class extends Zn{constructor(t,e,r){super();m(this,"constructorName",this.constructor.name);m(this,"userSelectedDevice");m(this,"mediaInterface");m(this,"isNonPreferredDevice");m(this,"_mediaTrack");m(this,"transformedMediaTrack");m(this,"middlewares",[]);m(this,"currentDevice");this.mediaInterface=t,e&&this.setMediaTrack(e),this.userSelectedDevice=void 0,this.isNonPreferredDevice=r,this.onTrackEnded=this.onTrackEnded.bind(this),this.onTrackMuted=this.onTrackMuted.bind(this)}disableTrack(){var t,e;this.removeMediaTrackListeners(),(t=this._mediaTrack)==null||t.stop(),this._mediaTrack=void 0,(e=this.transformedMediaTrack)==null||e.stop(),this.transformedMediaTrack=void 0}get mediaTrack(){return this._mediaTrack}async setMediaTrack(t){const e=r=>{l.error(`${this.constructorName}.setMediaTrack.error`,{error:r})};try{this.disableTrack()}catch(r){e(r)}this._mediaTrack=await this.conditionallyChangeTrack(t),await this.setTransformedTrack();try{this.addMediaTrackListeners(),await this.setCurrentDevice()}catch(r){e(r)}}get trackEnabled(){return!!this.mediaTrack&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled}muteTrack(){if(!this.mediaTrack){l.warn("BaseMediaHandler.muteTrack Tried muting with no track present");return}this.transformedMediaTrack&&(this.transformedMediaTrack.enabled=!1),this.mediaTrack.enabled=!1}async unmuteTrack(){try{this.mediaTrack?this.mediaTrack.enabled=!0:await this.enableTrack(!1)}catch(t){throw l.error(`${this.constructorName}.unmuteTrack.error`,{error:t}),this.disableTrack(),new b("Failed to unmute track")}}async setCurrentDevice(){var t;if(!this.mediaTrack){this.currentDevice=void 0;return}((t=this.currentDevice)==null?void 0:t.deviceId)!==this.mediaTrack.getSettings().deviceId&&(this.currentDevice=await this.mediaInterface.getDevice(this.mediaTrack.getSettings().deviceId))}async addMiddleware(t){if(Se.isWebKitBased()&&!J.hasFeature(X.ALLOW_SAFARI_MEDIA_MIDDLEWARES))return{success:!1,message:"Middlewares are not supported in this WebKit engine based browser."};if(this.middlewares.includes(t))return{success:!1,message:"This middleware has been applied, already. Skipping."};try{return this.middlewares.push(t),this.trackEnabled&&await this.setTransformedTrack(),{success:!0,message:"Successfully added the middleware."}}catch(e){return l.error("While adding middleware",{error:e}),this.removeMiddleware(t),{success:!1,message:e==null?void 0:e.message}}}async removeMiddleware(t){const e=this.middlewares.indexOf(t,0);if(e>-1)try{return this.middlewares.splice(e,1),await this.setTransformedTrack(!0),{success:!0,message:"Successfully removed the middleware."}}catch(r){return l.error("While removing middleware",{error:r}),{success:!1,message:r==null?void 0:r.message}}return{success:!1,message:"No such middleware was found. Skipping."}}addMediaTrackListeners(){var t,e,r;this.mediaTrack&&(l.info(`${this.constructorName}.addMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(r=this.mediaTrack)==null?void 0:r.kind}`),this.mediaTrack.addEventListener("ended",this.onTrackEnded),this.mediaTrack.addEventListener("mute",this.onTrackMuted))}removeMediaTrackListeners(){var t,e,r;this.mediaTrack&&(l.info(`${this.constructorName}.removeMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(r=this.mediaTrack)==null?void 0:r.kind}`),l.info(`${this.constructorName}.removeMediaTrackListeners`),this.mediaTrack.removeEventListener("ended",this.onTrackEnded),this.mediaTrack.removeEventListener("mute",this.onTrackMuted))}};vu=nD([pt("1600")],vu);const kg=vu;var iD=Object.defineProperty,aD=Object.getOwnPropertyDescriptor,yu=(s,t,e,r)=>{for(var n=r>1?void 0:r?aD(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&iD(t,e,n),n};const Tu="[Dyte]nonSilentDeviceLabels";class Gc extends kg{async setDevice(t){if(!t)throw l.warn("AudioMediaHandler.setDevice No device received"),new b("No device received!","1603");if(t.kind!=="audioinput")throw l.warn("AudioMediaHandler.setDevice Received non audio device"),new b("Non audio device received while setting device!","1603");try{const e=this.trackEnabled;this.userSelectedDevice=t.deviceId,await this.setMediaTrack(await this.mediaInterface.getAudioTrack(!e,t.deviceId))}catch(e){throw l.error("AudioMediaHandler.setDevice.error",{error:e}),this.disableTrack(),new b(e.message,"1604")}}async enableTrack(t){if(this.trackEnabled){l.warn("AudioMediaHandler.enableTrack Track already enabled!");return}const e=await this.mediaInterface.getAudioTrack(t,this.userSelectedDevice);await this.setMediaTrack(e)}async setTransformedTrack(t){var e;if(!t&&!((e=this.middlewares)!=null&&e.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=await N0(this.middlewares,this.mediaTrack),this.emit("trackChanged")}catch(r){l.error("AudioMediaHandler.setTransformedTrack",{error:r}),this.transformedMediaTrack=this.mediaTrack}}async onTrackEnded(){l.info("AudioMediaHandler.TrackEnded"),this.emit("trackEnded");const t=this.mediaTrack.enabled;this.disableTrack(),await this.enableTrack(!t),await this.setTransformedTrack(),this.emit("trackChanged")}onTrackMuted(){l.info("AudioMediaHandler.TrackMuted"),this.emit("trackMuted")}async conditionallyChangeTrack(t){var o;if(!t||this.userSelectedDevice)return t;let e=t;const r=await this.mediaInterface.getAudioInputDevices(),n=this.isNonPreferredDevice?r.filter(d=>d&&!this.isNonPreferredDevice(d)):r;if(!(n!=null&&n.length))return e;n.find(d=>d.deviceId===t.getSettings().deviceId)||(e.stop(),l.info("localmediahandler::setupstreams::found_audio_non_preferred"),e=await this.mediaInterface.getAudioTrack(!1,n[0].deviceId));const i=JSON.parse(fu.getItem(Tu));if(i!=null&&i.devices.some(d=>d.label===e.label))return e;if(!await Rg(e)){const d=(o=i==null?void 0:i.devices.concat({label:e.label}))!=null?o:[{label:e.label}];return fu.setItem(Tu,JSON.stringify({devices:d})),e}l.info("AudioMediaHandler.conditionallyChangeTrack.DetectedSilentTrack");const a=e.getSettings().deviceId;return n.filter(d=>d.deviceId!==a).some(async d=>{if(e=await this.mediaInterface.getAudioTrack(!1,d.deviceId),!await Rg(e)){const u=i.devices.concat({label:e.label});return fu.setItem(Tu,JSON.stringify({devices:u})),l.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return l.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1}),e}}yu([g.trace("AudioMediaHandler.setTransformedTrack")],Gc.prototype,"setTransformedTrack",1),yu([g.trace("AudioMediaHandler.onTrackEnded")],Gc.prototype,"onTrackEnded",1),yu([g.trace("AudioMediaHandler.conditionallyChangeTrack")],Gc.prototype,"conditionallyChangeTrack",1);const oD=Gc;class cD{constructor(t){S(this,Oi,void 0);m(this,"currentDevice");y(this,Oi,t)}async setupSpeaker(t){var r;if(!(c(this,Oi)instanceof bg))return;let e=t;if(t||([e]=(await c(this,Oi).getAvailableDevicesByKind("audiooutput")).sort((i,a)=>(Hc(i)?0:1)-(Hc(a)?0:1))),!e)throw new b("No speaker found");((r=this.currentDevice)==null?void 0:r.deviceId)!==e.deviceId&&(this.currentDevice=e,document.querySelectorAll("audio").forEach(async n=>{if(typeof n.sinkId!="undefined"&&this.currentDevice.deviceId&&n.sinkId!==this.currentDevice.deviceId)try{await n.setSinkId(this.currentDevice.deviceId)}catch(i){}}))}}Oi=new WeakMap;const dD=cD;class lD extends Zn{constructor(e){super();m(this,"mediaInterface");m(this,"audioMediaTrack");m(this,"videoMediaTrack");this.mediaInterface=e}get trackEnabled(){return!!this.videoMediaTrack}async enableScreenShare(){var e,r;try{const{audioTrack:n,videoTrack:i}=await this.mediaInterface.getScreenShareTracks();if(this.audioMediaTrack=n,this.videoMediaTrack=i,this.addMediaTrackListeners(),((r=(e=this.mediaInterface)==null?void 0:e.permissions)==null?void 0:r.screenshare)==="ACCEPTED")return;this.mediaInterface.permissions&&(this.mediaInterface.permissions.screenshare="ACCEPTED",w.emit(C.MEDIA_PERMISSION_UPDATE,{message:this.mediaInterface.permissions.screenshare,kind:"screenshare"}))}catch(n){}}disableScreenShare(){var e,r;this.removeMediaTrackListeners(),(e=this.audioMediaTrack)==null||e.stop(),(r=this.videoMediaTrack)==null||r.stop(),this.videoMediaTrack=void 0,this.audioMediaTrack=void 0}async updateConstraints(e){if(!this.videoMediaTrack)throw new b("No media track enabled!");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new b("update constraints not supported for non web clients","1100");try{this.videoMediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),this.addMediaTrackListeners()}catch(n){l.error("ScreenShareHandler.updateConstraints.error",{error:n})}}addMediaTrackListeners(){var e,r;(e=this.videoMediaTrack)==null||e.addEventListener("ended",this.onTrackEnded.bind(this)),Se.isWebKitBased()&&((r=this.videoMediaTrack)==null||r.addEventListener("mute",this.onTrackEnded.bind(this)))}removeMediaTrackListeners(){var e,r;(e=this.videoMediaTrack)==null||e.removeEventListener("ended",this.onTrackEnded),(r=this.videoMediaTrack)==null||r.removeEventListener("mute",this.onTrackEnded)}onTrackEnded(){this.emit("trackEnded")}}const uD=lD;var hD=Object.defineProperty,pD=Object.getOwnPropertyDescriptor,Jc=(s,t,e,r)=>{for(var n=r>1?void 0:r?pD(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&hD(t,e,n),n};class ya extends kg{constructor(e,r,n){super(e,r,n);S(this,Ni,void 0);S(this,$a,{disablePerFrameCanvasRendering:!1});y(this,Ni,new H0)}async setDevice(e){if(!e)throw l.warn("VideoMediaHandler.setDevice No device received"),new b("No device received!");if(e.kind!=="videoinput")throw l.warn("VideoMediaHandler.setDevice Received non video device",{devices:[e]}),new b("Non video device received while setting video device!");if(this.userSelectedDevice=e.deviceId,!(this.mediaTrack&&this.mediaTrack.enabled)){l.warn("VideoMediaHandler.setDevice Tried switching device with video disabled",{devices:[e]}),this.currentDevice=e;return}try{await this.setMediaTrack(await this.mediaInterface.getVideoTrack(this.userSelectedDevice))}catch(r){throw l.error("VideoMediaHandler.setDevice.error",{error:r}),this.disableTrack(),new b("Failed to change device")}}async enableTrack(){if(this.trackEnabled){l.warn("VideoMediaHandler.enableTrack Track already enabled!");return}await this.setMediaTrack(await this.mediaInterface.getVideoTrack(this.userSelectedDevice))}async setTransformedTrack(e){var r;if(!e&&!((r=this.middlewares)!=null&&r.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=await c(this,Ni).getTransformedVideoTrack(this.middlewares,this.mediaTrack,c(this,$a)),this.emit("trackChanged")}catch(n){l.error("VideoMediaHandler.setTransformedTrack",{error:n}),this.transformedMediaTrack=this.mediaTrack}}async setVideoMiddlewareGlobalConfig(e){y(this,$a,e)}async updateConstraints(e){if(!this._mediaTrack)throw new b("No media track enabled!");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new b("update constraints not supported for non web clients","1100");try{this._mediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),await this.setTransformedTrack(),this.addMediaTrackListeners(),await this.setCurrentDevice()}catch(n){l.error("VideoMediaHandler.updateConstraints.error",{error:n})}}terminateMiddlewareWebWorker(){c(this,Ni).terminateMiddlewareWebWorker()}async onTrackEnded(){l.info("VideoMediaHandler.TrackEnded"),this.disableTrack(),this.emit("trackEnded")}onTrackMuted(){l.info("VideoMediaHandler.TrackMuted"),this.emit("trackMuted")}async conditionallyChangeTrack(e){if(!e||this.userSelectedDevice)return e;let r=e;const n=await this.mediaInterface.getVideoInputDevices(),i=this.isNonPreferredDevice?n.filter(a=>!this.isNonPreferredDevice(a)):n;return!(i!=null&&i.length)||window.FAST_DYTE||i.find(a=>a.deviceId===e.getSettings().deviceId)||(r.stop(),l.info("localmediahandler::setupstreams::found_video_non_preferred"),r=await this.mediaInterface.getVideoTrack(i[0].deviceId)),r}}Ni=new WeakMap,$a=new WeakMap,Jc([g.trace("VideoMediaHandler.setTransformedTrack")],ya.prototype,"setTransformedTrack",1),Jc([g.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],ya.prototype,"setVideoMiddlewareGlobalConfig",1),Jc([g.trace("VideoMediaHandler.onTrackEnded")],ya.prototype,"onTrackEnded",1),Jc([g.trace("VideoMediaHandler.conditionallyChangeTrack")],ya.prototype,"conditionallyChangeTrack",1);const mD=ya,Ig=wr(Rl()),Fi=class{constructor(t){S(this,Kt,void 0);S(this,Ln,void 0);S(this,Ba,void 0);S(this,Li,void 0);if(!t)throw new b("Could not load preset.");y(this,Kt,t.config),y(this,Ba,t.name),y(this,Ln,t.ui||wr(Rl().ui)),y(this,Li,t.permissions.plugins.config)}static fromResponse(t){return new Fi(t)}static default(){return new Fi(Ig)}static init(t,e=!0){return!t||e?new Fi(Ig):new Fi(t)}get setupScreen(){return{isEnabled:!0}}get waitingRoom(){return{isEnabled:!0}}get controlBar(){return{isEnabled:!0,elements:{chat:!0,fullscreen:!0,invite:!1,layout:!1,participants:!0,plugins:!0,polls:!0,reactions:!1,screenshare:!0}}}get header(){return{isEnabled:!0,elements:{logo:c(this,Ln).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return c(this,Kt).viewType}get maxVideoStreams(){return c(this,Kt).maxVideoStreams}get maxScreenShareCount(){return c(this,Kt).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(c(this,Li)).filter(t=>c(this,Li)[t].disabled)}get designTokens(){return c(this,Ln).designTokens}get configDiff(){return c(this,Ln).configDiff}get mediaConstraints(){var t,e,r,n,i,a,o,d,u,h,p,f,v,T,P,k,I,x,V,O,W,Q,oe,ve;return{audio:{enableStereo:(n=(r=(e=(t=c(this,Kt))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.enableStereo)!=null?n:ni.audio.enableStereo,enableHighBitrate:(d=(o=(a=(i=c(this,Kt))==null?void 0:i.media)==null?void 0:a.audio)==null?void 0:o.enableHighBitrate)!=null?d:ni.audio.enableHighBitrate},video:{quality:(f=(p=(h=(u=c(this,Kt))==null?void 0:u.media)==null?void 0:h.video)==null?void 0:p.quality)!=null?f:ni.video.quality,frameRate:(k=(P=(T=(v=c(this,Kt))==null?void 0:v.media)==null?void 0:T.video)==null?void 0:P.frameRate)!=null?k:ni.video.frameRate},screenshare:{quality:(O=(V=(x=(I=c(this,Kt))==null?void 0:I.media)==null?void 0:x.screenshare)==null?void 0:V.quality)!=null?O:ni.screenshare.quality,frameRate:(ve=(oe=(Q=(W=c(this,Kt))==null?void 0:W.media)==null?void 0:Q.screenshare)==null?void 0:oe.frameRate)!=null?ve:ni.screenshare.frameRate}}}get name(){return c(this,Ba)}};let _u=Fi;Kt=new WeakMap,Ln=new WeakMap,Ba=new WeakMap,Li=new WeakMap;var fD=Object.defineProperty,gD=Object.getOwnPropertyDescriptor,Ag=(s,t,e,r)=>{for(var n=r>1?void 0:r?gD(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&fD(t,e,n),n};class Su extends Ht{constructor(e){super();S(this,xi,void 0);m(this,"state","IDLE");m(this,"playbackUrl");m(this,"viewerCount");y(this,xi,e),this.viewerCount=0}setLivestreamState(e){const r=this.state;this.state=e,r!==e&&this.emitCurrentLivestreamState()}emitCurrentLivestreamState(){this.emit("livestreamUpdate",this.state)}async start(){if(!c(this,xi).permissions.canLivestream)throw l.error("DyteLivestream::start::permission_denied"),new b("User does not have permission to start livestreaming");this.setLivestreamState("STARTING");try{const r=await We().startLivestreaming();this.playbackUrl=r}catch(e){throw l.error("DyteRecording::stop::livestream_failed_to_start",{error:e}),this.setLivestreamState("IDLE"),new b("Error while starting livestream")}}async stop(){if(!c(this,xi).permissions.canLivestream)throw l.error("DyteLivestream::stop::permission_denied"),new b("User does not have permission to stop livestreaming");if(this.state!=="LIVESTREAMING")throw l.error("DyteLivestream::stop::inconsistent_state"),new b("Livestream not started yet");try{this.setLivestreamState("STOPPING"),await We().stopLivestreaming()}catch(e){throw l.error("DyteLivestream::stop::livestream_failed_to_stop",{error:e}),this.setLivestreamState("STOPPING"),new b("Error while stopping livestream")}}}xi=new WeakMap,Ag([g.trace("livestream.start")],Su.prototype,"start",1),Ag([g.trace("livestream.stop")],Su.prototype,"stop",1);var vD=Object.defineProperty,yD=Object.getOwnPropertyDescriptor,TD=(s,t,e,r)=>{for(var n=r>1?void 0:r?yD(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&vD(t,e,n),n};class Mg{constructor(t,e){m(this,"livestream");S(this,Ui,void 0);S(this,Ds,void 0);this.livestream=new Su(t),y(this,Ds,e),this.setupEvents()}async fetchInitialLivestreamingState(){const t=We(),{status:e,playbackUrl:r}=await t.getActiveLivestream();this.livestream.playbackUrl=r,e==="LIVE"&&this.livestream.setLivestreamState("LIVESTREAMING")}setupEvents(){c(this,Ds).on($.startedLivestream,t=>{this.livestream.playbackUrl=t.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING")}),c(this,Ds).on($.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),c(this,Ds).on($.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),c(this,Ds).on($.roomPeerCount,t=>{this.livestream.viewerCount=t.count,this.livestream.emit("viewerCountUpdate",t.count)}),w.on(C.PEER_JOINED_INTERNAL,async t=>{var e;((e=t.flags)==null?void 0:e.hiddenParticipant)===!0&&t.recorderType==="LIVESTREAMER"&&(y(this,Ui,t.id),this.livestream.setLivestreamState("LIVESTREAMING"))}),w.on(C.PEER_CLOSED,t=>{t.id===c(this,Ui)&&(y(this,Ui,void 0),this.livestream.setLivestreamState("IDLE"))}),w.onAsync(C.LEAVE_MEDIA_ROOM,async()=>{this.livestream.playbackUrl||(l.info("Fetching livestreaming state on leave stage"),await this.fetchInitialLivestreamingState())}),w.on(C.SOCKET_SERVICE_ROOM_JOINED,async()=>{try{await this.fetchInitialLivestreamingState()}catch(t){l.error("Error: LivestreamController.fetchLivestream")}})}}Ui=new WeakMap,Ds=new WeakMap,TD([g.trace("LivestreamController.setupEvents")],Mg.prototype,"setupEvents",1);var _D=Object.defineProperty,SD=Object.getOwnPropertyDescriptor,Ta=(s,t,e,r)=>{for(var n=r>1?void 0:r?SD(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&_D(t,e,n),n};const _a={maxInvocations:5,period:1};class ii{constructor({name:t,socketHandler:e,meetingId:r}){S(this,bd);m(this,"name","");S(this,Tt,{});S(this,Os,"");S(this,Ns,void 0);m(this,"volatile");m(this,"rateLimitConfig",{maxInvocations:5,period:1});m(this,"bulkRateLimitConfig",{maxInvocations:5,period:1});m(this,"listeners",{});this.name=t,y(this,Ns,e),y(this,Os,r)}async set(t,e,r=!0,n=!1){c(this,Tt)[t]=e,r&&c(this,Ns).storeInsertKeys(c(this,Os),this.name,[{key:t,payload:e}]),n&&(this.listeners[t]&&this.listeners[t].forEach(i=>i({[t]:c(this,Tt)[t]})),this.listeners["*"]&&this.listeners["*"].forEach(i=>i({[t]:c(this,Tt)[t]})))}async bulkSet(t){t.forEach(({key:e,payload:r})=>{c(this,Tt)[e]=r}),c(this,Ns).storeInsertKeys(c(this,Os),this.name,t)}async update(t,e,r=!0){je(this,bd,Gv).call(this,t,e,r)}async delete(t,e=!0,r=!1){if(c(this,Tt)[t]&&delete c(this,Tt)[t],e)return c(this,Ns).storeDeleteKeys(c(this,Os),this.name,[{key:t}]);r&&(this.listeners[t]&&(this.listeners[t].forEach(n=>n({[t]:void 0})),delete this.listeners[t]),this.listeners["*"]&&this.listeners["*"].forEach(n=>n({[t]:void 0})))}async bulkDelete(t){return t.forEach(({key:e})=>{c(this,Tt)[e]&&delete c(this,Tt)[e]}),c(this,Ns).storeDeleteKeys(c(this,Os),this.name,t)}get(t){if(c(this,Tt)[t])return c(this,Tt)[t]}getAll(){return c(this,Tt)}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get bulkRateLimits(){return this.bulkRateLimitConfig}updateBulkRateLimits(t,e){this.bulkRateLimitConfig.maxInvocations=t,this.bulkRateLimitConfig.period=e}subscribe(t,e){if(this.listeners[t]){this.listeners[t].push(e);return}this.listeners[t]=[e]}unsubscribe(t,e){var r;if(e){this.listeners[t]=((r=this.listeners[t])==null?void 0:r.filter(n=>n!==e))||[];return}this.listeners[t]&&delete this.listeners[t]}populate(t){y(this,Tt,t)}}Tt=new WeakMap,Os=new WeakMap,Ns=new WeakMap,bd=new WeakSet,Gv=function(t,e,r=!0){let n;const i=c(this,Tt)[t],a=Object.prototype.toString.call(e),o=Object.prototype.toString.call(i);if(a!==o){this.set(t,e);return}switch(o){case"[object Array]":n=[...i,...e];break;case"[object Object]":n={...i,...e};break;case"[object Map]":n=new Map([...i,...e]);break;case"[object Set]":n=new Set([...i,...e]);break;default:n=e;break}this.set(t,n,r)},Ta([Lt(_a,"rateLimitConfig")],ii.prototype,"set",1),Ta([Lt(_a,"bulkRateLimitConfig")],ii.prototype,"bulkSet",1),Ta([Lt(_a,"rateLimitConfig")],ii.prototype,"update",1),Ta([Lt(_a,"rateLimitConfig")],ii.prototype,"delete",1),Ta([Lt(_a,"bulkRateLimitConfig")],ii.prototype,"bulkDelete",1);class ED{constructor(t,e){S(this,Ha);S(this,Pd);m(this,"stores",new Map);S(this,Fn,void 0);S(this,xn,"");S(this,qa,void 0);S(this,Ls,new Map);y(this,Fn,e),y(this,xn,t.getValue("meetingId")),y(this,qa,t),je(this,Pd,Jv).call(this)}create(t){const e=new ii({name:t,socketHandler:c(this,Fn),meetingId:c(this,xn)});return c(this,Fn).storeGetKeys(c(this,xn),t,[]),new Promise((n,i)=>{const a=setTimeout(()=>i(Error("Failed")),3e3);c(this,Ls).set(t,{rejectTimeout:a,resolve:n,store:e})})}}Fn=new WeakMap,xn=new WeakMap,Ha=new WeakSet,Yu=function(){return c(this,qa).getValue("peerId")},qa=new WeakMap,Ls=new WeakMap,Pd=new WeakSet,Jv=function(){[j.storeInsertKeys,j.storeGetKeys,j.storeDeleteKeys].forEach(t=>{c(this,Fn).on(t,async e=>{var i,a;if(e.pluginId!==c(this,xn))return;const r=(i=e.storeItems)==null?void 0:i.map(o=>{var d;return{timestamp:o.timestamp,peerId:o.peerId,payload:JSON.parse((d=o.payload)!=null&&d.length?new TextDecoder().decode(o.payload):"{}"),key:o.storeKey}});if(t===j.storeGetKeys){const o=c(this,Ls).get(e.storeName),d=this.stores.get(e.storeName)||(o==null?void 0:o.store);c(this,Ls).get(e.storeName)&&(this.stores.set(e.storeName,o.store),o.resolve(d),clearTimeout(o.rejectTimeout),c(this,Ls).delete(e.storeName)),r.forEach(u=>{d.set(u.key,u.payload,!1,!1)});return}const n=this.stores.get(e.storeName)||((a=c(this,Ls).get(e.storeName))==null?void 0:a.store);n!==void 0&&(t===j.storeInsertKeys&&r.forEach(({key:o,peerId:d,payload:u})=>{d===c(this,Ha,Yu)&&t!==j.storeGetKeys||n.set(o,u,!1,!0)}),t===j.storeDeleteKeys&&r.forEach(({key:o,peerId:d})=>{d!==c(this,Ha,Yu)&&n.delete(o,!1,!0)}))})})};function pn(s){var t,e,r,n,i,a,o,d,u,h,p,f,v;return s?{media:{audio:{enabled:s.audioEnabled,trackId:(t=s.audioTrack)==null?void 0:t.id,permission:"mediaPermissions"in s?(e=s.mediaPermissions)==null?void 0:e.audio:null},video:{enabled:s.videoEnabled,trackId:(r=s.videoTrack)==null?void 0:r.id,permission:"mediaPermissions"in s?(n=s.mediaPermissions)==null?void 0:n.video:null},screenshare:{enabled:s.screenShareEnabled,permission:"mediaPermissions"in s?(i=s.mediaPermissions)==null?void 0:i.screenshare:null,audio:{enabled:(o=(a=s.screenShareTracks)==null?void 0:a.audio)==null?void 0:o.enabled,trackId:(u=(d=s.screenShareTracks)==null?void 0:d.audio)==null?void 0:u.id},video:{enabled:(p=(h=s.screenShareTracks)==null?void 0:h.video)==null?void 0:p.enabled,trackId:(v=(f=s.screenShareTracks)==null?void 0:f.video)==null?void 0:v.id}}}}:{}}var wD=Object.defineProperty,CD=Object.getOwnPropertyDescriptor,ai=(s,t,e,r)=>{for(var n=r>1?void 0:r?CD(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&wD(t,e,n),n};const bD=.8,PD=1.2;let Gr=(Nv=class extends Ht{constructor(t,e,r,n){super();S(this,Fs);S(this,Hi);S(this,Ga);m(this,"id");m(this,"userId");m(this,"name");m(this,"picture");m(this,"isHost");m(this,"customParticipantId");m(this,"flags");m(this,"device");m(this,"videoTrack");m(this,"audioTrack");m(this,"screenShareTracks");m(this,"videoEnabled");m(this,"audioEnabled");m(this,"screenShareEnabled");m(this,"producers");m(this,"manualProducerConfig");S(this,Vi,void 0);m(this,"supportsRemoteControl",!1);S(this,$i,void 0);m(this,"presetName");S(this,Bi,void 0);S(this,rs,void 0);S(this,ja,void 0);S(this,xs,new Map);S(this,ss,1);S(this,Rd,Vr(t=>{if(!this.videoTrack)return;const{clientWidth:e,clientHeight:r}=t,{width:n,height:i}=this.videoTrack.getSettings();if(!n||!i)return;const a=i/r,o=n/e,d=Math.max(a,o);d>PD&&c(this,ss)===1?(y(this,ss,0),w.emit(C.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:c(this,ss)})):dc(this,Rd).call(this,t)),e.observe(t)),c(this,xs).set(t,{observer:e}),this.updateVideo(t),(a=c(this,Hi,Fd))==null||a.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(i=this.raised)!=null?i:!1)}deregisterVideoElement(t){var e,r,n;t.srcObject=void 0,(r=(e=c(this,xs).get(t))==null?void 0:e.observer)==null||r.disconnect(),c(this,xs).delete(t),(n=c(this,Hi,Fd))==null||n.removeSource(this.id)}updateVideo(t){var e;if(this.videoEnabled){if(this.videoTrack==null)return;const r=(e=t.srcObject)==null?void 0:e.getTracks()[0];if((r==null?void 0:r.id)===this.videoTrack.id)return;const n=new MediaStream;n.addTrack(this.videoTrack),t.srcObject=n}else t.srcObject=void 0;t.style.display=this.videoEnabled?"block":"none"}},Vi=new WeakMap,$i=new WeakMap,Bi=new WeakMap,Fs=new WeakSet,Zi=function(){return c(this,Bi).getValue("roomNodeClient")},rs=new WeakMap,ja=new WeakMap,xs=new WeakMap,Hi=new WeakSet,Fd=function(){return c(this,Bi).getValue("pip")},ss=new WeakMap,Rd=new WeakMap,Ga=new WeakSet,Qu=function(){Array.from(c(this,xs).keys()).forEach(this.updateVideo)},Nv);ai([g.trace("DyteParticipant.disableAudio")],Gr.prototype,"disableAudio",1),ai([g.trace("DyteParticipant.kick")],Gr.prototype,"kick",1),ai([g.trace("DyteParticipant.disableVideo")],Gr.prototype,"disableVideo",1),ai([g.trace("DyteParticipant.getPermissions")],Gr.prototype,"getPermissions",1),ai([g.trace("DyteParticipant.setStageStatus")],Gr.prototype,"setStageStatus",1),Gr=ai([pt("1200")],Gr);class Sa extends hg{constructor(t){const{onAddEvent:e="participantJoined",onDeleteEvent:r="participantLeft",onClearEvent:n="participantsCleared"}=t!=null?t:{};super({onAddEvent:e,onDeleteEvent:r,onClearEvent:n})}add(t,e=!0){return this.has(t.id)&&Object.is(this.get(t.id),t)===!1&&this.delete(t.id),super.add(t,e)}clear(t=!0,e=!1){return super.clear(t,e)}delete(t,e=!0,r=!1){return super.delete(t,e,r)}}class RD extends Zn{constructor(){super();S(this,Us,void 0);y(this,Us,new Map)}__set(e,r){return c(this,Us).set(e,r)}__clear(){return c(this,Us).clear()}get(e){return c(this,Us).get(e)}toArray(){return Array.from(c(this,Us).values())}}Us=new WeakMap;var mn={},Wc={},Kc={},kD={get exports(){return Kc},set exports(s){Kc=s}},Eu,Dg;function ID(){if(Dg)return Eu;Dg=1;var s=1e3,t=s*60,e=t*60,r=e*24,n=r*7,i=r*365.25;Eu=function(h,p){p=p||{};var f=typeof h;if(f==="string"&&h.length>0)return a(h);if(f==="number"&&isFinite(h))return p.long?d(h):o(h);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(h))};function a(h){if(h=String(h),!(h.length>100)){var p=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(h);if(p){var f=parseFloat(p[1]),v=(p[2]||"ms").toLowerCase();switch(v){case"years":case"year":case"yrs":case"yr":case"y":return f*i;case"weeks":case"week":case"w":return f*n;case"days":case"day":case"d":return f*r;case"hours":case"hour":case"hrs":case"hr":case"h":return f*e;case"minutes":case"minute":case"mins":case"min":case"m":return f*t;case"seconds":case"second":case"secs":case"sec":case"s":return f*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return f;default:return}}}}function o(h){var p=Math.abs(h);return p>=r?Math.round(h/r)+"d":p>=e?Math.round(h/e)+"h":p>=t?Math.round(h/t)+"m":p>=s?Math.round(h/s)+"s":h+"ms"}function d(h){var p=Math.abs(h);return p>=r?u(h,p,r,"day"):p>=e?u(h,p,e,"hour"):p>=t?u(h,p,t,"minute"):p>=s?u(h,p,s,"second"):h+" ms"}function u(h,p,f,v){var T=p>=f*1.5;return Math.round(h/f)+" "+v+(T?"s":"")}return Eu}function AD(s){e.debug=e,e.default=e,e.coerce=d,e.disable=i,e.enable=n,e.enabled=a,e.humanize=ID(),e.destroy=u,Object.keys(s).forEach(h=>{e[h]=s[h]}),e.names=[],e.skips=[],e.formatters={};function t(h){let p=0;for(let f=0;f{if(Q==="%%")return"%";O++;const ve=e.formatters[oe];if(typeof ve=="function"){const Mt=k[O];Q=ve.call(I,Mt),k.splice(O,1),O--}return Q}),e.formatArgs.call(I,k),(I.log||e.log).apply(I,k)}return P.namespace=h,P.useColors=e.useColors(),P.color=e.selectColor(h),P.extend=r,P.destroy=e.destroy,Object.defineProperty(P,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(v!==e.namespaces&&(v=e.namespaces,T=e.enabled(h)),T),set:k=>{f=k}}),typeof e.init=="function"&&e.init(P),P}function r(h,p){const f=e(this.namespace+(typeof p=="undefined"?":":p)+h);return f.log=this.log,f}function n(h){e.save(h),e.namespaces=h,e.names=[],e.skips=[];let p;const f=(typeof h=="string"?h:"").split(/[\s,]+/),v=f.length;for(p=0;p"-"+p)].join(",");return e.enable(""),h}function a(h){if(h[h.length-1]==="*")return!0;let p,f;for(p=0,f=e.skips.length;p{let d=!1;return()=>{d||(d=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function e(){return typeof window!="undefined"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document!="undefined"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window!="undefined"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(d){if(d[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+d[0]+(this.useColors?"%c ":" ")+"+"+s.exports.humanize(this.diff),!this.useColors)return;const u="color: "+this.color;d.splice(1,0,u,"color: inherit");let h=0,p=0;d[0].replace(/%[a-zA-Z%]/g,f=>{f!=="%%"&&(h++,f==="%c"&&(p=h))}),d.splice(p,0,u)}t.log=console.debug||console.log||(()=>{});function n(d){try{d?t.storage.setItem("debug",d):t.storage.removeItem("debug")}catch(u){}}function i(){let d;try{d=t.storage.getItem("debug")}catch(u){}return!d&&typeof process!="undefined"&&"env"in process&&(d=process.env.DEBUG),d}function a(){try{return localStorage}catch(d){}}s.exports=MD(t);const{formatters:o}=s.exports;o.j=function(d){try{return JSON.stringify(d)}catch(u){return"[UnexpectedJSONParseError]: "+u.message}}})(kD,Kc);var DD=De&&De.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Wc,"__esModule",{value:!0}),Wc.Logger=void 0;const oi=DD(Kc),ci="awaitqueue";class OD{constructor(t){t?(this._debug=(0,oi.default)(`${ci}:${t}`),this._warn=(0,oi.default)(`${ci}:WARN:${t}`),this._error=(0,oi.default)(`${ci}:ERROR:${t}`)):(this._debug=(0,oi.default)(ci),this._warn=(0,oi.default)(`${ci}:WARN`),this._error=(0,oi.default)(`${ci}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}}Wc.Logger=OD,Object.defineProperty(mn,"__esModule",{value:!0});var di=mn.AwaitQueue=mn.AwaitQueueRemovedTaskError=mn.AwaitQueueStoppedError=void 0;const ND=Wc,Ts=new ND.Logger;class wu extends Error{constructor(t){super(t!=null?t:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,wu)}}mn.AwaitQueueStoppedError=wu;class zc extends Error{constructor(t){super(t!=null?t:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,zc)}}mn.AwaitQueueRemovedTaskError=zc;class LD{constructor(){this.pendingTasks=new Map,this.nextTaskId=0,this.stopping=!1}get size(){return this.pendingTasks.size}async push(t,e){if(e=e!=null?e:t.name,Ts.debug(`push() [name:${e}]`),typeof t!="function")throw new TypeError("given task is not a function");if(e)try{Object.defineProperty(t,"name",{value:e})}catch(r){}return new Promise((r,n)=>{const i={id:this.nextTaskId++,task:t,name:e,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:a=>{if(i.completed)return;i.completed=!0,this.pendingTasks.delete(i.id),Ts.debug(`resolving task [name:${i.name}]`),r(a);const[o]=this.pendingTasks.values();o&&!o.executedAt&&this.execute(o)},reject:a=>{if(!i.completed&&(i.completed=!0,this.pendingTasks.delete(i.id),Ts.debug(`rejecting task [name:${i.name}]: %s`,String(a)),n(a),!this.stopping)){const[o]=this.pendingTasks.values();o&&!o.executedAt&&this.execute(o)}}};this.pendingTasks.set(i.id,i),this.pendingTasks.size===1&&this.execute(i)})}stop(){Ts.debug("stop()"),this.stopping=!0;for(const t of this.pendingTasks.values())Ts.debug(`stop() | stopping task [name:${t.name}]`);this.stopping=!1}remove(t){Ts.debug(`remove() [taskIdx:${t}]`);const e=Array.from(this.pendingTasks.values())[t];if(!e){Ts.debug(`stop() | no task with given idx [taskIdx:${t}]`);return}e.reject(new zc)}dump(){const t=Date.now();let e=0;return Array.from(this.pendingTasks.values()).map(r=>({idx:e++,task:r.task,name:r.name,enqueuedTime:r.executedAt?r.executedAt-r.enqueuedAt:t-r.enqueuedAt,executionTime:r.executedAt?t-r.executedAt:0}))}async execute(t){if(Ts.debug(`execute() [name:${t.name}]`),t.executedAt)throw new Error("task already being executed");t.executedAt=Date.now();try{const e=await t.task();t.resolve(e)}catch(e){t.reject(e)}}}di=mn.AwaitQueue=LD;class Og{constructor(){m(this,"meetingTitle");m(this,"roomName");m(this,"roomUUID");S(this,Ja,void 0);m(this,"context");m(this,"authToken");m(this,"maxPreferredStreams")}get peerId(){return this.context.getValue("peerId")}get roomJoined(){return!1}set roomJoined(t){throw new b("Method not implemented.")}get sfuHandler(){return c(this,Ja)}get mediaState(){return c(this,Ja).transportState}reconnect(){throw new b("Method not implemented.")}async partialJoinRoom(t,e,r=!1,n=void 0){throw new b("Method not implemented.")}async joinRoom(t,e,r={},n=!1,i=!1){throw new b("Method not implemented.")}async leaveRoom(){throw new b("Method not implemented.")}reset(t=!0){throw new b("Method not implemented")}async handleSocketCallbacks(t){throw new b("Method not implemented.")}async handleSockets(t,e){throw new b("Method not implemented.")}async shareMic(t){throw new b("Method not implemented.")}async shareWebcam(t){throw new b("Method not implemented.")}async shareScreen(t){throw new b("Method not implemented.")}async unmuteSelf(){throw new b("Method not implemented.")}async muteSelf(){throw new b("Method not implemented.")}async pauseWebcam(){throw new b("Method not implemented.")}async disableScreenShare(){throw new b("Method not implemented.")}async acceptWaitingRequest(t){throw new b("Method not implemented.")}async rejectWaitingRequest(t){throw new b("Method not implemented.")}async muteAll(t){throw new b("Method not implemented.")}async muteAllVideo(){throw new b("Method not implemented.")}async disableAudio(t){throw new b("Method not implemented.")}async disableVideo(t){throw new b("Method not implemented.")}async kickAll(){throw new b("Method not implemented.")}async kick(t){throw new b("Method not implemented.")}async pinPeer(t){throw new b("Method not implemented.")}getConsumers(){throw new b("Method not implemented.")}stopAllProducers(){throw new b("Method not implemented.")}async activatePeers(t){throw new b("Method not implemented.")}async deactivatePeers(t,e="default"){throw new b("Method not implemented.")}async createConsumers(t){throw new b("Method not implemented.")}async closeConsumers(t){throw new b("Method not implemented.")}async switchConsumersToLayer(t,e){throw new b("Method not implemented.")}}Ja=new WeakMap;var Ng={},Yc={},FD={get exports(){return Yc},set exports(s){Yc=s}},Lg=FD.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(s){return s.encoding?"rtpmap:%d %s/%s/%s":s.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(s){return s.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(s){return s.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(s){return"extmap:%d"+(s.direction?"/%s":"%v")+(s["encrypt-uri"]?" %s":"%v")+" %s"+(s.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(s){return s.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(s){var t="candidate:%s %d %s %d %s %d typ %s";return t+=s.raddr!=null?" raddr %s rport %d":"%v%v",t+=s.tcptype!=null?" tcptype %s":"%v",s.generation!=null&&(t+=" generation %d"),t+=s["network-id"]!=null?" network-id %d":"%v",t+=s["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(s){var t="ssrc:%d";return s.attribute!=null&&(t+=" %s",s.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(s){return s.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(s){return s.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(s){return"imageattr:%s %s %s"+(s.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(s){return"simulcast:%s %s"+(s.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(s){return"ts-refclk:%s"+(s.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(s){var t="mediaclk:";return t+=s.id!=null?"id=%s %s":"%v%s",t+=s.mediaClockValue!=null?"=%s":"",t+=s.rateNumerator!=null?" rate=%s":"",t+=s.rateDenominator!=null?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(Lg).forEach(function(s){var t=Lg[s];t.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})}),function(s){var t=function(o){return String(Number(o))===o?Number(o):o},e=function(o,d,u,h){if(h&&!u)d[h]=t(o[1]);else for(var p=0;p1&&(o[u[0]]=void 0),o};s.parseParams=function(o){return o.split(/;\s?/).reduce(a,{})},s.parseFmtpConfig=s.parseParams,s.parsePayloads=function(o){return o.toString().split(" ").map(Number)},s.parseRemoteCandidates=function(o){for(var d=[],u=o.split(" ").map(t),h=0;h=r)return n;var i=e[t];switch(t+=1,n){case"%%":return"%";case"%s":return String(i);case"%d":return Number(i);case"%v":return""}})},Ea=function(s,t,e){var r=t.format instanceof Function?t.format(t.push?e:e[t.name]):t.format,n=[s+"="+r];if(t.names)for(var i=0;i(s.INITIALIZING="INITIALIZING",s.INITIALIZED="INITIALIZED",s.NOT_INITIALIZED="NOT_INITIALIZED",s))(Jr||{});class Fg extends de.EventEmitter{}class gn extends de.EventEmitter{constructor(){super(),this.setMaxListeners(1/0)}safeEmit(t,...e){const r=this.listenerCount(t);try{return this.emit(t,...e)}catch(n){return l.error(`EnhancedEventEmitter:: safeEmit() | event listener ${t} threw an error`,{error:n}),Boolean(r)}}async safeEmitAsPromise(t,...e){const r={}.EVENT_PROMISE_TIMEOUT?parseInt({}.EVENT_PROMISE_TIMEOUT,10):1e4;return this.safeEmitAsPromiseWithTimeout(t,r,...e)}async safeEmitAsPromiseWithTimeout(t,e,...r){return new Promise((n,i)=>{setTimeout(i,e,"event request timeout");try{this.emit(t.toString(),...r,n,i)}catch(a){l.error(`EnhancedEventEmitter:: safeEmitAsPromise() | event listener for event ${t.toString()} threw an error [event:%s]:%o`,{error:a}),i(a)}})}}function jD(s,t){const e=new Error(t);return e.name=s,e}class vn extends b{constructor(t){super(t),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,vn):this.stack=new Error(t).stack}}class lt extends b{constructor(t){super(t),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,lt):this.stack=new Error(t).stack}}class xg extends gn{constructor({id:e,localId:r,producerId:n,producingPeerId:i,producingTransportId:a,handler:o,track:d,appData:u,paused:h,reuseTrack:p,rtpReceiver:f}){super();S(this,to);S(this,kd);S(this,Id);m(this,"rtpReceiver");m(this,"observer");S(this,Wa,void 0);S(this,Ka,void 0);S(this,za,void 0);S(this,Ya,void 0);S(this,Ir,void 0);S(this,Qa,void 0);S(this,Xa,void 0);S(this,gr,void 0);S(this,Un,void 0);S(this,Za,void 0);S(this,eo,void 0);y(this,Wa,e),y(this,Ka,r),y(this,Xa,o),y(this,eo,u),y(this,Za,i),y(this,Ya,a),y(this,Ir,!1),y(this,za,n),y(this,gr,d),y(this,Un,h!=null?h:!1),y(this,Qa,p),this.observer=new gn,this.rtpReceiver=f,je(this,kd,Wv).call(this)}get id(){return c(this,Wa)}get peerId(){return c(this,Za)}get localId(){return c(this,Ka)}get producerId(){return c(this,za)}get producingTransportId(){return c(this,Ya)}get closed(){return c(this,Ir)}get kind(){return c(this,gr).kind}get track(){return c(this,gr)}get paused(){return c(this,Un)}get remotelyPaused(){return this.paused}get appData(){return c(this,eo)}close(e){c(this,Ir)||(l.debug("Consumer::close() with reason:",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,closureReason:e,kind:this.kind}}),y(this,Ir,!0),c(this,Qa)||je(this,Id,Kv).call(this),this.emit("close",e),this.observer.safeEmit("close",e))}async getStats(){if(c(this,Ir))throw new lt("closed");return c(this,Xa).getReceiverStats(this.localId)}pause(){if(l.debug("consumer::pause()",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}),c(this,Ir)){l.error("consumer::pause() | Consumer closed",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}});return}y(this,Un,!0),c(this,gr).enabled=!1,this.observer.safeEmit("pause")}resume(){if(l.debug("consumer::resume()",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}),c(this,Ir)){l.error("Consumer::resume() | Consumer closed",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}});return}y(this,Un,!1),c(this,gr).enabled=!0,this.observer.safeEmit("resume")}}Wa=new WeakMap,Ka=new WeakMap,za=new WeakMap,Ya=new WeakMap,Ir=new WeakMap,Qa=new WeakMap,Xa=new WeakMap,gr=new WeakMap,Un=new WeakMap,Za=new WeakMap,eo=new WeakMap,to=new WeakSet,Xu=function(){l.debug('Consumer::track "ended" event',{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}),this.safeEmit("trackended"),this.observer.safeEmit("trackended")},kd=new WeakSet,Wv=function(){c(this,gr).addEventListener("ended",je(this,to,Xu).bind(this))},Id=new WeakSet,Kv=function(){try{c(this,gr).removeEventListener("ended",je(this,to,Xu)),c(this,gr).stop()}catch(e){l.error("Consumer::destroyTrack()",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind},error:e})}};let GD=class extends xg{};const Ug=s=>new Promise(t=>setTimeout(t,s));async function br(s,t){return new Promise(async(e,r)=>{const{strategy:n,maxRetryCount:i,delayTime:a}={strategy:"linear",maxRetryCount:3,delayTime:10,...t};let o=0,d,u=!1;const h=p=>{u=!0,r(p)};for(;oe.then(r=>({status:"fulfilled",value:r})).catch(r=>({status:"rejected",reason:r})));return Promise.all(t)}function JD(s,t){return typeof s=="undefined"?t:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(s):JSON.parse(JSON.stringify(s))}function Vg(s){return typeof s=="object"&&!Array.isArray(s)&&s!==null}function Pu(s){return Math.random().toString(36).substring(2,2+s)}const Xc=1;function $g(s){const t=s;return delete t.payload._bolt,t}function WD(s){return s.payload&&Vg(s.payload)}function Zc(s){var t,e;return WD(s)&&(e=(t=s.payload._bolt)==null?void 0:t.id)!=null?e:""}const qi=class extends de.EventEmitter{constructor(e,r,n){super();m(this,"channel");m(this,"queue");m(this,"serverProtocolVersion");S(this,Vs,new Map);m(this,"respond",(e,r,n=!1)=>{let i;n?i=qi.createErrorResponse(e,r):i=qi.createResponse(e,r),this.channel.send(JSON.stringify(i))});m(this,"notify",e=>{const r=qi.createNotification(e);this.channel.send(JSON.stringify(r))});m(this,"request",async e=>{const r=qi.createRequest(e),n=new Promise((i,a)=>{const o=1e3*(5+.1*this.queue.size),{id:d}=r.payload._bolt,u={id:d,method:r.type,resolve:h=>{this.queue.delete(d)&&(clearTimeout(u.timer),i(h))},timer:setTimeout(()=>{this.queue.delete(d)&&a(new Error(`request timeout for message id: ${d}`))},o),cancel:h=>{this.queue.delete(d)&&(clearTimeout(u.timer),a(h))}};this.queue.set(d,u)});return this.channel.send(JSON.stringify(r)),n});m(this,"send",e=>{const r=JSON.stringify(e),n=16384;if(r.length>n){const i=n-200,a=Math.ceil(r.length/i),o=[];for(let u=0;u{var n;c(this,Vs).has(e.id)||c(this,Vs).set(e.id,[]);const r=c(this,Vs).get(e.id);if(r[e.chunkIndex]=e,(r==null?void 0:r.length)===e.count&&!r.some(i=>i===void 0)){const i=c(this,Vs).get(e.id),a=i==null?void 0:i.reduce((d,u)=>d+u.chunk,"");c(this,Vs).delete(e.id);const o=JSON.parse(a);if(!o.payload||!Vg(o.payload))throw new Error("corrupted incoming message over dc",{cause:{code:"CORRUPT_DC_MESSAGE",values:o}});if(this.processBoltHandshake(o))return;if(this.serverProtocolVersion=(n=o.payload._bolt)==null?void 0:n.version,!this.processResponseMsg(o))return o}});m(this,"processResponseMsg",e=>{const{id:r}=e.payload._bolt,n=this.queue.get(r);return n?(l.debug(`resolving pending request with id: ${r}, complete response: ${JSON.stringify(e)}`),e.type==="error"?n.cancel($g(e)):n.resolve($g(e)),!0):!1});m(this,"processBoltHandshake",e=>{var r,n;return e.type==="_bolt"||e.type==="handshake"?(this.respond((n=(r=e.payload._bolt)==null?void 0:r.id)!=null?n:Pu(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1});this.label=r,this.transportId=n,this.channel=e,this.queue=new Map}};let yn=qi;Vs=new WeakMap,m(yn,"createRequest",e=>{var r;if((r=e.payload)!=null&&r._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:{...e.payload,_bolt:{id:Pu(8),type:"REQUEST",version:Xc}}}}),m(yn,"createResponse",(e,r)=>{var n;if((n=r.payload)!=null&&n._bolt)throw new Error("rpc fields are internal values");return{type:r.type,payload:{...r.payload,_bolt:{id:e,type:"RESPONSE",version:Xc}}}}),m(yn,"createNotification",e=>{var r;if((r=e.payload)!=null&&r._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:{...e.payload,bolt:{id:Pu(8),type:"NOTIFY",version:Xc}}}}),m(yn,"createErrorResponse",(e,r)=>({type:"error",payload:{error:r.message,_bolt:{id:e,type:"RESPONSE",version:Xc}}}));const Ru="transport closed";class Bg extends gn{constructor({id:e,direction:r,handlerFactory:n,iceServers:i,iceTransportPolicy:a,proprietaryConstraints:o,additionalSettings:d,appData:u,config:h}){var f,v;super();m(this,"awaitQueue");m(this,"observer");m(this,"id");m(this,"serverId");m(this,"closed",!1);m(this,"direction");m(this,"maxSctpMessageSize");m(this,"handler");m(this,"connectionState","new");m(this,"producers");m(this,"consumers");m(this,"datachannels");m(this,"connected",!1);m(this,"eventsDCReadyPromise");m(this,"eventsDCReadyPromiseResolver");m(this,"eventsDCFailureTimer");m(this,"transportConnectionPromise");m(this,"consumerTrackEvents");m(this,"unknownTracksMap");m(this,"consumerTrackPool");m(this,"appData");l.debug(`constructor() [id: ${e}, direction: ${r}]`),this.id=e,this.direction=r;const p=JD(d,{});delete p.iceServers,delete p.iceTransportPolicy,delete p.bundlePolicy,delete p.rtcpMuxPolicy,delete p.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.datachannels=new Map,this.consumerTrackEvents=new Map,this.consumerTrackPool=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new di,this.observer=new gn,this.handler=n(),this.handler._enableHighBitrate=(f=h==null?void 0:h.enableHighBitrate)!=null?f:!1,this.handler._enableStereo=(v=h==null?void 0:h.enableStereo)!=null?v:!1,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:r,iceServers:i,iceTransportPolicy:a,additionalSettings:d,proprietaryConstraints:o}),this.appData=u||{},this.transportConnectionPromise=new Promise(T=>{this.observer.once("connected",()=>{T(!0)}),this.observer.once("disconnect",()=>{T(!1)}),this.observer.once("close",()=>{T(!1)})}),this.eventsDCReadyPromise=new Promise(T=>{this.eventsDCReadyPromiseResolver=T}),this.handler.on("@connectionstatechange",T=>{T!==this.connectionState&&(l.debug(`connection state changed to ${T}`),this.connectionState=T,T==="connected"&&(this.connected=!0,this.observer.emit("connected")),T==="disconnected"&&(this.connected=!1,this.observer.emit("disconnect")),(T==="failed"||T==="closed")&&(this.connected=!1,this.observer.emit("close")),this.closed||this.safeEmit("connectionstatechange",T))}),this.handler.on("@icecandidate",({candidate:T})=>{this.closed||this.safeEmit("icecandidate",T)}),this.handler.on("dc_open",T=>{let P=this.datachannels.get(T.label);P||(P||(P=new yn(T,T.label,this.serverId),this.datachannels.set(T.label,P)),this.eventsDCFailureTimer=setTimeout(()=>{T.label==="events"&&(this.eventsDCReadyPromiseResolver(!1),this.safeEmit("dc_error",T.label))},5e3))}),this.handler.on("datachannel",(T,P)=>{T.label==="events"&&(this.eventsDCReadyPromiseResolver(!0),this.eventsDCFailureTimer&&clearTimeout(this.eventsDCFailureTimer));const k=this.datachannels.get(T.label);if(!k){l.error("unregistered datachannel for message",{rtcChannel:{label:T.label,message:P}});return}try{const I=JSON.parse(P);l.debug("datachannel message chunk recieved",{dataChannelMessageChunk:{id:I.id,count:I.count,chunkIndex:I.chunkIndex,chunk:I.chunk,transprtId:this.serverId}});const x=k.processMessage(I);if(!x)return;l.debug(`datachannel message with id:${I.id} on transport:${this.serverId}complete - ${JSON.stringify(x)}`),this.emit(`datachannel:${T.label}`,k.label,x)}catch(I){l.error("error parsing message",{error:I})}})}get isConnected(){return this.transportConnectionPromise}setServerId(e){this.serverId=e}getDatachannel(e){return this.datachannels.get(e)}get isEventsDCReady(){return this.eventsDCReadyPromise}close(){this.closed||(l.debug("Transport close called"),this.connected=!1,this.closed=!0,this.handler.close(),Array.from(this.producers.values()).forEach(e=>{e.close(Ru).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(Ru)}),this.consumers.clear(),this.consumerTrackPool.clear(),this.consumerTrackEvents.clear(),this.emit("close"),this.observer.emit("close"))}async getStats(){if(this.closed)throw new lt("closed");return this.handler.getTransportStats()}async restartIce(){if(l.debug("restartIce()"),this.closed)throw new lt("closed");return this.handler.restartIce()}async updateIceServers({iceServers:e}={}){if(l.debug("updateIceServers()"),this.closed)throw new lt("closed");return this.handler.updateIceServers(e)}async setRemoteOffer(e){await this.setRemoteDescription(e);const r=await this.handler.pc.createAnswer(),n=bu(r.sdp);return n.media=n.media.map(i=>{if(i.type==="audio"){const a={...i},o=a.fmtp.find(u=>u.payload===111);return o&&(o.config+=";stereo=1;sprop-stereo=1"),a.rtcpFb||(a.rtcpFb=[]),a.rtcpFb.some(u=>u.type==="nack")||a.rtcpFb.push({payload:parseInt(a.payloads,10),type:"nack"}),a}return i}),r.sdp=qD(n),await this.setLocalDescription(r),r}sendErrorOverDC(e,r,n){const i=this.getDatachannel(e);if(!i)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});i.respond(r,n,!0)}sendResponseOverDC(e,r,n){const i=this.getDatachannel(e);if(!i)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});i.respond(r,n)}async setRemoteDescription(e){await this.handler.pc.setRemoteDescription(e)}async setLocalDescription(e){l.debug(`${this.direction}() {transportId: ${this.serverId}} | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),await this.handler.pc.setLocalDescription(e)}async createConsumersOverDataChannel(e){const r=this.getDatachannel("events");if(!r)throw jD("DC_NOT_READY","events datachannel not ready");if(!e||e&&e.length===0)throw new Error("list of producers is required");const n={type:"create_consumer",payload:{producers:e.map(({producerId:d,producingTransportId:u})=>({producerId:d,producingTransportId:u}))}},i=new Map;e.forEach(d=>i.set(d.producerId,d));const a=(await r.request(n)).payload;l.info(`createConsumersOverDataChannel::response ${JSON.stringify(a)}`);const o=new Map;return Object.entries(a).forEach(([d,u])=>{const h=i.get(u.producerId);if(!h){l.error(`unknown entry in create consumer response, producerId: ${u.producerId}`,{consumerState:u});return}o.set(u.producerId,{consumerId:d,producingTransportId:h.producingTransportId,producingPeerId:h.producingPeerId,kind:h.kind,paused:h.pause,streamId:u.streamId,trackId:u.trackId,screenShare:h.screenShare,appData:{}})}),o}}class Hg extends gn{constructor({id:e,localId:r,track:n,stopTracks:i,disableTrackOnPause:a,zeroRtpOnPause:o,handler:d,appData:u,rtpSender:h}){super();m(this,"_id");m(this,"_localId");m(this,"_closed",!1);m(this,"_handler");m(this,"_track");m(this,"_kind");m(this,"_paused");m(this,"_maxSpatialLayer");m(this,"_stopTracks");m(this,"_disableTrackOnPause");m(this,"_zeroRtpOnPause");m(this,"_appData");m(this,"observer");m(this,"rtpSender");this._id=e,this._localId=r,this._track=n,this._kind=n.kind,this._paused=a?!n.enabled:!1,this._maxSpatialLayer=void 0,this._stopTracks=i,this._disableTrackOnPause=a,this._zeroRtpOnPause=o,this._appData=u||{},this._onTrackEnded=this._onTrackEnded.bind(this),this._handler=d,this.rtpSender=h,this.observer=new gn,this._handleTrack()}get id(){return this._id}get localId(){return this._localId}get closed(){return this._closed}get kind(){return this._kind}get track(){return this._track}get paused(){return this._paused}get maxSpatialLayer(){return this._maxSpatialLayer}get appData(){return this._appData}set appData(e){throw new Error("cannot override appData object")}async close(e){if(this._closed)return;if(l.debug("Producer::close() with reason:"),this._closed=!0,this._destroyTrack(),e===Ru){this.observer.emit("close");return}const{offerSdp:r,callback:n}=await this._handler.stopSending(this.localId);this.observer.emit("close");const{answer:i}=await this.safeEmitAsPromise("close",{offer:r,reason:e});n(i)}async getStats(){if(this._closed)throw new lt("closed");return this._handler.getSenderStats(this.localId)}pause(){l.debug("Producer::pause()",{producer:{id:this.id,appData:this.appData,kind:this.kind}}),this._closed&&l.error("Producer::pause() | Producer closed",{producer:{id:this.id,appData:this.appData,kind:this.kind}}),this._paused=!0,this._track&&this._disableTrackOnPause&&(this._track.enabled=!1),this._zeroRtpOnPause&&this._handler.replaceTrack(this.localId,null),this.observer.emit("pause")}resume(){if(l.debug("Producer::resume()",{producer:{id:this.id,appData:this.appData,kind:this.kind}}),this._closed){l.error("Producer::resume() | Producer closed",{producer:{id:this.id,appData:this.appData,kind:this.kind}});return}this._paused=!1,this._track&&this._disableTrackOnPause&&(this._track.enabled=!0),this._zeroRtpOnPause&&this._handler.replaceTrack(this.localId,this._track),this.observer.emit("resume")}async replaceTrack({track:e}){if(l.debug("Producer::replaceTrack()",{producer:{id:this.id,appData:this.appData,kind:this.kind,trackId:e==null?void 0:e.id}}),this._closed){if(e&&this._stopTracks)try{e.stop()}catch(r){l.error("Producer::replaceTrack",{producer:{id:this.id,appData:this.appData,kind:this.kind,trackId:e==null?void 0:e.id},error:r})}throw new lt("closed")}else if(e&&e.readyState==="ended")throw new lt("track ended");if(e===this._track){l.debug("replaceTrack() | same track, ignored",{producer:{id:this.id,appData:this.appData,kind:this.kind,trackId:e==null?void 0:e.id}});return}(!this._zeroRtpOnPause||!this._paused)&&await this._handler.replaceTrack(this.localId,e),this._destroyTrack(),this._track=e,this._handleTrack()}async setMaxSpatialLayer(e){if(this._closed)throw new lt("closed");if(this._kind!=="video")throw new vn("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");await this._handler.setMaxSpatialLayer(this.localId,e),this._maxSpatialLayer=e}async setRtpEncodingParameters(e){if(this._closed)throw new lt("closed");if(typeof e!="object")throw new TypeError("invalid params");await this._handler.setRtpEncodingParameters(this.localId,e)}_onTrackEnded(){l.debug('Producer::track "ended" event',{producer:{id:this.id,appData:this.appData,kind:this.kind,trackId:this.track.id}}),this.observer.emit("trackended"),this.safeEmit("trackended",this.track.id)}_handleTrack(){this._track&&this._track.addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(this._track)try{this._track.removeEventListener("ended",this._onTrackEnded),this._stopTracks&&this._track.stop()}catch(r){l.error("Producer::_destroyTrack",{producer:{id:this.id,appData:this.appData,kind:this.kind,trackId:(e=this._track)==null?void 0:e.id},error:r})}}}let KD=class extends Hg{},zD=class extends Bg{async consume(t){if(l.debug(`consume() producers: ${JSON.stringify(t)}`),this.closed)throw new lt("closed");if(this.direction!=="recv")throw new vn("not a receiving Transport");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(!await this.isConnected)return Promise.reject(new Error("Transport not connected"));const e=[];return(await this.createConsumersOverDataChannel(t)).forEach((n,i)=>{const{consumerId:a,trackId:o,screenShare:d,paused:u,streamId:h,kind:p,appData:f,producingTransportId:v,producingPeerId:T}=n;e.push(this.consumerCreationTask({consumerId:a,trackId:o,streamId:h,kind:p,producerId:i,producingPeerId:T,producingTransportId:v,paused:u,screenShare:d,appData:f}))}),Qc(e)}async connect(){try{const{offerSdp:t,callback:e}=await this.handler.connect(),{answer:r}=await this.safeEmitAsPromise("connect",{offer:t});if(await e(r),!await this.isConnected)throw new Error("ice connection failed");if(!await this.isEventsDCReady)throw new Error("events datachannel not open")}catch(t){throw l.error("transport failed to connect:",t),t}}_ontrack(t){const{track:e,transceiver:r,streams:n}=t;l.info(`track event received [trackId: ${e.id}]`);const i=`${n[0].id}:${e.kind}`;e.addEventListener("ended",()=>{l.info(`rtc consumer track ended [trackId: ${e.id}]`),this.consumerTrackPool.delete(e.id),this.unknownTracksMap.delete(i)}),this.consumerTrackPool.set(e.id,[e,r]);const a=this.consumerTrackEvents.get(i);a?(a(e,r),this.consumerTrackEvents.delete(i)):(l.warn(`track event handler not found ${i}`),this.unknownTracksMap.set(i,t))}async consumerCreationTask({consumerId:t,producerId:e,producingPeerId:r,producingTransportId:n,streamId:i,trackId:a,paused:o,screenShare:d,appData:u,kind:h}){const p=`${i}:${h}`,f={consumerId:t,producerId:e,producingPeerId:r,producingTransportId:n,streamId:i,trackId:a,appData:u,kind:h,paused:o,screenShare:d,name:"consumer creation task error",message:"consumer creation failed"};return new Promise((T,P)=>{const k=setTimeout(()=>{this.consumerTrackEvents.delete(p),f.isTimedout=!0,P(f)},5e3),I=(O,W)=>{try{if(O.readyState==="ended")clearTimeout(k),P(f);else{const Q=O;Q.enabled=!0,this.handler.midTransceiverMap.set(W.mid,W);const oe=new GD({id:t,localId:W.mid,track:Q,paused:o,producerId:e,producingPeerId:r,producingTransportId:n,handler:this.handler,appData:{...u,screenShare:d,peerId:r},reuseTrack:!0,rtpReceiver:W.receiver});this.consumers.set(t,oe),oe.once("close",()=>{this.consumers.delete(oe.id),this.handler.midTransceiverMap.delete(W.mid)}),l.info("consumer created for ",{consumer:{id:t,kind:h,appData:{screenShare:d},peerId:r,producerId:e}}),this.observer.emit("newconsumer",oe),clearTimeout(k),T(oe)}}catch(Q){l.warn("error while creating consumer:",Q),clearTimeout(k),P(f)}},x=this.consumerTrackPool.get(t);if((x==null?void 0:x.length)===2){I(x[0],x[1]);return}const V=this.unknownTracksMap.get(p);V?(this.unknownTracksMap.delete(p),I(V.track,V.transceiver)):this.consumerTrackEvents.set(p,I)})}async retryFailedConsumerCreationTasks(t){return Qc(t.map(async e=>br(async r=>(r>0&&l.warn(`retrying failed consumer creation task: ${JSON.stringify(e)}`),this.consumerCreationTask({...e})))))}async produce({track:t,encodings:e,codecOptions:r,stopTracks:n=!0,disableTrackOnPause:i=!0,zeroRtpOnPause:a=!1,appData:o={}}={}){if(l.debug(`produce() [track:${t.id}]`),t){if(this.direction!=="send")throw new vn("not a sending Transport");if(t.readyState==="ended")throw new lt("track ended");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(this.listenerCount("produce")===0)throw new TypeError('no "produce" listener set into this transport');if(o&&typeof o!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!await this.isConnected)return Promise.reject(new Error("Transport not connected"));const{producerId:d,localId:u,rtpSender:h}=await this.awaitQueue.push(async()=>{const{offerSdp:f,callback:v,sender:T,mid:P}=await this.handler.send({track:t,encodings:e,codecOption:r,screenShare:o==null?void 0:o.screenShare}),{answer:k,producerId:I}=await this.safeEmitAsPromise("produce",{offer:f,kind:t.kind,paused:i?!t.enabled:!1,appData:{...o||{},mid:P}}),x=await v(k);return{producerId:I,localId:x,rtpSender:T}},"producer"),p=new KD({id:d,localId:u,track:t,stopTracks:n,disableTrackOnPause:i,zeroRtpOnPause:a,appData:o,handler:this.handler,rtpSender:h});return this.producers.set(d,p),p.observer.on("close",()=>{this.producers.delete(p.id)}),this.emit("newproducer",p),this.observer.emit("newproducer",p),p}};class ku extends gn{constructor(){super();m(this,"_mapMidTransceiver",new Map);m(this,"_enableHighBitrate",!1);m(this,"_enableStereo",!1);this._mapMidTransceiver=new Map,this._enableHighBitrate=!1}get midTransceiverMap(){return this._mapMidTransceiver}}class Iu extends ku{constructor(){super();m(this,"_direction");m(this,"_pc");m(this,"_sendWebStream",new MediaStream);m(this,"_sendScreenShareStream",new MediaStream);m(this,"_transportReady",!1)}static createFactory(){return()=>new Iu}get name(){return"Chrome74"}get pc(){return this._pc}close(){if(l.debug("close()"),this._pc)try{this._pc.close()}catch(e){l.error("pc.close()",e)}}init({direction:e,iceServers:r,iceTransportPolicy:n,additionalSettings:i,proprietaryConstraints:a,onTrackHandler:o}){this._direction=e,this._pc=new RTCPeerConnection({iceServers:r||[],iceTransportPolicy:n||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...i},a),o&&this._pc.addEventListener("track",d=>{o(d)}),this._addEventListeners()}async connect(){const e=this._pc.createDataChannel("dyte"),r=await this._pc.createOffer();return l.info(`connect offer: ${JSON.stringify(r)}`),await this._pc.setLocalDescription(r),{offerSdp:r,callback:async i=>{l.debug(`Chrome74::connect() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),await this._pc.setRemoteDescription(i),e.close()}}}async updateIceServers(e){l.debug("updateIceServers()");const r=this._pc.getConfiguration();r.iceServers=e,this._pc.setConfiguration(r)}async restartIce(){l.debug("restartIce()");const e=await this.pc.createOffer({iceRestart:!0});return l.debug(`restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:async n=>{l.info(`restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(n)}]`),await this._pc.setRemoteDescription(n)}}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:r,codecOption:n,screenShare:i}){var u;this._assertSendDirection(),l.debug(`send() [kind:${e.kind}, track.id:${e.id}]`);const a=this._pc.addTransceiver(e,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:r});if(!navigator.isReactNative){l.debug("creating new transceiver");const h=RTCRtpSender.getCapabilities(e.kind);l.info(`senders available params: ${JSON.stringify(h)}`);const p=[];if(n){const f=h.codecs.find(v=>v.mimeType.includes(n.name));if(n.parameters){l.info(`codecOption.parameters:${JSON.stringify(n.parameters)}`);const v=((u=f.sdpFmtpLine)==null?void 0:u.split(";"))||[];v.push(...n.parameters);const T=Array.from(new Set(v).values());f.sdpFmtpLine=T.join(";")}p.push(f)}l.info(`selected codecs: ${JSON.stringify(p)}`),a.setCodecPreferences(p)}const o=await this._pc.createOffer();if(!this._transportReady)throw new Error("webrtc transport not connected");if(await this._pc.setLocalDescription(o),n&&n.name==="opus"){const h=this._enableStereo,p=this._enableHighBitrate?h?128e3:64e3:h?64e3:32e3;o.sdp=o.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;usedtx=1${h?"":";stereo=1;sprop-stereo=1"};maxaveragebitrate=${p}`),o.sdp+=`a=rtcp-fb:111 nack\r -`}return{offerSdp:o,callback:async h=>(l.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(h)}]`),await this._pc.setRemoteDescription(h),this.midTransceiverMap.set(a.mid,a),a.mid),sender:a.sender,mid:a.mid}}async stopSending(e){this._assertSendDirection(),l.debug(`stopSending() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.sender.replaceTrack(null),this._pc.removeTrack(r.sender),r.direction="inactive";const n=await this._pc.createOffer();return l.debug(`stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),await this._pc.setLocalDescription(n),{offerSdp:n,callback:async a=>{l.debug(`stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(a)}]`),await this._pc.setRemoteDescription(a),this.midTransceiverMap.delete(e)}}}async replaceTrack(e,r){this._assertSendDirection(),r?l.debug(`replaceTrack() [localId:${e}, track.id:${r.id}]`):l.debug(`replaceTrack() [localId:${e}, no track]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");await n.sender.replaceTrack(r)}async setMaxSpatialLayer(e,r){this._assertSendDirection(),l.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((a,o)=>{o<=r?a.active=!0:a.active=!1}),await n.sender.setParameters(i)}async setRtpEncodingParameters(e,r){this._assertSendDirection(),l.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((a,o)=>{i.encodings[o]={...a,...r}}),await n.sender.setParameters(i)}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.sender.getStats()}async stopReceiving(e){throw this._assertRecvDirection(),l.debug(`stopReceiving() [localId:${e}]`),Error("method not implemented")}async pauseReceiving(e){throw this._assertRecvDirection(),l.debug(`pauseReceiving() [localId:${e}]`),Error("method not implemented")}async resumeReceiving(e){throw this._assertRecvDirection(),l.debug(`resumeReceiving() [localId:${e}]`),Error("method not implemented")}async getReceiverStats(e){this._assertRecvDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.receiver.getStats()}_assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}_assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}async _generateOffer(){const e=await this._pc.createOffer();return await this._pc.setLocalDescription(e),e}async _setAnswer(e){l.debug(`setAnswer() | calling pc.setRemoteDescription() [answer:${JSON.stringify(e)}]`),await this._pc.setRemoteDescription(e)}_addEventListeners(){this._pc.addEventListener("iceconnectionstatechange",()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected"),this._transportReady=!0;break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed");break;default:l.warn("unknown state");break}}),this._pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this._pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),l.debug("negotiationneeded")}),this._pc.addEventListener("icegatheringstatechange",()=>{switch(this._pc.iceGatheringState){case"gathering":l.debug("icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":l.debug("icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:l.warn("unknown state");break}}),this._pc.addEventListener("icecandidateerror",e=>{l.error("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})}),this._pc.addEventListener("datachannel",e=>{l.info("data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:r}=e;r.onopen=()=>{l.info("data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},r.onclose=()=>{l.warn("data channel closed: ",{rtcChannel:{label:e.channel.label}})},r.onerror=()=>{l.error("data channel error: ",{rtcChannel:{label:e.channel.label}})},r.onmessage=n=>{this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(n.data)))}})}}class ed extends ku{constructor(e){super();m(this,"_direction");m(this,"_pc");m(this,"_sendWebStream",new MediaStream);m(this,"_sendScreenShareStream",new MediaStream);m(this,"_transportReady",!1);m(this,"supportsSendEncodings",!1);this.supportsSendEncodings=e.supportsSendEncodings}static createFactory(e){return()=>new ed(e)}get name(){return"Firefox60"}get pc(){return this._pc}close(){if(l.debug("Firefox60::close()"),this._pc)try{this._pc.close()}catch(e){l.error("Firefox60::pc.close()",{error:e})}}init({direction:e,iceServers:r,iceTransportPolicy:n,additionalSettings:i,proprietaryConstraints:a,onTrackHandler:o}){l.debug("Firefox60::init()"),this._direction=e,this._pc=new RTCPeerConnection({iceServers:r||[],iceTransportPolicy:n||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...i},a),o&&this._pc.addEventListener("track",d=>{o(d)}),this._addEventListeners()}async connect(){const e=this._pc.createDataChannel("dyte"),r=await this._pc.createOffer();return l.info(`Firefox60::connect offer: ${JSON.stringify(r)}`),await this._pc.setLocalDescription(r),{offerSdp:r,callback:async i=>{l.debug(`Firefox60::connect() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),await this._pc.setRemoteDescription(i),e.close()}}}async updateIceServers(e){throw l.debug("Firefox60::updateIceServers()"),new Error("not supported")}async restartIce(){l.debug("Firefox60::restartIce()");const e=await this.pc.createOffer({iceRestart:!0});return l.debug(`Firefox60::restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:async n=>{l.info(`Firefox60::restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(n)}]`),await this._pc.setRemoteDescription(n)}}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:r,screenShare:n}){this._assertSendDirection(),l.debug(`Firefox60::send() [kind:${e.kind}, track.id:${e.id}]`),l.debug("Firefox60::creating new transceiver");const i=this.supportsSendEncodings&&r!==void 0?{sendEncodings:r}:{},a=this._pc.addTransceiver(e,{direction:"sendonly",streams:[n?this._sendScreenShareStream:this._sendWebStream],...i});if(!this.supportsSendEncodings&&r){r.reverse();const u=a.sender.getParameters();u.encodings=r,await a.sender.setParameters(u)}const o=await this._pc.createOffer();if(!this._transportReady)throw new Error("webrtc transport not connected");if(await this._pc.setLocalDescription(o),e.kind==="audio"){const u=this._enableStereo,h=this._enableHighBitrate?u?128e3:64e3:u?64e3:32e3;o.sdp=o.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;usedtx=1${this.supportsSendEncodings?"":`${u?"":";stereo=1;sprop-stereo=1"};maxaveragebitrate=${h}`}`)}return{offerSdp:o,callback:async u=>(l.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(u)}]`),await this._pc.setRemoteDescription(u),this.midTransceiverMap.set(a.mid,a),a.mid),sender:a.sender,mid:a.mid}}async stopSending(e){this._assertSendDirection(),l.debug(`Firefox60::stopSending() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated transceiver not found");r.sender.replaceTrack(null),this._pc.removeTrack(r.sender),r.direction="inactive";const n=await this._pc.createOffer();return l.debug(`stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),await this._pc.setLocalDescription(n),{offerSdp:n,callback:async a=>{l.debug(`stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(a)}]`),await this._pc.setRemoteDescription(a),this.midTransceiverMap.delete(e)}}}async replaceTrack(e,r){this._assertSendDirection(),r?l.debug(`replaceTrack() [localId:${e}, track.id:${r.id}]`):l.debug(`Firefox60::replaceTrack() [localId:${e}, no track]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");await n.sender.replaceTrack(r)}async setMaxSpatialLayer(e,r){this._assertSendDirection(),l.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters(),a=i.encodings.length-1-r;i.encodings.forEach((o,d)=>{d>=a?o.active=!0:o.active=!1}),await n.sender.setParameters(i)}async setRtpEncodingParameters(e,r){this._assertSendDirection(),l.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((a,o)=>{i.encodings[o]={...a,...r}}),await n.sender.setParameters(i)}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.sender.getStats()}async stopReceiving(e){this._assertRecvDirection(),l.debug(`Firefox60::stopReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="inactive",l.info(`Firefox60::active transcievers: ${JSON.stringify(this._pc.getTransceivers())}`);const n=await this._pc.createOffer();return l.debug(`Firefox60::stopRecieving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),await this._pc.setLocalDescription(n),{offerSdp:n,callback:async a=>{l.debug(`Firefox60::stopRecieving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(a)}]`),await this._pc.setRemoteDescription(a),this.midTransceiverMap.delete(e)}}}async pauseReceiving(e){this._assertRecvDirection(),l.debug(`Firefox60::pauseReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="inactive";const n=await this._pc.createOffer();return l.debug(`pauseReceiving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),await this._pc.setLocalDescription(n),{offerSdp:n,callback:async a=>{l.debug(`pauseReceiving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(a)}]`),await this._pc.setRemoteDescription(a)}}}async resumeReceiving(e){this._assertRecvDirection(),l.debug(`Firefox60::resumeReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="recvonly";const n=await this._generateOffer();return l.debug(`resumeReceiving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),{offerSdp:n,callback:async a=>{l.debug(`resumeReceiving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(a)}]`),await this._pc.setRemoteDescription(a)}}}async getReceiverStats(e){this._assertRecvDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.receiver.getStats()}_assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}_assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}async _generateOffer(){const e=await this._pc.createOffer();return await this._pc.setLocalDescription(e),e}async _setAnswer(e){l.debug(`_setAnswer() | calling pc.setRemoteDescription() [answer:${JSON.stringify(e)}]`),await this._pc.setRemoteDescription(e)}_addEventListeners(){this._pc.addEventListener("datachannel",e=>{l.info("Firefox60::data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:r}=e;r.onopen=()=>{l.info("Firefox60::data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},r.onclose=()=>{l.warn("data channel closed: ",{rtcChannel:{label:e.channel.label}})},r.onerror=()=>{l.error("Firefox60::data channel error: ",{rtcChannel:{label:e.channel.label}})},r.onmessage=async n=>{const i=await n.data.arrayBuffer();this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(i)))}}),this._pc.addEventListener("iceconnectionstatechange",()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected"),this._transportReady=!0;break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed");break;default:l.warn("unknown state");break}}),this._pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this._pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),l.debug("Firefox60::negotiationneeded")}),this._pc.addEventListener("icegatheringstatechange",()=>{switch(this._pc.iceGatheringState){case"gathering":l.debug("Firefox60::icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":l.debug("Firefox60::icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:l.warn("unknown state");break}}),this._pc.addEventListener("icecandidateerror",e=>{l.error("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})})}}class Au extends ku{constructor(){super();m(this,"_direction");m(this,"_pc");m(this,"_sendWebStream",new MediaStream);m(this,"_sendScreenShareStream",new MediaStream);m(this,"_transportReady",!1)}static createFactory(){return()=>new Au}get name(){return"Chrome74"}get pc(){return this._pc}close(){if(l.debug("Safari12::close()"),this._pc)try{this._pc.close()}catch(e){l.error("Safari12::pc.close()",e)}}init({direction:e,iceServers:r,iceTransportPolicy:n,additionalSettings:i,proprietaryConstraints:a,onTrackHandler:o}){l.debug("Safari12::init()"),this._direction=e,this._pc=new RTCPeerConnection({iceServers:r||[],iceTransportPolicy:n||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...i},a),o&&this._pc.addEventListener("track",d=>{o(d)}),this._addEventListeners()}async connect(){const e=this._pc.createDataChannel("dyte"),r=await this._pc.createOffer();return l.info(`Safari12::connect offer: ${JSON.stringify(r)}`),await this._pc.setLocalDescription(r),{offerSdp:r,callback:async i=>{l.debug(`Safari12::connect() | calling pc.setRemoteDescription() [answer: ${JSON.stringify(i)}]`),await this._pc.setRemoteDescription(i),e.close()}}}async updateIceServers(e){l.debug("Safari12::updateIceServers()");const r=this._pc.getConfiguration();r.iceServers=e,this._pc.setConfiguration(r)}async restartIce(){l.debug("Safari12::restartIce()");const e=await this.pc.createOffer({iceRestart:!0});return l.debug(`restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:async n=>{l.info(`restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(n)}]`),await this._pc.setRemoteDescription(n)}}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:r,codecOption:n,screenShare:i}){var p;this._assertSendDirection(),l.debug(`Safari12::send() [kind: ${e.kind}, track.id: ${e.id}]`),l.debug("Safari12::creating new transceiver");const a=this._pc.addTransceiver(e,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:r}),o=RTCRtpSender.getCapabilities(e.kind);l.info(`Safari12::senders available params: ${JSON.stringify(o)}`);const d=[];if(n){const f=o.codecs.find(v=>v.mimeType.includes(n.name));if(n.parameters){l.info(`Safari12::codecOption.parameters:, ${JSON.stringify(n.parameters)}`);const v=((p=f.sdpFmtpLine)==null?void 0:p.split(";"))||[];v.push(...n.parameters);const T=[...new Set(v).values()];f.sdpFmtpLine=T.join(";")}d.push(f)}l.info(`Safari12::selected codecs: ${JSON.stringify(d)}`),a.setCodecPreferences(d);const u=await this._pc.createOffer();if(!this._transportReady)throw new Error("webrtc transport not connected");if(await this._pc.setLocalDescription(u),e.kind==="audio"){const f=this._enableStereo,v=this._enableHighBitrate?f?128e3:64e3:f?64e3:32e3;u.sdp=u.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;usedtx=1${f?"":";stereo=1;sprop-stereo=1"};maxaveragebitrate=${v}`)}return{offerSdp:u,callback:async f=>(l.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(f)}]`),await this._pc.setRemoteDescription(f),this.midTransceiverMap.set(a.mid,a),a.mid),sender:a.sender,mid:a.mid}}async stopSending(e){this._assertSendDirection(),l.debug(`Safari12::stopSending() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.sender.replaceTrack(null),this._pc.removeTrack(r.sender),r.direction="inactive";const n=await this._pc.createOffer();return l.debug(`Safari12::stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),await this._pc.setLocalDescription(n),{offerSdp:n,callback:async a=>{l.debug(`Safari12::stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(a)}]`),await this._pc.setRemoteDescription(a),this.midTransceiverMap.delete(e)}}}async replaceTrack(e,r){this._assertSendDirection(),r?l.debug(`Safari12::replaceTrack() [localId:${e}, track.id:${r.id}]`):l.debug(`Safari12::replaceTrack() [localId:${e}, no track]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");await n.sender.replaceTrack(r)}async setMaxSpatialLayer(e,r){this._assertSendDirection(),l.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((a,o)=>{o<=r?a.active=!0:a.active=!1}),await n.sender.setParameters(i)}async setRtpEncodingParameters(e,r){this._assertSendDirection(),l.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((a,o)=>{i.encodings[o]={...a,...r}}),await n.sender.setParameters(i)}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.sender.getStats()}async receive(e){this._assertRecvDirection(),l.debug(`recieve() | calling pc.setLocalDescription() [answer:${JSON.stringify(e)}]`);const r=this._pc.getTransceivers().at(-1);return l.info("Safari12::Transceiver is now receiving"),this.midTransceiverMap.set(r.mid,r),{track:r.receiver.track,localId:r.mid}}async stopReceiving(e){this._assertRecvDirection(),l.debug(`Safari12::stopReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="inactive",l.info(`Safari12::active transcievers: ${JSON.stringify(this._pc.getTransceivers())}`);const n=await this._pc.createOffer();return l.debug(`stopRecieving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),await this._pc.setLocalDescription(n),{offerSdp:n,callback:async a=>{l.debug(`stopRecieving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(a)}]`),await this._pc.setRemoteDescription(a),this.midTransceiverMap.delete(e)}}}async pauseReceiving(e){this._assertRecvDirection(),l.debug(`Safari12::pauseReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="inactive";const n=await this._pc.createOffer();return l.debug(`pauseReceiving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),await this._pc.setLocalDescription(n),{offerSdp:n,callback:async a=>{l.debug(`pauseReceiving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(a)}]`),await this._pc.setRemoteDescription(a)}}}async resumeReceiving(e){this._assertRecvDirection(),l.debug(`Safari12::resumeReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="recvonly";const n=await this._generateOffer();return l.debug(`Safari12::resumeReceiving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),{offerSdp:n,callback:async a=>{l.debug(`Safari12::resumeReceiving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(a)}]`),await this._pc.setRemoteDescription(a)}}}async getReceiverStats(e){this._assertRecvDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.receiver.getStats()}_assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}_assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}async _generateOffer(){const e=await this._pc.createOffer();return await this._pc.setLocalDescription(e),e}async _setAnswer(e){l.debug(`Safari12::_setAnswer() | calling pc.setRemoteDescription() [answer:${JSON.stringify(e)}]`),await this._pc.setRemoteDescription(e)}_addEventListeners(){this._pc.addEventListener("iceconnectionstatechange",()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected"),this._transportReady=!0;break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed");break;default:l.warn("Safari12::unknown state");break}}),this._pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this._pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),l.debug("Safari12::negotiationneeded")}),this._pc.addEventListener("icegatheringstatechange",()=>{switch(this._pc.iceGatheringState){case"gathering":l.debug("Safari12::icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":l.debug("Safari12::icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:l.warn("Safari12::unknown state");break}}),this._pc.addEventListener("icecandidateerror",e=>{l.error("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})}),this._pc.ondatachannel=e=>{l.info("Safari12::data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:r}=e;r.onopen=()=>{l.info("Safari12::data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},r.onclose=()=>{l.warn("Safari12::data channel closed: ",{rtcChannel:{label:e.channel.label}})},r.onerror=()=>{l.error("Safari12::data channel error: ",{rtcChannel:{label:e.channel.label}})},r.onmessage=async n=>{const i=String.fromCharCode(...new Uint8Array(n.data));this.safeEmit("datachannel",e.channel,i)}}}}function YD(){if(typeof navigator=="object"&&navigator.product==="ReactNative"){if(typeof RTCPeerConnection=="undefined"){l.warn("Device::this._detectDevice() | unsupported ReactNative without RTCPeerConnection");return}return l.debug("Device::this._detectDevice() | ReactNative handler chosen"),"Chrome74"}if(typeof navigator=="object"&&typeof navigator.userAgent=="string"){const s=navigator.userAgent,t=Rm.getParser(s),e=t.getEngine();if(t.satisfies({chrome:">=74",chromium:">=74","microsoft edge":">=88"}))return"Chrome74";if(t.satisfies({chrome:">=70",chromium:">=70"}))return"Chrome70";if(t.satisfies({chrome:">=67",chromium:">=67"}))return"Chrome67";if(t.satisfies({chrome:">=55",chromium:">=55"}))return"Chrome55";if(t.satisfies({firefox:">=110"}))return"Firefox110";if(t.satisfies({firefox:">=60"}))return"Firefox60";if(t.satisfies({ios:{OS:">=14.3",firefox:">=30.0"}})||t.satisfies({safari:">=12.0"})&&typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(t.satisfies({safari:">=11"}))return"Safari11";if(t.satisfies({"microsoft edge":">=11"})&&t.satisfies({"microsoft edge":"<=18"}))return"Edge11";if(e.name&&e.name.toLowerCase()==="blink"){const r=s.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);if(r){const n=Number(r[1]);return n>=74?"Chrome74":n>=70?"Chrome70":n>=67?"Chrome67":"Chrome55"}return"Chrome74"}if(e.name.toLowerCase()==="webkit"&&t.getOS().name.toLowerCase()==="ios")return typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection")?"Safari12":"Safari11";l.warn("Device::this._detectDevice() | browser not supported");return}l.warn("Device::this._detectDevice() | unknown device")}class qg{constructor({handlerName:t,handlerFactory:e}={}){m(this,"handlerFactory");m(this,"_handlerName");m(this,"_observer");if(l.debug("constructor()"),t&&e)throw new TypeError("just one of handlerName or handlerInterface can be given");if(e)this.handlerFactory=e;else{if(t)l.debug(`Device::constructor() | handler given: ${t}`);else if(t=YD(),t)l.debug(`Device::constructor() | detected handler: ${t}`);else throw new Error("device not supported");switch(t){case"Chrome74":this.handlerFactory=Iu.createFactory();break;case"Safari12":this.handlerFactory=Au.createFactory();break;case"Firefox60":this.handlerFactory=ed.createFactory({supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=ed.createFactory({supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${t}"`)}}const r=this.handlerFactory();this._handlerName=r.name,r.close(),this._observer=new de}get handlerName(){return this._handlerName}createSendTransport({iceServers:t,iceTransportPolicy:e,additionalSettings:r,proprietaryConstraints:n,appData:i,config:a}){return l.debug("Device::createSendTransport()"),this.createTransport({direction:"send",iceServers:t,iceTransportPolicy:e,additionalSettings:r,proprietaryConstraints:n,appData:i,config:a})}createRecvTransport({iceServers:t,iceTransportPolicy:e,additionalSettings:r,proprietaryConstraints:n,appData:i}){return l.debug("Device::createRecvTransport()"),this.createTransport({direction:"recv",iceServers:t,iceTransportPolicy:e,additionalSettings:r,proprietaryConstraints:n,appData:i})}}let QD=class extends qg{createTransport({direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:a,config:o}){const d=Xs(),u=new zD({id:d,direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:a,handlerFactory:this.handlerFactory,config:o});return this._observer.emit("newtransport",u),u}};class XD{constructor(t){S(this,_t,void 0);y(this,_t,t)}async joinRoom(t,e,r=!1,n=null){const i={roomUuid:t,displayName:e,prejoined:r};return n&&(i.location=n),(await c(this,_t).sendMessagePromiseWithTimeout({event:se.joinRoom,protobuf:af.toBinary(i),timeout:5e3})).payload}async connectTransport(t){const e=(await c(this,_t).sendMessagePromise(se.createWebRTCTransport,Zm.toBinary(t))).payload,{transportId:r,description:n}=Hl.fromBinary(e),i={sdp:n==null?void 0:n.sdp,type:n.type};return{transportId:r,answer:i}}async produce(t){var i,a;const e=(await c(this,_t).sendMessagePromise(se.produce,lf.toBinary(t))).payload,r=Ef.fromBinary(e);return{answer:{sdp:(i=r==null?void 0:r.description)==null?void 0:i.sdp,type:(a=r==null?void 0:r.description)==null?void 0:a.type},producerId:r.producerId}}async consume(t){const e=(await c(this,_t).sendMessagePromise(se.consume,df.toBinary(t))).payload,{consumerIdsMap:{map:r}}=Sf.fromBinary(e);return r}async closeProducer(t){const e=(await c(this,_t).sendMessagePromise(se.closeProducer,hf.toBinary(t))).payload,{description:r}=wf.fromBinary(e);return r}async closeConsumer(t){return(await c(this,_t).sendMessagePromise(se.closeConsumer,pf.toBinary(t))).payload}async hostControlForPeer(t,e){const r={audio:e==="audio",screeShare:!1,video:e==="video",participantId:t},n=(await c(this,_t).sendMessagePromise(se.hostControlPeer,gf.toBinary(r))).payload;if(!n)return!1;const{status:i}=Pf.fromBinary(n);return i==="success"}async hostControlForAll(t){const e={audio:t==="audio",screenShare:!1,video:t==="video"},r=(await c(this,_t).sendMessagePromise(se.hostControlAllPeers,vf.toBinary(e))).payload;if(!r)return!1;const{status:n}=Rf.fromBinary(r);return n==="success"}async kickAll(){const t={},e=(await c(this,_t).sendMessagePromise(se.kickAll,ql.toBinary(t))).payload;if(!e)return!1;const{status:r}=bf.fromBinary(e);return r==="success"}async kickPeer(t){const e=(await c(this,_t).sendMessagePromise(se.kickPeer,mf.toBinary(t))).payload;if(!e)return!1;const{status:r}=Cf.fromBinary(e);return r==="success"}async changeDisplayName(t){const e=(await c(this,_t).sendMessagePromise(se.changeDisplayName,ff.toBinary(t))).payload;if(!e)return!1;const{status:r}=kf.fromBinary(e);return r==="success"}async notifySelfJoinComplete(){const t={},e=(await c(this,_t).sendMessagePromise(se.selfJoinComplete,of.toBinary(t))).payload;return Rc.fromBinary(e)}}_t=new WeakMap;var Rt=(s=>(s.NEW="new",s.CONNECTING="connecting",s.RECONNECTING="reconnecting",s.DISCONNECTED="disconnected",s.CONNECTED="connected",s.FAILED="failed",s))(Rt||{}),li=(s=>(s[s.HIVE=1]="HIVE",s[s.ROOM_NODE=2]="ROOM_NODE",s[s.CF=3]="CF",s))(li||{});const ZD=2e3;class eO extends Fg{constructor(e,r){super();S(this,Vn);m(this,"_device");m(this,"_sendTransport");m(this,"_recvTransport");m(this,"_consumers");m(this,"_producers");m(this,"_producerStatus");m(this,"_producerIdToConsumerIdMap");m(this,"_socket");m(this,"_socketHandler");m(this,"_totalTransportReconnectionCount");m(this,"_transportReconnectFailureCount");m(this,"_consumerCreationFailureCount");m(this,"_producerNotReadyFailureCount");m(this,"_consumerNotBoundFailureCount");m(this,"_transportDisconnectedTimer");m(this,"_iceTransportPolicy","all");m(this,"_transportConnectionFailCount",0);m(this,"lastConnectionTime",0);m(this,"transportConnectionStatus");m(this,"transportState");m(this,"transportDisconnected");S(this,Ar,void 0);y(this,Ar,e),this._device=new QD({}),this._socket=r,c(this,Vn,No).mediaState={consuming:{state:Rt.NEW,reconnected:!1},producing:{state:Rt.NEW,reconnected:!1}},this.transportDisconnected={consuming:!1,producing:!1},this._socketHandler=new XD(r),this.reset()}get socket(){return this._socket}get producers(){return this._producers}get consumers(){return this._consumers}get producerIdToConsumerIdMap(){return this._producerIdToConsumerIdMap}get hiveSocketHandler(){return this._socketHandler}get sendTransport(){return this._sendTransport}get recvTransport(){return this._recvTransport}reset(){this._producers=new Map,this._consumers=new Map,this._producerStatus=new Map,this._producerIdToConsumerIdMap=new Map,this._transportReconnectFailureCount=0,this._consumerCreationFailureCount=0,this._totalTransportReconnectionCount=0,this._producerNotReadyFailureCount=0,this._consumerNotBoundFailureCount=0,this._transportDisconnectedTimer={consuming:void 0,producing:void 0}}async setupTransports(e){var a,o,d,u,h,p,f,v;const n=await We().getICEServers().catch(T=>(l.warn(`failed to get iceservers from server: ${T.message}`),[])),i=[];if(e.send){const T=this.createSendTransport({iceServers:n,additionalSettings:{encodedInsertableStreams:(a=c(this,Ar).getValue("modules").e2ee)==null?void 0:a.enabled},config:{enableHighBitrate:(u=(d=(o=c(this,Ar).getValue("defaults").mediaConfiguration)==null?void 0:o.audio)==null?void 0:d.enableHighBitrate)!=null?u:!1,enableStereo:(f=(p=(h=c(this,Ar).getValue("defaults").mediaConfiguration)==null?void 0:h.audio)==null?void 0:p.enableStereo)!=null?f:!1},iceTransportPolicy:this._iceTransportPolicy});i.push(T)}if(e.recv){const T=this.createRecvTransport({iceServers:n,additionalSettings:{encodedInsertableStreams:(v=c(this,Ar).getValue("modules").e2ee)==null?void 0:v.enabled},iceTransportPolicy:this._iceTransportPolicy});i.push(T)}await Promise.all(i)}stopAllTransports(){var e,r,n,i;l.info("closing all the transports"),(e=this._sendTransport)==null||e.close(),(r=this._sendTransport)==null||r.removeAllListeners(),(n=this._recvTransport)==null||n.close(),(i=this._recvTransport)==null||i.removeAllListeners(),this._sendTransport=void 0,this._recvTransport=void 0,this.reset()}async createSendTransport(e){var n,i,a,o;if(this._sendTransport&&this._sendTransport.connected){l.info("sendTransport::already_exists_in_connected_state",{transport:{id:(n=this._sendTransport)==null?void 0:n.id,serverId:(i=this._sendTransport)==null?void 0:i.serverId,type:"send"}});return}l.info("sendTransport::initializing_transport",{transport:{id:(a=this._sendTransport)==null?void 0:a.id,serverId:(o=this._sendTransport)==null?void 0:o.serverId,type:"send"}});const r=this._device.createSendTransport(e);this._transportDisconnectedTimer.producing=void 0,l.info("sendTransport::initialized_transport",{transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"send"}}),this.handleTransport(r,!1),l.info("sendTransport::connecting_transport",{transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"send"}});try{await br(async(d,u)=>{this.socket.isConnected||u(new Error("socket is not connected")),r.connectionState==="closed"&&u(new Error("transport is closed")),d>0&&l.debug(`retrying transport connect, count: ${d}`,{transport:{id:r.id,serverId:r.serverId,type:"send"}});try{await r.connect()}catch(h){throw l.error(`failed to connect send transport: ${r.id}`,{error:h,transport:{id:r.id,serverId:r.serverId,type:"send"}}),h.message==="ice connection failed"&&u(h),h}},{delayTime:100,strategy:"exponential",maxRetryCount:J.hasFeature(X.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3}),l.info("sendTransport::connected_transport",{transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"send"}}),this._transportReconnectFailureCount=Math.max(0,this._transportReconnectFailureCount-1),this._producerNotReadyFailureCount=0,this._sendTransport=r,U.onSafeInitialization(()=>{U.configureSendTransport(r)})}catch(d){throw l.error(`failed to connect send transport after retry:${r.id}`,{error:d,transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"send"}}),r.close(),r.removeAllListeners(),this._transportReconnectFailureCount+=1,this.handleFailure(),d}}async createRecvTransport(e){var n,i,a,o,d;if(this._recvTransport&&this._recvTransport.connected){l.info("recvTransport::already_exists_in_connected_state",{transport:{id:(n=this._recvTransport)==null?void 0:n.id,serverId:(i=this._recvTransport)==null?void 0:i.serverId,type:"recv"}});return}l.info("recvTransport::initializing_transport",{transport:{id:(a=this._recvTransport)==null?void 0:a.id,serverId:(o=this._recvTransport)==null?void 0:o.serverId,type:"recv"}});const r=this._device.createRecvTransport({...e,additionalSettings:{...(d=e.additionalSettings)!=null?d:{},rtcAudioJitterBufferMaxPackets:25,rtcAudioJitterBufferFastAccelerate:!0,rtcAudioJitterBufferMinDelayMs:20}});this._transportDisconnectedTimer.consuming=void 0,l.info("recvTransport::initialized_transport",{transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"recv"}}),this.handleTransport(r,!0),l.info("recvTransport::connecting_transport",{transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"recv"}});try{await br(async(u,h)=>{this.socket.isConnected||h(new Error("socket is not connected")),r.connectionState==="closed"&&h(new Error("transport is closed")),u>0&&l.debug(`retrying transport connect, count: ${u}`,{transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"recv"}});try{await r.connect()}catch(p){throw l.error(`fail to connect recv transport: ${r.id}`,{error:p,transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"recv"}}),p.message==="ice connection failed"&&h(p),p}},{delayTime:100,strategy:"exponential",maxRetryCount:J.hasFeature(X.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3}),l.info("recvTransport::connected_transport",{transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"recv"}}),this._transportReconnectFailureCount=Math.max(0,this._transportReconnectFailureCount-1),this._consumerCreationFailureCount=0,this._consumerNotBoundFailureCount=0,this.producerIdToConsumerIdMap.clear(),this._recvTransport=r,U.onSafeInitialization(()=>{U.configureRecvTransport(r)})}catch(u){throw l.error(`failed to connect recv transport after retry:${r.id}`,{error:u,transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"recv"}}),r.close(),r.removeAllListeners(),this._transportReconnectFailureCount+=1,this.handleFailure(),u}}handleTransport(e,r){if(e.on("connect",async({offer:n},i,a)=>{try{const o={consuming:r,description:{sdp:n.sdp,type:n.type,target:r?qt.SUBSCRIBER:qt.PUBLISHER}},{transportId:d,answer:u}=await this._socketHandler.connectTransport(o);e.setServerId(d),i({answer:u})}catch(o){l.error(`${r?"consumer":"producer"} transport connection error:`,{error:o,transport:{id:e==null?void 0:e.id,serverId:e==null?void 0:e.serverId,type:r?"recv":"send"}}),a(o)}}),e.on("connectionstatechange",async n=>{this.updateTransportState({state:n,direction:r?"consuming":"producing"}),l.info(`${r?"consumer":"producer"} transport connectionState:`,{transport:{id:e==null?void 0:e.id,serverId:e==null?void 0:e.serverId,type:r?"recv":"send",status:n}});const i=()=>{this._transportDisconnectedTimer[r?"consuming":"producing"]!==void 0&&(clearTimeout(this._transportDisconnectedTimer[r?"consuming":"producing"]),this._transportDisconnectedTimer[r?"consuming":"producing"]=void 0)};switch(n){case"connected":i(),this.lastConnectionTime=performance.now();break;case"disconnected":this._transportDisconnectedTimer[r?"consuming":"producing"]=setTimeout(()=>{this.triggerTransportReconnection(e,r)},ZD);break;case"failed":if(e.closed)return;i(),this.triggerTransportReconnection(e,r);break}}),e.on("icecandidate",async n=>{l.debug("sending icecandidate:",{iceCandidate:n})}),e.on("datachannel:events",async(n,i)=>{var a,o;l.debug("got data channel message on event:",{rtcChannel:{label:n,message:i}});try{switch(i.type){case"negotiation":{e.awaitQueue.push(async()=>this.negotiateOverDC(i,Zc(i),n,e));break}case"handshake":{const d={type:"handshake",payload:{message:"pong"}};e.sendResponseOverDC(n,Zc(i),d);break}case"consumer_toggle":{this.handleConsumerToggle(i.payload);break}case"hub-disconnect":{l.debug(`media hub disconnected, full_reconnect: ${(a=i.payload)==null?void 0:a.full_reconnect}`),((o=i.payload)==null?void 0:o.full_reconnect)===!0&&this.emit("rejoin");break}case"error":{this.handleErrorOverDC(i.payload,e.id);break}default:l.warn(`unknown event received from hive node, event: ${i.type}`);break}}catch(d){l.error(`Unable to handle the incoming datachannel message on channel ${n}`)}}),e.on("dc_error",()=>{e.direction==="recv"&&(l.warn("events datachannel did not open in 5s"),this.handleFailure())}),e.on("negotiate",async({description:n},i,a)=>{try{const o={sdp:n==null?void 0:n.sdp,type:n==null?void 0:n.type},d=await this.negotiate(e,o);i({answer:d})}catch(o){l.error("negotiate error:",{transport:{id:e.id,serverId:e.serverId,type:e.direction},error:o}),a(o)}}),!r){e.on("produce",async({offer:n,kind:i,paused:a,appData:o},d,u)=>{var v;const p=bu(n.sdp).media.filter(T=>i==="video"?T.type==="video":T.type==="audio").at(-1).msid,f={description:{sdp:n.sdp,type:n.type,target:qt.PUBLISHER},paused:a,kind:i,msid:p,appData:JSON.stringify(o),screenShare:(v=o.screenShare)!=null?v:!1};try{const{answer:T,producerId:P}=await this._socketHandler.produce(f);d({answer:T,producerId:P})}catch(T){l.error("create producer error:",T),u(T)}});return}e.on("consume_peer",async({producingPeerId:n,producerId:i},a,o)=>{l.info("consumePeer:",n);const d={producingPeerId:n,producerId:i};try{const u=await this._socketHandler.consume(d);l.debug(`consumePeer response for ${n}:`,{consumerStateMap:u});const h=new Map;Object.entries(u).forEach(([p,f])=>{var T,P,k;let v={};try{v=JSON.parse(f.producerState.appData)}catch(I){}h.set(p,{consumerId:f.consumerId,trackId:(T=f.producerTrack)==null?void 0:T.trackId,streamId:f.producerTrack.streamId,kind:f.producerState.kind===Nt.VIDEO?"video":"audio",appData:v,screenShare:(P=f.producerState)==null?void 0:P.screenShare,paused:(k=f.producerState)==null?void 0:k.pause,producingPeerId:n})}),a({consumersMap:h})}catch(u){l.error("consumePeer error:",{error:u}),o(u)}}),e.on("consume",async({producerId:n,producingPeerId:i},a,o)=>{var u,h,p,f,v,T,P,k,I;const d={producingPeerId:i,producerId:n};try{const V=(await this._socketHandler.consume(d))[n];let O={};try{O=JSON.parse((u=V.producerState)==null?void 0:u.appData)}catch(W){}l.info("consumer create response:",{consumer:{remotelyPaused:(h=V.producerState)==null?void 0:h.pause,producerId:(p=V.producerState)==null?void 0:p.producerId,kind:(v=(f=V.producerState)==null?void 0:f.kind)==null?void 0:v.toString(),appData:{...O,screenShare:(T=V.producerState)==null?void 0:T.screenShare},id:V.consumerId},consumerState:V}),a({consumerId:V.consumerId,screenShare:(P=V.producerState)==null?void 0:P.screenShare,trackId:(k=V.producerTrack)==null?void 0:k.trackId,streamId:V.producerTrack.streamId,kind:V.producerState.kind===Nt.VIDEO?"video":"audio",paused:(I=V.producerState)==null?void 0:I.pause,appData:O})}catch(x){l.error("error during consuming on server:",x),o(x)}})}async createProducer(e,r,n){var a;if(this._sendTransport===void 0||this._sendTransport.closed)return null;l.info("createProducer::initializing_producer",{producer:{id:"TO_BE_CREATED",kind:e,status:"initializing",appData:r==null?void 0:r.appData}});const i=this._producerStatus.get(e);if((i==null?void 0:i.trackId)===r.track.id&&(i==null?void 0:i.status)===Jr.INITIALIZING)return l.info("createProducer::producer getting initializing",{producer:{id:"GETTING_CREATED",status:"initializing",kind:e,appData:r==null?void 0:r.appData}}),null;this._producerStatus.set(e,{trackId:r.track.id,status:Jr.INITIALIZING});try{const o=await this._sendTransport.produce(r);return(a=r.appData)!=null&&a.e2ee&&w.emit(C.E2EE_ACTIVE_PRODUCER,o),l.info("createProducer::initialized_producer",{producer:{id:o==null?void 0:o.id,kind:e,status:"producing",appData:r==null?void 0:r.appData}}),o.on("close",async({offer:d,reason:u},h)=>{l.info("producer::closing",{debuggingHint:u,producer:{id:o==null?void 0:o.id,kind:e,status:"closing",appData:r==null?void 0:r.appData}});const p={producerId:o.id,description:{sdp:d.sdp,type:d.type,target:qt.PUBLISHER}};try{const f=await this._socketHandler.closeProducer(p),v={sdp:f==null?void 0:f.sdp,type:f==null?void 0:f.type};l.info("producer::closed",{producer:{id:o==null?void 0:o.id,kind:e,status:"closed",appData:r==null?void 0:r.appData}}),h({answer:v})}catch(f){l.error("producer close error",f)}this._producerStatus.delete(e),this._producers.delete(e),n(),this.reconfigureWebcamLayers()}),o.on("trackended",()=>{l.info("producer::trackended",{producer:{id:o==null?void 0:o.id,kind:e,status:"UNKNOWN",appData:o==null?void 0:o.appData}}),[Y.MIC,Y.WEBCAM].includes(e)||n()}),this._producers.set(e,o),this._producerStatus.set(e,{trackId:r.track.id,status:Jr.INITIALIZED}),this.reconfigureWebcamLayers(),o.track}catch(o){throw this._producerStatus.set(e,{status:Jr.NOT_INITIALIZED,trackId:r.track.id}),l.error("createProducer::transport_initialization_failed",{producer:{id:"FAILED_TO_CREATE",kind:e,status:"failed",appData:r==null?void 0:r.appData,error:o}}),o}}async reconfigureWebcamLayers(){if(!J.hasFeature(X.DISABLE_WEBCAM_LAYERS_ON_SCREENSHARE))return;const e=this.producers.get(Y.WEBCAM);e&&await this._switchProducerSpatialLayer(e,this.producers.get(Y.SCREENSHARE_VIDEO)?0:3)}async _switchProducerSpatialLayer(e,r){try{l.debug("switching layer of webcam producer to:",{media:{video:{layer:r}},producer:{id:e.id,kind:e.kind,appData:e.appData}}),await e.setMaxSpatialLayer(r)}catch(n){l.error("failed to switch spatial layer",{error:n})}}_initConsumer(e){e&&(e.observer.on("close",async r=>{l.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),this._consumers.delete(e.id),w.emit(C.CONSUMER_CLOSED,{id:e.id})}),this._consumers.set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),w.emit(C.NEW_CONSUMER,{id:e.id,appData:e.appData,peerId:e.peerId}))}async createConsumers(e){if(this._recvTransport===void 0||this._recvTransport.closed||!this._recvTransport.connected)return;if(e.every(n=>this.getProducer(n.producerId))){l.warn("why are you creating a consumer for local producer?");return}await br(async n=>{n>0&&l.debug(`retrying consume call, retryCount: ${n}`),(await this._recvTransport.consume(e).catch(a=>{throw l.error("failed to consume:",{error:a}),a})).forEach(a=>{a.status==="rejected"?(l.error("consumer creation task is failing",a.reason),this._consumerCreationFailureCount+=1,setTimeout(this.handleFailure.bind(this),0)):this._initConsumer(a.value)})}).catch(n=>{l.error("create consumer failed after retries",{error:n}),this._consumerCreationFailureCount+=1,this.handleFailure()})}async pauseProducer(e){const r=this._producers.get(e);if(!r){l.warn(`producer type: ${e} not found`);return}r.pause(),r.appData.e2ee&&w.emit(C.E2EE_INACTIVE_PRODUCER,r),l.info(`Paused the producer of type: ${r.kind}`,{producer:{id:r.id,kind:r.kind,appData:r.appData}})}async resumeProducer(e){const r=this._producers.get(e);if(!r){l.warn(`producer type: ${e} not found`);return}r.resume(),l.info(`Resumed the producer of type: ${r.kind}`,{producer:{id:r.id,kind:r.kind,appData:r.appData}})}async replaceTrack(e,r){const n=this._producers.get(e);if(!n){l.warn(`producer type: ${e} not found`);return}await n.replaceTrack({track:r}),l.info(`Replaced track for the producer of type: ${n.kind}`,{producer:{id:n.id,kind:n.kind,appData:n.appData,trackId:r.id}})}async removeProducer(e,r){const n=this._producers.get(e);if(!n){l.warn(`producer type: ${e} not found`);return}r&&n.track.stop(),await this.sendTransport.awaitQueue.push(n.close.bind(n),"producer").then(()=>{c(this,Ar).getValue("modules").e2ee.enabled&&w.emit(C.E2EE_INACTIVE_PRODUCER,n)}).catch(i=>{l.error("failed to close producer on server",i)})}async pauseConsumer(e){const r=this._consumers.get(e);if(!r){l.warn(`consumer with id: ${e} not found`);return}this.toggleConsumerOverDC(e,!0),l.info(`Paused the consumer of type: ${r.kind}`,{consumer:{id:r.id,kind:r.kind,appData:r.appData}})}async pauseConsumerOverSocket(e){try{const r={consumerId:e.id,pause:!0};await this.socket.sendMessagePromise(se.toggleConsumer,Pc.toBinary(r)),e.pause(),w.emit(C.CONSUMER_PAUSED,{id:e.id}),l.info(`Paused the consumer of type: ${e.kind} over socket`,{consumer:{id:e.id,kind:e.kind,appData:e.appData}})}catch(r){l.error("error on pausing consumer",{error:r,consumer:{id:e.id,kind:e.kind,appData:e.appData}})}}async toggleConsumerOverDC(e,r){const n={type:"consumer_toggle",payload:{consumerId:e,mute:r}},i=this._recvTransport.getDatachannel("events");if(!i){l.warn("recvTransport:: events datachannel not found");return}await i.request(n),l.info(`HiveSFUHandler::consumer toggled, consumerId: ${e}, muted: ${r}`)}async resumeConsumer(e){const r=this._consumers.get(e);if(!r){l.warn(`consumer with id: ${e} not found`);return}if(!r.paused){l.warn(`consumer with id:${e} is not paused so not resuming`);return}try{const n={consumerId:e,pause:!1};await this.socket.sendMessagePromise(se.toggleConsumer,Pc.toBinary(n)),r.resume(),w.emit(C.CONSUMER_RESUMED,{id:r.id}),l.info(`Resumed the consumer of type: ${r.kind}`,{consumer:{id:r.id,kind:r.kind,appData:r.appData}})}catch(n){l.error("error on resuming consumer",n)}}async closeConsumer(e,r){return this.closeConsumers([e],r)}async closeConsumers(e,r=!1){l.info(`Closing consumers: ${JSON.stringify(e)} with force: ${r}`);let n=!0;const i=e.filter(d=>this._consumers.get(d)?!0:(l.warn(`consumer with id: ${d} not found`),!1));if(!i.length)return;const a={consumerIds:i},o=async()=>{var d;return(d=this._recvTransport)==null?void 0:d.awaitQueue.push(async()=>{await this._socketHandler.closeConsumer(a)},"close_consumer").catch(u=>{l.warn("error on closing consumer:",{error:u}),n=r})};r?o():await o(),n&&i.forEach(d=>{const u=this.consumers.get(d);u&&(this.producerIdToConsumerIdMap.delete(u.producerId),u.close(r?"force closed":void 0))})}async cleanupConsumers(e){l.debug("cleaning up all consumers");const r=[];this._consumers.forEach(n=>{e?n.peerId===e&&r.push(n.id):r.push(n.id)}),this.closeConsumers(r,!0)}async stopAllProducers(){l.info("stopping all available producers"),this._producers.forEach((e,r)=>{l.debug(`closing producer type: ${r}`,{producer:{id:e==null?void 0:e.id,kind:e.kind,appData:e.appData}}),e.close()})}getProducer(e){return Array.from(this.producers.values()).filter(r=>r.id===e).at(0)}hasProducer(e){return this.getProducer(e)!==void 0}async negotiate(e,r){l.debug(`setting remote offer : ${JSON.stringify(r)} on ${e.direction} transport`,{transport:{id:e.id,serverId:e.serverId,type:e.direction}});const n=await e.setRemoteOffer(r),i={transportId:e.serverId,description:{sdp:n.sdp,type:n.type,target:qt.SUBSCRIBER}};return l.debug(`sending renegotiate request: ${JSON.stringify(i)} on ${e.direction} transport`,{transport:{id:e.id,serverId:e.serverId,type:e.direction}}),await this.socket.sendMessagePromise(se.renegotiateSessionDescription,ef.toBinary(i)),l.info("renegotiation done",{transport:{id:e.id,serverId:e.serverId,type:e.direction}}),n}async negotiateOverDC(e,r,n,i){const{sdp:a}=e.payload,o={sdp:a,type:"offer"};try{l.debug(`got offer over dc: ${a} for transport: ${i.id}`);const d=await i.setRemoteOffer(o),u={type:"answer",payload:{type:d.type,sdp:d.sdp}};l.debug(`datachannel answer: ${JSON.stringify(u)}`),i.sendResponseOverDC(n,r,u)}catch(d){l.error("datachannel:events::Error:",d),d.code!=="DC_NOT_FOUND"&&i.sendErrorOverDC(n,r,d)}}handleConsumerToggle(e){const{mute:r,trackId:n}=e;l.info(`consumer toggled for trackId: ${n} muted: ${r}`);const i=this.consumers.get(n);if(!i){l.warn(`consumer with trackId: ${n} not found`);return}i.paused!==r&&(l.debug("consumer state is not same",{consumer:{id:i.id,remotelyPaused:i.paused}}),r?(i.pause(),w.emit(C.CONSUMER_PAUSED,{id:i.id})):(i.resume(),w.emit(C.CONSUMER_RESUMED,{id:i.id})))}async handleErrorOverDC(e,r){l.error(`got error over dc: ${JSON.stringify(e)} for transport: ${r}`);const{type:n,error:i,id:a}=e;if(n==="consumer"){if(i==="bind-fail"){if(J.hasFeature(X.CONSUMER_BIND_NO_RETRY))return;if(this._consumerNotBoundFailureCount>=2){this.handleFailure();return}this._consumerNotBoundFailureCount+=1;const o=this.consumers.get(a);if(!o)return;try{await this.closeConsumer(o.id),await this.createConsumers([{kind:o.kind,pause:o.paused,producerId:o.producerId,producingTransportId:o.producingTransportId,screenShare:o.appData.screenShare,producingPeerId:o.peerId}])}catch(d){l.error("failed to recreate consumer on downtrack bound failure,",{consumer:{id:o.id,producerId:o.producerId,kind:o.kind,appData:o.appData}})}}}else if(n==="producer")if(i==="ready-fail"){if(this._producerNotReadyFailureCount>=2){this.handleFailure();return}this._producerNotReadyFailureCount+=1;const[o]=Array.from(this.producers.entries()).find(d=>d[1].id===a);if(!o)return;await this.removeProducer(o).catch(d=>{l.error("failed to remove ready-fail producer:",{error:d,producer:{id:a,kind:o,appData:null}})})}else i==="general-failure"&&(this.updateTransportState({state:Rt.RECONNECTING,direction:"producing"}),this.emit("reconnect_transport",this._sendTransport))}async handleFailure(){if(this._transportReconnectFailureCount>0||this._totalTransportReconnectionCount>3){l.warn("transport failure detected"),J.hasFeature(X.ENABLE_HIVE_EXPERIMENTAL_FAIL_RECOVERY)&&(l.debug("rejoining room"),this.emit("rejoin"));return}(this._consumerCreationFailureCount>0||this._consumerNotBoundFailureCount>=2)&&(l.warn("consumer creation failure detected or consumer not bound failure increased"),J.hasFeature(X.ENABLE_HIVE_EXPERIMENTAL_FAIL_RECOVERY)&&(l.debug("reconnecting recv transport"),this._totalTransportReconnectionCount+=1,this.updateTransportState({state:Rt.RECONNECTING,direction:"consuming"}),this.emit("reconnect_transport",this._recvTransport))),this._producerNotReadyFailureCount>=2&&(l.warn("producer receiver not getting added needs to reconnect send transport"),this._totalTransportReconnectionCount+=1,this.updateTransportState({state:Rt.RECONNECTING,direction:"producing"}),this.emit("reconnect_transport",this._sendTransport))}triggerTransportReconnection(e,r){l.info("triggerTransportReconnection:: reconnecting transport",{transport:{type:e.direction,id:e.id,serverId:e.serverId}});const n=J.hasFeature(X.ENABLE_HIVE_TRANSPORT_RECONNECTION_ON_ICE_FAILED),i=J.hasFeature(X.HIVE_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED);n&&(i&&this._socket.isConnected&&(performance.now()-this.lastConnectionTime>2e4&&(this._transportConnectionFailCount=0),this._transportConnectionFailCount>2&&(l.warn("Multiple disconnections, forcing relay"),this._iceTransportPolicy="relay"),this._transportConnectionFailCount+=1),this.updateTransportState({state:Rt.RECONNECTING,direction:r?"consuming":"producing"}),this.emit("reconnect_transport",e))}async switchConsumersToLayer(e,r){const n=this._recvTransport.getDatachannel("events");if(!n){l.warn("events datachannel not found");return}const i={type:"switch_consumer_layer",payload:{consumerIds:e,layer:r}};await n.request(i),l.info(`HiveSFUHandler::consumer id: ${e} layer switched to ${r}`)}updateTransportState(e){const{state:r,direction:n}=e;r==="disconnected"&&(this.transportDisconnected[n]=!0),c(this,Vn,No).mediaState[n]={state:r,reconnected:r==="connected"?this.transportDisconnected[n]:c(this,Vn,No).mediaState[n].reconnected},r==="connected"&&(this.transportDisconnected[n]=!1),w.emit(C.TRANSPORT_STATE_UPDATE,{transport:n,...c(this,Vn,No).mediaState[n]})}}Vn=new WeakSet,No=function(){return c(this,Ar).getValue("connectionHandler")},Ar=new WeakMap;var tO=Object.defineProperty,rO=Object.getOwnPropertyDescriptor,ue=(s,t,e,r)=>{for(var n=r>1?void 0:r?rO(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&tO(t,e,n),n};const jg=(Lv=class extends Og{constructor(t,e){var d,u;super();S(this,Dr);S(this,St,void 0);S(this,me,void 0);S(this,Mr,void 0);S(this,$n,void 0);S(this,Bn,void 0);S(this,$s,void 0);S(this,ro,void 0);S(this,so,void 0);S(this,no,void 0);S(this,ns,void 0);S(this,ji,void 0);m(this,"legacyMode");m(this,"roomNodeUrl");m(this,"peerDisplayName");m(this,"e2ee");m(this,"partialJoinRoomPromise");this.context=t;const{roomName:r,authToken:n,legacyMode:i,socketClient:a,meetingTitle:o}=e;this.roomJoined=!1,this.roomName=r,this.authToken=n,this.legacyMode=i,this.meetingTitle=o,y(this,St,a),y(this,Mr,!1),y(this,me,new eO(t,a)),this.maxPreferredStreams=6,y(this,ns,new Set),y(this,$n,!1),y(this,Bn,0),y(this,$s,new di),this.e2ee=(u=(d=t.getValue("modules").e2ee)==null?void 0:d.enabled)!=null?u:!1,U.legacySwitch(i),this.handleSocketEvents(),this.handleSFUEvents(),this.handleCallstatsEvents(),y(this,ro,Vr(async()=>{if(!c(this,Dr,Ys).mediaJoinAttempted)return;const{roomJoined:h}=await this.joinRoom(this.peerDisplayName,this.roomUUID,{},!0,!0);h&&(w.emit(C.RESET_PRODUCER_STATE),w.emit(C.ROOM_NODE_RECONNECTED))},5e3,{leading:!0,maxWait:1e3})),y(this,so,Vr(async h=>{h.close(),h.removeAllListeners(),await this.sfuHandler.setupTransports({send:!0}),l.info("send transport reconected!"),w.emit(C.RESET_PRODUCER_STATE)},1e3)),y(this,no,Vr(async h=>{h.close(),h.removeAllListeners(),await this.sfuHandler.setupTransports({recv:!0}),l.info("recv transport reconnected!"),w.emit(C.UPDATE_ACTIVE,{createAllConsumers:!0})},1e3))}get mediaState(){return c(this,Dr,Ys).mediaState}static async init(t,e){const{legacyMode:r=!0,meetingId:n,authToken:i,meetingTitle:a,socket:o}=e;return new jg(t,{legacyMode:r,authToken:i,socketClient:o,roomName:n,meetingTitle:a})}get sfuHandler(){return c(this,me)}get rejoinRoom(){return c(this,ro)}get roomJoined(){return c(this,Dr,Ys).roomJoined}set roomJoined(t){c(this,Dr,Ys).roomJoined=t}reset(t=!0){var e,r,n,i;(r=(e=c(this,me))==null?void 0:e.cleanupConsumers)==null||r.call(e),(i=(n=c(this,me))==null?void 0:n.stopAllProducers)==null||i.call(n),c(this,ns).clear(),t&&(c(this,$s).stop(),this.sfuHandler.stopAllTransports(),this.sfuHandler.reset(),y(this,$s,new di))}async reconnectTransport(t){l.info(`HiveNodeClient::Room joining state: ${c(this,Mr)}`),!(!t||c(this,Mr))&&(t.direction==="send"?await c(this,so).call(this,t):await c(this,no).call(this,t))}async setupTransports(){await c(this,me).setupTransports({send:!0,recv:!0})}async stopAllProducers(){await c(this,me).stopAllProducers()}async joinRoom(t,e,r={},n=!1,i=!1){c(this,Dr,Ys).mediaJoinAttempted=!0,y(this,Mr,!0),this.reset(n);const a=We().ipInfo;if(a!=null&&a.loc&&!c(this,ji)){const d=a.loc.split(",");y(this,ji,{latitude:parseFloat(d[0]),longitude:parseFloat(d[1])})}let o;try{return o=await c(this,$s).push(()=>this._joinRoom(t,e,r,i,c(this,ji)),"joinRoom"),o}catch(d){o={roomJoined:!1}}return o.roomJoined||w.emit(C.ROOM_NODE_FAILED),o}async _partialJoinRoom(t,e,r=!1,n=void 0){const{ipInfo:i}=We();let a=n;if(i!=null&&i.loc&&!n){const[o,d]=i.loc.split(",").map(parseFloat);a={latitude:o,longitude:d}}await br((o,d)=>(c(this,St).isConnected||d(new Error("socket is not connected")),o>0&&l.warn(`retrying sending join room request, count: ${o}`),this.sfuHandler.hiveSocketHandler.joinRoom(e,t,r,a).catch(u=>{throw l.error("failed to send join room request, error:",{error:u}),u})),{delayTime:1e3,strategy:"exponential",maxRetryCount:J.hasFeature(X.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3}),await this.setupTransports()}async partialJoinRoom(t,e,r=!1,n=void 0){this.partialJoinRoomPromise=c(this,$s).push(()=>this._partialJoinRoom(t,e,r,n))}async _joinRoom(t,e,r={},n=!1,i=null){this.peerDisplayName=t;try{return this.partialJoinRoomPromise?await this.partialJoinRoomPromise:await this._partialJoinRoom(t,e,n,i),navigator.product!=="ReactNative"&&setTimeout(async()=>{const d={userId:this.context.getValue("userId"),peerId:this.peerId,displayName:t,roomUUID:e,roomViewType:"groupCall",roomName:this.roomName,deviceInfo:{...Se.getDeviceInfo(),userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency},sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};U.onSafeInitialization(()=>{U.roomJoined(d),r!=null&&r.audio?U.audioOn():U.audioOff(),r!=null&&r.video?U.videoOn():U.videoOff()})}),{roomJoined:await this.completeJoinRoom()}}catch(a){return l.error("error on sending join room request",{error:a}),{roomJoined:!1}}finally{this.partialJoinRoomPromise=void 0}}async completeJoinRoom(){try{this.roomJoined=!0;const{maxPreferredStreams:t,roomState:e}=await this.sfuHandler.hiveSocketHandler.notifySelfJoinComplete();return this.roomUUID=e.roomUuid,y(this,$n,!0),y(this,Mr,!1),this.maxPreferredStreams=t!=null?t:6,w.emit(C.UPDATE_ACTIVE,{createAllConsumers:!0}),!0}catch(t){return l.error("error on completing join room:",{error:t}),this.roomJoined=!1,!1}}async leaveRoom(){c(this,me).stopAllTransports(),y(this,$n,!1),c(this,Dr,Ys).mediaJoinAttempted=!1;const t={closeRoom:!1};c(this,St).sendMessagePromise(se.leaveRoom,cf.toBinary(t)).then(e=>{var n;((n=_f.fromBinary(e.payload))==null?void 0:n.closed)||l.warn("weird state on peer closed and should not happen")}).catch(e=>{l.error("error on sending leave room request",{error:e})}),U.callEnded(),g.destruct()}getConsumers(){return c(this,me).consumers}async activatePeers(t){return this.createConsumers(t)}async deactivatePeers(t,e="default"){const r=new Set;t.forEach(i=>{i.screenShare&&i.kind==="video"&&r.add(i.producingPeerId)});const n=e==="default"?t.filter(i=>!r.has(i.producingPeerId)).filter(i=>i.kind!=="audio"):t;await Promise.all(n.map(i=>{const a=this.sfuHandler.producerIdToConsumerIdMap.get(i.producerId);if(!a){l.warn(`consumer not found in deactivate producers: ${i.producerId}`);return}return this.sfuHandler.closeConsumer(a)}))}async createConsumers(t){return t.length===0?Promise.resolve():this.sfuHandler.createConsumers(t)}async pauseConsumers(t){t.forEach(e=>{this.sfuHandler.pauseConsumer(e)})}async resumeConsumers(t){t.forEach(e=>{this.sfuHandler.resumeConsumer(e)})}async closeConsumers(t){const e=t.reduce((r,n)=>{const i=this.sfuHandler.producerIdToConsumerIdMap.get(n.producerId);return i?(r.push(i),r):(l.warn(`consumer not found in deactivate producers: ${n.producerId}`),r)},[]);await this.sfuHandler.closeConsumers(e)}async shareWebcam(t){if(t===void 0)return null;if(c(this,me).producers.has(Y.WEBCAM)){const n=c(this,me).producers.get(Y.WEBCAM);if(!n.closed&&!navigator.isReactNative)return await n.replaceTrack({track:t}),await this.resumeWebcam(),t;await c(this,me).removeProducer(Y.WEBCAM)}const e={track:t,codecOptions:{name:"VP8"},appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1};if(J.hasFeature(X.ENABLE_HIVE_SIMULCAST)){let n=t.getConstraints().width;n in wg||(n=320),e.encodings=wg[n]}const r=()=>{l.info("Disabling video due to the producer closure"),this.disableWebcam()};return c(this,me).createProducer(Y.WEBCAM,e,r)}async shareScreen(t){const{video:e,audio:r}=t;if(e===void 0)return;const n={track:e,codecOptions:{name:"VP8"},appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Se.isElectron()},stopTracks:!1};let i=()=>{l.info("Disabling screenShare due to the producer closure"),this.disableScreenShare()};if(await c(this,me).createProducer(Y.SCREENSHARE_VIDEO,n,i),r){const a={track:r,codecOptions:{name:"opus"},appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Se.isElectron()},stopTracks:!1,zeroRtpOnPause:!0};i=()=>{},await c(this,me).createProducer(Y.SCREENSHARE_AUDIO,a,i)}U.screenShareStart()}async shareMic(t){try{if(t===void 0)throw new lt("track undefined");if(c(this,me).producers.has(Y.MIC)){const n=c(this,me).producers.get(Y.MIC);if(!n.closed&&!navigator.isReactNative){await n.replaceTrack({track:t}),await this.resumeMic();return}await c(this,me).removeProducer(Y.MIC,!1)}const e={track:t,encodings:[{priority:"high"}],codecOptions:{name:"opus"},appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!0},r=()=>{l.info("Disabling audio due to the producer closure"),this.disableMic()};await c(this,me).createProducer(Y.MIC,e,r)}catch(e){throw new b(e)}}pauseMic(){const t=c(this,me).producers.get(Y.MIC);if(!t){l.error("pauseMic::could_not_find_mic_producer");return}if(t.paused){l.info("pauseMic::mic_producer_already_paused");return}t.pause();const e={producerId:t.id,pause:!0};c(this,St).sendMessage(se.toggleProducer,fs.toBinary(e))}async pauseWebcam(){const t=c(this,me).producers.get(Y.WEBCAM);if(!t){l.error("pauseWebcam::could_not_find_webcam_producer");return}t.pause();const e={producerId:t.id,pause:!0};c(this,St).sendMessage(se.toggleProducer,fs.toBinary(e))}async resumeMic(){const t=c(this,me).producers.get(Y.MIC);if(!t){l.error("resumeMic::could_not_find_mic_producer");return}if(!t.pause){l.info("resumeMic::mic_producer_already_resumed");return}t.resume(),t.appData.e2ee&&w.emit(C.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,St).sendMessage(se.toggleProducer,fs.toBinary(e))}async resumeWebcam(){const t=c(this,me).producers.get(Y.WEBCAM);if(!t){l.error("resumeWebcam::could_not_find_webcam_producer");return}t.resume(),t.appData.e2ee&&w.emit(C.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,St).sendMessage(se.toggleProducer,fs.toBinary(e))}async disableWebcam(){await c(this,me).removeProducer(Y.WEBCAM)}async disableMic(){await c(this,me).removeProducer(Y.MIC)}async disableScreenShare(){l.info("screen_sharing_stopped"),U.screenShareStop(),await c(this,me).removeProducer(Y.SCREENSHARE_VIDEO),await c(this,me).removeProducer(Y.SCREENSHARE_AUDIO),c(this,ns).clear()}async muteSelf(){this.pauseMic()}async unmuteSelf(){}async resetVideoProducers(t,e){t&&(await c(this,me).removeProducer(Y.WEBCAM,!1),this.shareWebcam(t)),e&&(await c(this,me).removeProducer(Y.SCREENSHARE_VIDEO,!1),this.shareScreen({video:e}))}async changeDisplayName(t,e){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!await this.sfuHandler.hiveSocketHandler.changeDisplayName(r))throw new Error("failed to change display name!")}async kick(t){const e={participantId:t};if(!await this.sfuHandler.hiveSocketHandler.kickPeer(e))throw new Error("failed to kickout the participant!")}async kickAll(){if(!await this.sfuHandler.hiveSocketHandler.kickAll())throw new Error("failed to kickout all participant!")}async muteAll(t){if(!await this.sfuHandler.hiveSocketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await this.sfuHandler.hiveSocketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(t){if(!await this.sfuHandler.hiveSocketHandler.hostControlForPeer(t,"audio"))throw new Error("failed to mute given participant")}async disableVideo(t){if(!await this.sfuHandler.hiveSocketHandler.hostControlForPeer(t,"video"))throw new Error("failed to mute video of given participant")}async pinPeer(t){const e={participantId:t!=null?t:""};try{await c(this,St).sendMessagePromise(se.globalPinPeer,uf.toBinary(e))}catch(r){l.error("Error in pinning peer:",{error:r})}}validateScreenShare(t){return this.peerId===t.peerId&&this.sfuHandler.hasProducer(t.producerId)&&c(this,ns).add(t.consumerPeerId),c(this,ns).size}async switchConsumersToLayer(t,e){this.sfuHandler.switchConsumersToLayer(t,e)}async handleSocketEvents(){c(this,St).on(se.peerProducerCreateBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:r}=Mf.fromBinary(t);if(e===this.peerId)return;l.info(`producer created broadcast: ${e}, producer state: ${r}`),w.emit(C.NEW_PRODUCER,{peerId:e,producer:{...r,kind:r.kind===Nt.AUDIO?"audio":"video",producingPeerId:e}})}catch(e){l.error("error in peer-producer-create-broadcast",{error:e})}}),c(this,St).on(se.peerProducerToggleBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:{kind:r,pause:n,producerId:i}}=Df.fromBinary(t),a=r===Nt.AUDIO?"audio":"video";if(l.info(`producer toggle broadcast: ${e}, producerId: ${i}, kind:${a}, paused:${n}`),e===this.peerId&&n){w.emit(a==="audio"?C.MUTE_SELF:C.MUTE_SELF_VIDEO);return}w.emit(C.PRODUCER_TOGGLE,{peerId:e,producerId:i,paused:n,kind:a}),Array.from(this.getConsumers().values()).filter(d=>d.producerId===i).forEach(d=>{d.paused!==n&&(l.debug(`consumer state mismatched for ${d.id}. updating consumer pause state ${d.paused} to ${n}`),n?(d.pause(),w.emit(C.CONSUMER_PAUSED,{id:d.id})):(d.resume(),w.emit(C.CONSUMER_RESUMED,{id:d.id})))})}catch(e){l.error("error in producer toggle broadcast handler",{error:e})}}),c(this,St).on(se.peerLeaveBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e}=kc.fromBinary(t);if(e===this.peerId)return;l.info(`peer left broadcast:${e}`),c(this,ns).delete(e),this.sfuHandler.cleanupConsumers(e),w.emit(C.PEER_CLOSED,{id:e})}catch(e){l.error("error in peer left broadcast",{error:e})}}),c(this,St).on(se.peerProducerCloseBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:{producerId:r}}=Of.fromBinary(t);if(e===this.peerId)return;l.info(`producer closed broadcast:${e}`),w.emit(C.PRODUCER_CLOSED,{peerId:e,producerId:r});const n=this.sfuHandler.producerIdToConsumerIdMap.get(r);if(!n){l.warn(`no consumer found for producer:${r}`);return}l.info(`closing consumer ${n}, producer id: ${r}`),this.sfuHandler.closeConsumer(n).then(()=>{l.info(`closed consumer: ${n}`),this.sfuHandler.producerIdToConsumerIdMap.delete(r),w.emit(C.CONSUMER_CLOSED,{id:n})}).catch(i=>{l.error("error closing consumer",{error:i})})}catch(e){l.error("error on producer close broadcast",{error:e})}}),c(this,St).on(se.mediaRoomTerminationBroadcastResponse,()=>{!this.roomJoined&&!c(this,Mr)&&!c(this,$n)||(l.warn("media hub termination broadcast received, rejoining room"),w.emit(C.ROOM_NODE_DISCONNECTED),this.rejoinRoom())})}handleSFUEvents(){c(this,me).on("reconnect_transport",async t=>{try{await this.reconnectTransport(t),l.info(`transport reconnected [id:${t.id}]`)}catch(e){l.error("error on reconnection transports",{error:e})}}),c(this,me).on("rejoin",t=>{var e;if(((e=c(this,Dr,Ys).socketState)==null?void 0:e.state)!=="connected"){l.warn("Ignoring rejoin attempt because socket is not connected");return}if(c(this,Bn)>3&&!t){l.warn("cannot rejoin more already rejoined 3 times");return}if(c(this,Mr)&&!t){l.warn("room joining in progress, cannot start rejoining");return}y(this,Bn,c(this,Bn)+1),l.warn(`rejoining the room because transports are failing. [rejoinCount: ${c(this,Bn)}]`),this.roomJoined=!1,w.emit(C.ROOM_NODE_DISCONNECTED),this.rejoinRoom()})}handleCallstatsEvents(){U.onSafeInitialization(()=>{U.onConsumerScore(t=>{t.forEach((e,r)=>{const n=this.sfuHandler.consumers.get(r);n&&w.emit(C.CONSUMER_SCORE_UPDATE,{id:r,kind:n.kind,peerId:n.peerId,score:e.score,scoreStats:e})})}),U.onProducerScore(t=>{t.forEach((e,r)=>{const n=Array.from(this.sfuHandler.producers.values()).find(i=>i.id===r);n&&w.emit(C.PRODUCER_SCORE_UPDATE,{id:r,kind:n.kind,appData:n.appData,score:e.score,scoreStats:e})})})})}},St=new WeakMap,me=new WeakMap,Mr=new WeakMap,$n=new WeakMap,Bn=new WeakMap,$s=new WeakMap,ro=new WeakMap,so=new WeakMap,no=new WeakMap,ns=new WeakMap,ji=new WeakMap,Dr=new WeakSet,Ys=function(){return this.context.getValue("connectionHandler")},Lv);let ie=jg;ue([g.trace("HiveNodeClient.reset")],ie.prototype,"reset",1),ue([g.trace("HiveNodeClient.reconnect")],ie.prototype,"reconnectTransport",1),ue([g.trace("HiveNodeClient.setupTransport")],ie.prototype,"setupTransports",1),ue([g.trace("HiveNodeClient.stopAllProducers")],ie.prototype,"stopAllProducers",1),ue([g.trace("HiveNodeClient.joinRoom")],ie.prototype,"joinRoom",1),ue([g.trace("HiveNodeClient.completeJoinRoom")],ie.prototype,"completeJoinRoom",1),ue([g.trace("HiveNodeClient.leaveRoom")],ie.prototype,"leaveRoom",1),ue([g.trace("HiveNodeClient.activatePeers")],ie.prototype,"activatePeers",1),ue([g.trace("HiveNodeClient.deactivatePeers")],ie.prototype,"deactivatePeers",1),ue([g.trace("HiveNodeClient.createConsumers")],ie.prototype,"createConsumers",1),ue([g.trace("HiveNodeClient.pauseConsumers")],ie.prototype,"pauseConsumers",1),ue([g.trace("HiveNodeClient.resumeConsumers")],ie.prototype,"resumeConsumers",1),ue([g.trace("HiveNodeClient.closeConsumers")],ie.prototype,"closeConsumers",1),ue([g.trace("HiveNodeClient.shareWebcam")],ie.prototype,"shareWebcam",1),ue([g.trace("HiveNodeClient.shareScreen")],ie.prototype,"shareScreen",1),ue([g.trace("HiveNodeClient.shareMic")],ie.prototype,"shareMic",1),ue([g.trace("HiveNodeClient.pauseMic")],ie.prototype,"pauseMic",1),ue([g.trace("HiveNodeClient.pauseWebcam")],ie.prototype,"pauseWebcam",1),ue([g.trace("HiveNodeClient.resumeMic")],ie.prototype,"resumeMic",1),ue([g.trace("HiveNodeClient.resumeWebcam")],ie.prototype,"resumeWebcam",1),ue([g.trace("HiveNodeClient.disableWebcam")],ie.prototype,"disableWebcam",1),ue([g.trace("HiveClient.disableMic")],ie.prototype,"disableMic",1),ue([g.trace("HiveClient.disableScreenShare")],ie.prototype,"disableScreenShare",1),ue([g.trace("HiveNodeClient.muteSelf")],ie.prototype,"muteSelf",1),ue([g.trace("HiveNodeClient.resetVideoProducers")],ie.prototype,"resetVideoProducers",1),ue([g.trace("HiveNodeClient.changeDisplayName")],ie.prototype,"changeDisplayName",1),ue([g.trace("HiveNodeClient.kickPeer")],ie.prototype,"kick",1),ue([g.trace("HiveNodeClient.kickAllPeers")],ie.prototype,"kickAll",1),ue([g.trace("HiveNodeClient.muteAll")],ie.prototype,"muteAll",1),ue([g.trace("HiveNodeClient.muteAllVideo")],ie.prototype,"muteAllVideo",1),ue([g.trace("HiveNodeClient.disableAudio")],ie.prototype,"disableAudio",1),ue([g.trace("HiveNodeClient.disableVideo")],ie.prototype,"disableVideo",1),ue([g.trace("HiveNodeClient.pinPeer")],ie.prototype,"pinPeer",1),ue([g.trace("HiveNodeClient.validateScreenShare")],ie.prototype,"validateScreenShare",1),ue([g.trace("HiveNodeClient.init")],ie,"init",1);class sO{constructor(){m(this,"_orderedArray");m(this,"_map");this._map=new Map,this._orderedArray=[]}add(t,e){if(!this._map.has(t))return this._map.set(t,{peerId:t,priority:e}),this._orderedArray.splice(Math.max(e-1,0),0,t),this.index(t);const r=this.index(t);this.delete(t);const n=this.add(t,e);return r!==n?n:-1}delete(t){if(this._map.has(t)){const e=this.index(t);this._map.delete(t),this._orderedArray.splice(e,1)}}index(t){return this._map.has(t)?this._orderedArray.indexOf(t):-1}[Symbol.iterator](){return this._orderedArray[Symbol.iterator]()}}class Mu{constructor(){m(this,"_activeSpeakerPeers");m(this,"_compulsoryPeers");this._activeSpeakerPeers=new sO,this._compulsoryPeers=new Set}add(t,e){if(e<0)return this._compulsoryPeers.add(t),0;if(this.compulsoryPeers.includes(t)&&(e>0||e===246267631)){if(l.info("DyteSelectedPeer::removing_compulsory_peer",{selectedPeer:{peerId:t}}),this._removeFromCompulsoryPeer(t),e===246267631)return-1}else if(e===229490415)return this.delete(t),-1;return this._activeSpeakerPeers.add(t,e)}delete(t){l.info("DyteSelectedPeer::deleting_peer_from_selectedPeer",{selectedPeer:{peerId:t}}),this._removeFromCompulsoryPeer(t),this._activeSpeakerPeers.delete(t)}index(t){return this._activeSpeakerPeers.index(t)}get peers(){return Array.from(new Set(this.compulsoryPeers.concat(this.activeSpeakerPeers)))}get compulsoryPeers(){return Array.from(this._compulsoryPeers.values())}get peerPriorities(){return Array.from(this._activeSpeakerPeers).map((t,e)=>e)}get activeSpeakerPeers(){return Array.from(this._activeSpeakerPeers)}_removeFromCompulsoryPeer(t){this._compulsoryPeers.delete(t)}}var nO=Object.defineProperty,iO=Object.getOwnPropertyDescriptor,Jt=(s,t,e,r)=>{for(var n=r>1?void 0:r?iO(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&nO(t,e,n),n};const aO=["ACTIVE_GRID","PAGINATED","MANUAL"];let kt=(Fv=class extends Ht{constructor(t,e,r){super();S(this,vr);m(this,"waitlisted");m(this,"joined");m(this,"active");m(this,"videoSubscribed");m(this,"audioSubscribed");m(this,"pinned");m(this,"all");S(this,Bs,void 0);S(this,Hs,void 0);S(this,Kt,void 0);m(this,"viewMode");m(this,"currentPage");m(this,"lastActiveSpeaker");m(this,"selectedPeers",new Mu);y(this,Bs,t),y(this,Hs,e),y(this,Kt,r),this.waitlisted=new Sa,this.joined=new Sa,this.videoSubscribed=new Sa,this.audioSubscribed=new Sa,this.active=this.videoSubscribed,this.pinned=new Sa,this.selectedPeers=new Mu,this.all=new RD,this.viewMode="ACTIVE_GRID",this.currentPage=0,this.setupEvents()}get pip(){return c(this,Bs).getValue("pip")}get roomJoined(){var t;return((t=c(this,vr,ds))==null?void 0:t.roomJoined)===!0}setupEvents(){w.on(C.E2EE_ACTIVE_CONSUMER,({peerId:t})=>{var e;((e=c(this,Bs).getValue("modules").e2ee)==null?void 0:e.enabled)!==!0&&this.emit("media_decode_error",{reason:`Got encrypted media for participantId ${t}, but encryption wasn't enabled in init.defaults`,code:"1702"})})}get count(){return this.joined.size}get maxActiveParticipantsCount(){return c(this,vr,ds).maxPreferredStreams}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new b("0 <= Max active participants count limit <= 24");c(this,vr,ds).maxPreferredStreams=t,c(this,Hs).roomJoined&&w.emit(C.UPDATE_ACTIVE)}get pageCount(){if(this.viewMode==="PAGINATED"){const t=this.joined.toArray().filter(e=>e.stageStatus==="ON_STAGE");return Math.ceil(t.length/this.maxActiveParticipantsCount)}return 0}acceptWaitingRoomRequest(t){var r,n;if(!this.roomJoined)throw new b("Can`t accept waiting room request without joining room");const e=(n=(r=this.waitlisted.get(t))==null?void 0:r.userId)!=null?n:t;return c(this,Kt).acceptWaitingRoomRequest([e])}async acceptAllWaitingRoomRequest(t){const e=t.map(r=>{var n,i;return(i=(n=this.waitlisted.get(r))==null?void 0:n.userId)!=null?i:r});return c(this,Kt).acceptWaitingRoomRequest(e)}async rejectWaitingRoomRequest(t){var r,n;if(!this.roomJoined)throw new b("Can`t reject waiting room request without joining room");const e=(n=(r=this.waitlisted.get(t))==null?void 0:r.userId)!=null?n:t;c(this,Kt).rejectWaitingRoomRequest([e])}async setViewMode(t){if(l.info("DyteParticipants::set_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),!(r=>aO.includes(r))(t))throw l.error("DyteParticipants::setViewMode::invalid_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),new b(`Invalid view mode: ${t}. Try ACTIVE_GRID, PAGINATED or MANUAL.`);if(this.viewMode===t){l.info("DyteParticipants::setViewMode::view_mode_same_as_previous");return}if(t==="MANUAL"&&!(c(this,vr,ds)instanceof ie))throw new b("Manual Subscription is not enabled for your Organization. Please contact support.");this.viewMode=t,t==="PAGINATED"?(this.currentPage=1,w.emit(C.UPDATE_ACTIVE,{page:this.currentPage})):t==="ACTIVE_GRID"&&(this.currentPage=0,w.emit(C.UPDATE_ACTIVE)),this.emit("viewModeChanged",{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount})}async subscribe(t,e=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new b("MANUAL subscription mode was not activated.");const r=[];t.forEach(n=>{const i=this.joined.get(n);if(i){if(e.includes("audio")){i.manualProducerConfig={...i.manualProducerConfig,audio:!0},this.videoSubscribed.add(i);const a=i.producers.find(o=>o.kind==="audio"&&!o.screenShare);a&&r.push(a)}if(e.includes("video")){i.manualProducerConfig={...i.manualProducerConfig,video:!0},this.audioSubscribed.add(i);const a=i.producers.find(o=>o.kind==="video"&&!o.screenShare);a&&r.push(a)}if(e.includes("screenshareAudio")){i.manualProducerConfig={...i.manualProducerConfig,screenshareAudio:!0};const a=i.producers.find(o=>o.kind==="audio"&&o.screenShare);r.push(a)}if(e.includes("screenshareVideo")){i.manualProducerConfig={...i.manualProducerConfig,screenshareVideo:!0};const a=i.producers.find(o=>o.kind==="video"&&o.screenShare);r.push(a)}}}),await c(this,vr,ds).createConsumers(r)}async unsubscribe(t,e=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new b("MANUAL subscription mode was not activated.");const r=[];t.forEach(n=>{const i=this.joined.get(n);if(i){if(e.includes("audio")){i.manualProducerConfig={...i.manualProducerConfig,audio:!1};const a=i.producers.find(o=>o.kind==="audio"&&!o.screenShare);a&&r.push(a)}if(e.includes("video")){i.manualProducerConfig={...i.manualProducerConfig,video:!1};const a=i.producers.find(o=>o.kind==="video"&&!o.screenShare);a&&r.push(a)}if(e.includes("screenshareAudio")){i.manualProducerConfig={...i.manualProducerConfig,screenshareAudio:!1};const a=i.producers.find(o=>o.kind==="audio"&&o.screenShare);r.push(a)}if(e.includes("screenshareVideo")){i.manualProducerConfig={...i.manualProducerConfig,screenshareVideo:!1};const a=i.producers.find(o=>o.kind==="video"&&o.screenShare);r.push(a)}}}),await c(this,vr,ds).closeConsumers(r)}getPeerIdsForCurrentPage(){l.info("DyteParticipants::getPeerIdsForCurrentPage()",{pageNavigation:{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}});const{compulsoryPeers:t}=this.selectedPeers,e=t.filter(o=>this.joined.has(o)),r=Array.from(this.pinned.keys()).filter(o=>!e.includes(o)),n=Array.from(this.joined.toArray().filter(o=>o.stageStatus==="ON_STAGE").map(o=>o.id)),i=Math.max((this.currentPage-1)*(this.maxActiveParticipantsCount-e.length-r.length)),a=this.currentPage*(this.maxActiveParticipantsCount-e.length-r.length);return e.concat(r,n.slice(i,a))}async setPage(t){if(l.info("DyteParticipants::set_page",{pageNavigation:{settingPage:t,viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),this.viewMode==="PAGINATED"){if(!Number.isInteger(t))throw l.error("DyteParticipants::invalid_page_number"),new b(`Invalid page: ${t}. Page must be an integer and greater than 0 and less than or equal to .pageCount`);this.currentPage=t,w.emit(C.UPDATE_ACTIVE,{page:t}),this.emit("pageChanged",{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount})}}async disableAllAudio(t){if(l.info("DyteParticipants::disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),!this.roomJoined)throw new b("Can`t disable all audio without joining room");if(c(this,Hs).permissions.canAllowParticipantAudio)return c(this,vr,ds).muteAll(t);throw l.error("DyteParticipants::unauthorized_disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),new b("Unauthorized: User does not have permission to disable peer audio.")}async disableAllVideo(){if(l.info("DyteParticipants::disable_all_video"),!this.roomJoined)throw new b("Can`t disable all video without joining room");if(c(this,Hs).permissions.canAllowParticipantVideo)return c(this,vr,ds).muteAllVideo();throw l.error("DyteParticipants::unauthorized_disable_all_video"),new b("Unauthorized: User does not have permission to disable peer video.")}async disableAudio(t){this.joined.get(t).disableAudio()}async disableVideo(t){this.joined.get(t).disableVideo()}async kick(t){await w.emitAsync(C.KICK_PEER,{peerId:t})}async kickAll(){if(l.info("DyteParticipants::kick_all"),c(this,Bs).getValue("viewType")!=="LIVESTREAM"&&!this.roomJoined)throw new b("Can`t kick all without joining room");if(!c(this,Hs).permissions.kickParticipant)throw l.error("DyteParticipants::unauthorized_kick_all"),new b("Unauthorized: User does not have permission to kick peers.");const e=J.hasFeature(X.PROPAGATE_KICK_ALL);c(this,Kt).kickAll(e)}async broadcastMessage(t,e,r){if(l.info("DyteParticipants::broadcastMessage"),!this.roomJoined)throw new b("Can`t broadcast message without joining room");if(!(t!=null&&t.trim()))throw new b("`type` must be a non-empty string.");if(r){let n=[];"participantIds"in r?n=r.participantIds:n=this.joined.toArray().filter(i=>{var a;return(a=r.presetNames)==null?void 0:a.includes(i.presetName)}).map(i=>i.id),c(this,Kt).broadcastToPeers(t,n,e)}else c(this,Kt).broadcastMessage(t,e)}async getAllJoinedPeers(t,e,r){return(await c(this,Kt).getRoomPeers(t,e,r)).peers.map(Wr.formatSocketServiceMessage)}async updatePermissions(t,e){const r=this.joined.toArray().filter(i=>t.includes(i.id)).map(i=>i.userId),n=[...new Set(r)];if(!n.length)throw new b("Cannot update permissions, no valid userIDs found");c(this,Kt).updatePermissions(n,e)}async getParticipantsInMeetingPreJoin(){return c(this,Kt).getRoomPeersNonPaginated()}},Bs=new WeakMap,vr=new WeakSet,ds=function(){return c(this,Bs).getValue("roomNodeClient")},Hs=new WeakMap,Kt=new WeakMap,Fv);Jt([g.trace("DyteParticipants.setViewMode")],kt.prototype,"setViewMode",1),Jt([g.trace("DyteParticipants.setPage")],kt.prototype,"setPage",1),Jt([g.trace("DyteParticipants.disableAllAudio")],kt.prototype,"disableAllAudio",1),Jt([g.trace("DyteParticipants.disableAllVideo")],kt.prototype,"disableAllVideo",1),Jt([g.trace("DyteParticipants.disablePeerAudio")],kt.prototype,"disableAudio",1),Jt([g.trace("DyteParticipants.disablePeerVideo")],kt.prototype,"disableVideo",1),Jt([g.trace("DyteParticipants.kickPeer")],kt.prototype,"kick",1),Jt([g.trace("DyteParticipants.kickAll")],kt.prototype,"kickAll",1),Jt([g.trace("DyteParticipants.broadcastMessage"),Lt({maxInvocations:500,period:60})],kt.prototype,"broadcastMessage",1),Jt([g.trace("DyteParticipants.getAllJoinedPeers"),Lt({maxInvocations:10,period:60})],kt.prototype,"getAllJoinedPeers",1),Jt([g.trace("DyteParticipant.updatePermissions"),Lt({maxInvocations:1e3,period:60})],kt.prototype,"updatePermissions",1),Jt([g.trace("DyteParticipants.getParticipantsInMeetingPreJoin")],kt.prototype,"getParticipantsInMeetingPreJoin",1),kt=Jt([pt("1200")],kt);var oO=Object.defineProperty,cO=Object.getOwnPropertyDescriptor,ui=(s,t,e,r)=>{for(var n=r>1?void 0:r?cO(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&oO(t,e,n),n};const Gg=class{constructor(s,t,e){m(this,"participants");m(this,"self");m(this,"selectedPeers",new Mu);m(this,"maxSpatialLayerUpdates",new Map);m(this,"consumerPeerMap");m(this,"roomSocketHandler");m(this,"context");m(this,"videoPeerConsumerMap",new Map);m(this,"updateConsumerSpatialLayers",Vr(()=>{const s={},t=new Map(this.maxSpatialLayerUpdates);this.maxSpatialLayerUpdates.clear(),Array.from(t.entries()).forEach(([e,r])=>{s[r]===void 0&&(s[r]={layer:r,consumerIds:[]}),s[r].consumerIds.push(e)}),Object.keys(s).forEach(e=>{const r=s[e];l.log(`Switching max spatial layer to ${r.layer}`,{consumerIds:r.consumerIds}),this.roomNodeClient.switchConsumersToLayer(r.consumerIds,r.layer)})},2e3));m(this,"updateConsumers",Vr((s,t)=>{this.roomNodeClient.closeConsumers(t).then(()=>{this.roomNodeClient.createConsumers(s).catch(e=>l.error("Error activating peers",{error:e}))}).catch(e=>l.error("Error deactivating peers",{error:e}))},2e3,{trailing:!0}));this.context=s,this.roomSocketHandler=e,this.participants=new kt(s,t,this.roomSocketHandler),this.self=t,this.consumerPeerMap=new Map,t.config.viewType!=="CHAT"&&this.setupEventsGlobal()}get roomJoined(){var s;return((s=this.roomNodeClient)==null?void 0:s.roomJoined)===!0}get pip(){return this.context.getValue("pip")}waitingRoomRequestHandler(s){const t=s.requests.filter(r=>!this.participants.waitlisted.toArray().find(n=>n.userId===r.userId)),e=this.participants.waitlisted.toArray().filter(r=>!s.requests.find(n=>n.userId===r.userId));t.forEach(r=>this.participants.waitlisted.add(new Gr(this.context,{id:r.peerId,displayName:r.displayName,audioMuted:!0,videoEnabled:!1,audioTrack:void 0,videoTrack:void 0,stageStatus:"OFF_STAGE",userId:r.userId,flags:{},isHost:!1,customParticipantId:r.customParticipantId,picture:r.picture,metadata:{preset_name:r.presetName}},this.self,this.roomSocketHandler))),e.forEach(r=>this.participants.waitlisted.delete(r.id))}get maxPreferredStreams(){return this.participants.maxActiveParticipantsCount}async selectPagePeers(s){const{compulsoryPeers:t}=this.selectedPeers,e=t.filter(d=>this.participants.joined.has(d)),r=Array.from(this.participants.pinned.keys()).filter(d=>!e.includes(d)),n=Array.from(this.participants.joined.toArray().filter(d=>d.stageStatus==="ON_STAGE").map(d=>d.id)),i=Math.max((s-1)*(this.roomNodeClient.maxPreferredStreams-e.length-r.length)),a=s*(this.roomNodeClient.maxPreferredStreams-e.length-r.length);return e.concat(r,n.slice(i,a))}async selectActivePeers(){const s=new Map,t=Array.from(this.participants.joined.toArray().filter(u=>u.stageStatus==="ON_STAGE").map(u=>(s.set(u.id,!0),u.id))),e=this.selectedPeers.peers,r=this.participants.pinned.toArray().reduce((u,h)=>(h.stageStatus!=="ON_STAGE"?this.participants.pinned.delete(h.id):u.push(h.id),u),[]),n=this.self.stageStatus==="ON_STAGE"?1:0,i=this.participants.maxActiveParticipantsCount-n,a=new Set(e.concat(r).filter(u=>u!==this.self.id&&s.has(u)));let o=Array.from(a);const d=i-a.size;if(d>=0){const u=t.filter(h=>!a.has(h)&&h!==this.self.id).slice(0,d);o=Array.from(a).concat(u)}else o=o.slice(0,i);return o}async updateActive(s,t){const{page:e,createAllConsumers:r}=t!=null?t:{};let{strategies:n}=t!=null?t:{},i;switch(s){case"PAGINATED":{if(!e)return;i=await this.selectPagePeers(e),l.info("ParticipantController::updateActive::updating_current_page_peers",{peerIds:i}),n!=null||(n={video:this.updateParticipantsMap.bind(this),audio:this.updateParticipantsMap.bind(this)});break}case"ACTIVE_GRID":{i=await this.selectActivePeers(),l.info("ParticipantController::updateActive::updating_current_selected_peers",{peerIds:i}),n!=null||(n={video:this.updateParticipantsMapMinReplacement.bind(this),audio:this.updateParticipantsMap.bind(this)});break}default:throw new Error(`View mode ${s} not supported`)}let a,o;const d=this.updateGrid(i,n);r?(a=this.mapPeerIdsToProducers(i,["audio","video","screenshare"]),o=[]):(a=[...this.mapPeerIdsToProducers([...d.video.add],["video"]),...this.mapPeerIdsToProducers([...d.audio.add],["audio"])],o=[...this.mapPeerIdsToProducers([...d.video.remove],["video"]),...this.mapPeerIdsToProducers([...d.audio.remove],["audio"])]),this.updateConsumers(a,o)}computeActivateParticipants(s,t){const e=s.map((n,i)=>({peerId:n,priority:i+1})),r=t==null?void 0:t.map((n,i)=>({peerId:n,priority:-(i+1)}));e.push(...r!=null?r:[]),e.length>0&&this.updateActiveParticipantsWithPriorities(e)}fromSocketService(s){const t=Gg.formatSocketServiceMessage(s);return new Gr(this.context,{...t,isHost:!1,videoEnabled:!1,audioMuted:!0,videoTrack:void 0,audioTrack:void 0},this.self,this.roomSocketHandler)}updatePipSource(s,t){var e,r;t?(e=this.pip)==null||e.enableSource(s):(r=this.pip)==null||r.disableSource(s)}onMediaJoined(s,t){if(!this.roomJoined||s===this.self.id)return;const e=this.participants.joined.get(s);if(!e){l.warn(`Recieved media.peerJoinedBroadcast for non-existent peer ${s}`);return}t.forEach(r=>{r.kind===Nt.AUDIO&&!r.screenShare?e.setAudioEnabled(!r.pause):r.kind===Nt.VIDEO&&!r.screenShare&&(e.setVideoEnabled(!r.pause),this.updatePipSource(e.id,!r.pause)),e.producers.push({...r,producingTransportId:r.producingTransportId,kind:r.kind===Nt.AUDIO?"audio":"video",producingPeerId:s})})}updateParticipantsMapMinReplacement(s,t){const e=Array.from(s.keys()),r=new Map(s),n=[],i=[],a=new Set(t),o=[];return e.forEach((d,u)=>{(!a.has(d)||!this.participants.joined.get(d))&&o.push(u)}),t.forEach(d=>{if(s.get(d))return;if(e.length{a.has(d)||i.concat(e.splice(u,1))}),Array.from(s.keys()).forEach(d=>{s.delete(d,!a.has(d))}),e.forEach(d=>{if(!this.participants.joined.get(d)){l.warn("updateActiveParticipants::participant_not_in_joined_list",{dyteParticipant:{id:d}});return}s.add(this.participants.joined.get(d),!r.get(d)),n.push(d)}),s.emit("participantsUpdate"),[n,i]}updateParticipantsMap(s,t){const e=Array.from(s.keys()),r=[],n=[];return e.forEach(i=>{t.includes(i)||(s.delete(i,!0),n.push(i))}),t.forEach(i=>{s.get(i)||(s.add(this.participants.joined.get(i)),r.push(i))}),s.emit("participantsUpdate"),[r,n]}updatePinnedParticipants(){this.participants.pinned.forEach(s=>{s.setIsPinned(!1),this.participants.pinned.delete(s.id)})}setupEventsGlobal(){this.roomSocketHandler.on($.joinRoom,({peer:s})=>{if(!s.waitlisted){const t=J.hasFeature(X.DEBUG_SOCKET_JOIN);t&&l.info("Processing socket join",{peers:s.peerId}),this.onParticipantJoined(this.fromSocketService(s)),t&&l.info("Processed socket join",{peers:s.peerId})}}),this.roomSocketHandler.on($.leaveRoom,s=>{this.selectedPeers.delete(s.peer.peerId),this.onParticipantLeave(s.peer.peerId)}),w.on(C.SOCKET_SERVICE_ROOM_JOINED,()=>{this.self.permissions.acceptWaitingRequests&&this.roomSocketHandler.getWaitingRoomRequests()}),this.self.permissions.on("permissionsUpdate",s=>{const{acceptWaitingRequests:t}=s;t!==void 0&&(t?this.roomSocketHandler.getWaitingRoomRequests():this.participants.waitlisted.clear())}),w.on(C.SOCKET_SERVICE_DISCONNECTED,()=>{this.participants.joined.clear(),this.participants.videoSubscribed.clear(),this.participants.audioSubscribed.clear(),this.participants.pinned.clear(),this.participants.currentPage=0,this.participants.viewMode="ACTIVE_GRID",this.participants.emit("viewModeChanged",{viewMode:"ACTIVE_GRID",currentPage:this.participants.currentPage,pageCount:this.participants.pageCount})}),w.on(C.CONSUMER_PAUSED,({id:s})=>{this.processConsumerPaused(s)}),w.on(C.CONSUMER_RESUMED,({id:s})=>{this.processConsumerResumed(s)}),w.on(C.NEW_CONSUMER,({id:s})=>{this.processNewConsumer(s)}),w.on(C.CONSUMER_CLOSED,({id:s})=>{this.processConsumerClosed(s)}),w.on(C.ROOM_MESSAGE,async({payload:s,type:t,timestamp:e})=>{this.participants.emit("broadcastedMessage",{type:t,payload:s,timestamp:e})}),w.on(C.MESSAGE,async({payload:s,type:t,timestamp:e})=>{t!=="spotlight"&&this.participants.emit("broadcastedMessage",{type:t,payload:s,timestamp:e})}),w.on(C.LOW_CONSUMER_SCORE,({peerId:s,score:t,kind:e})=>{const r=this.participants.joined.get(s);r&&(r.emit("poorConnection",{score:t,kind:e}),this.participants.emit("poorConnection",{participantId:s,score:t,kind:e}))}),w.on(C.CONSUMER_SCORE_UPDATE,({score:s,kind:t,appData:e,peerId:r,scoreStats:n})=>{var o;const i=t==="video"&&((o=e==null?void 0:e.screenShare)!=null?o:!1),a=this.participants.joined.get(r);a&&(a.emit("mediaScoreUpdate",{kind:t,isScreenshare:i,score:s,participantId:r,scoreStats:n}),this.participants.emit("mediaScoreUpdate",{kind:t,isScreenshare:i,score:s,participantId:r,scoreStats:n}))}),w.onAsync(C.KICK_PEER,async({peerId:s})=>{const t=this.participants.joined.get(s);await this.roomNodeClient.kick(s),await this.roomSocketHandler.kick(s),t?t.emit("kicked"):this.participants.joined.emit("kicked",{id:s})}),w.on(C.UPDATE_ACTIVE,async({page:s,createAllConsumers:t}={})=>{await this.updateActive(s?"PAGINATED":"ACTIVE_GRID",{page:s,createAllConsumers:t})})}async onParticipantPinned(s){if(!s){this.self.isPinned&&this.self.setIsPinned(!1),this.participants.pinned.size!==0&&this.updatePinnedParticipants();return}if(s===this.self.id){this.participants.pinned.size!==0&&this.updatePinnedParticipants(),this.self.setIsPinned(!0);return}const t=this.participants.joined.get(s);this.self.isPinned&&this.self.setIsPinned(!1),this.updatePinnedParticipants(),t.setIsPinned(!0),this.participants.pinned.add(t)}async onParticipantJoined(s){var e,r,n;if(this.self.id!==s.id&&!((e=s.flags)!=null&&e.recorder)&&!((r=s.flags)!=null&&r.hidden_participant)&&!((n=s.flags)!=null&&n.hiddenParticipant)&&(this.participants.videoSubscribed.delete(s.id),this.participants.audioSubscribed.delete(s.id),this.participants.joined.add(s),this.participants.waitlisted.delete(s.id),s.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&w.emit(C.UPDATE_STAGE_REQUESTS,{request:{displayName:s.name,userId:s.userId,peerId:s.id},add:!0})),w.emit(C.PEER_JOINED_INTERNAL,s),this.self.config.viewType===Xe.Webinar&&s.stageStatus!=="ON_STAGE"||this.roomNodeClient===void 0||this.participants.videoSubscribed.size>=this.roomNodeClient.maxPreferredStreams)return;const t=this.participants.currentPage;this.updateActive(t?"PAGINATED":"ACTIVE_GRID",{page:t})}async onParticipantLeave(s){const t=this.participants.joined.get(s);this.participants.joined.delete(s,!0,!0),this.participants.pinned.delete(s,!0,!0),this.participants.waitlisted.delete(s,!0,!0),t&&t.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&w.emit(C.UPDATE_STAGE_REQUESTS,{request:{displayName:t.name,userId:t.userId,peerId:t.id},add:!1});const{currentPage:e}=this.participants,r=this.maxPreferredStreams*(e-1),n=this.participants.videoSubscribed.get(s);r===0?this.participants.setViewMode("ACTIVE_GRID"):this.participants.joined.size<=r?e===2?this.participants.setViewMode("ACTIVE_GRID"):this.participants.setPage(e-1):n&&this.updateActive(e?"PAGINATED":"ACTIVE_GRID",{page:e})}processMedia(s){var h;const t=this.roomNodeClient.getConsumers(),{peerId:e,kind:r,appData:n,remotelyPaused:i,track:a,producerId:o,rtpReceiver:d}=(h=t.get(s))!=null?h:{};if(!e)return l.warn("processMedia::Peer ID is undefined",{consumer:{id:s,kind:r,peerId:e,appData:{supportsRemoteControl:n==null?void 0:n.supportsRemoteControl,screenShare:n==null?void 0:n.screenShare},remotelyPaused:i,producerId:o}}),{};const u=n;return r==="video"&&u.screenShare!==!0&&this.videoPeerConsumerMap.set(e,s),l.info("ParticipantController::processMedia",{consumer:{id:s,peerId:e,kind:r,appData:u,remotelyPaused:i,producerId:o}}),this.consumerPeerMap.set(s,{type:r,peerId:e,appData:u,remotelyPaused:i,producerId:o}),{peerId:e,kind:r,appData:u,remotelyPaused:i,track:a,producerId:o,rtpReceiver:d}}processConsumerClosed(s){const{peerId:t,type:e,appData:r,remotelyPaused:n,producerId:i}=this.consumerPeerMap.get(s)||{},a=this.participants.joined.get(t);if(l.info("ParticipantController::processConsumerClosed",{consumer:{id:s,peerId:t,appData:r,kind:e,remotelyPaused:n,producerId:i}}),this.consumerPeerMap.delete(s),e==="video"&&r.screenShare!==!0&&this.videoPeerConsumerMap.delete(t),!a)return;const o=[];r&&r.screenShare?(a.setScreenShareEnabled(!1),U.consumerSharedMediaState(s,{screen:!1}),a.screenShareTracks.video&&o.push(a.screenShareTracks.video.id),a.screenShareTracks.audio&&o.push(a.screenShareTracks.audio.id),a.screenShareTracks={audio:void 0,video:void 0}):e==="audio"?(a.setAudioEnabled(!1),a.audioTrack&&o.push(a.audioTrack.id),U.consumerSharedMediaState(s,{audio:!1}),a.audioTrack=void 0):e==="video"&&(a.setVideoEnabled(!1),this.updatePipSource(a.id,!1),a.videoTrack&&o.push(a.videoTrack.id),U.consumerSharedMediaState(s,{video:!1}),a.videoTrack=void 0),r.e2ee&&o.forEach(d=>{w.emit(C.E2EE_INACTIVE_CONSUMER,{peerId:t,trackId:d})})}processConsumerResumed(s){const{peerId:t,kind:e,appData:r,track:n,remotelyPaused:i,producerId:a,rtpReceiver:o}=this.processMedia(s);if(!t)return;l.info("ParticipantController::processConsumerResumed",{consumer:{id:s,peerId:t,kind:e,appData:r,remotelyPaused:i,producerId:a}});const d=this.participants.joined.get(t);if(d){if(r.e2ee&&w.emit(C.E2EE_ACTIVE_CONSUMER,{peerId:t,rtpReceiver:o,track:n}),r.screenShare){e==="video"?d.screenShareTracks.video=n:e==="audio"&&(d.screenShareTracks.audio=n),d.setScreenShareEnabled(!0),U.consumerSharedMediaState(s,{screen:!0});return}e==="video"?(d.videoTrack=n,d.setVideoEnabled(!0),this.updatePipSource(d.id,!0),U.consumerSharedMediaState(s,{video:!0})):e==="audio"&&(d.audioTrack=n,d.setAudioEnabled(d.audioEnabled),U.consumerSharedMediaState(s,{audio:d.audioEnabled}))}}processConsumerPaused(s){l.info(`ParticipantController::processConsumerPaused called for consumerId: ${s}`);const{peerId:t,kind:e,track:r,appData:n,remotelyPaused:i,producerId:a}=this.processMedia(s);if(!t)return;l.info("ParticipantController::processConsumerPaused",{consumer:{id:s,peerId:t,kind:e,appData:n,remotelyPaused:i,producerId:a}});const o=this.participants.joined.get(t);o&&(r&&n.e2ee&&w.emit(C.E2EE_INACTIVE_CONSUMER,{peerId:t,trackId:r.id}),e==="video"?(o.videoTrack=r,o.setVideoEnabled(!1),this.updatePipSource(o.id,!1),U.consumerSharedMediaState(s,{video:!1})):e==="audio"&&(o.audioTrack=r,o.setAudioEnabled(o.audioEnabled),U.consumerSharedMediaState(s,{audio:o.audioEnabled})))}processNewConsumer(s){const{peerId:t,kind:e,remotelyPaused:r,track:n,appData:i,producerId:a,rtpReceiver:o}=this.processMedia(s);if(!t)return;l.info("ParticipantController::processNewConsumer",{consumer:{id:s,peerId:t,kind:e,remotelyPaused:r,appData:i,producerId:a}});const d=this.participants.joined.get(t);if(d){if(i.screenShare){e==="video"?d.screenShareTracks.video=n:e==="audio"&&(d.screenShareTracks.audio=n),(!r||this.self.permissions.isRecorder||J.hasFeature(X.SCREEENSHARE_ERR_HACK))&&d.setScreenShareEnabled(!0),i.supportsRemoteControl&&(d.supportsRemoteControl=!0),this.participants.broadcastMessage("screenshareConsumerCreated",{producerId:a,peerId:t,screenShare:!0,consumerId:s,consumerPeerId:this.self.id}),l.info("ParticipantController::newScreenshareConsumer::screenshareConsumerCreated",{consumer:{id:s,peerId:t,kind:e,remotelyPaused:r,appData:i,producerId:a}});return}e==="video"?(d.videoTrack=n,r||(d.setVideoEnabled(!0),this.updatePipSource(d.id,!0)),U.consumerSharedMediaState(s,{video:!r})):e==="audio"&&(d.audioTrack=n,r||d.setAudioEnabled(!0),U.consumerSharedMediaState(s,{audio:!r})),!r&&i.e2ee&&w.emit(C.E2EE_ACTIVE_CONSUMER,{peerId:t,rtpReceiver:o,track:n})}}static formatSocketServiceMessage(s){var e,r,n,i,a,o;if(!s)return;const t=lu(s.stageType);return{id:s.peerId,userId:s.userId,name:s.displayName,displayName:s.displayName,stageType:t,customParticipantId:s.customParticipantId,presetId:s.presetId,picture:s.displayPictureUrl,waitlisted:s.waitlisted,stageStatus:t,metadata:{preset_name:(e=s.flags)==null?void 0:e.presetName},recorderType:(r=s.flags)==null?void 0:r.recorderType,flags:{hiddenParticipant:(n=s.flags)==null?void 0:n.hiddenParticipant,hidden_participant:(i=s.flags)==null?void 0:i.hiddenParticipant,recorder:((a=s.flags)==null?void 0:a.recorderType)!==void 0&&((o=s.flags)==null?void 0:o.recorderType)!=="NONE"}}}mapPeerIdsToProducers(s,t){const e=(n,i)=>n.filter(({kind:a,screenShare:o})=>i.includes(a)||o&&i.includes("screenshare"));return s.flatMap(n=>{const i=this.participants.joined.get(n);if(i)return e(i.producers,t)}).filter(n=>!!n)}updateGrid(s,t){const[e,r]=t.video(this.participants.videoSubscribed,s),[n,i]=t.audio(this.participants.audioSubscribed,s);return{video:{add:e,remove:r},audio:{add:n,remove:i}}}async onSelectedPeers(s,t){if(this.participants.viewMode!=="ACTIVE_GRID")return;const e=s.map((n,i)=>({peerId:n,priority:i+1})),r=t==null?void 0:t.map((n,i)=>({peerId:n,priority:-(i+1)}));e.push(...r!=null?r:[]),e.length>0&&this.updateActiveParticipantsWithPriorities(e)}updateActiveParticipantsWithPriorities(s,t=!1){if(!this.roomJoined){l.warn("Skipped::ParticipantController::updateActiveParticipantsWithPriorities",{roomJoined:this.roomJoined});return}let e=null;s.forEach(r=>{this.selectedPeers.add(r.peerId,r.priority),(e===null||r.priority{for(var n=r>1?void 0:r?lO(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&dO(t,e,n),n};class Jg extends Wr{get roomNodeClient(){return this.context.getValue("roomNodeClient")}constructor(t,e,r){super(t,e,r),this.setupEvents()}setupEvents(){this.roomSocketHandler.on($.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),w.on(C.SOCKET_PEERS,async t=>{t==null||t.forEach(e=>this.onParticipantJoined(this.fromSocketService(e)))}),this.roomSocketHandler.on(ne.peerJoinedBroadcast,({participant:t})=>this.onMediaJoined(t.peerId,t.producerStates)),this.roomSocketHandler.on(ne.selfJoinComplete,({participants:t,selectedPeers:e,roomState:r})=>{t.forEach(a=>this.onMediaJoined(a.peerId,a.producerStates));const{audioPeers:n,compulsoryPeers:i}=e!=null?e:{};r.pinnedPeerIds.length!==0&&this.onParticipantPinned(r.pinnedPeerIds[0]),this.computeActivateParticipants(n!=null?n:[],i),w.emit(C.UPDATE_ACTIVE,{createAllConsumers:!0})}),w.on(C.MAX_SPATIAL_LAYER_CHANGE,({peerId:t,maxSpatialLayer:e})=>{const r=this.videoPeerConsumerMap.get(t);r&&(this.maxSpatialLayerUpdates.set(r,e),this.updateConsumerSpatialLayers())}),w.on(C.NEW_PRODUCER,({peerId:t,producer:e})=>{const r=this.participants.joined.get(t);if(!r){l.warn("ParticipantController::NEW_PRODUCER::participant not found",{producer:{id:e==null?void 0:e.producerId,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}},dyteParticipant:{id:t}});return}r.producers.push(e),l.info("ParticipantController::NEW_PRODUCER::producer_added_to_participant",{producer:{id:e==null?void 0:e.producerId,peerId:t,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}}}),(e==null?void 0:e.kind)==="audio"||e!=null&&e.screenShare||this.currentActiveGridParticipants.has(t)?this.roomNodeClient.createConsumers([e]).catch(n=>{l.error("ParticipantController::createConsumer failed",{error:n})}):l.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:e==null?void 0:e.producerId,peerId:t,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}}})}),w.on(C.PRODUCER_CLOSED,({peerId:t,producerId:e})=>{const r=this.participants.joined.get(t);if(!r){l.warn("ParticipantController::NEW_PRODUCER::participant not found",{dyteParticipant:{id:t}});return}r.producers=r.producers.filter(n=>n.producerId!==e)}),w.on(C.PRODUCER_TOGGLE,({peerId:t,producerId:e,paused:r,kind:n})=>{const i=this.participants.joined.get(t);if(i){n==="audio"&&i.setAudioEnabled(!r);const a=i.producers.find(o=>o.producerId===e);a&&(a.pause=r)}}),this.roomSocketHandler.on(ne.globalPeerPinBroadcast,({participantId:t})=>{if(!this.roomJoined)return;const e=t;this.onParticipantPinned(e);const r=this.participants.joined.get(e);this.roomNodeClient.activatePeers(r.producers).catch(n=>{l.error("unable to create consumers",{error:n})})}),this.roomSocketHandler.on(ne.selectedPeer,({audioPeers:t,compulsoryPeers:e})=>{this.roomJoined&&this.onSelectedPeers(e.concat(t))}),this.roomSocketHandler.on(ne.selectedPeerDiff,({entries:t})=>{if(!this.roomJoined||this.participants.viewMode!=="ACTIVE_GRID")return;const e=t.map(r=>({peerId:r.peerId,priority:r.priority}));this.updateActiveParticipantsWithPriorities(e,!0)})}}uO([g.trace("ParticipantController.setupEvents")],Jg.prototype,"setupEvents",1);var hO=Object.defineProperty,pO=Object.getOwnPropertyDescriptor,mO=(s,t,e,r)=>{for(var n=r>1?void 0:r?pO(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&hO(t,e,n),n};class Wg extends Wr{get roomNodeClient(){return this.context.getValue("roomNodeClient")}constructor(t,e,r){super(t,e,r),this.setupEvents()}setupEvents(){this.roomSocketHandler.on($.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),w.on(C.SOCKET_PEERS,async t=>{const e=J.hasFeature(X.DEBUG_SOCKET_JOIN);if(e){const r=t&&(t==null?void 0:t.length)<20?{peers:JSON.stringify(t.map(n=>n.peerId))}:void 0;l.info("Processing socket peers",r)}t==null||t.forEach(r=>{r.waitlisted||this.onParticipantJoined(this.fromSocketService(r))}),e&&l.info("Processed socket peers")}),this.roomSocketHandler.on(se.peerJoinedBroadcast,({participant:t})=>{J.hasFeature(X.DEBUG_SOCKET_JOIN)&&l.info("mediaEvents.peerJoinedBroadcast",{peers:t.peerId}),this.onMediaJoined(t.peerId,t.producerStates)}),this.roomSocketHandler.on(se.selfJoinComplete,({participants:t,selectedPeers:e,roomState:r})=>{if(J.hasFeature(X.DEBUG_SOCKET_JOIN)){const a=t&&(t==null?void 0:t.length)<20?{peers:JSON.stringify(t.map(o=>o.peerId))}:void 0;l.info("mediaEvents.selfJoinComplete",a)}t.forEach(a=>this.onMediaJoined(a.peerId,a.producerStates));const{audioPeers:n,compulsoryPeers:i}=e!=null?e:{};r.pinnedPeerIds.length!==0&&this.onParticipantPinned(r.pinnedPeerIds[0]),this.computeActivateParticipants(n!=null?n:[],i),w.emit(C.UPDATE_ACTIVE,{createAllConsumers:!0})}),w.on(C.MAX_SPATIAL_LAYER_CHANGE,({peerId:t,maxSpatialLayer:e})=>{const r=this.videoPeerConsumerMap.get(t);r&&(this.maxSpatialLayerUpdates.set(r,e),this.updateConsumerSpatialLayers())}),w.on(C.NEW_PRODUCER,({peerId:t,producer:e})=>{const r=this.participants.joined.get(t);if(!r){l.warn("ParticipantController::NEW_PRODUCER::participant not found",{producer:{id:e==null?void 0:e.producerId,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}},dyteParticipant:{id:t}});return}if(r.producers.push(e),l.info("ParticipantController::NEW_PRODUCER::producer_added_to_participant",{producer:{id:e==null?void 0:e.producerId,peerId:t,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}}}),this.participants.viewMode==="MANUAL"){let n=!1;const i=e.kind==="audio",a=e.kind==="video",o=r.manualProducerConfig;(i&&(o.audio&&!e.screenShare||o.screenshareAudio&&e.screenShare)||a&&(o.video&&!e.screenShare||o.screenshareVideo&&e.screenShare))&&(n=!0),n?this.roomNodeClient.createConsumers([e]):l.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:e==null?void 0:e.producerId,peerId:t,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}}});return}(e==null?void 0:e.kind)==="audio"&&this.participants.audioSubscribed.get(t)||(e==null?void 0:e.kind)==="video"&&this.participants.videoSubscribed.get(t)||e!=null&&e.screenShare?this.roomNodeClient.createConsumers([e]).catch(n=>{l.error("ParticipantController::createConsumer failed",{error:n})}):l.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:e==null?void 0:e.producerId,peerId:t,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}}})}),w.on(C.PRODUCER_CLOSED,({peerId:t,producerId:e})=>{const r=this.participants.joined.get(t);if(!r){l.warn("ParticipantController::PRODUCER_CLOSED::participant not found",{dyteParticipant:{id:t}});return}r.producers=r.producers.filter(n=>n.producerId!==e)}),w.on(C.PRODUCER_TOGGLE,({peerId:t,producerId:e,paused:r,kind:n})=>{const i=this.participants.joined.get(t);if(i){n==="audio"&&i.setAudioEnabled(!r);const a=i.producers.find(o=>o.producerId===e);a&&(a.pause=r)}}),this.roomSocketHandler.on(se.globalPeerPinBroadcast,t=>{let e;if(t&&(e=t.participantId),!this.roomJoined)return;const r=e;this.onParticipantPinned(r);const n=this.participants.joined.get(r);n&&this.roomNodeClient.activatePeers(n.producers).catch(i=>{l.error("unable to create consumers",{error:i})})}),this.roomSocketHandler.on(se.selectedPeer,({audioPeers:t,compulsoryPeers:e})=>{this.roomJoined&&this.onSelectedPeers(e.concat(t))}),this.roomSocketHandler.on(se.selectedPeerDiff,({entries:t})=>{if(!this.roomJoined||this.participants.viewMode!=="ACTIVE_GRID")return;const e=t.map(r=>({peerId:r.peerId,priority:r.priority}));this.updateActiveParticipantsWithPriorities(e,!0)})}}mO([g.trace("ParticipantController.setupEvents")],Wg.prototype,"setupEvents",1);const we=wr(Rl().permissions),Wi=class extends Ht{constructor(e,r,n,i=!1){super();S(this,At);S(this,q,void 0);S(this,Gi,void 0);S(this,Ji,void 0);S(this,Ad,e=>{var u,h,p;const{chat:r,connectedMeetings:n,plugins:i,polls:a,media:o,...d}=e;if(r&&(r.private&&ps(c(this,q).chat.private,r.private),r.public&&ps(c(this,q).chat.public,r.public),this.emit("chatUpdate")),n&&ps(c(this,q).connectedMeetings,n),o){const f=T=>{switch(T){case gs.NONE:return H.Allowed;case gs.ALLOWED:return H.Allowed;case gs.NOT_ALLOWED:return H.NotAllowed;case gs.CAN_REQUEST:return H.CanRequest;default:return}},v={audio:void 0,video:void 0,screenshare:void 0};(u=o.audio)!=null&&u.canProduce&&(v.audio={canProduce:f(o.audio.canProduce)}),(h=o.video)!=null&&h.canProduce&&(v.video={canProduce:f(o.video.canProduce)}),(p=o.screenshare)!=null&&p.canProduce&&(v.screenshare={canProduce:f(o.screenshare.canProduce)}),ps(c(this,q).media,v)}i&&(ps(c(this,q).plugins,i),this.emit("pluginsUpdate")),a&&(ps(c(this,q).polls,a),this.emit("pollsUpdate")),Object.keys(d).length!==0&&ps(c(this,q),d),this.emit("permissionsUpdate",e)});if(!r)throw l.error("DytePermissionsPreset::load_preset_permissions_failed"),new b("Could not load preset permissions.");y(this,Ji,e),y(this,Gi,n),y(this,q,r),i&&this.setupEvents()}setupEvents(){w.on(C.UPDATE_PERMISSIONS,c(this,Ad))}static fromResponse(e,r,n){return new Wi(n,e,r,!0)}static default(e,r){return new Wi(e,we,r)}static init(e,r,n){let i;return n?i=new Wi(e,n,r,!0):i=new Wi(e,we,r),i}get mediaRoomType(){const{sfu:e}=c(this,Ji).getValue("roomNodeOptions");return e===li.CF?"CF":"HIVE"}get stageEnabled(){var e;return((e=c(this,q))==null?void 0:e.stageEnabled)||c(this,Gi)===Xe.Webinar||c(this,Gi)===Xe.Livestream}get acceptStageRequests(){var e,r;return this.stageEnabled?((e=c(this,q))==null?void 0:e.acceptStageRequests)||((r=c(this,q))==null?void 0:r.canAcceptProductionRequests):!1}get stageAccess(){var e,r,n;return((e=c(this,q))==null?void 0:e.stageAccess)===H.NotAllowed?H.NotAllowed:((r=c(this,q))==null?void 0:r.stageAccess)===H.CanRequest?H.CanRequest:((n=c(this,q))==null?void 0:n.stageAccess)===H.Allowed||c(this,q).media.audio.canProduce===H.Allowed||c(this,q).media.video.canProduce===H.Allowed||c(this,q).media.screenshare.canProduce===H.Allowed?H.Allowed:c(this,q).media.audio.canProduce===H.CanRequest||c(this,q).media.video.canProduce===H.CanRequest||c(this,q).media.screenshare.canProduce===H.CanRequest?H.CanRequest:H.NotAllowed}get acceptWaitingRequests(){var e,r;return(r=(e=c(this,q))==null?void 0:e.acceptWaitingRequests)!=null?r:we.acceptWaitingRequests}get requestProduceVideo(){var e,r,n;return((n=(r=(e=c(this,q))==null?void 0:e.media)==null?void 0:r.video)==null?void 0:n.canProduce)===H.CanRequest}get requestProduceAudio(){var e,r,n;return((n=(r=(e=c(this,q))==null?void 0:e.media)==null?void 0:r.audio)==null?void 0:n.canProduce)===H.CanRequest}get requestProduceScreenshare(){var e,r,n;return((n=(r=(e=c(this,q))==null?void 0:e.media)==null?void 0:r.screenshare)==null?void 0:n.canProduce)===H.CanRequest}get canAllowParticipantAudio(){var e,r;return(r=(e=c(this,q))==null?void 0:e.disableParticipantAudio)!=null?r:we.disableParticipantAudio}get canAllowParticipantScreensharing(){var e,r;return(r=(e=c(this,q))==null?void 0:e.canAcceptProductionRequests)!=null?r:we.canAcceptProductionRequests}get canAllowParticipantVideo(){var e,r;return(r=(e=c(this,q))==null?void 0:e.disableParticipantVideo)!=null?r:we.disableParticipantVideo}get canDisableParticipantAudio(){return this.canAllowParticipantAudio}get canDisableParticipantVideo(){return this.canAllowParticipantVideo}get kickParticipant(){var e,r;return(r=(e=c(this,q))==null?void 0:e.kickParticipant)!=null?r:we.kickParticipant}get pinParticipant(){var e,r;return(r=(e=c(this,q))==null?void 0:e.pinParticipant)!=null?r:we.pinParticipant}get canRecord(){var e,r;return(r=(e=c(this,q))==null?void 0:e.canRecord)!=null?r:we.canRecord}get waitingRoomType(){var e,r;return(r=(e=c(this,q))==null?void 0:e.waitingRoomType)!=null?r:we.waitingRoomType}get waitingRoomBehaviour(){var e,r;return(r=(e=c(this,q))==null?void 0:e.waitingRoomType)!=null?r:we.waitingRoomType}get plugins(){var e,r;return(r=(e=c(this,q))==null?void 0:e.plugins)!=null?r:we.plugins}get polls(){var e,r;return(r=(e=c(this,q))==null?void 0:e.polls)!=null?r:we.polls}get produceVideo(){return this.canProduceVideo}get requestProduce(){return c(this,q).media.audio.canProduce===H.CanRequest||c(this,q).media.video.canProduce===H.CanRequest||c(this,q).media.screenshare.canProduce===H.CanRequest}get canProduceVideo(){var r;const e=(r=c(this,q).media.video.canProduce)!=null?r:we.media.video.canProduce;return this.stageEnabled&&(c(this,At,zt)==="ACCEPTED_TO_JOIN_STAGE"||c(this,At,zt)==="ON_STAGE")&&e===H.CanRequest?H.Allowed:this.stageEnabled&&(c(this,At,zt)==="OFF_STAGE"||c(this,At,zt)==="REQUESTED_TO_JOIN_STAGE")&&e===H.Allowed?H.NotAllowed:e}get produceScreenshare(){return this.canProduceScreenshare}get canProduceScreenshare(){var r;const e=(r=c(this,q).media.screenshare.canProduce)!=null?r:we.media.screenshare.canProduce;return this.stageEnabled&&(c(this,At,zt)==="ACCEPTED_TO_JOIN_STAGE"||c(this,At,zt)==="ON_STAGE")&&e===H.CanRequest?H.Allowed:this.stageEnabled&&(c(this,At,zt)==="OFF_STAGE"||c(this,At,zt)==="REQUESTED_TO_JOIN_STAGE")&&e===H.Allowed?H.NotAllowed:e}get produceAudio(){return this.canProduceAudio}get canProduceAudio(){var r;const e=(r=c(this,q).media.audio.canProduce)!=null?r:we.media.audio.canProduce;return this.stageEnabled&&(c(this,At,zt)==="ACCEPTED_TO_JOIN_STAGE"||c(this,At,zt)==="ON_STAGE")&&e===H.CanRequest?H.Allowed:this.stageEnabled&&(c(this,At,zt)==="OFF_STAGE"||c(this,At,zt)==="REQUESTED_TO_JOIN_STAGE")&&e===H.Allowed?H.NotAllowed:e}get chatPublic(){var e,r,n;return(n=(r=(e=c(this,q))==null?void 0:e.chat)==null?void 0:r.public)!=null?n:we.chat.public}get chatPrivate(){var e,r,n;return(n=(r=(e=c(this,q))==null?void 0:e.chat)==null?void 0:r.private)!=null?n:we.chat.private}get chatChannel(){var e,r,n;return(n=(r=(e=c(this,q))==null?void 0:e.chat)==null?void 0:r.channel)!=null?n:we.chat.channel}get chatMessage(){var e,r,n;return(n=(r=(e=c(this,q))==null?void 0:e.chat)==null?void 0:r.message)!=null?n:we.chat.message}get connectedMeetings(){var e,r;return(r=(e=c(this,q))==null?void 0:e.connectedMeetings)!=null?r:we==null?void 0:we.connectedMeetings}get hiddenParticipant(){var e,r;return(r=(e=c(this,q))==null?void 0:e.hiddenParticipant)!=null?r:we.hiddenParticipant}get showParticipantList(){var e;return(e=c(this,q).showParticipantList)!=null?e:we.showParticipantList}get canChangeParticipantRole(){var e,r;return(r=(e=c(this,q))==null?void 0:e.canChangeParticipantPermissions)!=null?r:we.canChangeParticipantPermissions}get canChangeParticipantPermissions(){var e,r;return(r=(e=c(this,q))==null?void 0:e.canChangeParticipantPermissions)!=null?r:we.canChangeParticipantPermissions}get canChangeTheme(){return!1}get canPresent(){return c(this,q).media.audio.canProduce===H.Allowed||c(this,q).media.video.canProduce===H.Allowed||c(this,q).media.screenshare.canProduce===H.Allowed}get acceptPresentRequests(){return this.acceptStageRequests}get canEditDisplayName(){var e;return(e=c(this,q).canEditDisplayName)!=null?e:!1}get maxScreenShareCount(){return 1}get isRecorder(){return c(this,q).isRecorder}get canSpotlight(){return c(this,q).canSpotlight}get canLivestream(){return c(this,q).canLivestream}get transcriptionEnabled(){return c(this,q).transcriptionEnabled}};let Du=Wi;q=new WeakMap,Gi=new WeakMap,Ji=new WeakMap,Ad=new WeakMap,At=new WeakSet,zt=function(){return c(this,Ji).getValue("stageStatus")};class fO extends Ht{constructor(){super(...arguments);m(this,"localMediaHandler");S(this,Gu,void 0)}async updatePermission(){var d,u;const e=(h,p)=>{this.mediaPermissions[h]=p;const f={message:this.mediaPermissions[h],kind:h};p==="DENIED"?w.emit(C.MEDIA_PERMISSION_ERROR,f):w.emit(C.MEDIA_PERMISSION_UPDATE,f)};if(Se.getName()==="firefox")return;const r="microphone",n="camera",i=await((d=navigator==null?void 0:navigator.permissions)==null?void 0:d.query({name:r})),a=await((u=navigator==null?void 0:navigator.permissions)==null?void 0:u.query({name:n})),o=(h,p)=>{switch(p){case"granted":e(h,"ACCEPTED");break;case"denied":e(h,"DENIED");break;case"prompt":e(h,"NOT_REQUESTED");break}this.localMediaHandler.repopulateAvailableDevices()};i&&(i.onchange=()=>o("audio",i.state)),a&&(a.onchange=()=>o("video",a.state))}async populateMediaPermissionsInCallstats({message:e,kind:r}){U.onSafeInitialization(()=>{switch(r){case"audio":{U.mediaPermission("AUDIO",e),U.mediaPermission("SPEAKER",e);break}case"video":{U.mediaPermission("VIDEO",e);break}case"screenshare":{U.mediaPermission("SCREENSHARE",e);break}}})}async init(e={},r=!1,n=null){var i,a,o,d,u;if(Se.init(),!this.localMediaHandler)try{let h=!0;if(n!=null&&n.getValue("defaults").mediaHandler)h=!1,this.localMediaHandler=n.getValue("defaults").mediaHandler.localMediaHandler;else if(navigator.RNLocalMediaHandlerImpl){const{RNLocalMediaHandlerImpl:p}=navigator;this.localMediaHandler=await p.init()}else this.localMediaHandler=new Ft(n,e.constraints,(i=n==null?void 0:n.getValue("defaults"))==null?void 0:i.isNonPreferredDevice,(a=n==null?void 0:n.getValue("defaults"))==null?void 0:a.autoSwitchAudioDevice);if(w.on(C.MEDIA_PERMISSION_UPDATE,async p=>{if(this.populateMediaPermissionsInCallstats({message:p.message,kind:p.kind}),p.message==="NOT_REQUESTED")switch(p==null?void 0:p.kind){case"audio":this.rawAudioTrack&&(l.info("Disabling audio due to media permission update"),this.disableAudio());break;case"video":this.rawVideoTrack&&(l.info("Disabling video due to media permission update"),this.disableVideo());break;default:break}this.emit("mediaPermissionUpdate",p)}),w.on(C.MEDIA_PERMISSION_ERROR,async p=>{const{kind:f,message:v,constraints:T}=p;this.populateMediaPermissionsInCallstats({message:v,kind:f}),f==="audio"?(l.info(`Disabling audio due to media permission error skipping: ${this.localMediaHandler.audioUpdateInProgress}`),this.localMediaHandler.audioUpdateInProgress===!1&&this.disableAudio()):f==="video"&&(l.info(`Disabling video due to media permission error skipping: ${this.localMediaHandler.videoUpdateInProgress}`),this.localMediaHandler.videoUpdateInProgress===!1&&this.disableVideo()),l.error("SelfController::mediaPermissionError",{error:{message:v},constraints:T,mediaPermissionsErrors:{kind:f,message:v}}),this.emit("mediaPermissionError",p),this.emit("mediaPermissionUpdate",{message:v,kind:f})}),h){l.info(`Setting up DyteSelfMedia streams using media handler. audio:${!!(e!=null&&e.audio)} video:${(o=e==null?void 0:e.video)!=null?o:!0}`);const p=this.localMediaHandler.setupStreams({video:(d=e==null?void 0:e.video)!=null?d:!0,audio:(u=e==null?void 0:e.audio)!=null?u:!0});r||await p}}catch(h){l.error("DyteSelf::init::Failed To Setup Streams",{error:{name:h.name,message:h.message}})}}get audioTrack(){return this.localMediaHandler.audioTrack}get rawAudioTrack(){return this.localMediaHandler.rawAudioTrack}get mediaPermissions(){return this.localMediaHandler.permissions}async addAudioMiddleware(e){return this.localMediaHandler.addAudioMiddleware(e)}async removeAudioMiddleware(e){return this.localMediaHandler.removeAudioMiddleware(e)}get videoTrack(){return this.localMediaHandler.videoTrack}get rawVideoTrack(){return this.localMediaHandler.rawVideoTrack}async addVideoMiddleware(e){return this.localMediaHandler.addVideoMiddleware(e)}async setVideoMiddlewareGlobalConfig(e={disablePerFrameCanvasRendering:!1}){return this.localMediaHandler.setVideoMiddlewareGlobalConfig(e)}async removeVideoMiddleware(e){return this.localMediaHandler.removeVideoMiddleware(e)}get screenShareTracks(){return this.localMediaHandler.screenShareTracks}get audioEnabled(){return this.localMediaHandler.audioEnabled}get videoEnabled(){return this.localMediaHandler.videoEnabled}get screenShareEnabled(){return this.localMediaHandler.screenShareEnabled}async enableAudio(){await this.localMediaHandler.enableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}async enableVideo(){await this.localMediaHandler.enableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}async disableAudio(){this.localMediaHandler.disableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}async enableScreenShare(){await this.localMediaHandler.enableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}async disableScreenShare(){await this.localMediaHandler.disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}async disableVideo(){await this.localMediaHandler.disableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}getCurrentDevices(){return this.localMediaHandler.getCurrentDevices()}async getAudioDevices(){return await this.localMediaHandler.getAudioDevices()}async getVideoDevices(){return await this.localMediaHandler.getVideoDevices()}async getSpeakerDevices(){return await this.localMediaHandler.getSpeakerDevices()}getDeviceById(e,r){let n;return r==="audio"?n="audioinput":r==="video"?n="videoinput":r==="speaker"&&(n="audiooutput"),this.localMediaHandler.getDeviceById(e,n)}async setDevice(e){switch(e.kind){case"audioinput":try{await this.localMediaHandler.setAudioDevice(e)}catch(r){}finally{this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}break;case"audiooutput":await this.localMediaHandler.setSpeakerDevice(e);break;case"videoinput":try{await this.localMediaHandler.setVideoDevice(e)}catch(r){}finally{this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}this.emit("deviceUpdate",{device:e})}}Gu=new WeakMap;const wa={},_s={executeWithLock({methodName:s,lockName:t,timeout:e}){return(r,n,i)=>{const a=i.value;return i.value=function(...d){if(wa[t]){const p=new Error(`Unsupported concurrent calls on Dyte method: ${s}.`);throw p.name="UnsupportedConcurrentMethodExecution",l.error("DyteLocker::UnsupportedConcurrentMethodExecution",{error:{stack:p.stack},dyteLocker:{methodName:s,lockName:t}}),p}wa[t]=!0;const u=setTimeout(()=>delete wa[t],e),h=a.apply(this,d);return Promise.resolve(h).then(()=>{delete wa[t],clearTimeout(u)}).catch(()=>{delete wa[t],clearTimeout(u)}),h},i}}};var gO=Object.defineProperty,vO=Object.getOwnPropertyDescriptor,xt=(s,t,e,r)=>{for(var n=r>1?void 0:r?vO(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&gO(t,e,n),n};let ut=(xv=class extends fO{constructor(t,e,r,n,i){var a;super();S(this,js);S(this,Ye);S(this,ao);m(this,"name");m(this,"picture");m(this,"customParticipantId");m(this,"waitlistStatus");S(this,io,void 0);S(this,Ut,void 0);S(this,Ki,void 0);m(this,"role");m(this,"userId");m(this,"organizationId");m(this,"supportsRemoteControl",!1);m(this,"device");S(this,qs,void 0);m(this,"presetName");m(this,"roomState","init");S(this,zi,new Set);S(this,Yi,new Set);y(this,qs,t),this.userId=e.id,this.name=e.name,this.picture=e.picture,this.customParticipantId=(a=e.customParticipantId)!=null?a:e.clientSpecificId,this.waitlistStatus="none",y(this,Ut,r),y(this,io,n),y(this,Ki,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=Se.isElectron(),this.device=Se.getDeviceInfo(),this.presetName=i,n.viewType!==Xe.Chat&&this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),je(this,ao,Zu).call(this)}get stageStatus(){return c(this,qs).getValue("stageStatus")}get id(){return c(this,qs).getValue("peerId")}static async __init__(t,e,r,n,i,a=!1){var p,f,v,T,P;let o=(f=(p=t.getValue("defaults"))==null?void 0:p.audio)!=null?f:!0,d=(T=(v=t.getValue("defaults"))==null?void 0:v.video)!=null?T:!0;r.canProduceAudio!=="ALLOWED"&&(o=!1),r.canProduceVideo!=="ALLOWED"&&(d=!1);const u=new ut(t,e,r,n,i);if(n.viewType===Xe.Chat)return u;const h=G0(n.mediaConstraints);return ps(h,(P=t.getValue("defaults"))==null?void 0:P.mediaConfiguration),await u.init({audio:o,video:d,constraints:h},a,t),u.setupEvents(),u}setupEvents(){this.on("videoUpdate",je(this,ao,Zu)),this.localMediaHandler.on("AUDIO_TRACK_CHANGE",async()=>{if(l.info("DyteSelf::setupEvents::AUDIO_TRACK_CHANGE",{...pn(this)}),this.roomJoined&&this.audioEnabled)try{await c(this,Ye,it).shareMic(this.audioTrack)}catch(t){l.error("DyteSelf::setupEvents::Error while sharing mic",{error:t}),this.localMediaHandler.disableAudio()}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}),this.localMediaHandler.on("VIDEO_TRACK_CHANGE",async()=>{if(l.info("DyteSelf::setupEvents::VIDEO_TRACK_CHANGE",{...pn(this)}),this.roomJoined&&this.rawVideoTrack===void 0)l.info("DyteSelf::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&this.roomJoined)try{const t=await c(this,Ye,it).shareWebcam(this.videoTrack);t&&t.id!==this.videoTrack.id&&J.hasFeature(X.EXP_RESHARE)&&await c(this,Ye,it).shareWebcam(this.videoTrack)}catch(t){l.error("DyteSelf::setupEvents::failed shareWebcam",{error:t}),this.videoEnabled&&await this.localMediaHandler.disableVideo()}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}),this.localMediaHandler.on("DEVICE_CHANGE",async({device:t})=>{this.emit("deviceUpdate",{device:t})}),this.localMediaHandler.on("DEVICE_LIST_UPDATED",t=>{this.emit("deviceListUpdate",t)}),this.localMediaHandler.on("SCREENSHARE_TRACK_CHANGE",async()=>{if(!this.roomJoined){l.error("DyteSelf.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{await c(this,Ye,it).shareScreen(this.screenShareTracks)}catch(t){l.error("DyteSelf::setupEvents::Error while sharing screen",{error:t}),this.screenShareEnabled&&await this.localMediaHandler.disableScreenShare()}l.info("DyteSelf::setupEvents::SCREENSHARE_TRACK_CHANGE",{...pn(this)}),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}),this.localMediaHandler.on("SCREENSHARE_ENDED",async()=>{l.log("Disabling screenshare due to SCREENSHARE_ENDED"),await this.disableScreenShare(),l.info("DyteSelf::setupEvents::SCREENSHARE_ENDED",{...pn(this)})}),this.localMediaHandler.on("AUDIO_TRACK_SILENT",()=>{U.mediaTrackMuted("AUDIO")}),this.localMediaHandler.on("FORCE_MUTE_AUDIO",()=>{this.disableAudio()}),this.localMediaHandler.on("FORCE_MUTE_VIDEO",async()=>{this.roomJoined&&await c(this,Ye,it).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),U.videoOff()}),c(this,Ut).on("permissionsUpdate",t=>{var e,r,n;(e=t==null?void 0:t.media)!=null&&e.audio&&c(this,Ut).canProduceAudio!==H.Allowed&&(this.disableAudio(),l.info(`Disabled audio due to dynamic preset change: canProduceAudio: ${this.permissions.canProduceAudio}`)),(r=t==null?void 0:t.media)!=null&&r.video&&c(this,Ut).canProduceVideo!==H.Allowed&&(this.disableVideo(),l.info(`Disabled video due to dynamic preset change: canProduceVideo: ${this.permissions.canProduceVideo}`)),(n=t==null?void 0:t.media)!=null&&n.screenshare&&c(this,Ut).canProduceScreenshare!==H.Allowed&&(this.disableScreenShare(),l.info(`Disabled screenshare due to dynamic preset change: canProduceScreenshare: ${this.permissions.canProduceScreenshare}`))})}get permissions(){return c(this,Ut)}get config(){return c(this,io)}get roomJoined(){var t;return((t=c(this,Ye,it))==null?void 0:t.roomJoined)===!0}setName(t){if(!t)throw new b("Name cannot be empty.");this.name=t}async setupTracks(t={}){var e,r;return t.forceReset&&(c(this,Ye,it).stopAllProducers(),this.localMediaHandler.removeAllTracks()),this.localMediaHandler.setupStreams({video:(e=t.video)!=null?e:!0,audio:(r=t.audio)!=null?r:!0})}async destructMediaHandler(){return this.localMediaHandler.destruct()}async removeDocumentEventListeners(){return this.localMediaHandler.removeDocumentEventListeners()}async enableAudio(){if(this.permissions.canProduceAudio!==H.NotAllowed&&!(c(this,Ut).canProduceAudio===H.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.audioEnabled){if(await this.localMediaHandler.enableAudio(),this.roomJoined&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{await c(this,Ye,it).shareMic(this.audioTrack)}catch(t){l.error("DyteSelf::enableAudio::Error while sharing mic",{error:t}),this.localMediaHandler.disableAudio()}if(!this.audioEnabled)return;c(this,Ye,it).unmuteSelf()}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),U.audioOn()}}async enableVideo(){if(c(this,Ut).canProduceVideo!==H.NotAllowed&&!(c(this,Ut).canProduceVideo===H.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.videoEnabled){if(await this.localMediaHandler.enableVideo(),this.roomJoined&&this.stageStatus==="ON_STAGE")try{await c(this,Ye,it).shareWebcam(this.videoTrack)}catch(t){l.error("DyteSelf::enableVideo::Error while sharing video",{error:t}),this.videoEnabled&&await this.localMediaHandler.disableVideo()}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),l.info("DyteSelf.enableVideo",{...pn(this)}),U.videoOn()}}async updateVideoConstraints(t){if(!this.localMediaHandler.updateVideoConstraints)throw new b("Unsupported");await this.localMediaHandler.updateVideoConstraints(t)}async enableScreenShare(){if(!this.roomJoined)throw new b("Can`t enable screenshare without joining room");if(c(this,Ut).canProduceScreenshare!==H.NotAllowed&&!(c(this,Ut).canProduceScreenshare===H.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.screenShareEnabled&&(await this.localMediaHandler.enableScreenShare(),this.screenShareTracks.audio||this.screenShareTracks.video)){try{await c(this,Ye,it).shareScreen(this.screenShareTracks)}catch(t){l.error("DyteSelf::enableScreenShare::Error while sharing screen",{error:t}),this.screenShareEnabled&&await this.localMediaHandler.disableScreenShare()}this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}}async updateScreenshareConstraints(t){if(!this.localMediaHandler.updateScreenshareConstraints)throw new b("Unsupported");await this.localMediaHandler.updateScreenshareConstraints(t)}async disableAudio(){this.audioEnabled&&(this.localMediaHandler.disableAudio(),this.roomJoined&&c(this,Ye,it).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),U.audioOff())}async disableVideo(){this.videoEnabled&&(await this.localMediaHandler.disableVideo(),this.roomJoined&&await c(this,Ye,it).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),U.videoOff())}async disableScreenShare(){this.screenShareEnabled&&(await this.localMediaHandler.disableScreenShare(),this.roomJoined&&await c(this,Ye,it).disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var n;y(this,Ki,t);const r=t?"pinned":"unpinned";(n=c(this,js,ea))==null||n.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}get isPinned(){return c(this,Ki)}async pin(){if(!this.roomJoined)throw new b("Can`t pin participants without joining room");return c(this,Ye,it).pinPeer(this.id)}async unpin(){if(!this.roomJoined)throw new b("Can`t unpin participants without joining room");return c(this,Ye,it).pinPeer(null)}async setDevice(t){var r,n,i;if(!t)throw new b("No device selected");const e=this.getCurrentDevices();if(t.deviceId&&(((r=e==null?void 0:e.audio)==null?void 0:r.deviceId)===t.deviceId||((n=e==null?void 0:e.video)==null?void 0:n.deviceId)===t.deviceId||((i=e==null?void 0:e.speaker)==null?void 0:i.deviceId)===t.deviceId)&&(l.warn("DyteSelf.setDevice.setting_to_in_use_device",{devices:[t]}),J.hasFeature(X.SKIP_SETTING_IN_USE_DEVICE)))throw new b("Cannot set device currently in use");switch(t.kind){case"audioinput":try{await this.localMediaHandler.setAudioDevice(t)}catch(a){this.roomJoined&&await c(this,Ye,it).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}break;case"audiooutput":await this.localMediaHandler.setSpeakerDevice(t);break;case"videoinput":try{await this.localMediaHandler.setVideoDevice(t)}catch(a){this.roomJoined&&await c(this,Ye,it).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}}cleanUpTracks(){var t,e,r,n;(t=this.audioTrack)==null||t.stop(),(e=this.rawAudioTrack)==null||e.stop(),(r=this.videoTrack)==null||r.stop(),(n=this.rawVideoTrack)==null||n.stop()}registerVideoElement(t,e=!1){var r;e?c(this,zi).add(t):c(this,Yi).add(t),this.updateVideo(t),e||c(this,js,ea).addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(r=this.raised)!=null?r:!1)}deregisterVideoElement(t,e=!1){t.srcObject=void 0,e?c(this,zi).delete(t):(c(this,Yi).delete(t),c(this,js,ea).removeSource(this.id))}updateVideo(t,e=!1){var r,n,i;if(this.videoEnabled){if(this.videoTrack==null)return;const a=(r=t.srcObject)==null?void 0:r.getTracks()[0];if((a==null?void 0:a.id)===this.videoTrack.id)return;const o=new MediaStream;o.addTrack(this.videoTrack),t.srcObject=o,e||(n=c(this,js,ea))==null||n.enableSource(this.id)}else t.srcObject=void 0,e||(i=c(this,js,ea))==null||i.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},io=new WeakMap,Ut=new WeakMap,Ki=new WeakMap,qs=new WeakMap,js=new WeakSet,ea=function(){return c(this,qs).getValue("pip")},Ye=new WeakSet,it=function(){return c(this,qs).getValue("roomNodeClient")},zi=new WeakMap,Yi=new WeakMap,ao=new WeakSet,Zu=function(){Array.from(c(this,Yi)).forEach(t=>this.updateVideo(t,!1)),Array.from(c(this,zi)).forEach(t=>this.updateVideo(t,!0))},xv);xt([g.trace("DyteSelf.setupEvents")],ut.prototype,"setupEvents",1),xt([g.trace("DyteSelf.setupTracks")],ut.prototype,"setupTracks",1),xt([g.trace("DyteSelf.destructMediaHandler")],ut.prototype,"destructMediaHandler",1),xt([g.trace("DyteSelf.removeDocumentEventListeners")],ut.prototype,"removeDocumentEventListeners",1),xt([_s.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),g.trace("DyteSelf.enableAudio")],ut.prototype,"enableAudio",1),xt([_s.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),g.trace("DyteSelf.enableVideo")],ut.prototype,"enableVideo",1),xt([g.trace("DyteSelf.updateVideoConstraints")],ut.prototype,"updateVideoConstraints",1),xt([g.trace("DyteSelf.enableScreenShare"),_s.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3})],ut.prototype,"enableScreenShare",1),xt([g.trace("DyteSelf.updateScreenshareConstraints")],ut.prototype,"updateScreenshareConstraints",1),xt([_s.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),g.trace("DyteSelf.disableAudio")],ut.prototype,"disableAudio",1),xt([_s.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),g.trace("DyteSelf.disableVideo")],ut.prototype,"disableVideo",1),xt([_s.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3}),g.trace("DyteSelf.disableScreenShare")],ut.prototype,"disableScreenShare",1),xt([g.trace("DyteSelf.setDevice")],ut.prototype,"setDevice",1),ut=xt([pt("1100")],ut);class yO extends xg{constructor(e){super(e);m(this,"sessionDescription");this.sessionDescription=e.sessionDescription}}class TO extends Hg{}class _O extends Bg{async retryFailedConsumerCreationTasks(t){return Qc(t.map(async e=>br(async r=>(r>0&&l.warn(`retrying failed consumer creation task: ${JSON.stringify(e)}`),this.consumerCreationTask({...e})))))}async consumerCreationTask({consumerId:t,producerId:e,producingPeerId:r,producingTransportId:n,streamId:i,trackId:a,paused:o,screenShare:d,appData:u,kind:h,sessionDescription:p}){const f=`${i}:${h}`,v={consumerId:t,producerId:e,producingPeerId:r,producingTransportId:n,streamId:i,trackId:a,sessionDescription:p,appData:u,kind:h,paused:o,screenShare:d,name:"consumer creation task error",message:"consumer creation failed"};return new Promise(async(P,k)=>{const I=setTimeout(()=>{this.consumerTrackEvents.delete(f),v.isTimedout=!0,k(v)},5e3),x=(W,Q)=>{try{if(W.readyState==="ended")clearTimeout(I),k(v);else{const oe=W;oe.enabled=!0,this.handler.midTransceiverMap.set(Q.mid,Q);const ve=new yO({id:t,localId:Q.mid,track:oe,paused:o,producerId:e,producingPeerId:r,handler:this.handler,appData:{...u,screenShare:d,peerId:r},reuseTrack:!0,rtpReceiver:Q.receiver,producingTransportId:n,sessionDescription:p});this.consumers.set(t,ve),ve.once("close",()=>{this.consumers.delete(ve.id),this.handler.midTransceiverMap.delete(Q.mid)}),l.info("consumer created for ",{consumer:{id:t,kind:h,appData:{screenShare:d},peerId:r,producerId:e}}),this.observer.emit("newconsumer",ve),clearTimeout(I),P(ve)}}catch(oe){l.warn("error while creating consumer:",oe),clearTimeout(I),k(v)}},V=this.consumerTrackPool.get(t);if((V==null?void 0:V.length)===2){x(V[0],V[1]);return}const O=this.unknownTracksMap.get(f);O?(this.unknownTracksMap.delete(f),x(O.track,O.transceiver)):this.consumerTrackEvents.set(f,x),p&&await this.safeEmitAsPromise("negotiate",{description:p})})}async connect(){try{const{offerSdp:t,callback:e}=await this.handler.connect(),{answer:r}=await this.safeEmitAsPromise("connect",{offer:t});if(await e(r),!await this.isConnected)throw new Error("ice connection failed")}catch(t){throw l.error("transport failed to connect:",t),t}}_ontrack(t){const{track:e,transceiver:r}=t;l.info(`track event received [trackId: ${e.id}]`);const n=`${r.mid}:${e.kind}`;e.addEventListener("ended",()=>{l.info(`rtc consumer track ended [trackId: ${e.id}]`),this.consumerTrackPool.delete(e.id),this.unknownTracksMap.delete(n)}),this.consumerTrackPool.set(e.id,[e,r]);const i=this.consumerTrackEvents.get(n);i?(i(e,r),this.consumerTrackEvents.delete(n)):(l.warn(`track event handler not found ${n}`),this.unknownTracksMap.set(n,t))}async consume(t){if(l.debug(`consume() producers: ${JSON.stringify(t)}`),this.closed)throw new lt("closed");if(this.direction!=="recv")throw new vn("not a receiving Transport");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(!await this.isConnected)return Promise.reject(new Error("Transport not connected"));const e=[],r=new Map;return t.forEach(n=>{var a;const i=(a=r.get(n.producingPeerId))!=null?a:[];r.set(n.producingPeerId,i.concat([n]))}),r.forEach(async(n,i)=>{const{consumersMap:a}=await this.safeEmitAsPromise("consume_peer",{producingPeerId:i});a.forEach((o,d)=>{const{consumerId:u,trackId:h,screenShare:p,paused:f,streamId:v,kind:T,appData:P,producingTransportId:k,sessionDescription:I}=o;e.push(this.consumerCreationTask({consumerId:u,trackId:h,streamId:v,kind:T,producerId:d,producingPeerId:i,producingTransportId:k,paused:f,screenShare:p,appData:P,sessionDescription:I}))})}),Qc(e)}async produce({track:t,encodings:e,codecOptions:r,stopTracks:n=!0,disableTrackOnPause:i=!0,zeroRtpOnPause:a=!1,appData:o={}}={}){if(l.debug(`produce() [track:${t.id}]`),t){if(this.direction!=="send")throw new vn("not a sending Transport");if(t.readyState==="ended")throw new lt("track ended");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(this.listenerCount("produce")===0)throw new TypeError('no "produce" listener set into this transport');if(o&&typeof o!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!await this.isConnected)return Promise.reject(new Error("Transport not connected"));const{producerId:d,localId:u,rtpSender:h}=await this.awaitQueue.push(async()=>{const{offerSdp:f,callback:v,sender:T,mid:P}=await this.handler.send({track:t,encodings:e,codecOption:r,screenShare:o==null?void 0:o.screenShare}),{answer:k,producerId:I}=await this.safeEmitAsPromise("produce",{offer:f,kind:t.kind,paused:i?!t.enabled:!1,appData:{...o||{},mid:P}}),x=await v(k);return{producerId:I,localId:x,rtpSender:T}},"producer"),p=new TO({id:d,localId:u,track:t,stopTracks:n,disableTrackOnPause:i,zeroRtpOnPause:a,appData:o,handler:this.handler,rtpSender:h});return this.producers.set(d,p),p.observer.on("close",()=>{this.producers.delete(p.id)}),this.emit("newproducer",p),this.observer.emit("newproducer",p),p}}class SO extends qg{createTransport({direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:a,config:o}){const d=Xs(),u=new _O({id:d,direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:a,handlerFactory:this.handlerFactory,config:o});return this._observer.emit("newtransport",u),u}}class EO{constructor(t){S(this,Et,void 0);y(this,Et,t)}async joinRoom(t,e,r=!1,n=null){const i={roomUuid:t,displayName:e,prejoined:r};return n&&(i.location=n),(await c(this,Et).sendMessagePromiseWithTimeout({event:ne.joinRoom,protobuf:af.toBinary(i),timeout:5e3})).payload}async connectTransport(t){const e=(await c(this,Et).sendMessagePromise(ne.createWebRTCTransport,Zm.toBinary(t))).payload,{transportId:r,description:n}=Hl.fromBinary(e),i={sdp:n==null?void 0:n.sdp,type:n.type};return{transportId:r,answer:i}}async produce(t){var i,a;const e=(await c(this,Et).sendMessagePromise(ne.produce,lf.toBinary(t))).payload,r=Ef.fromBinary(e);return{answer:{sdp:(i=r==null?void 0:r.description)==null?void 0:i.sdp,type:(a=r==null?void 0:r.description)==null?void 0:a.type},producerId:r.producerId}}async consume(t){const e=(await c(this,Et).sendMessagePromise(ne.consume,df.toBinary(t))).payload,{consumerIdsMap:{map:r},description:n}=Sf.fromBinary(e);return{consumerStateMap:r,sessionDescription:n}}async closeProducer(t){const e=(await c(this,Et).sendMessagePromise(ne.closeProducer,hf.toBinary(t))).payload,{description:r}=wf.fromBinary(e);return r}async closeConsumer(t){return(await c(this,Et).sendMessagePromise(ne.closeConsumer,pf.toBinary(t))).payload}async hostControlForPeer(t,e){const r={audio:e==="audio",screeShare:!1,video:e==="video",participantId:t},n=(await c(this,Et).sendMessagePromise(ne.hostControlPeer,gf.toBinary(r))).payload;if(!n)return!1;const{status:i}=Pf.fromBinary(n);return i==="success"}async hostControlForAll(t){const e={audio:t==="audio",screenShare:!1,video:t==="video"},r=(await c(this,Et).sendMessagePromise(ne.hostControlAllPeers,vf.toBinary(e))).payload;if(!r)return!1;const{status:n}=Rf.fromBinary(r);return n==="success"}async kickAll(){const t={},e=(await c(this,Et).sendMessagePromise(ne.kickAll,ql.toBinary(t))).payload;if(!e)return!1;const{status:r}=bf.fromBinary(e);return r==="success"}async kickPeer(t){const e=(await c(this,Et).sendMessagePromise(ne.kickPeer,mf.toBinary(t))).payload;if(!e)return!1;const{status:r}=Cf.fromBinary(e);return r==="success"}async changeDisplayName(t){const e=(await c(this,Et).sendMessagePromise(ne.changeDisplayName,ff.toBinary(t))).payload;if(!e)return!1;const{status:r}=kf.fromBinary(e);return r==="success"}async notifySelfJoinComplete(){const t={},e=(await c(this,Et).sendMessagePromise(ne.selfJoinComplete,of.toBinary(t))).payload;return Rc.fromBinary(e)}}Et=new WeakMap;const wO=Error("task execution aborted");class CO{constructor(t,e){m(this,"id");m(this,"executor");m(this,"cancel");this.id=t,this.executor=e}async execute(){return new Promise((t,e)=>{this.cancel=()=>e(wO),this.executor.then(r=>t(r))})}}let Kg=0;const td=new Map;class Ou{static execute(t){const e=Kg;Kg+=1;const r=new CO(e,t);return td.set(e,r),{id:e,value:r.execute().finally(()=>td.delete(e))}}static stop(t){const e=td.get(t);e&&(e.cancel(),td.delete(t))}}const bO=2e3;class PO extends Fg{constructor(e,r){super();S(this,Hn);m(this,"_device");m(this,"_sendTransport");m(this,"_recvTransport");m(this,"_consumers");m(this,"_producers");m(this,"_producerStatus");m(this,"_producerIdToConsumerIdMap");m(this,"_socket");m(this,"_socketHandler");m(this,"_totalTransportReconnectionCount");m(this,"_transportReconnectFailureCount");m(this,"_consumerCreationFailureCount");m(this,"_producerNotReadyFailureCount");m(this,"_consumerNotBoundFailureCount");m(this,"_transportDisconnectedTimer");m(this,"_iceTransportPolicy","all");m(this,"_transportConnectionFailCount",0);m(this,"lastConnectionTime",0);m(this,"transportConnectionStatus");m(this,"transportDisconnected");S(this,Or,void 0);y(this,Or,e),this._device=new SO({}),this._socket=r,c(this,Hn,Lo).mediaState={consuming:{state:Rt.NEW,reconnected:!1},producing:{state:Rt.NEW,reconnected:!1}},this.transportDisconnected={consuming:!1,producing:!1},this._socketHandler=new EO(r),this.reset()}get socket(){return this._socket}get producers(){return this._producers}get consumers(){return this._consumers}get producerIdToConsumerIdMap(){return this._producerIdToConsumerIdMap}get cfSocketHandler(){return this._socketHandler}get sendTransport(){return this._sendTransport}get recvTransport(){return this._recvTransport}reset(){this._producers=new Map,this._consumers=new Map,this._producerStatus=new Map,this._producerIdToConsumerIdMap=new Map,this.transportConnectionStatus=new Map,this._transportReconnectFailureCount=0,this._consumerCreationFailureCount=0,this._totalTransportReconnectionCount=0,this._producerNotReadyFailureCount=0,this._consumerNotBoundFailureCount=0,this._transportDisconnectedTimer={consuming:void 0,producing:void 0}}async setupTransports(e,r){const i=await We().getICEServers().catch(o=>(l.warn(`failed to get iceservers from server: ${o.message}`),[])),a=e.map(o=>{var u,h,p,f,v,T,P,k;const d=this.transportConnectionStatus.get(o);if(d&&!r)return d;switch(d&&r&&Ou.stop(d.id),o){case"send":{const I=Ou.execute(this.createSendTransport({iceServers:i,additionalSettings:{encodedInsertableStreams:(u=c(this,Or).getValue("modules").e2ee)==null?void 0:u.enabled},config:{enableHighBitrate:(f=(p=(h=c(this,Or).getValue("defaults").mediaConfiguration)==null?void 0:h.audio)==null?void 0:p.enableHighBitrate)!=null?f:!1,enableStereo:(P=(T=(v=c(this,Or).getValue("defaults").mediaConfiguration)==null?void 0:v.audio)==null?void 0:T.enableStereo)!=null?P:!1},iceTransportPolicy:this._iceTransportPolicy}));return this.transportConnectionStatus.set(o,I),I.value}case"recv":{const I=Ou.execute(this.createRecvTransport({iceServers:i,additionalSettings:{encodedInsertableStreams:(k=c(this,Or).getValue("modules").e2ee)==null?void 0:k.enabled},iceTransportPolicy:this._iceTransportPolicy}));return this.transportConnectionStatus.set(o,I),I.value}default:return l.warn(`What are you thinking when passing this transportType: ${o}?`,{transport:{type:o}}),Promise.reject(Error("TYPE_OF_TRANSPORT_UNKNOWN"))}});return Promise.all(a).finally(()=>{e.forEach(o=>{this.transportConnectionStatus.delete(o)})})}stopAllTransports(){var e,r,n,i;l.info(" closing all the transports"),(e=this._sendTransport)==null||e.close(),(r=this._sendTransport)==null||r.removeAllListeners(),(n=this._recvTransport)==null||n.close(),(i=this._recvTransport)==null||i.removeAllListeners(),this._sendTransport=void 0,this._recvTransport=void 0,this.reset()}async createSendTransport(e){var n,i,a,o;if(this._sendTransport&&this._sendTransport.connected){l.info("sendTransport::already_exists_in_connected_state",{transport:{id:(n=this._sendTransport)==null?void 0:n.id,serverId:(i=this._sendTransport)==null?void 0:i.serverId,type:"send"}});return}l.info("sendTransport::initializing_transport",{transport:{id:(a=this._sendTransport)==null?void 0:a.id,serverId:(o=this._sendTransport)==null?void 0:o.serverId,type:"send"}});const r=this._device.createSendTransport(e);this._transportDisconnectedTimer.producing=void 0,l.info("sendTransport::initialized_transport",{transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"send"}}),this.handleTransport(r,!1),l.info("sendTransport::connecting_transport",{transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"send"}});try{await br(async(d,u)=>{this.socket.isConnected||u(new Error("socket is not connected")),r.connectionState==="closed"&&u(new Error("transport is closed")),d>0&&l.debug(`retrying transport connect, count: ${d}`,{transport:{id:r.id,serverId:r.serverId,type:"send"}});try{await r.connect()}catch(h){throw l.error(`failed to connect send transport: ${r.id}`,{error:h,transport:{id:r.id,serverId:r.serverId,type:"send"}}),h.message==="ice connection failed"&&u(h),h}},{delayTime:100,strategy:"exponential",maxRetryCount:J.hasFeature(X.ENABLE_CF_INFINITE_RETRIES)?1/0:3}),l.info("sendTransport::connected_transport",{transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"send"}}),this._transportReconnectFailureCount=Math.max(0,this._transportReconnectFailureCount-1),this._producerNotReadyFailureCount=0,this._sendTransport=r,U.onSafeInitialization(()=>{U.configureSendTransport(r)})}catch(d){throw l.error(`failed to connect send transport after retry:${r.id}`,{error:d,transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"send"}}),r.close(),r.removeAllListeners(),this._transportReconnectFailureCount+=1,this.handleFailure(),d}}async createRecvTransport(e){var n,i,a,o,d;if(this._recvTransport&&this._recvTransport.connected){l.info("recvTransport::already_exists_in_connected_state",{transport:{id:(n=this._recvTransport)==null?void 0:n.id,serverId:(i=this._recvTransport)==null?void 0:i.serverId,type:"recv"}});return}l.info("recvTransport::initializing_transport",{transport:{id:(a=this._recvTransport)==null?void 0:a.id,serverId:(o=this._recvTransport)==null?void 0:o.serverId,type:"recv"}});const r=this._device.createRecvTransport({...e,additionalSettings:{...(d=e.additionalSettings)!=null?d:{},rtcAudioJitterBufferMaxPackets:25,rtcAudioJitterBufferFastAccelerate:!0,rtcAudioJitterBufferMinDelayMs:20}});this._transportDisconnectedTimer.consuming=void 0,l.info("recvTransport::initialized_transport",{transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"recv"}}),this.handleTransport(r,!0),l.info("recvTransport::connecting_transport",{transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"recv"}});try{await br(async(u,h)=>{this.socket.isConnected||h(new Error("socket is not connected")),r.connectionState==="closed"&&h(new Error("transport is closed")),u>0&&l.debug(`retrying transport connect, count: ${u}`,{transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"recv"}});try{await r.connect()}catch(p){throw l.error(`fail to connect recv transport: ${r.id}`,{error:p,transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"recv"}}),p.message==="ice connection failed"&&h(p),p}},{delayTime:100,strategy:"exponential",maxRetryCount:J.hasFeature(X.ENABLE_CF_INFINITE_RETRIES)?1/0:3}),l.info("recvTransport::connected_transport",{transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"recv"}}),this._transportReconnectFailureCount=Math.max(0,this._transportReconnectFailureCount-1),this._consumerCreationFailureCount=0,this._consumerNotBoundFailureCount=0,this.producerIdToConsumerIdMap.clear(),this._recvTransport=r,U.onSafeInitialization(()=>{U.configureRecvTransport(r)})}catch(u){throw l.error(`failed to connect recv transport after retry:${r.id}`,{error:u,transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"recv"}}),r.close(),r.removeAllListeners(),this._transportReconnectFailureCount+=1,this.handleFailure(),u}}handleTransport(e,r){if(e.on("connect",async({offer:n},i,a)=>{try{const o={consuming:r,description:{sdp:n.sdp,type:n.type,target:r?qt.SUBSCRIBER:qt.PUBLISHER}},{transportId:d,answer:u}=await this._socketHandler.connectTransport(o);e.setServerId(d),i({answer:u})}catch(o){l.error(`${r?"consumer":"producer"} transport connection error:`,{error:o,transport:{id:e==null?void 0:e.id,serverId:e==null?void 0:e.serverId,type:r?"recv":"send"}}),a(o)}}),e.on("connectionstatechange",async n=>{this.updateTransportState({state:n,direction:r?"consuming":"producing"}),l.info(`${r?"consumer":"producer"} transport connectionState:`,{transport:{id:e==null?void 0:e.id,serverId:e==null?void 0:e.serverId,type:r?"recv":"send",status:n}});const i=()=>{this._transportDisconnectedTimer[r?"consuming":"producing"]!==void 0&&(clearTimeout(this._transportDisconnectedTimer[r?"consuming":"producing"]),this._transportDisconnectedTimer[r?"consuming":"producing"]=void 0)};switch(n){case"connected":i(),this.lastConnectionTime=performance.now();break;case"disconnected":this._transportDisconnectedTimer[r?"consuming":"producing"]=setTimeout(()=>{this.triggerTransportReconnection(e,r)},bO);break;case"failed":if(e.closed)return;i(),this.triggerTransportReconnection(e,r);break}}),e.on("icecandidate",async n=>{l.debug("sending icecandidate:",{iceCandidate:n})}),e.on("datachannel:events",async(n,i)=>{var a,o;l.debug("got data channel message on event:",{rtcChannel:{label:n,message:i}});try{switch(i.type){case"negotiation":{this.negotiateOverDC(i,Zc(i),n,e);break}case"handshake":{const d={type:"handshake",payload:{message:"pong"}};e.sendResponseOverDC(n,Zc(i),d);break}case"consumer_toggle":{this.handleConsumerToggle(i.payload);break}case"hub-disconnect":{l.debug(`media hub disconnected, full_reconnect: ${(a=i.payload)==null?void 0:a.full_reconnect}`),((o=i.payload)==null?void 0:o.full_reconnect)===!0&&this.emit("rejoin");break}case"error":{this.handleErrorOverDC(i.payload,e.id);break}default:l.warn(`unknown event received from cf node, event: ${i.type}`);break}}catch(d){l.error(`Unable to handle the incoming datachannel message on channel ${n}`)}}),e.on("dc_error",()=>{e.direction==="recv"&&(l.warn("events datachannel did not open in 5s"),this.handleFailure())}),e.on("negotiate",async({description:n},i,a)=>{try{const o={sdp:n==null?void 0:n.sdp,type:n==null?void 0:n.type},d=await this.negotiate(e,o);i({answer:d})}catch(o){l.error("negotiate error:",{transport:{id:e.id,serverId:e.serverId,type:e.direction},error:o}),a(o)}}),!r){e.on("produce",async({offer:n,kind:i,paused:a,appData:o},d,u)=>{var v;const p=bu(n.sdp).media.filter(T=>i==="video"?T.type==="video":T.type==="audio").at(-1).msid,f={description:{sdp:n.sdp,type:n.type,target:qt.PUBLISHER},paused:a,kind:i,msid:p,appData:JSON.stringify(o),screenShare:(v=o.screenShare)!=null?v:!1};try{const{answer:T,producerId:P}=await this._socketHandler.produce(f);d({answer:T,producerId:P})}catch(T){l.error("create producer error:",{error:T}),u(T)}});return}e.on("consume_peer",async({producingPeerId:n},i,a)=>{l.info("consumePeer:",n);const o={producingPeerId:n};try{const d=await this._socketHandler.consume(o);l.debug(`consumePeer response for ${n}:`,{consumerStateMap:d.consumerStateMap});const u=new Map;Object.entries(d.consumerStateMap).forEach(([h,p])=>{var v,T,P;let f={};try{f=JSON.parse(p.producerState.appData)}catch(k){}u.set(h,{consumerId:p.consumerId,trackId:(v=p.producerTrack)==null?void 0:v.trackId,streamId:p.producerTrack.streamId,kind:p.producerState.kind===Nt.VIDEO?"video":"audio",appData:f,screenShare:(T=p.producerState)==null?void 0:T.screenShare,paused:(P=p.producerState)==null?void 0:P.pause,sessionDescription:d.sessionDescription,producingPeerId:n})}),i({consumersMap:u})}catch(d){l.error("consumePeer error:",{error:d}),a(d)}}),e.on("consume",async({producerId:n,producingPeerId:i},a,o)=>{var u,h,p,f,v,T,P,k,I;const d={producingPeerId:i,producerId:n};try{const x=await this._socketHandler.consume(d),V=x.consumerStateMap[n];let O={};try{O=JSON.parse((u=V.producerState)==null?void 0:u.appData)}catch(W){}l.info("consumer create response:",{consumer:{remotelyPaused:(h=V.producerState)==null?void 0:h.pause,producerId:(p=V.producerState)==null?void 0:p.producerId,kind:(v=(f=V.producerState)==null?void 0:f.kind)==null?void 0:v.toString(),appData:{...O,screenShare:(T=V.producerState)==null?void 0:T.screenShare},id:V.consumerId,sessionDescription:x.sessionDescription},consumerState:V}),a({consumerId:V.consumerId,screenShare:(P=V.producerState)==null?void 0:P.screenShare,trackId:(k=V.producerTrack)==null?void 0:k.trackId,streamId:V.producerTrack.streamId,kind:V.producerState.kind===Nt.VIDEO?"video":"audio",paused:(I=V.producerState)==null?void 0:I.pause,appData:O,sessionDescription:x.sessionDescription})}catch(x){l.error("error during consuming on server:",x),o(x)}})}async createProducer(e,r,n){var a;if(this._sendTransport===void 0||this._sendTransport.closed)return null;l.info("createProducer::initializing_producer",{producer:{id:"TO_BE_CREATED",kind:e,status:"initializing",appData:r==null?void 0:r.appData}});const i=this._producerStatus.get(e);if((i==null?void 0:i.trackId)===r.track.id&&(i==null?void 0:i.status)===Jr.INITIALIZING)return l.info("createProducer::producer getting initializing",{producer:{id:"GETTING_CREATED",status:"initializing",kind:e,appData:r==null?void 0:r.appData}}),null;this._producerStatus.set(e,{trackId:r.track.id,status:Jr.INITIALIZING});try{const o=await this._sendTransport.produce(r);return(a=r.appData)!=null&&a.e2ee&&w.emit(C.E2EE_ACTIVE_PRODUCER,o),l.info("createProducer::initialized_producer",{producer:{id:o==null?void 0:o.id,kind:e,status:"producing",appData:r==null?void 0:r.appData}}),o.on("close",async({offer:d,reason:u},h)=>{l.info("producer::closing",{debuggingHint:u,producer:{id:o==null?void 0:o.id,kind:e,status:"closing",appData:r==null?void 0:r.appData}});const p={producerId:o.id,description:{sdp:d.sdp,type:d.type,target:qt.PUBLISHER}};try{const f=await this._socketHandler.closeProducer(p),v={sdp:f==null?void 0:f.sdp,type:f==null?void 0:f.type};l.info("producer::closed",{producer:{id:o==null?void 0:o.id,kind:e,status:"closed",appData:r==null?void 0:r.appData}}),h({answer:v})}catch(f){l.error("producer close error",f)}this._producerStatus.delete(e),this._producers.delete(e),n(),this.reconfigureWebcamLayers()}),o.on("trackended",()=>{l.info("producer::trackended",{producer:{id:o==null?void 0:o.id,kind:e,status:"UNKNOWN",appData:o==null?void 0:o.appData}}),[Y.MIC,Y.WEBCAM].includes(e)||n()}),this._producers.set(e,o),this._producerStatus.set(e,{trackId:r.track.id,status:Jr.INITIALIZED}),this.reconfigureWebcamLayers(),o.track}catch(o){throw this._producerStatus.set(e,{status:Jr.NOT_INITIALIZED,trackId:r.track.id}),l.error("createProducer::transport_initialization_failed",{producer:{id:"FAILED_TO_CREATE",kind:e,status:"failed",appData:r==null?void 0:r.appData,error:o}}),o}}async reconfigureWebcamLayers(){if(!J.hasFeature(X.DISABLE_WEBCAM_LAYERS_ON_SCREENSHARE))return;const e=this.producers.get(Y.WEBCAM);e&&await this._switchProducerSpatialLayer(e,this.producers.get(Y.SCREENSHARE_VIDEO)?0:3)}async _switchProducerSpatialLayer(e,r){try{l.debug("switching layer of webcam producer to:",{media:{video:{layer:r}},producer:{id:e.id,kind:e.kind,appData:e.appData}}),await e.setMaxSpatialLayer(r)}catch(n){l.error("failed to switch spatial layer",{error:n})}}_initConsumer(e){e&&(e.observer.on("close",async r=>{l.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),this._consumers.delete(e.id),w.emit(C.CONSUMER_CLOSED,{id:e.id})}),this._consumers.set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),w.emit(C.NEW_CONSUMER,{id:e.id,appData:e.appData,peerId:e.peerId}))}async createConsumers(e){if(this._recvTransport===void 0||this._recvTransport.closed||!this._recvTransport.connected)return;if(e.every(n=>this.getProducer(n.producerId))){l.warn("why are you creating a consumer for local producer?");return}await br(async n=>{n>0&&l.debug(`retrying consume call, retryCount: ${n}`),(await this._recvTransport.consume(e).catch(a=>{throw l.error("failed to consume:",{error:a}),a})).forEach(a=>{a.status==="rejected"?(l.error("consumer creation task is failing",a.reason),this._consumerCreationFailureCount+=1,setTimeout(this.handleFailure.bind(this),0)):this._initConsumer(a.value)})}).catch(n=>{l.error("create consumer failed after retries",{error:n}),this._consumerCreationFailureCount+=1,this.handleFailure()})}async pauseProducer(e){const r=this._producers.get(e);if(!r){l.warn(`producer type: ${e} not found`);return}r.pause(),r.appData.e2ee&&w.emit(C.E2EE_INACTIVE_PRODUCER,r),l.info(`Paused the producer of type: ${r.kind}`,{producer:{id:r.id,kind:r.kind,appData:r.appData}})}async resumeProducer(e){const r=this._producers.get(e);if(!r){l.warn(`producer type: ${e} not found`);return}r.resume(),l.info(`Resumed the producer of type: ${r.kind}`,{producer:{id:r.id,kind:r.kind,appData:r.appData}})}async replaceTrack(e,r){const n=this._producers.get(e);if(!n){l.warn(`producer type: ${e} not found`);return}await n.replaceTrack({track:r}),l.info(`Replaced track for the producer of type: ${n.kind}`,{producer:{id:n.id,kind:n.kind,appData:n.appData,trackId:r.id}})}async removeProducer(e,r){const n=this._producers.get(e);if(!n){l.warn(`producer type: ${e} not found`);return}r&&n.track.stop(),await this.sendTransport.awaitQueue.push(n.close.bind(n),"producer").then(()=>{c(this,Or).getValue("modules").e2ee.enabled&&w.emit(C.E2EE_INACTIVE_PRODUCER,n)}).catch(i=>{l.error("failed to close producer on server",i)})}async pauseConsumer(e){const r=this._consumers.get(e);if(!r){l.warn(`consumer with id: ${e} not found`);return}this.toggleConsumerOverDC(e,!0),l.info(`Paused the consumer of type: ${r.kind}`,{consumer:{id:r.id,kind:r.kind,appData:r.appData}})}async pauseConsumerOverSocket(e){try{const r={consumerId:e.id,pause:!0};await this.socket.sendMessagePromise(ne.toggleConsumer,Pc.toBinary(r)),e.pause(),w.emit(C.CONSUMER_PAUSED,{id:e.id}),l.info(`Paused the consumer of type: ${e.kind} over socket`,{consumer:{id:e.id,kind:e.kind,appData:e.appData}})}catch(r){l.error("error on pausing consumer",{error:r,consumer:{id:e.id,kind:e.kind,appData:e.appData}})}}async toggleConsumerOverDC(e,r){const n={type:"consumer_toggle",payload:{consumerId:e,mute:r}},i=this._recvTransport.getDatachannel("events");if(!i){l.warn("recvTransport:: events datachannel not found");return}await i.request(n),l.info(`HiveSFUHandler::consumer toggled, consumerId: ${e}, muted: ${r}`)}async resumeConsumer(e){const r=this._consumers.get(e);if(!r){l.warn(`consumer with id: ${e} not found`);return}if(!r.paused){l.warn(`consumer with id:${e} is not paused so not resuming`);return}try{const n={consumerId:e,pause:!1};await this.socket.sendMessagePromise(ne.toggleConsumer,Pc.toBinary(n)),r.resume(),w.emit(C.CONSUMER_RESUMED,{id:r.id}),l.info(`Resumed the consumer of type: ${r.kind}`,{consumer:{id:r.id,kind:r.kind,appData:r.appData}})}catch(n){l.error("error on resuming consumer",n)}}async closeConsumer(e,r){return this.closeConsumers([e],r)}async closeConsumers(e,r=!1){l.info(`Closing consumers: ${JSON.stringify(e)} with force: ${r}`);let n=!0;const i=e.filter(d=>this._consumers.get(d)?!0:(l.warn(`consumer with id: ${d} not found`),!1));if(!i.length)return;const a={consumerIds:i},o=async()=>{var d;return(d=this._recvTransport)==null?void 0:d.awaitQueue.push(async()=>{await this._socketHandler.closeConsumer(a)},"close_consumer").catch(u=>{l.warn("error on closing consumer:",{error:u}),n=r})};r?o():await o(),n&&i.forEach(d=>{const u=this.consumers.get(d);this.producerIdToConsumerIdMap.delete(u.producerId),u.close(r?"force closed":void 0)})}async cleanupConsumers(e){l.debug("cleaning up all consumers");const r=[];this._consumers.forEach(n=>{e?n.peerId===e&&r.push(n.id):r.push(n.id)}),this.closeConsumers(r,!0)}async stopAllProducers(){l.info("stopping all available producers"),this._producers.forEach((e,r)=>{l.debug(`closing producer type: ${r}`,{producer:{id:e==null?void 0:e.id,kind:e.kind,appData:e.appData}}),e.close()})}getProducer(e){return Array.from(this.producers.values()).filter(r=>r.id===e).at(0)}hasProducer(e){return this.getProducer(e)!==void 0}async negotiate(e,r){l.debug(`setting remote offer : ${JSON.stringify(r)} on ${e.direction} transport`,{transport:{id:e.id,serverId:e.serverId,type:e.direction}});const n=await e.setRemoteOffer(r),i={transportId:e.serverId,description:{sdp:n.sdp,type:n.type,target:qt.SUBSCRIBER}};return l.debug(`sending renegotiate request: ${JSON.stringify(i)} on ${e.direction} transport`,{transport:{id:e.id,serverId:e.serverId,type:e.direction}}),await this.socket.sendMessagePromise(ne.renegotiateSessionDescription,ef.toBinary(i)),l.info("renegotiation done",{transport:{id:e.id,serverId:e.serverId,type:e.direction}}),n}async negotiateOverDC(e,r,n,i){const{sdp:a}=e.payload,o={sdp:a,type:"offer"};try{l.debug(`got offer over dc: ${a} for transport: ${i.id}`);const d=await i.setRemoteOffer(o),u={type:"answer",payload:{type:d.type,sdp:d.sdp}};l.debug(`datachannel answer: ${JSON.stringify(u)}`),i.sendResponseOverDC(n,r,u)}catch(d){l.error("datachannel:events::Error:",d),d.code!=="DC_NOT_FOUND"&&i.sendErrorOverDC(n,r,d)}}handleConsumerToggle(e){const{mute:r,trackId:n}=e;l.info(`consumer toggled for trackId: ${n} muted: ${r}`);const i=this.consumers.get(n);if(!i){l.warn(`consumer with trackId: ${n} not found`);return}i.paused!==r&&(l.debug("consumer state is not same",{consumer:{id:i.id,remotelyPaused:i.paused}}),r?(i.pause(),w.emit(C.CONSUMER_PAUSED,{id:i.id})):(i.resume(),w.emit(C.CONSUMER_RESUMED,{id:i.id})))}async handleErrorOverDC(e,r){l.error(`got error over dc: ${JSON.stringify(e)} for transport: ${r}`);const{type:n,error:i,id:a}=e;if(n==="consumer"){if(i==="bind-fail"){if(this._consumerNotBoundFailureCount>=2){this.handleFailure();return}this._consumerNotBoundFailureCount+=1;const o=this.consumers.get(a);if(!o)return;try{await this.closeConsumer(o.id),await this.createConsumers([{kind:o.kind,pause:o.paused,producerId:o.producerId,producingTransportId:o.producingTransportId,screenShare:o.appData.screenShare,producingPeerId:o.peerId}])}catch(d){l.error("failed to recreate consumer on downtrack bound failure,",{consumer:{id:o.id,producerId:o.producerId,kind:o.kind,appData:o.appData}})}}}else if(n==="producer")if(i==="ready-fail"){if(this._producerNotReadyFailureCount>=2){this.handleFailure();return}this._producerNotReadyFailureCount+=1;const[o]=Array.from(this.producers.entries()).find(d=>d[1].id===a);if(!o)return;await this.removeProducer(o).catch(d=>{l.error("failed to remove ready-fail producer:",{error:d,producer:{id:a,kind:o,appData:null}})})}else i==="general-failure"&&(this.updateTransportState({state:Rt.RECONNECTING,direction:"producing"}),this.emit("reconnect_transport",this._sendTransport))}async handleFailure(){if(this._transportReconnectFailureCount>0||this._totalTransportReconnectionCount>3){l.warn("transport failure detected"),J.hasFeature(X.ENABLE_CF_EXPERIMENTAL_FAIL_RECOVERY)&&(l.debug("rejoining room"),this.emit("rejoin"));return}(this._consumerCreationFailureCount>0||this._consumerNotBoundFailureCount>=2)&&(l.warn("consumer creation failure detected or consumer not bound failure increased"),J.hasFeature(X.ENABLE_CF_EXPERIMENTAL_FAIL_RECOVERY)&&(l.debug("reconnecting recv transport"),this._totalTransportReconnectionCount+=1,this.updateTransportState({state:Rt.RECONNECTING,direction:"consuming"}),this.emit("reconnect_transport",this._recvTransport))),this._producerNotReadyFailureCount>=2&&(l.warn("producer receiver not getting added needs to reconnect send transport"),this._totalTransportReconnectionCount+=1,this.updateTransportState({state:Rt.RECONNECTING,direction:"producing"}),this.emit("reconnect_transport",this._sendTransport))}triggerTransportReconnection(e,r){l.info("triggerTransportReconnection:: reconnecting transport",{transport:{type:e.direction,id:e.id,serverId:e.serverId}});const n=J.hasFeature(X.ENABLE_CF_TRANSPORT_RECONNECTION_ON_ICE_FAILED),i=J.hasFeature(X.CF_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED);n&&(i&&this._socket.isConnected&&(performance.now()-this.lastConnectionTime>2e4&&(this._transportConnectionFailCount=0),this._transportConnectionFailCount>2&&(l.warn("Multiple disconnections, forcing relay"),this._iceTransportPolicy="relay"),this._transportConnectionFailCount+=1),this.updateTransportState({state:Rt.RECONNECTING,direction:r?"consuming":"producing"}),this.emit("reconnect_transport",e))}async switchConsumersToLayer(e,r){const n=this._recvTransport.getDatachannel("events");if(!n){l.warn("events datachannel not found");return}const i={type:"switch_consumer_layer",payload:{consumerIds:e,layer:r}};await n.request(i),l.info(`CFSFUHandler::consumer id: ${e} layer switched to ${r}`)}updateTransportState(e){const{state:r,direction:n}=e;r==="disconnected"&&(this.transportDisconnected[n]=!0),c(this,Hn,Lo).mediaState[n]={state:r,reconnected:r==="connected"?this.transportDisconnected[n]:c(this,Hn,Lo).mediaState[n].reconnected},r==="connected"&&(this.transportDisconnected[n]=!1),w.emit(C.TRANSPORT_STATE_UPDATE,{transport:n,...c(this,Hn,Lo).mediaState[n]})}}Hn=new WeakSet,Lo=function(){return c(this,Or).getValue("connectionHandler")},Or=new WeakMap;var RO=Object.defineProperty,kO=Object.getOwnPropertyDescriptor,le=(s,t,e,r)=>{for(var n=r>1?void 0:r?kO(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&RO(t,e,n),n};const zg=(Uv=class extends Og{constructor(t,e){var d,u;super();S(this,Lr);S(this,wt,void 0);S(this,pe,void 0);S(this,Nr,void 0);S(this,qn,void 0);S(this,jn,void 0);S(this,Gs,void 0);S(this,oo,void 0);S(this,co,void 0);S(this,lo,void 0);S(this,is,void 0);S(this,Qi,void 0);m(this,"legacyMode");m(this,"roomNodeUrl");m(this,"peerDisplayName");m(this,"activatedProducingPeerIds");m(this,"e2ee");m(this,"partialJoinRoomPromise");this.context=t;const{roomName:r,authToken:n,legacyMode:i,socketClient:a,meetingTitle:o}=e;this.roomJoined=!1,this.roomName=r,this.authToken=n,this.legacyMode=i,this.meetingTitle=o,y(this,wt,a),y(this,Nr,!1),y(this,pe,new PO(t,a)),this.maxPreferredStreams=6,this.activatedProducingPeerIds=new Set,y(this,is,new Set),y(this,qn,!1),y(this,jn,0),y(this,Gs,new di),this.e2ee=(u=(d=t.getValue("modules").e2ee)==null?void 0:d.enabled)!=null?u:!1,U.legacySwitch(i),this.handleSocketEvents(),this.handleSFUEvents(),this.handleCallstatsEvents(),y(this,oo,Vr(async()=>{if(!c(this,Lr,Qs).mediaJoinAttempted)return;const{roomJoined:h}=await this.joinRoom(this.peerDisplayName,this.roomUUID,{},!0,!0);h&&(w.emit(C.RESET_PRODUCER_STATE),w.emit(C.ROOM_NODE_RECONNECTED))},5e3,{leading:!0,maxWait:1e3})),y(this,co,Vr(async h=>{h.close(),h.removeAllListeners(),await this.sfuHandler.setupTransports(["send"]),l.info("send transport reconected!"),w.emit(C.RESET_PRODUCER_STATE)},1e3)),y(this,lo,Vr(async h=>{h.close(),h.removeAllListeners(),await this.sfuHandler.setupTransports(["recv"]),l.info("recv transport reconnected!"),this.activatedProducingPeerIds=new Set,w.emit(C.UPDATE_ACTIVE,{createAllConsumers:!0})},1e3))}get mediaState(){return c(this,Lr,Qs).mediaState}get roomJoined(){return c(this,Lr,Qs).roomJoined}set roomJoined(t){c(this,Lr,Qs).roomJoined=t}static async init(t,e){const{legacyMode:r=!0,meetingId:n,authToken:i,meetingTitle:a,socket:o}=e;return new zg(t,{legacyMode:r,authToken:i,socketClient:o,roomName:n,meetingTitle:a})}get sfuHandler(){return c(this,pe)}get rejoinRoom(){return c(this,oo)}reset(t=!0){var e,r,n,i;(r=(e=c(this,pe))==null?void 0:e.cleanupConsumers)==null||r.call(e),(i=(n=c(this,pe))==null?void 0:n.stopAllProducers)==null||i.call(n),c(this,is).clear(),this.activatedProducingPeerIds.clear(),t&&(c(this,Gs).stop(),this.sfuHandler.stopAllTransports(),this.sfuHandler.reset(),y(this,Gs,new di))}async reconnectTransport(t){l.info(`CFNodeClient::Room joining state: ${c(this,Nr)}`),!(!t||c(this,Nr))&&(t.direction==="send"?await c(this,co).call(this,t):await c(this,lo).call(this,t))}async setupTransports(t=!1){await c(this,pe).setupTransports(["recv","send"],t)}async stopAllProducers(){await c(this,pe).stopAllProducers()}async joinRoom(t,e,r={},n=!1,i=!1){c(this,Lr,Qs).mediaJoinAttempted=!0,y(this,Nr,!0),this.reset(n);const a=We().ipInfo;if(a!=null&&a.loc&&!c(this,Qi)){const d=a.loc.split(",");y(this,Qi,{latitude:parseFloat(d[0]),longitude:parseFloat(d[1])})}let o;try{return o=await c(this,Gs).push(()=>this._joinRoom(t,e,r,i,c(this,Qi)),"joinRoom"),o}catch(d){o={roomJoined:!1}}return o.roomJoined||w.emit(C.ROOM_NODE_FAILED),o}async _partialJoinRoom(t,e,r=!1,n=void 0){const i=We().ipInfo;let a=n;if(i!=null&&i.loc&&!n){const o=i.loc.split(",");a={latitude:parseFloat(o[0]),longitude:parseFloat(o[1])}}await br((o,d)=>(c(this,wt).isConnected||d(new Error("socket is not connected")),o>0&&l.warn(`retrying sending join room request, count: ${o}`),this.sfuHandler.cfSocketHandler.joinRoom(e,t,r,a).catch(u=>{throw l.error("failed to send join room request, error:",{error:u}),u})),{delayTime:1e3,strategy:"exponential",maxRetryCount:J.hasFeature(X.ENABLE_CF_INFINITE_RETRIES)?1/0:3}),await this.setupTransports(!0)}async partialJoinRoom(t,e,r=!1,n=void 0){this.partialJoinRoomPromise=c(this,Gs).push(()=>this._partialJoinRoom(t,e,r,n))}async _joinRoom(t,e,r={},n=!1,i=null){this.peerDisplayName=t;try{return this.partialJoinRoomPromise?await this.partialJoinRoomPromise:await this._partialJoinRoom(t,e,n,i),navigator.product!=="ReactNative"&&setTimeout(async()=>{const d={userId:this.context.getValue("userId"),peerId:this.peerId,displayName:t,roomUUID:e,roomViewType:"groupCall",roomName:this.roomName,deviceInfo:{...Se.getDeviceInfo(),userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency},sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};U.onSafeInitialization(()=>{U.roomJoined(d),r!=null&&r.audio?U.audioOn():U.audioOff(),r!=null&&r.video?U.videoOn():U.videoOff()})}),{roomJoined:await this.completeJoinRoom()}}catch(a){return l.error("error on sending join room request",{error:a}),{roomJoined:!1}}finally{this.partialJoinRoomPromise=void 0}}async completeJoinRoom(){try{const{maxPreferredStreams:t,roomState:e}=await this.sfuHandler.cfSocketHandler.notifySelfJoinComplete();return this.roomUUID=e.roomUuid,this.maxPreferredStreams=t!=null?t:6,y(this,Nr,!1),y(this,qn,!0),this.roomJoined=!0,w.emit(C.UPDATE_ACTIVE,{createAllConsumers:!0}),!0}catch(t){return l.error("error on completing join room:",{error:t}),!1}}async leaveRoom(){c(this,pe).stopAllTransports(),y(this,qn,!1),c(this,Lr,Qs).mediaJoinAttempted=!1;const t={closeRoom:!1};c(this,wt).sendMessagePromise(ne.leaveRoom,cf.toBinary(t)).then(e=>{var n;((n=_f.fromBinary(e.payload))==null?void 0:n.closed)||l.warn("weird state on peer closed and should not happen")}).catch(e=>{l.error("error on sending leave room request",{error:e})}),U.callEnded(),g.destruct()}getConsumers(){return c(this,pe).consumers}async activatePeers(t){return this.createConsumers(t)}async deactivatePeers(t,e="default"){const r=new Set;t.forEach(i=>{i.screenShare&&i.kind==="video"&&r.add(i.producingPeerId)});const n=e==="default"?t.filter(i=>!r.has(i.producingPeerId)).filter(i=>i.kind!=="audio"):t;await Promise.all(n.map(i=>{const a=this.sfuHandler.producerIdToConsumerIdMap.get(i.producerId);if(!a){l.warn(`consumer not found in deactivate producers: ${i.producerId}`);return}return this.sfuHandler.closeConsumer(a)}))}async createConsumers(t){return this.sfuHandler.createConsumers(t)}async pauseConsumers(t){t.forEach(e=>{this.sfuHandler.pauseConsumer(e)})}async resumeConsumers(t){t.forEach(e=>{this.sfuHandler.resumeConsumer(e)})}async closeConsumers(t){await Promise.all(t.map(e=>{const r=this.sfuHandler.producerIdToConsumerIdMap.get(e.producerId);if(!r){l.warn(`consumer not found in deactivate producers: ${e.producerId}`);return}return this.sfuHandler.closeConsumer(r)}))}async consumePeer(t,e,r){if(l.info(`current activated Peer ids: ${JSON.stringify(Array.from(this.activatedProducingPeerIds.values()))}, forced?:${r}`),!this.activatedProducingPeerIds.has(t)||r)try{await c(this,pe).createConsumers(e),this.activatedProducingPeerIds.add(t)}catch(n){l.error("consumePeer failed in CFNodeClient.ts",{error:n})}else l.info(`not creating consumer for this peerId: ${t}`)}async shareWebcam(t){if(t===void 0)return null;if(c(this,pe).producers.has(Y.WEBCAM)){const i=c(this,pe).producers.get(Y.WEBCAM);if(!i.closed&&!navigator.isReactNative)return await i.replaceTrack({track:t}),await this.resumeWebcam(),t;await c(this,pe).removeProducer(Y.WEBCAM)}const e={track:t,codecOptions:{name:"VP8"},appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1};let r=t.getConstraints().width;r in Cg||(r=640),e.encodings=q0[r],J.hasFeature(X.ENABLE_CF_SIMULCAST)&&(e.encodings=Cg[r]);const n=()=>{l.info("Disabling video due to the producer closure"),this.disableWebcam()};return c(this,pe).createProducer(Y.WEBCAM,e,n)}async shareScreen(t){const{video:e,audio:r}=t;if(e===void 0)return;const n={track:e,codecOptions:{name:"VP8"},appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Se.isElectron()},stopTracks:!1};let i=()=>{l.info("Disabling screenShare due to the producer closure"),this.disableScreenShare()};if(await c(this,pe).createProducer(Y.SCREENSHARE_VIDEO,n,i),r){const a={track:r,codecOptions:{name:"opus"},appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Se.isElectron()},stopTracks:!1,zeroRtpOnPause:!0};i=()=>{},await c(this,pe).createProducer(Y.SCREENSHARE_AUDIO,a,i)}U.screenShareStart()}async shareMic(t){try{if(t===void 0)throw new lt("track undefined");if(c(this,pe).producers.has(Y.MIC)){const n=c(this,pe).producers.get(Y.MIC);if(!n.closed&&!navigator.isReactNative){await n.replaceTrack({track:t}),await this.resumeMic();return}await c(this,pe).removeProducer(Y.MIC,!1)}const e={track:t,encodings:[{priority:"high"}],codecOptions:{name:"opus"},appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!0},r=()=>{l.info("Disabling audio due to the producer closure"),this.disableMic()};await c(this,pe).createProducer(Y.MIC,e,r)}catch(e){throw new b(e)}}pauseMic(){const t=c(this,pe).producers.get(Y.MIC);if(!t){l.error("pauseMic::could_not_find_mic_producer");return}if(t.paused){l.info("pauseMic::mic_producer_already_paused");return}t.pause();const e={producerId:t.id,pause:!0};c(this,wt).sendMessage(ne.toggleProducer,fs.toBinary(e))}async pauseWebcam(){const t=c(this,pe).producers.get(Y.WEBCAM);if(!t){l.error("pauseWebcam::could_not_find_webcam_producer");return}t.pause();const e={producerId:t.id,pause:!0};c(this,wt).sendMessage(ne.toggleProducer,fs.toBinary(e))}async resumeMic(){const t=c(this,pe).producers.get(Y.MIC);if(!t){l.error("resumeMic::could_not_find_mic_producer");return}if(!t.pause){l.info("resumeMic::mic_producer_already_resumed");return}t.resume(),t.appData.e2ee&&w.emit(C.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,wt).sendMessage(ne.toggleProducer,fs.toBinary(e))}async resumeWebcam(){const t=c(this,pe).producers.get(Y.WEBCAM);if(!t){l.error("resumeWebcam::could_not_find_webcam_producer");return}t.resume(),t.appData.e2ee&&w.emit(C.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,wt).sendMessage(ne.toggleProducer,fs.toBinary(e))}async disableWebcam(){await c(this,pe).removeProducer(Y.WEBCAM)}async disableMic(){await c(this,pe).removeProducer(Y.MIC)}async disableScreenShare(){l.info("screen_sharing_stopped"),U.screenShareStop(),await c(this,pe).removeProducer(Y.SCREENSHARE_VIDEO),await c(this,pe).removeProducer(Y.SCREENSHARE_AUDIO),c(this,is).clear()}async muteSelf(){this.pauseMic()}async unmuteSelf(){}async resetVideoProducers(t,e){t&&(await c(this,pe).removeProducer(Y.WEBCAM,!1),this.shareWebcam(t)),e&&(await c(this,pe).removeProducer(Y.SCREENSHARE_VIDEO,!1),this.shareScreen({video:e}))}async changeDisplayName(t,e){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!await this.sfuHandler.cfSocketHandler.changeDisplayName(r))throw new Error("failed to change display name!")}async kick(t){const e={participantId:t};if(!await this.sfuHandler.cfSocketHandler.kickPeer(e))throw new Error("failed to kickout the participant!")}async kickAll(){if(!await this.sfuHandler.cfSocketHandler.kickAll())throw new Error("failed to kickout all participant!")}async muteAll(t){if(!await this.sfuHandler.cfSocketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await this.sfuHandler.cfSocketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(t){if(!await this.sfuHandler.cfSocketHandler.hostControlForPeer(t,"audio"))throw new Error("failed to mute given participant")}async disableVideo(t){if(!await this.sfuHandler.cfSocketHandler.hostControlForPeer(t,"video"))throw new Error("failed to mute video of given participant")}async pinPeer(t){const e={participantId:t!=null?t:""};try{await c(this,wt).sendMessagePromise(ne.globalPinPeer,uf.toBinary(e))}catch(r){l.error("Error in pinning peer:",{error:r})}}validateScreenShare(t){return this.peerId===t.peerId&&this.sfuHandler.hasProducer(t.producerId)&&c(this,is).add(t.consumerPeerId),c(this,is).size}async switchConsumersToLayer(t,e){this.sfuHandler.switchConsumersToLayer(t,e)}async handleSocketEvents(){c(this,wt).on(ne.peerProducerCreateBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:r}=Mf.fromBinary(t);if(e===this.peerId)return;l.info(`producer created broadcast: ${e}, producer state: ${r}`),w.emit(C.NEW_PRODUCER,{peerId:e,producer:{...r,kind:r.kind===Nt.AUDIO?"audio":"video"}})}catch(e){l.error("error in peer-producer-create-broadcast",{error:e})}}),c(this,wt).on(ne.peerProducerToggleBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:{kind:r,pause:n,producerId:i}}=Df.fromBinary(t),a=r===Nt.AUDIO?"audio":"video";l.info(`producer toggle broadcast: ${e}, producerId: ${i}, kind:${a}, paused:${n}`),w.emit(C.PRODUCER_TOGGLE,{peerId:e,producerId:i,paused:n,kind:a}),Array.from(this.getConsumers().values()).filter(d=>d.producerId===i).forEach(d=>{d.paused!==n&&(l.debug(`consumer state mismatched for ${d.id}. updating consumer pause state ${d.paused} to ${n}`),n?(d.pause(),w.emit(C.CONSUMER_PAUSED,{id:d.id})):(d.resume(),w.emit(C.CONSUMER_RESUMED,{id:d.id})))})}catch(e){l.error("error in producer toggle broadcast handler",{error:e})}}),c(this,wt).on(ne.peerLeaveBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e}=kc.fromBinary(t);if(e===this.peerId)return;l.info(`peer left broadcast:${e}`),c(this,is).delete(e),this.sfuHandler.cleanupConsumers(e)}catch(e){l.error("error in peer left broadcast",{error:e})}}),c(this,wt).on(ne.peerProducerCloseBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:{producerId:r}}=Of.fromBinary(t);if(e===this.peerId)return;l.info(`producer closed broadcast:${e}`),w.emit(C.PRODUCER_CLOSED,{peerId:e,producerId:r});const n=this.sfuHandler.producerIdToConsumerIdMap.get(r);if(!n){l.warn(`no consumer found for producer:${r}`);return}l.info(`closing consumer ${n}, producer id: ${r}`),this.sfuHandler.closeConsumer(n).then(()=>{l.info(`closed consumer: ${n}`),this.sfuHandler.producerIdToConsumerIdMap.delete(r),w.emit(C.CONSUMER_CLOSED,{id:n})}).catch(i=>{l.error("error closing consumer",{error:i})})}catch(e){l.error("error on producer close broadcast",{error:e})}}),c(this,wt).on(ne.mediaRoomTerminationBroadcastResponse,()=>{!this.roomJoined&&!c(this,Nr)&&!c(this,qn)||(l.warn("media hub termination broadcast received, rejoining room"),w.emit(C.ROOM_NODE_DISCONNECTED),this.rejoinRoom())})}handleSFUEvents(){c(this,pe).on("reconnect_transport",async t=>{try{await this.reconnectTransport(t),l.info(`transport reconnected [id:${t.id}]`)}catch(e){l.error("error on reconnection transports",{error:e})}}),c(this,pe).on("rejoin",t=>{var e;if(((e=c(this,Lr,Qs).socketState)==null?void 0:e.state)!=="connected"){l.warn("Ignoring rejoin attempt because socket is not connected");return}if(c(this,jn)>3&&!t){l.warn("cannot rejoin more already rejoined 3 times");return}if(c(this,Nr)&&!t){l.warn("room joining in progress, cannot start rejoining");return}y(this,jn,c(this,jn)+1),l.warn(`rejoining the room because transports are failing. [rejoinCount: ${c(this,jn)}]`),this.roomJoined=!1,w.emit(C.ROOM_NODE_DISCONNECTED),this.rejoinRoom()})}handleCallstatsEvents(){U.onSafeInitialization(()=>{U.onConsumerScore(t=>{t.forEach((e,r)=>{const n=this.sfuHandler.consumers.get(r);n&&w.emit(C.CONSUMER_SCORE_UPDATE,{id:r,kind:n.kind,peerId:n.peerId,score:e.score,scoreStats:e})})}),U.onProducerScore(t=>{t.forEach((e,r)=>{const n=Array.from(this.sfuHandler.producers.values()).find(i=>i.id===r);n&&w.emit(C.PRODUCER_SCORE_UPDATE,{id:r,kind:n.kind,appData:n.appData,score:e.score,scoreStats:e})})})})}},wt=new WeakMap,pe=new WeakMap,Nr=new WeakMap,qn=new WeakMap,jn=new WeakMap,Gs=new WeakMap,oo=new WeakMap,co=new WeakMap,lo=new WeakMap,is=new WeakMap,Qi=new WeakMap,Lr=new WeakSet,Qs=function(){return this.context.getValue("connectionHandler")},Uv);let ae=zg;le([g.trace("CFNodeClient.reset")],ae.prototype,"reset",1),le([g.trace("CFNodeClient.reconnect")],ae.prototype,"reconnectTransport",1),le([g.trace("CFNodeClient.setupTransport")],ae.prototype,"setupTransports",1),le([g.trace("CFNodeClient.stopAllProducers")],ae.prototype,"stopAllProducers",1),le([g.trace("CFNodeClient.joinRoom")],ae.prototype,"joinRoom",1),le([g.trace("CFNodeClient.completeJoinRoom")],ae.prototype,"completeJoinRoom",1),le([g.trace("CFNodeClient.leaveRoom")],ae.prototype,"leaveRoom",1),le([g.trace("CFNodeClient.activatePeers")],ae.prototype,"activatePeers",1),le([g.trace("CFNodeClient.deactivatePeers")],ae.prototype,"deactivatePeers",1),le([g.trace("CFNodeClient.createConsumers")],ae.prototype,"createConsumers",1),le([g.trace("CFNodeClient.pauseConsumers")],ae.prototype,"pauseConsumers",1),le([g.trace("CFNodeClient.resumeConsumers")],ae.prototype,"resumeConsumers",1),le([g.trace("CFNodeClient.closeConsumers")],ae.prototype,"closeConsumers",1),le([g.trace("CFNodeClient.consumePeer")],ae.prototype,"consumePeer",1),le([g.trace("CFNodeClient.shareWebcam")],ae.prototype,"shareWebcam",1),le([g.trace("CFNodeClient.shareScreen")],ae.prototype,"shareScreen",1),le([g.trace("CFNodeClient.shareMic")],ae.prototype,"shareMic",1),le([g.trace("CFNodeClient.pauseMic")],ae.prototype,"pauseMic",1),le([g.trace("CFNodeClient.pauseWebcam")],ae.prototype,"pauseWebcam",1),le([g.trace("CFNodeClient.resumeMic")],ae.prototype,"resumeMic",1),le([g.trace("CFNodeClient.resumeWebcam")],ae.prototype,"resumeWebcam",1),le([g.trace("CFNodeClient.disableWebcam")],ae.prototype,"disableWebcam",1),le([g.trace("CFClient.disableMic")],ae.prototype,"disableMic",1),le([g.trace("CFClient.disableScreenShare")],ae.prototype,"disableScreenShare",1),le([g.trace("CFNodeClient.muteSelf")],ae.prototype,"muteSelf",1),le([g.trace("CFNodeClient.resetVideoProducers")],ae.prototype,"resetVideoProducers",1),le([g.trace("CFNodeClient.changeDisplayName")],ae.prototype,"changeDisplayName",1),le([g.trace("CFNodeClient.kickPeer")],ae.prototype,"kick",1),le([g.trace("CFNodeClient.kickAllPeers")],ae.prototype,"kickAll",1),le([g.trace("CFNodeClient.muteAll")],ae.prototype,"muteAll",1),le([g.trace("CFNodeClient.muteAllVideo")],ae.prototype,"muteAllVideo",1),le([g.trace("CFNodeClient.disableAudio")],ae.prototype,"disableAudio",1),le([g.trace("CFNodeClient.disableVideo")],ae.prototype,"disableVideo",1),le([g.trace("CFNodeClient.pinPeer")],ae.prototype,"pinPeer",1),le([g.trace("CFNodeClient.validateScreenShare")],ae.prototype,"validateScreenShare",1),le([g.trace("CFNodeClient.init")],ae,"init",1);async function IO(s,t){const e=s.getValue("roomNodeClient");if(e){if(e instanceof ie)return e;throw new Error("Room Node Client already setup")}const r=await ie.init(s,t);return s.setValue("roomNodeClient",r),r}async function AO(s,t){const e=s.getValue("roomNodeClient");if(e){if(e instanceof ae)return e;throw new Error("Room Node Client already setup")}const r=await ae.init(s,t);return s.setValue("roomNodeClient",r),r}async function Yg(s,t,e=li.HIVE){return e===li.CF?AO(s,t):IO(s,t)}function Qg(s){const t=s.getValue("roomNodeClient");try{t==null||t.leaveRoom()}catch(e){l.error("roomNodeClient::cleanupRoomNodeClient")}s.setValue("roomNodeClient",void 0)}var MO=Object.defineProperty,DO=Object.getOwnPropertyDescriptor,OO=(s,t,e,r)=>{for(var n=r>1?void 0:r?DO(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&MO(t,e,n),n};let Tn;const Xg=class{constructor(s){m(this,"socket");this.socket=s,this.handleSocketEvents()}static create(s){return Tn||(Tn=new Xg(s)),Tn}static cleanup(){var s;try{(s=Tn==null?void 0:Tn.socket)==null||s.disconnect()}catch(t){l.error("roomSocketHandler::cleanup")}Tn=void 0}async joinRoom(s,t){var n;this.socket.joinAttempted=!0;const e={capabilities:[],peer:{displayName:(n=s.name)!=null?n:"Participant",customParticipantId:s.customParticipantId,peerId:s.id,userId:s.userId,displayPictureUrl:s.picture,waitlisted:!1},roomUuid:""},r=this.socket.sendMessagePromise($.joinRoom,KR.toBinary(e));try{const{peer:i}=ei.fromBinary((await r).payload);w.emit(C.SOCKET_SERVICE_ROOM_JOINED,{peer:i});const a=this.getRoomState();let o=()=>new Promise(h=>{h({peers:[]})});t!==Xe.Livestream&&(o=this.getRoomPeersNonPaginated()),t===Xe.Livestream&&i.stageType===1&&(o=this.getStagePeers());const[{room:d},{peers:u}]=await Promise.all([a,o]);return w.emit(C.ROOM_STATE,d),w.emit(C.SOCKET_PEERS,u),{peer:i}}catch(i){throw l.error("RoomSocketHandler.joinRoom.failed",{error:i}),new b("Error: RoomSocketHandler.joinRoom failed.","0002",i)}}async getAllAddedParticipants(){try{return Dk.fromBinary((await this.socket.sendMessagePromise($.getAllAddedParticipants)).payload).participants.map(({id:t,...e})=>({...e,userId:t}))}catch(s){return[]}}async getRoomPeers(s,t,e){let r;try{const n={seachQuery:s,limit:t,offset:e},i=await this.socket.sendMessagePromise($.getRoomPeersInfo,UR.toBinary(n));r=Wl.fromBinary(i.payload)}catch(n){l.error("getRoomPeers::binary_decode_error",{error:n})}return r}async getRoomPeersNonPaginated(){let s;try{const t=await this.socket.sendMessagePromise($.getRoomPeersInfo);s=Wl.fromBinary(t.payload)}catch(t){l.error("getRoomJoinedPeers::binary_decode_error",{error:t})}return s}async getStagePeers(){let s;try{const t=await this.socket.sendMessagePromise($.getRoomPeersInfo);s=Wl.fromBinary(t.payload)}catch(t){l.error("getRoomJoinedPeers::binary_decode_error",{error:t})}return s}async getPeerInfo(s){let t;try{const e=await this.socket.sendMessagePromise($.getPeerInfo,Vf.toBinary({peerId:s}));t=ei.fromBinary(e.payload)}catch(e){l.error("getPeerInfo::binary_decode_error",{error:e})}return t}async getRoomState(){let s=Uf.create();try{const t=await this.socket.sendMessagePromise($.getRoomInfo);s=Uf.fromBinary(t.payload)}catch(t){l.error("getRoomState::binary_decode_error",{error:t})}return s}async getRoomStageState(){let s=jf.create();try{const t=await this.socket.sendMessagePromise($.getRoomStageState);s=jf.fromBinary(t.payload)}catch(t){l.error("getRoomStageState::binary_decode_error",{error:t})}return s}async broadcastMessage(s,t){const e={type:s,payload:new TextEncoder().encode(JSON.stringify(t)),timestamp:Date.now(),peerIds:[]};return this.socket.sendMessagePromise($.broadcastMessage,Mc.toBinary(e))}async broadcastToPeers(s,t,e){const r={type:s,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),peerIds:t};return this.socket.sendMessage($.broadcastToPeers,Mc.toBinary(r))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise($.leaveRoom,YR.toBinary({}))}async kick(s){const t={peerIds:[s]};this.socket.sendMessage($.kick,Fk.toBinary(t))}async kickAll(s=!1){const t={propagateKickAcrossRooms:s};this.socket.sendMessage($.kickAll,ql.toBinary(t))}getWaitingRoomRequests(){this.socket.sendMessage($.getWaitingRoomRequests)}acceptWaitingRoomRequest(s){const t={userIds:s};this.socket.sendMessage($.acceptWaitingRoomRequests,Vk.toBinary(t))}rejectWaitingRoomRequest(s){const t={userIds:s};this.socket.sendMessage($.denyWaitingRoomRequests,Bk.toBinary(t))}async updatePermissions(s,t){const e={updatePeersPresets:[]};return s.forEach(r=>{e.updatePeersPresets.push({userIds:r,patch:t})}),this.socket.sendMessagePromise(Lc.updateUserPreset,gI.toBinary(e))}handleSocketEvents(){this.socket.on($.broadcastMessage,({payload:s})=>{try{const t=Mc.fromBinary(s);w.emit(C.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(t.payload)),type:t.type,timestamp:t.timestamp})}catch(t){l.error("failed to decode broadcast message:",t)}}),this.socket.on($.broadcastToPeers,({payload:s})=>{try{const t=Mc.fromBinary(s);w.emit(C.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(t.payload)),type:t.type,timestamp:t.timestamp})}catch(t){l.error("failed to decode peer broadcast message:",t)}})}on(s,t){let e,r;switch(s){case $.joinRoom:case $.leaveRoom:case $.kick:case $.kickAll:{e=ei.fromBinary.bind(ei),r=ei.create();break}case $.getWaitingRoomRequests:{e=(n,i)=>n?qf.fromBinary(n,i):{requests:[]},r=qf.create();break}case $.recordingPaused:case $.recordingStarted:case $.recordingStopped:{e=rg.fromBinary.bind(rg);break}case Lc.updateUserPreset:{e=Jf.fromBinary.bind(Jf);break}case ne.peerJoinedBroadcast:case se.peerJoinedBroadcast:{e=If.fromBinary.bind(If);break}case ne.selfJoinComplete:case se.selfJoinComplete:{e=Rc.fromBinary.bind(Rc);break}case ne.globalPeerPinBroadcast:case se.globalPeerPinBroadcast:{e=Nf.fromBinary.bind(Nf);break}case ne.selectedPeer:case se.selectedPeer:{e=jl.fromBinary.bind(jl);break}case ne.selectedPeerDiff:case se.selectedPeerDiff:{e=Tf.fromBinary.bind(Tf);break}case ne.leaveRoom:case se.leaveRoom:{e=kc.fromBinary.bind(kc);break}}this.socket.on(s,({payload:n})=>{let i=r;if(!e)return t(void 0);try{i=e(n)}catch(a){l.error("roomSocketHandler::on::binary_decode_error",{error:a})}return t(i)})}async getUserPermissions(s){const t={userIds:[s]};try{const e=await this.socket.sendMessagePromise(Lc.getUserPresets,dI.toBinary(t)),r=pI.fromBinary(e.payload).peerPresets[0],n=new TextDecoder().decode(r.preset),i=JSON.parse(n).permissions;return{chat:i.chat,polls:i.polls,plugins:i.plugins}}catch(e){throw l.error("Error in getting user preset",{error:e}),e}}};let rd=Xg;OO([g.trace("RoomSocketHandler.joinRoom")],rd.prototype,"joinRoom",1);var NO=Object.defineProperty,LO=Object.getOwnPropertyDescriptor,_n=(s,t,e,r)=>{for(var n=r>1?void 0:r?LO(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&NO(t,e,n),n};const Zg=(Vv=class{constructor(s,t,e,r){S(this,Vt);m(this,"self");m(this,"authToken");S(this,Js,void 0);m(this,"viewType");S(this,yr,void 0);S(this,Ct,void 0);const{socket:n}=e,i=s.getValue("authToken");this.self=t,y(this,Ct,s),this.viewType=r,this.authToken=i,y(this,Js,n),y(this,yr,e),t.config.viewType!==Xe.Chat&&this.setupEvents()}get peerId(){return c(this,Ct).getValue("peerId")}static async init(s,t,e,r,n){const i=We(),a=s.getValue("peerId"),o=!!s.getValue("cachedUserDetails"),d=await ut.__init__(s,e,r,n,n.name,o);if(navigator.product!=="ReactNative"){const u=!J.hasFeature(X.PRECALL_BANDWIDTH_TEST);setTimeout(async()=>{const h=await d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(h)}),U.onSafeInitialization(async()=>{U.devices("AUDIO",h==null?void 0:h.filter(p=>p.kind==="audioinput")),U.devices("VIDEO",h==null?void 0:h.filter(p=>p.kind==="videoinput")),U.devices("SPEAKER",h==null?void 0:h.filter(p=>p.kind==="audiooutput"))}),l.info("Callstats:: initializing");try{await U.initialize({peerId:a,engineName:Se.getDeviceInfo().engineName,env:s.getValue("env"),iceServers:await i.getICEServers(),apiBase:s.getValue("apiBase"),flags:J.getAllFlags(),logger:l,apiHostnames:Lm(s),skipConnectivityChecks:u}),l.info("Callstats:: initialized")}catch(p){l.error("Callstats:: initialization failed",{error:p})}},0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new Zg(s,d,t,n.viewType)}async shareMediaTracks(){var o;const{audioTrack:s,videoTrack:t,permissions:e,audioEnabled:r,videoEnabled:n,screenShareEnabled:i,screenShareTracks:a}=this.self;if(e.canProduceAudio&&r)try{await c(this,Vt,ir).shareMic(s)}catch(d){this.self.disableAudio()}if(e.canProduceVideo&&n)try{const d=await c(this,Vt,ir).shareWebcam(t);d&&d.id!==t.id&&J.hasFeature(X.EXP_RESHARE)&&await c(this,Vt,ir).shareWebcam(d)}catch(d){this.self.disableVideo()}if(e.canProduceScreenshare&&i)try{await((o=c(this,Vt,ir))==null?void 0:o.shareScreen({video:a.video,audio:a.audio}))}catch(d){this.self.disableScreenShare()}}async kickHandler(s){let t="kicked";(s==null?void 0:s.kickType)==="kickAll"&&(t="ended"),this.leaveRoom(t)}waitlistedHandler(){l.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(l.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){l.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(l.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){l.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}async resetSelf(s){U.callEnded(),c(this,Vt,ir).reset(),s&&await this.joinRoom(s)}setupEvents(){w.on(C.RESET_PRODUCER_STATE,async()=>{this.self.roomJoined&&this.shareMediaTracks()}),w.on(C.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),w.on(C.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),w.on(C.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),w.on(C.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),w.on(C.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;let{peerId:t}=this;s&&J.hasFeature(X.REFRESH_ID_ON_DISCONNECTION)&&(t=Xs()),c(this,Js).updateURL(t),g.resetPeerId(t),We().setHeader("dyte-tracing-id",t),pa.remapContext(t,c(this,Ct)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),w.on(C.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),c(this,yr).on($.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),c(this,yr).on(Lc.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&w.emit(C.UPDATE_PERMISSIONS,t.patch)})}),c(this,yr).on($.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),c(this,yr).on($.kick,()=>{this.kickHandler({kickType:"kick"})}),c(this,yr).on($.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),w.onAsync(C.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),w.on(C.PRODUCER_SCORE_UPDATE,({score:s,kind:t,appData:e,scoreStats:r})=>{var i;const n=(i=e==null?void 0:e.screenShare)!=null?i:!1;this.self.emit("mediaScoreUpdate",{kind:t,isScreenshare:n,score:s,participantId:this.self.id,scoreStats:r})}),w.on(C.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),U.audioOff())}),w.on(C.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),U.videoOff())}),w.onAsync(C.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),w.on(C.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{const{peer:t}=await c(this,yr).joinRoom(this.self,this.self.config.viewType);c(this,yr).socket.flush();const e=lu(t.stageType);if(c(this,Ct).setValue("stageStatus",e,!1),t.waitlisted){this.waitlistedHandler();return}await this.joinMediaRoom(s),c(this,Ct).notify("stageStatus")}catch(t){throw l.error("Error in joinRoom",{error:t}),t}}async leaveRoom(s="left"){var t,e;if(s==="rejected"){try{(t=c(this,Js))==null||t.disconnect()}catch(r){l.error("SelfController::leaveRoom::socketDisconnect")}this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),c(this,Ct).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),c(this,Ct).notify("stageStatus");try{(e=c(this,Js))==null||e.disconnect()}catch(r){l.error("SelfController::leaveRoom::socketDisconnect")}Qg(c(this,Ct)),rd.cleanup(),this.self.roomState=s,this.self.emit("roomLeft",{state:s})}partialMediaRoom(){var s;(s=c(this,Vt,ir))==null||s.partialJoinRoom(this.self.name,c(this,Ct).getValue("meetingId"),void 0)}async joinMediaRoom(s=!1){var h,p;const{peerId:t,viewType:e,meetingId:r,authToken:n,stageStatus:i,roomNodeOptions:a}=c(this,Ct).getAllValues(),{sfu:o,roomNodeUrl:d,meetingTitle:u}=a;try{if(e===Xe.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}await Yg(c(this,Ct),{socket:c(this,Js),peerId:t,meetingId:r,authToken:n,roomNodeUrl:d,meetingTitle:u},o)}const{roomJoined:f}=(p=await((h=c(this,Vt,ir))==null?void 0:h.joinRoom(this.self.name,r,{audio:this.self.audioEnabled,video:this.self.videoEnabled,screen:this.self.screenShareEnabled},s,s)))!=null?p:{};if(!f)return;i==="ON_STAGE"&&await this.shareMediaTracks(),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s})}catch(f){throw l.error("Error:SelfController.mediaRoomJoin",f),new b("Error: could not join media room",f)}}async leaveMediaRoom(s){const t=c(this,Ct).getValue("viewType");await this.cleanupSelf(),!(s==="stageLeft"&&t===Xe.Webinar)&&c(this,Vt,ir)&&(c(this,Vt,ir).roomJoined&&s!=="disconnected"&&await c(this,Vt,ir).leaveRoom(),!(s==="stageLeft"&&t===Xe.Livestream)&&(c(this,Vt,ir).roomJoined=!1))}async cleanupSelf(){await this.self.disableAudio(),await this.self.disableVideo(),await this.self.disableScreenShare(),this.self.cleanUpTracks(),this.self.destructMediaHandler(),navigator.isReactNative||this.self.removeDocumentEventListeners()}},Js=new WeakMap,yr=new WeakMap,Ct=new WeakMap,Vt=new WeakSet,ir=function(){return c(this,Ct).getValue("roomNodeClient")},Vv);let Ss=Zg;_n([g.trace("SelfController.resetSelf")],Ss.prototype,"resetSelf",1),_n([g.trace("SelfController.setupEvents")],Ss.prototype,"setupEvents",1),_n([g.trace("SelfController.joinRoom")],Ss.prototype,"joinRoom",1),_n([g.trace("SelfController.leaveRoom")],Ss.prototype,"leaveRoom",1),_n([g.trace("SelfController.joinMediaRoom")],Ss.prototype,"joinMediaRoom",1),_n([g.trace("SelfController.leaveMediaRoom")],Ss.prototype,"leaveMediaRoom",1),_n([g.trace("SelfController.init")],Ss,"init",1);class FO{constructor(t){S(this,uo,void 0);y(this,uo,t)}on(t,e){let r;t===$.roomPeerCount?r=Ff.fromBinary.bind(Ff):r=Xf.fromBinary.bind(Xf),c(this,uo).on(t,({payload:n})=>{const i=r(n);return e(i)})}}uo=new WeakMap;class xO{constructor(t){S(this,ho,void 0);y(this,ho,t)}on(t,e){let r,n;switch(t){case $.transcript:{r=Gl.fromBinary.bind(Gl),n=Gl.create();break}default:{l.debug("AISocketHandler switch case hit default, event not accounted for.");break}}c(this,ho).on(t,({payload:i})=>{let a=n;try{a=r(i)}catch(o){l.error("chatSocketHandler::on::binary_decode_error",{error:o})}return e(a)})}}ho=new WeakMap;var UO=Object.defineProperty,VO=Object.getOwnPropertyDescriptor,Nu=(s,t,e,r)=>{for(var n=r>1?void 0:r?VO(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&UO(t,e,n),n};class sd{constructor(t){S(this,as,void 0);y(this,as,t)}getPolls(){return c(this,as).sendMessagePromise(qr.getPolls)}createPoll(t,e,r=!1,n=!1){const i={anonymous:r,hideVotes:n,question:t,options:e};return c(this,as).sendMessage(qr.createPoll,cM.toBinary(i))}votePoll(t,e){const r={index:e,pollId:t};return c(this,as).sendMessage(qr.votePoll,lM.toBinary(r))}on(t,e){let r,n;switch(t){case qr.updatePoll:case qr.createPoll:case qr.votePoll:{r=su.fromBinary.bind(su),n=su.create();break}}c(this,as).on(t,({payload:i})=>{let a=n;try{a=r(i)}catch(o){l.error("pollSocketHandler::on::binary_decode_error",{error:o})}return e(a)})}removeListeners(t){c(this,as).removeListeners(t)}}as=new WeakMap,Nu([g.trace("PollSocketHandler.getPolls")],sd.prototype,"getPolls",1),Nu([g.trace("PollSocketHandler.createPoll")],sd.prototype,"createPoll",1),Nu([g.trace("PollSocketHandler.votePoll")],sd.prototype,"votePoll",1);class $O{constructor(t){S(this,$t,void 0);y(this,$t,t)}async getStageRequests(){const{payload:t}=await c(this,$t).sendMessagePromise($.getStageRequests);return t?ru.fromBinary(t):{stageRequests:[]}}requestAccess(){c(this,$t).sendMessage($.requestStageAccess)}cancelRequestAccess(){c(this,$t).sendMessage($.cancelStageRequest)}async grantAccess(t){const e={userIds:t};c(this,$t).sendMessage($.grantStageAccess,XA.toBinary(e))}async denyAccess(t){const e={userIds:t};c(this,$t).sendMessage($.denyStageAccess,eM.toBinary(e))}joinStage(){return c(this,$t).sendMessagePromise($.joinStage,void 0,void 0,$.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return c(this,$t).sendMessagePromise($.leaveStage,eg.toBinary(e),void 0,$.peerStageStatusUpdate)}kick(t){const e={userIds:t};return c(this,$t).sendMessagePromise($.leaveStage,eg.toBinary(e))}on(t,e){let r;switch(t){case $.grantStageAccess:case $.denyStageAccess:{r=void 0;break}case $.getStagePeers:{r=Zf.fromBinary.bind(Zf);break}case $.getStageRequests:case $.requestStageAccess:case $.cancelStageRequest:{r=ru.fromBinary.bind(ru);break}case $.peerStageStatusUpdate:{r=Lf.fromBinary.bind(Lf);break}}c(this,$t).on(t,({payload:n,id:i})=>{if(!n||!r)return e(void 0,i);const a=r(n);return e(a,i)})}async getPeerInfo(t){const e=await c(this,$t).sendMessagePromise($.getPeerInfo,Vf.toBinary({peerId:t}));return ei.fromBinary(e.payload)}}$t=new WeakMap;class BO{constructor(t){S(this,nt,void 0);y(this,nt,t)}addPlugin(t,e){c(this,nt).sendMessage(j.addPlugin,fA.toBinary({pluginId:t,staggered:e}))}removePlugin(t){c(this,nt).sendMessage(j.removePlugin,vA.toBinary({pluginId:t,staggered:!1}))}async getActivePlugins(){const{payload:t}=await c(this,nt).sendMessagePromise(j.getPlugins);return t?$A.fromBinary(t):{plugins:[]}}customPluginEventToRoom(t,e,r){const n={pluginId:t,pluginData:new TextEncoder().encode(JSON.stringify(e))};c(this,nt).sendMessage(j.customPluginEventToRoom,RA.toBinary(n),r)}customPluginEventToPeers(t,e,r,n){const i={pluginId:t,peerIds:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};c(this,nt).sendMessage(j.customPluginEventToPeers,IA.toBinary(i),n)}enablePluginForRoom(t,e){c(this,nt).sendMessage(j.enablePluginForRoom,TA.toBinary({pluginId:t}),e)}enablePluginForPeers(t,e,r){c(this,nt).sendMessage(j.enablePluginForPeers,wA.toBinary({pluginId:t,peerIds:e}),r)}disablePluginForRoom(t,e){c(this,nt).sendMessage(j.disablePluginForRoom,SA.toBinary({pluginId:t}),e)}disablePluginForPeers(t,e,r){c(this,nt).sendMessage(j.disablePluginForPeers,bA.toBinary({pluginId:t,peerIds:e}),r)}storeInsertKeys(t,e,r,n){const i={pluginId:t,storeName:e,insertKeys:r.map(a=>({storeKey:a.key,payload:new TextEncoder().encode(JSON.stringify(a.payload))}))};c(this,nt).sendMessage(j.storeInsertKeys,Kf.toBinary(i),n)}storeGetKeys(t,e,r,n){const i={pluginId:t,storeName:e,getKeys:r.map(a=>({storeKey:a.key}))};c(this,nt).sendMessage(j.storeGetKeys,OA.toBinary(i),n)}storeDeleteKeys(t,e,r,n){const i={pluginId:t,storeName:e,deleteKeys:r.map(a=>({storeKey:a.key}))};c(this,nt).sendMessage(j.storeDeleteKeys,LA.toBinary(i),n)}storeDelete(t,e,r){c(this,nt).sendMessage(j.storeDelete,xA.toBinary({pluginId:t,storeName:e}),r)}getPluginDataOld(t,e){l.info("getPluginDataOld",{plugin:{id:t,storeName:e}})}storePluginDataOld(t,e,r){const n={pluginId:t,storeName:e,insertKeys:[{storeKey:r.key,payload:new TextEncoder().encode(JSON.stringify(r))}]};c(this,nt).sendMessage(j.storeInsertKeys,Kf.toBinary(n))}on(t,e){let r;switch(t){case j.addPlugin:case j.enablePluginForPeers:case j.enablePluginForRoom:{r=tu.fromBinary.bind(tu);break}case j.removePlugin:case j.disablePluginForPeers:case j.disablePluginForRoom:{r=zf.fromBinary.bind(zf);break}case j.customPluginEventToPeers:case j.customPluginEventToRoom:{r=Qf.fromBinary.bind(Qf);break}case j.storeInsertKeys:case j.storeGetKeys:case j.storeDeleteKeys:case j.storeDelete:{r=Yf.fromBinary.bind(Yf);break}}c(this,nt).on(t,({payload:n,id:i})=>{const a=r(n);return e(a,i)})}}nt=new WeakMap;var HO=Object.defineProperty,qO=(s,t,e)=>t in s?HO(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,jO=(s,t,e)=>(qO(s,typeof t!="symbol"?t+"":t,e),e),Lu=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},L=(s,t,e)=>(Lu(s,t,"read from private field"),e?e.call(s):t.get(s)),Ie=(s,t,e)=>{if(t.has(s))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(s):t.set(s,e)},ge=(s,t,e,r)=>(Lu(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),Ne=(s,t,e)=>(Lu(s,t,"access private method"),e),Es,Sn,En,He,wn,Le,Ke,ws,ot,Kr,Cs,pr,hi,zr,Fu,ev,Ca,nd,xu,tv,Uu,rv,id,Vu,$u,sv,ba,ad,Pa,od,cd,Bu,pi,Ra,ka,dd,Hu={exports:{}},mi=typeof Reflect=="object"?Reflect:null,nv=mi&&typeof mi.apply=="function"?mi.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},ld;mi&&typeof mi.ownKeys=="function"?ld=mi.ownKeys:Object.getOwnPropertySymbols?ld=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:ld=function(t){return Object.getOwnPropertyNames(t)};function GO(s){console&&console.warn&&console.warn(s)}var iv=Number.isNaN||function(t){return t!==t};function Te(){Te.init.call(this)}Hu.exports=Te,Hu.exports.once=zO,Te.EventEmitter=Te,Te.prototype._events=void 0,Te.prototype._eventsCount=0,Te.prototype._maxListeners=void 0;var av=10;function ud(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(Te,"defaultMaxListeners",{enumerable:!0,get:function(){return av},set:function(s){if(typeof s!="number"||s<0||iv(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");av=s}}),Te.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Te.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||iv(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function ov(s){return s._maxListeners===void 0?Te.defaultMaxListeners:s._maxListeners}Te.prototype.getMaxListeners=function(){return ov(this)},Te.prototype.emit=function(t){for(var e=[],r=1;r0&&(a=e[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var d=i[t];if(d===void 0)return!1;if(typeof d=="function")nv(d,this,e);else for(var u=d.length,h=hv(d,u),r=0;r0&&a.length>n&&!a.warned){a.warned=!0;var o=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");o.name="MaxListenersExceededWarning",o.emitter=s,o.type=t,o.count=a.length,GO(o)}return s}Te.prototype.addListener=function(t,e){return cv(this,t,e,!1)},Te.prototype.on=Te.prototype.addListener,Te.prototype.prependListener=function(t,e){return cv(this,t,e,!0)};function JO(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function dv(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},n=JO.bind(r);return n.listener=e,r.wrapFn=n,n}Te.prototype.once=function(t,e){return ud(e),this.on(t,dv(this,t,e)),this},Te.prototype.prependOnceListener=function(t,e){return ud(e),this.prependListener(t,dv(this,t,e)),this},Te.prototype.removeListener=function(t,e){var r,n,i,a,o;if(ud(e),n=this._events,n===void 0)return this;if(r=n[t],r===void 0)return this;if(r===e||r.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete n[t],n.removeListener&&this.emit("removeListener",t,r.listener||e));else if(typeof r!="function"){for(i=-1,a=r.length-1;a>=0;a--)if(r[a]===e||r[a].listener===e){o=r[a].listener,i=a;break}if(i<0)return this;i===0?r.shift():WO(r,i),r.length===1&&(n[t]=r[0]),n.removeListener!==void 0&&this.emit("removeListener",t,o||e)}return this},Te.prototype.off=Te.prototype.removeListener,Te.prototype.removeAllListeners=function(t){var e,r,n;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[t]),this;if(arguments.length===0){var i=Object.keys(r),a;for(n=0;n=0;n--)this.removeListener(t,e[n]);return this};function lv(s,t,e){var r=s._events;if(r===void 0)return[];var n=r[t];return n===void 0?[]:typeof n=="function"?e?[n.listener||n]:[n]:e?KO(n):hv(n,n.length)}Te.prototype.listeners=function(t){return lv(this,t,!0)},Te.prototype.rawListeners=function(t){return lv(this,t,!1)},Te.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):uv.call(s,t)},Te.prototype.listenerCount=uv;function uv(s){var t=this._events;if(t!==void 0){var e=t[s];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}Te.prototype.eventNames=function(){return this._eventsCount>0?ld(this._events):[]};function hv(s,t){for(var e=new Array(t),r=0;r{setTimeout(e,t)})}getAttempts(){return L(this,Es)}reset(){ge(this,Es,0)}}Es=new WeakMap;const bs={debug:0,info:1,warn:2,error:3};class tN{constructor(t){Ie(this,Sn,void 0),Ie(this,En,void 0),ge(this,Sn,console),ge(this,En,t)}debug(...t){bs[L(this,En)]>bs.debug||L(this,Sn).debug("[Sockrates]:",...t)}info(...t){bs[L(this,En)]>bs.info||L(this,Sn).info("[Sockrates]:",...t)}warn(...t){bs[L(this,En)]>bs.warn||L(this,Sn).warn("[Sockrates]:",...t)}error(...t){bs[L(this,En)]>bs.error||L(this,Sn).error("[Sockrates]:",...t)}}Sn=new WeakMap,En=new WeakMap;var gv=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(gv||{});const rN="2",sN="3";class nN{constructor(t,e){Ie(this,Fu),Ie(this,Ca),Ie(this,xu),Ie(this,Uu),Ie(this,id),Ie(this,$u),Ie(this,ba),Ie(this,Pa),Ie(this,cd),Ie(this,pi),Ie(this,ka),Ie(this,He,void 0),Ie(this,wn,void 0),Ie(this,Le,void 0),Ie(this,Ke,void 0),Ie(this,ws,void 0),Ie(this,ot,void 0),Ie(this,Kr,void 0),Ie(this,Cs,void 0),Ie(this,pr,void 0),Ie(this,hi,void 0),Ie(this,zr,void 0);var r,n,i,a,o,d,u,h,p,f,v,T,P,k,I,x,V,O,W;ge(this,wn,t),ge(this,ws,[]),ge(this,ot,new QO),ge(this,Kr,!0),ge(this,pr,!1),ge(this,Le,e!=null?e:{}),(n=(r=L(this,Le)).autoReconnect)!=null||(r.autoReconnect=!0),(a=(i=L(this,Le)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(d=(o=L(this,Le)).pingTimeout)!=null||(o.pingTimeout=3e4),(h=(u=L(this,Le)).connectionTimeout)!=null||(u.connectionTimeout=5e3),(f=(p=L(this,Le)).debug)!=null||(p.debug=!0),(T=(v=L(this,Le)).maxReconnectionAttempts)!=null||(v.maxReconnectionAttempts=10),(k=(P=L(this,Le)).disconnectOnPingTimeout)!=null||(P.disconnectOnPingTimeout=!0),(x=(I=L(this,Le)).queueOnDisconnect)!=null||(I.queueOnDisconnect=!1),(O=(V=L(this,Le)).flushOnReconnect)!=null||(V.flushOnReconnect=!1),ge(this,Cs,{code:void 0,reason:void 0}),ge(this,Ke,(W=L(this,Le).logger)!=null?W:new tN(L(this,Le).debug?"debug":"info")),ge(this,zr,new eN)}get readyState(){var t;return(t=L(this,He))==null?void 0:t.readyState}get url(){return L(this,wn)}updateURL(t){ge(this,wn,t),Ne(this,$u,sv).call(this)}get config(){return L(this,Le)}get sendQueue(){return L(this,ws)}flush(){if(!L(this,Le).queueOnDisconnect)return!1;const t=[];return L(this,ws).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),ge(this,ws,t),L(this,ws)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){L(this,Ke).debug("Websocket was already connecting or connected.");return}if(L(this,Kr)!==!1)return new Promise((e,r)=>{Ne(this,pi,Ra).call(this),Ne(this,ka,dd).call(this);try{ge(this,He,new WebSocket(Ne(this,Fu,ev).call(this,L(this,wn)))),L(this,He).binaryType="arraybuffer",L(this,Ke).debug("Connecting to",L(this,wn));const n=setTimeout(()=>{L(this,Ke).debug("Connection timeout. Closing socket"),ge(this,Kr,!0),Ne(this,ka,dd).call(this),L(this,He).close(3001,"Connection Timeout"),L(this,Le).autoReconnect&&!L(this,pr)&&(L(this,ot).emit("reconnecting"),Ne(this,ba,ad).call(this)),r(new Error("Connection timed out!"))},L(this,Le).connectionTimeout);L(this,He).onopen=()=>{L(this,Ke).debug(`Ready State: ${gv[L(this,He).readyState]}`),n&&clearTimeout(n),Ne(this,cd,Bu).call(this),ge(this,Cs,{code:void 0,reason:void 0}),L(this,ot).emit("connected"),L(this,Le).flushOnReconnect&&this.flush(),e()},L(this,He).onclose=i=>{try{n&&clearTimeout(n);const{code:a,reason:o}=i;r(o),L(this,Ke).debug("Socket closed. Close event:",i),L(this,Ke).debug("Connection closed code:",a),L(this,Ke).debug("Connection closed reason:",o),L(this,pr)||Ne(this,id,Vu).call(this,a,o)}catch(a){Ne(this,Ca,nd).call(this,a)}},L(this,He).onerror=i=>{Ne(this,Ca,nd).call(this,i)},L(this,He).onmessage=i=>Ne(this,xu,tv).call(this,i)}catch(n){Ne(this,Ca,nd).call(this,n,r)}})}send(t,e,r,n){const i={event:t,id:e,payload:r,metadata:n};if(L(this,Le).queueOnDisconnect&&(!L(this,He)||L(this,He).readyState!==1))return L(this,Ke).debug("Queuing message since socket is not connected!",i),L(this,ws).push(i),!1;const a=fv.encode(i);return Ne(this,Pa,od).call(this,a)}emit(t,e,r,n){return this.send(t,e,r,n)}sendRaw(t){return Ne(this,Pa,od).call(this,t)}receive(t,e){return L(this,ot).on(t.toString(),e)}on(t,e){if(typeof t=="string"&&(t==="connected"||t==="disconnected"||t==="errored"||t==="reconnected"||t==="reconnecting"||t==="reconnectAttempt"||t==="reconnectFailure"||t==="failed")){L(this,ot).on(t,e);return}this.receive(t,e)}removeAllListeners(){L(this,ot).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){L(this,ot).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){L(this,ot).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){ge(this,Kr,!1),Ne(this,pi,Ra).call(this),this.removeAllListeners(),ge(this,Cs,{code:1e3,reason:"Sockrates disconnect method called"}),L(this,He).close(1e3,"Sockrates disconnect method called.")}}He=new WeakMap,wn=new WeakMap,Le=new WeakMap,Ke=new WeakMap,ws=new WeakMap,ot=new WeakMap,Kr=new WeakMap,Cs=new WeakMap,pr=new WeakMap,hi=new WeakMap,zr=new WeakMap,Fu=new WeakSet,ev=function(s){if(s.startsWith("ws://")||s.startsWith("wss://"))return s;if(s.startsWith("https://"))return`wss://${s.substring(8)}`;if(s.startsWith("http://"))return`ws://${s.substring(7)}`;throw new Error("Invalid URL. URL must start with http(s):// or ws(s)://.")},Ca=new WeakSet,nd=function(s,t){L(this,Ke).error("Error:",{error:s}),L(this,ot).emit("errored",{error:s}),t==null||t(s)},xu=new WeakSet,tv=function(s){if(Ne(this,cd,Bu).call(this),s.data===rN){L(this,Ke).debug("Received ping from server"),Ne(this,Pa,od).call(this,sN);return}const t=fv.decode(s.data),{id:e,payload:r}=t;L(this,Ke).debug("Received message",{event:t.event,messageID:e}),L(this,ot).emit(t.event.toString(),{id:e,payload:r})},Uu=new WeakSet,rv=function(){return L(this,He).readyState===1},id=new WeakSet,Vu=function(s,t){ge(this,Cs,{reason:t,code:s}),L(this,ot).emit("disconnected",{code:s,reason:t})},$u=new WeakSet,sv=function(){const{reason:s,code:t}=L(this,Cs);t&&t!==1e3&&L(this,Kr)&&L(this,Le).autoReconnect&&!L(this,pr)&&(L(this,Ke).debug(`Triggering reconnection due to ${s}.`),L(this,ot).emit("reconnecting"),Ne(this,ba,ad).call(this))},ba=new WeakSet,ad=async function(s=!0){if(s&&L(this,pr)){L(this,Ke).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(L(this,pr)||L(this,zr).reset(),L(this,Le).maxReconnectionAttempts!==null&&L(this,zr).getAttempts()>=L(this,Le).maxReconnectionAttempts){L(this,ot).emit("failed"),ge(this,pr,!1);return}ge(this,pr,!0),Ne(this,ka,dd).call(this),Ne(this,pi,Ra).call(this);try{if(await L(this,zr).wait(),L(this,Kr)===!1)return;if(L(this,Ke).debug(`Reconnection attempt ${L(this,zr).getAttempts()}`),L(this,ot).emit("reconnectAttempt",{attempt:L(this,zr).getAttempts()}),await this.connect(),!Ne(this,Uu,rv).call(this))throw Error("Reconnect Failed");ge(this,pr,!1),ge(this,Cs,{code:void 0,reason:void 0}),L(this,ot).emit("reconnected")}catch(t){L(this,Ke).debug("Failed to reconnect."),L(this,ot).emit("reconnectFailure",{attempt:L(this,zr).getAttempts()}),Ne(this,ba,ad).call(this,!1)}},Pa=new WeakSet,od=function(s){try{return L(this,He).send(s),!0}catch(t){return L(this,Ke).error(t.message),!1}},cd=new WeakSet,Bu=function(){this.config.disconnectOnPingTimeout&&(L(this,Ke).debug("Resetting ping timeout"),Ne(this,pi,Ra).call(this),ge(this,hi,setTimeout(()=>{var s;L(this,Ke).debug("Disconnecting the socket due to ping timeout"),ge(this,Kr,!0);const t=3002,e="Ping timeout";(s=L(this,He))==null||s.close(t,e),Ne(this,id,Vu).call(this,t,e)},L(this,Le).pingTimeout)))},pi=new WeakSet,Ra=function(){L(this,hi)&&(clearTimeout(L(this,hi)),ge(this,hi,void 0))},ka=new WeakSet,dd=function(){L(this,He)&&(L(this,He).onopen=void 0,L(this,He).onerror=void 0,L(this,He).onmessage=void 0,L(this,He).onclose=void 0)};var iN=Object.defineProperty,aN=Object.getOwnPropertyDescriptor,hd=(s,t,e,r)=>{for(var n=r>1?void 0:r?aN(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&iN(t,e,n),n};const vv=65535,oN=3e3,yv=($v=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:n}){S(this,Me);S(this,po);S(this,mo);S(this,Ws,void 0);S(this,Ve,void 0);m(this,"roomName");m(this,"authToken");m(this,"capabilities");S(this,nr,void 0);S(this,os,void 0);var i;if(!t||!e||!r)throw new b("peerId, roomName, or authToken can not be empty");y(this,nr,void 0),y(this,os,s),this.capabilities=n,this.roomName=e,this.authToken=r,y(this,Ws,je(this,po,eh).call(this,t)),y(this,Ve,new nN(c(this,Ws),{autoReconnect:!0,disconnectOnPingTimeout:(i=n.includes("PING"))!=null?i:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:l})),this.handleSocketConnectionEvents()}get joinAttempted(){return c(this,Me,$e).socketJoinAttempted}set joinAttempted(s){c(this,Me,$e).socketJoinAttempted=s}get peerId(){return c(this,os).getValue("peerId")}updateURL(s){s!==this.peerId&&(y(this,Ws,je(this,po,eh).call(this,s)),l.debug("SocketService:: Connection URL updated.")),c(this,Ve).updateURL(c(this,Ws))}static getSocketEdgeDomain(s){return Xn({servicePrefix:"socket-edge",baseURI:s})}get url(){return c(this,Ws)}async connect(){c(this,Me,$e).socketJoinAttempted=!0,await c(this,Ve).connect(),c(this,Me,$e).socketJoinAttempted=!0,c(this,Me,$e).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}async disconnect(){c(this,Me,$e).socketJoinAttempted=!1,c(this,Ve).disconnect(),c(this,Me,$e).socketJoinAttempted=!0,c(this,Me,$e).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return c(this,Ve).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return g.injectContext(r),c(this,Ve).send(s,e!=null?e:je(this,mo,th).call(this),t,new TextEncoder().encode(JSON.stringify(r)))}sendMessagePromise(s,t,e,r){const n=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:s,timeout:n,protobuf:t,messageId:e,resp:r})}sendMessagePromiseWithTimeout({event:s,timeout:t,protobuf:e,messageId:r,resp:n}){const i=n!=null?n:s;return new Promise((a,o)=>{const d=(v,T)=>{c(this,Ve).removeListener(i,v),c(this,Ve).removeListener(vv,T),c(this,Ve).removeListener(se.errorResponse,T),c(this,Ve).removeListener(ne.errorResponse,T)},u=r!=null?r:je(this,mo,th).call(this),h={};g.injectContext(h);const p=({id:v,payload:T})=>{if(u===v){let P;try{const k=$P.fromBinary(T);P=new Error(k.errorMessage)}catch(k){P=new Error("failed to parse error message",{cause:k});try{const I=MR.fromBinary(T);P=new Error(I.message)}catch(I){P=new Error("failed to parse error message",{cause:I})}}o(P),d(f,p)}},f=({id:v,payload:T})=>{u===v&&(a({id:v,payload:T}),d(f,p))};c(this,Ve).on(i,f),c(this,Ve).on(vv,p),c(this,Ve).on(se.errorResponse,p),c(this,Ve).on(ne.errorResponse,p),setTimeout(()=>{d(f,p),o(new Error(`request timeout for callback eventId:${s}`))},t),c(this,Ve).send(s,u,e,new TextEncoder().encode(JSON.stringify(h)))})}on(s,t){c(this,Ve).on(s,t)}onStateEvent(s,t){c(this,Ve).on(s,t)}removeListener(s,t){c(this,Ve).removeListener(s,t)}removeListeners(s){c(this,Ve).removeListeners(s)}flush(){return c(this,Ve).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{l.info("SocketService::Connected to socket-edge"),c(this,nr)&&(clearTimeout(c(this,nr)),y(this,nr,void 0)),c(this,Me,$e).updateSocketConnectionState("connected")}),this.onStateEvent("disconnected",({code:s,reason:t})=>{var n;l.info("SocketService::Disconnected from socket-edge",{error:{code:s,reason:t}});const{consuming:e,producing:r}=(n=c(this,Me,$e).mediaState)!=null?n:{};e!=null&&e.state&&(e==null?void 0:e.state)!==Rt.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==Rt.CONNECTED?w.emit(C.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:c(this,Me,$e).joinAttempted}):y(this,nr,setTimeout(()=>{w.emit(C.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:c(this,Me,$e).joinAttempted}),y(this,nr,void 0)},oN)),c(this,Me,$e).updateSocketConnectionState("disconnected"),c(this,Me,$e).roomJoined=!1}),this.onStateEvent("reconnecting",async()=>{l.info("SocketService::Reconnecting to socket-edge"),c(this,Me,$e).updateSocketConnectionState("reconnecting")}),this.onStateEvent("reconnectAttempt",async({attempt:s})=>{l.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),c(this,Me,$e).updateSocketConnectionState("reconnectAttempt",s)}),this.onStateEvent("reconnectFailure",({attempt:s})=>{l.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),c(this,Me,$e).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",async()=>{l.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:c(this,Me,$e).joinAttempted}}),c(this,nr)&&(clearTimeout(c(this,nr)),y(this,nr,void 0)),w.emit(C.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:c(this,Me,$e).joinAttempted}),c(this,Me,$e).updateSocketConnectionState("reconnected")}),this.onStateEvent("failed",async()=>{l.info("SocketService::Failed to connect to socket-edge"),w.emit(C.SOCKET_SERVICE_FAILED),c(this,Me,$e).updateSocketConnectionState("failed"),c(this,Me,$e).roomJoined=!1})}},Ws=new WeakMap,Ve=new WeakMap,Me=new WeakSet,$e=function(){return c(this,os).getValue("connectionHandler")},nr=new WeakMap,os=new WeakMap,po=new WeakSet,eh=function(s){let t=yv.getSocketEdgeDomain(c(this,os).getValue("baseURI"));typeof Nl(c(this,os),"socket_server_base")=="string"&&(t=Nl(c(this,os),"socket_server_base"));const e=`wss://${t}`,r=new URL(`${e}/ws`),n=this.peerId,i={roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0,...n!==s&&{oldPeerID:n},ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(a=>Ic[a]).join(" "),joinWithDetails:!0};return Object.entries(i).forEach(([a,o])=>{r.searchParams.append(a,o.toString())}),r.href},mo=new WeakSet,th=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},$v);let Ia=yv;hd([g.trace("SocketService.connect")],Ia.prototype,"connect",1),hd([g.trace("SocketService.disconnect")],Ia.prototype,"disconnect",1),hd([g.trace("SocketService.sendMessagePromise")],Ia.prototype,"sendMessagePromise",1),hd([g.trace("SocketService.sendMessagePromiseWithTimeout")],Ia.prototype,"sendMessagePromiseWithTimeout",1);const Ks=class{static handleConnectedRoomsDumpRaw({payload:t}){var i;const e=nk.fromBinary(t),r=e.meetings.map(a=>{var o;return{id:a.id,title:a.title,participants:(o=a.participants)!=null?o:[]}});return{parentMeeting:{id:e.parentMeeting.id,title:e.parentMeeting.title,participants:(i=e.parentMeeting.participants)!=null?i:[]},meetings:r}}static handleTransferPeerRaw({payload:t}){const e=Ak.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}static handleMovedPeerRaw({payload:t}){const e=Hf.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}static handleConnectedRoomsUpdatedRaw({payload:t}){return Bf.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}static handleConnectedRoomsDeletedRaw({payload:t}){return _k.fromBinary(t).payloads}static async getConnectedRoomsDump(){const t=await Ks.socketService.sendMessagePromise($.getConnectedRoomsDump);return Ks.handleConnectedRoomsDumpRaw(t)}static async createConnectedRooms(t){const{payload:e}=await Ks.socketService.sendMessagePromise($.createConnectedRooms,ck.toBinary({payloads:t}));return Bf.fromBinary(e).payloads.map(n=>({id:n.id,title:n.title}))}static async updateConnectedRooms(t){}static async disableConnectedRooms(t){const e=t.map(n=>({id:n})),r=await Ks.socketService.sendMessagePromise($.deleteConnectedRooms,yk.toBinary({payloads:e}));return Ks.handleConnectedRoomsDeletedRaw(r)}static async movePeersBetweenRooms(t){try{const e=await Ks.socketService.sendMessagePromise($.movePeers,Pk.toBinary({sourceMeetingId:t.sourceMeetingId,destinationMeetingId:t.destinationMeetingId,participants:t.participants}));return new TextDecoder().decode(e.payload).includes("error")?{success:!1,error:"failed to move participants"}:{success:!0}}catch(e){return{success:!1,error:e}}}};let Ae=Ks;m(Ae,"socketService"),m(Ae,"currentMeetingId");var cN=Object.defineProperty,dN=Object.getOwnPropertyDescriptor,pd=(s,t,e,r)=>{for(var n=r>1?void 0:r?dN(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&cN(t,e,n),n};const Cn=class{constructor(s,t){m(this,"apiBase");m(this,"selfController");m(this,"pollController");m(this,"chatController");m(this,"metaController");m(this,"storesManager");m(this,"stageController");m(this,"pluginController");m(this,"internalsController");m(this,"recordingController");m(this,"livestreamController");m(this,"participantController");this.apiBase=s,this.storesManager=t.storesManager,this.metaController=t.metaController,this.selfController=t.selfController,this.chatController=t.chatController,this.pollController=t.pollController,this.stageController=t.stageController,this.pluginController=t.pluginController,this.recordingController=t.recordingController,this.internalsController=t.internalsController,this.participantController=t.participantController,this.livestreamController=t.livestreamController}static async init(s){var x;const{peerId:t,apiBase:e,authToken:r,meetingId:n,organizationId:i,cachedUserDetails:a}=s.getAllValues();if(w.reset(),rd.cleanup(),Qg(s),Se.isSupported()===!1)throw new b("Browser not supported","0010",!0);const o=HM(s,{authToken:r,baseURL:e,cachedUserDetails:a});o.setRoomName(n),o.setRoomUUID(n),o.setOrganizationId(i),o.setHeader("dyte-tracing-id",t),s.setValue("apiClient",o);const d=new C0;s.setValue("connectionHandler",d);const u=Cn.createSocketService(s),h=u.connect(),p=o.getPlugins(),[{sfu:f,userResponse:v,meetingTitle:T,roomNodeUrl:P}]=await Promise.all([Cn.getRoomMetadata(),Cn.setupFlagsmith(s)]);g.location.country=(x=o.ipInfo)==null?void 0:x.country,s.setValue("roomNodeOptions",{sfu:f,meetingTitle:T,roomNodeUrl:P});const{theme:k,controllers:I}=await Cn.setupControllers(u,s,v,p);p0(k)&&Cn.createRoomNodeClient(s,u),vb();try{await h,I.selfController.partialMediaRoom()}catch(V){throw l.error("[Socket Service] Failed to connect to socket server:",{error:V}),new b("Failed to connect to websocket","0012")}return new Cn(e,I)}static async getRoomMetadata(){const s=We(),[{roomNodeUrl:t,meetingTitle:e,sfu:r=li.HIVE},n]=await Promise.all([s.getRoomNodeData(),s.getUserDetails()]);return{sfu:r,roomNodeUrl:t,meetingTitle:e,userResponse:n}}static async setupFlagsmith(s){const{peerId:t,baseURI:e,overrides:r,meetingId:n,organizationId:i}=s.getAllValues(),a=fb(n),o={entity:Dl.PEER,clientId:i,isAnonUser:!i,sdkVersion:s.getValue("sdkVersion"),meetingHash:a,roomName:n,...Se.getDeviceInfo(),isReactNative:navigator.isReactNative};try{const d=r!=null&&r.whitelabelled_flags_endpoint?Xn({servicePrefix:"flags",baseURI:e}):"edge.api.flagsmith.com";await J.identify(`${Dl.PEER}_${t}`,JSON.parse(JSON.stringify(o)),!1,5e3,d),l.info("flagsmith::allFlags",{flags:JSON.stringify(J.getAllFlags())},!0)}catch(d){l.error("Failed to fetch flagsmith flags")}}static async setupControllers(s,t,e,r){var G,A,rt;const n=t.getValue("modules"),{preset:i,participant:a}=e,o=t.getValue("defaults"),{sfu:d,meetingTitle:u}=t.getValue("roomNodeOptions"),h=_u.init(i,!n.theme),{viewType:p,mediaConstraints:{audio:f}}=h;t.setValue("viewType",p),t.setValue("defaults",{mediaConfiguration:{audio:{enableHighBitrate:(G=f.enableHighBitrate)!=null?G:!1,enableStereo:(A=f.enableStereo)!=null?A:!1}},...o});const v=Du.init(t,p,i.permissions);let T,P,k,I,x,V,O,W;const Q=new xO(s);Ae.socketService=s;const oe=new sd(s),ve=new Qt(s),Mt=new $O(s),Fe=rd.create(s),Dt=new BO(s),M=new FO(s),E=new dn(s),R=await Ss.init(t,Fe,a,v,h),B=await lg.init(t,R.self,Fe,Q,u);if(n.participant&&(d===li.CF&&(W=new Jg(t,R.self,Fe)),W=new Wg(t,R.self,Fe)),(rt=n.e2ee)!=null&&rt.enabled&&n.e2ee.manager.init(l,w),n.chat&&(P=await ur.init(t,ve,E,R.self,W.participants)),n.internals&&(x=await pu.init()),n.livestream&&h.viewType===Xe.Livestream&&J.hasFeature(X.LIVESTREAM)&&(O=new Mg(R.self,M)),h.viewType!==Xe.Chat){if(n.poll&&(T=await ag.init(t,R.self,oe)),n.recording&&(V=new fg(t,R.self,Fe)),n.stage&&(k=new ug(t,Mt,Fe,R.self,W.participants)),n.plugin){if(!W)throw new b("The plugin module cannot be initialized without the `participant` module");const cs=await r;I=await ga.init(t,cs,Dt,ve,P==null?void 0:P.chat,R.self,W.participants)}if(n.pip){const cs=await Ll._init(t,R.self);t.setValue("pip",cs)}}const Qe={storesManager:new ED(t,Dt),pollController:T,selfController:R,metaController:B,chatController:P,stageController:k,pluginController:I,recordingController:V,internalsController:x,livestreamController:O,participantController:W};return{theme:h,permissions:v,controllers:Qe}}static async createRoomNodeClient(s,t){const{peerId:e,meetingId:r,authToken:n,roomNodeOptions:i}=s.getAllValues(),{sfu:a,roomNodeUrl:o,meetingTitle:d}=i;return Yg(s,{socket:t,peerId:e,meetingId:r,authToken:n,roomNodeUrl:o,meetingTitle:d},a)}static createSocketService(s){const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),n=["PING"];return new Ia(s,{peerId:t,meetingId:e,authToken:r,capabilities:n})}};let Aa=Cn;pd([g.trace("Controller.init")],Aa,"init",1),pd([g.trace("setupFlagsmith")],Aa,"setupFlagsmith",1),pd([g.trace("Controller.createSocketServiceAndRoomNodeClient")],Aa,"createRoomNodeClient",1),pd([g.trace("Controller.createSocketService")],Aa,"createSocketService",1);var lN=Object.defineProperty,uN=Object.getOwnPropertyDescriptor,hN=(s,t,e,r)=>{for(var n=r>1?void 0:r?uN(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&lN(t,e,n),n};class Tv extends Ht{constructor(e,r){super();S(this,fo,void 0);m(this,"meetings",[]);m(this,"parentMeeting",null);S(this,Md,void 0);y(this,Md,e),y(this,fo,r.self)}get supportsConnectedMeetings(){return c(this,fo).id!==""}get isActive(){return this.meetings.length!==0}get currentMeetingId(){return Ae.currentMeetingId}validateConnectedMeetingsAction(){if(!this.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action. +`}return{offerSdp:o,callback:async h=>(l.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(h)}]`),await this._pc.setRemoteDescription(h),this.midTransceiverMap.set(a.mid,a),a.mid),sender:a.sender,mid:a.mid}}async stopSending(e){this._assertSendDirection(),l.debug(`stopSending() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.sender.replaceTrack(null),this._pc.removeTrack(r.sender),r.direction="inactive";const n=await this._pc.createOffer();return l.debug(`stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),await this._pc.setLocalDescription(n),{offerSdp:n,callback:async a=>{l.debug(`stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(a)}]`),await this._pc.setRemoteDescription(a),this.midTransceiverMap.delete(e)}}}async replaceTrack(e,r){this._assertSendDirection(),r?l.debug(`replaceTrack() [localId:${e}, track.id:${r.id}]`):l.debug(`replaceTrack() [localId:${e}, no track]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");await n.sender.replaceTrack(r)}async setMaxSpatialLayer(e,r){this._assertSendDirection(),l.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((a,o)=>{o<=r?a.active=!0:a.active=!1}),await n.sender.setParameters(i)}async setRtpEncodingParameters(e,r){this._assertSendDirection(),l.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((a,o)=>{i.encodings[o]={...a,...r}}),await n.sender.setParameters(i)}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.sender.getStats()}async stopReceiving(e){throw this._assertRecvDirection(),l.debug(`stopReceiving() [localId:${e}]`),Error("method not implemented")}async pauseReceiving(e){throw this._assertRecvDirection(),l.debug(`pauseReceiving() [localId:${e}]`),Error("method not implemented")}async resumeReceiving(e){throw this._assertRecvDirection(),l.debug(`resumeReceiving() [localId:${e}]`),Error("method not implemented")}async getReceiverStats(e){this._assertRecvDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.receiver.getStats()}_assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}_assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}async _generateOffer(){const e=await this._pc.createOffer();return await this._pc.setLocalDescription(e),e}async _setAnswer(e){l.debug(`setAnswer() | calling pc.setRemoteDescription() [answer:${JSON.stringify(e)}]`),await this._pc.setRemoteDescription(e)}_addEventListeners(){this._pc.addEventListener("iceconnectionstatechange",()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected"),this._transportReady=!0;break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed");break;default:l.warn("unknown state");break}}),this._pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this._pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),l.debug("negotiationneeded")}),this._pc.addEventListener("icegatheringstatechange",()=>{switch(this._pc.iceGatheringState){case"gathering":l.debug("icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":l.debug("icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:l.warn("unknown state");break}}),this._pc.addEventListener("icecandidateerror",e=>{l.error("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})}),this._pc.addEventListener("datachannel",e=>{l.info("data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:r}=e;r.onopen=()=>{l.info("data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},r.onclose=()=>{l.warn("data channel closed: ",{rtcChannel:{label:e.channel.label}})},r.onerror=()=>{l.error("data channel error: ",{rtcChannel:{label:e.channel.label}})},r.onmessage=n=>{this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(n.data)))}})}}class ed extends ku{constructor(e){super();m(this,"_direction");m(this,"_pc");m(this,"_sendWebStream",new MediaStream);m(this,"_sendScreenShareStream",new MediaStream);m(this,"_transportReady",!1);m(this,"supportsSendEncodings",!1);this.supportsSendEncodings=e.supportsSendEncodings}static createFactory(e){return()=>new ed(e)}get name(){return"Firefox60"}get pc(){return this._pc}close(){if(l.debug("Firefox60::close()"),this._pc)try{this._pc.close()}catch(e){l.error("Firefox60::pc.close()",{error:e})}}init({direction:e,iceServers:r,iceTransportPolicy:n,additionalSettings:i,proprietaryConstraints:a,onTrackHandler:o}){l.debug("Firefox60::init()"),this._direction=e,this._pc=new RTCPeerConnection({iceServers:r||[],iceTransportPolicy:n||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...i},a),o&&this._pc.addEventListener("track",d=>{o(d)}),this._addEventListeners()}async connect(){const e=this._pc.createDataChannel("dyte"),r=await this._pc.createOffer();return l.info(`Firefox60::connect offer: ${JSON.stringify(r)}`),await this._pc.setLocalDescription(r),{offerSdp:r,callback:async i=>{l.debug(`Firefox60::connect() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),await this._pc.setRemoteDescription(i),e.close()}}}async updateIceServers(e){throw l.debug("Firefox60::updateIceServers()"),new Error("not supported")}async restartIce(){l.debug("Firefox60::restartIce()");const e=await this.pc.createOffer({iceRestart:!0});return l.debug(`Firefox60::restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:async n=>{l.info(`Firefox60::restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(n)}]`),await this._pc.setRemoteDescription(n)}}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:r,screenShare:n}){this._assertSendDirection(),l.debug(`Firefox60::send() [kind:${e.kind}, track.id:${e.id}]`),l.debug("Firefox60::creating new transceiver");const i=this.supportsSendEncodings&&r!==void 0?{sendEncodings:r}:{},a=this._pc.addTransceiver(e,{direction:"sendonly",streams:[n?this._sendScreenShareStream:this._sendWebStream],...i});if(!this.supportsSendEncodings&&r){r.reverse();const u=a.sender.getParameters();u.encodings=r,await a.sender.setParameters(u)}const o=await this._pc.createOffer();if(!this._transportReady)throw new Error("webrtc transport not connected");if(await this._pc.setLocalDescription(o),e.kind==="audio"){const u=this._enableStereo,h=this._enableHighBitrate?u?128e3:64e3:u?64e3:32e3;o.sdp=o.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;usedtx=1${this.supportsSendEncodings?"":`${u?"":";stereo=1;sprop-stereo=1"};maxaveragebitrate=${h}`}`)}return{offerSdp:o,callback:async u=>(l.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(u)}]`),await this._pc.setRemoteDescription(u),this.midTransceiverMap.set(a.mid,a),a.mid),sender:a.sender,mid:a.mid}}async stopSending(e){this._assertSendDirection(),l.debug(`Firefox60::stopSending() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated transceiver not found");r.sender.replaceTrack(null),this._pc.removeTrack(r.sender),r.direction="inactive";const n=await this._pc.createOffer();return l.debug(`stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),await this._pc.setLocalDescription(n),{offerSdp:n,callback:async a=>{l.debug(`stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(a)}]`),await this._pc.setRemoteDescription(a),this.midTransceiverMap.delete(e)}}}async replaceTrack(e,r){this._assertSendDirection(),r?l.debug(`replaceTrack() [localId:${e}, track.id:${r.id}]`):l.debug(`Firefox60::replaceTrack() [localId:${e}, no track]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");await n.sender.replaceTrack(r)}async setMaxSpatialLayer(e,r){this._assertSendDirection(),l.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters(),a=i.encodings.length-1-r;i.encodings.forEach((o,d)=>{d>=a?o.active=!0:o.active=!1}),await n.sender.setParameters(i)}async setRtpEncodingParameters(e,r){this._assertSendDirection(),l.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((a,o)=>{i.encodings[o]={...a,...r}}),await n.sender.setParameters(i)}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.sender.getStats()}async stopReceiving(e){this._assertRecvDirection(),l.debug(`Firefox60::stopReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="inactive",l.info(`Firefox60::active transcievers: ${JSON.stringify(this._pc.getTransceivers())}`);const n=await this._pc.createOffer();return l.debug(`Firefox60::stopRecieving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),await this._pc.setLocalDescription(n),{offerSdp:n,callback:async a=>{l.debug(`Firefox60::stopRecieving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(a)}]`),await this._pc.setRemoteDescription(a),this.midTransceiverMap.delete(e)}}}async pauseReceiving(e){this._assertRecvDirection(),l.debug(`Firefox60::pauseReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="inactive";const n=await this._pc.createOffer();return l.debug(`pauseReceiving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),await this._pc.setLocalDescription(n),{offerSdp:n,callback:async a=>{l.debug(`pauseReceiving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(a)}]`),await this._pc.setRemoteDescription(a)}}}async resumeReceiving(e){this._assertRecvDirection(),l.debug(`Firefox60::resumeReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="recvonly";const n=await this._generateOffer();return l.debug(`resumeReceiving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),{offerSdp:n,callback:async a=>{l.debug(`resumeReceiving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(a)}]`),await this._pc.setRemoteDescription(a)}}}async getReceiverStats(e){this._assertRecvDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.receiver.getStats()}_assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}_assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}async _generateOffer(){const e=await this._pc.createOffer();return await this._pc.setLocalDescription(e),e}async _setAnswer(e){l.debug(`_setAnswer() | calling pc.setRemoteDescription() [answer:${JSON.stringify(e)}]`),await this._pc.setRemoteDescription(e)}_addEventListeners(){this._pc.addEventListener("datachannel",e=>{l.info("Firefox60::data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:r}=e;r.onopen=()=>{l.info("Firefox60::data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},r.onclose=()=>{l.warn("data channel closed: ",{rtcChannel:{label:e.channel.label}})},r.onerror=()=>{l.error("Firefox60::data channel error: ",{rtcChannel:{label:e.channel.label}})},r.onmessage=async n=>{const i=await n.data.arrayBuffer();this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(i)))}}),this._pc.addEventListener("iceconnectionstatechange",()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected"),this._transportReady=!0;break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed");break;default:l.warn("unknown state");break}}),this._pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this._pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),l.debug("Firefox60::negotiationneeded")}),this._pc.addEventListener("icegatheringstatechange",()=>{switch(this._pc.iceGatheringState){case"gathering":l.debug("Firefox60::icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":l.debug("Firefox60::icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:l.warn("unknown state");break}}),this._pc.addEventListener("icecandidateerror",e=>{l.error("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})})}}class Au extends ku{constructor(){super();m(this,"_direction");m(this,"_pc");m(this,"_sendWebStream",new MediaStream);m(this,"_sendScreenShareStream",new MediaStream);m(this,"_transportReady",!1)}static createFactory(){return()=>new Au}get name(){return"Chrome74"}get pc(){return this._pc}close(){if(l.debug("Safari12::close()"),this._pc)try{this._pc.close()}catch(e){l.error("Safari12::pc.close()",e)}}init({direction:e,iceServers:r,iceTransportPolicy:n,additionalSettings:i,proprietaryConstraints:a,onTrackHandler:o}){l.debug("Safari12::init()"),this._direction=e,this._pc=new RTCPeerConnection({iceServers:r||[],iceTransportPolicy:n||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...i},a),o&&this._pc.addEventListener("track",d=>{o(d)}),this._addEventListeners()}async connect(){const e=this._pc.createDataChannel("dyte"),r=await this._pc.createOffer();return l.info(`Safari12::connect offer: ${JSON.stringify(r)}`),await this._pc.setLocalDescription(r),{offerSdp:r,callback:async i=>{l.debug(`Safari12::connect() | calling pc.setRemoteDescription() [answer: ${JSON.stringify(i)}]`),await this._pc.setRemoteDescription(i),e.close()}}}async updateIceServers(e){l.debug("Safari12::updateIceServers()");const r=this._pc.getConfiguration();r.iceServers=e,this._pc.setConfiguration(r)}async restartIce(){l.debug("Safari12::restartIce()");const e=await this.pc.createOffer({iceRestart:!0});return l.debug(`restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:async n=>{l.info(`restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(n)}]`),await this._pc.setRemoteDescription(n)}}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:r,codecOption:n,screenShare:i}){var p;this._assertSendDirection(),l.debug(`Safari12::send() [kind: ${e.kind}, track.id: ${e.id}]`),l.debug("Safari12::creating new transceiver");const a=this._pc.addTransceiver(e,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:r}),o=RTCRtpSender.getCapabilities(e.kind);l.info(`Safari12::senders available params: ${JSON.stringify(o)}`);const d=[];if(n){const f=o.codecs.find(v=>v.mimeType.includes(n.name));if(n.parameters){l.info(`Safari12::codecOption.parameters:, ${JSON.stringify(n.parameters)}`);const v=((p=f.sdpFmtpLine)==null?void 0:p.split(";"))||[];v.push(...n.parameters);const T=[...new Set(v).values()];f.sdpFmtpLine=T.join(";")}d.push(f)}l.info(`Safari12::selected codecs: ${JSON.stringify(d)}`),a.setCodecPreferences(d);const u=await this._pc.createOffer();if(!this._transportReady)throw new Error("webrtc transport not connected");if(await this._pc.setLocalDescription(u),e.kind==="audio"){const f=this._enableStereo,v=this._enableHighBitrate?f?128e3:64e3:f?64e3:32e3;u.sdp=u.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;usedtx=1${f?"":";stereo=1;sprop-stereo=1"};maxaveragebitrate=${v}`)}return{offerSdp:u,callback:async f=>(l.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(f)}]`),await this._pc.setRemoteDescription(f),this.midTransceiverMap.set(a.mid,a),a.mid),sender:a.sender,mid:a.mid}}async stopSending(e){this._assertSendDirection(),l.debug(`Safari12::stopSending() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.sender.replaceTrack(null),this._pc.removeTrack(r.sender),r.direction="inactive";const n=await this._pc.createOffer();return l.debug(`Safari12::stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),await this._pc.setLocalDescription(n),{offerSdp:n,callback:async a=>{l.debug(`Safari12::stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(a)}]`),await this._pc.setRemoteDescription(a),this.midTransceiverMap.delete(e)}}}async replaceTrack(e,r){this._assertSendDirection(),r?l.debug(`Safari12::replaceTrack() [localId:${e}, track.id:${r.id}]`):l.debug(`Safari12::replaceTrack() [localId:${e}, no track]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");await n.sender.replaceTrack(r)}async setMaxSpatialLayer(e,r){this._assertSendDirection(),l.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((a,o)=>{o<=r?a.active=!0:a.active=!1}),await n.sender.setParameters(i)}async setRtpEncodingParameters(e,r){this._assertSendDirection(),l.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((a,o)=>{i.encodings[o]={...a,...r}}),await n.sender.setParameters(i)}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.sender.getStats()}async receive(e){this._assertRecvDirection(),l.debug(`recieve() | calling pc.setLocalDescription() [answer:${JSON.stringify(e)}]`);const r=this._pc.getTransceivers().at(-1);return l.info("Safari12::Transceiver is now receiving"),this.midTransceiverMap.set(r.mid,r),{track:r.receiver.track,localId:r.mid}}async stopReceiving(e){this._assertRecvDirection(),l.debug(`Safari12::stopReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="inactive",l.info(`Safari12::active transcievers: ${JSON.stringify(this._pc.getTransceivers())}`);const n=await this._pc.createOffer();return l.debug(`stopRecieving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),await this._pc.setLocalDescription(n),{offerSdp:n,callback:async a=>{l.debug(`stopRecieving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(a)}]`),await this._pc.setRemoteDescription(a),this.midTransceiverMap.delete(e)}}}async pauseReceiving(e){this._assertRecvDirection(),l.debug(`Safari12::pauseReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="inactive";const n=await this._pc.createOffer();return l.debug(`pauseReceiving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),await this._pc.setLocalDescription(n),{offerSdp:n,callback:async a=>{l.debug(`pauseReceiving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(a)}]`),await this._pc.setRemoteDescription(a)}}}async resumeReceiving(e){this._assertRecvDirection(),l.debug(`Safari12::resumeReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="recvonly";const n=await this._generateOffer();return l.debug(`Safari12::resumeReceiving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),{offerSdp:n,callback:async a=>{l.debug(`Safari12::resumeReceiving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(a)}]`),await this._pc.setRemoteDescription(a)}}}async getReceiverStats(e){this._assertRecvDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.receiver.getStats()}_assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}_assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}async _generateOffer(){const e=await this._pc.createOffer();return await this._pc.setLocalDescription(e),e}async _setAnswer(e){l.debug(`Safari12::_setAnswer() | calling pc.setRemoteDescription() [answer:${JSON.stringify(e)}]`),await this._pc.setRemoteDescription(e)}_addEventListeners(){this._pc.addEventListener("iceconnectionstatechange",()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected"),this._transportReady=!0;break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed");break;default:l.warn("Safari12::unknown state");break}}),this._pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this._pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),l.debug("Safari12::negotiationneeded")}),this._pc.addEventListener("icegatheringstatechange",()=>{switch(this._pc.iceGatheringState){case"gathering":l.debug("Safari12::icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":l.debug("Safari12::icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:l.warn("Safari12::unknown state");break}}),this._pc.addEventListener("icecandidateerror",e=>{l.error("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})}),this._pc.ondatachannel=e=>{l.info("Safari12::data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:r}=e;r.onopen=()=>{l.info("Safari12::data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},r.onclose=()=>{l.warn("Safari12::data channel closed: ",{rtcChannel:{label:e.channel.label}})},r.onerror=()=>{l.error("Safari12::data channel error: ",{rtcChannel:{label:e.channel.label}})},r.onmessage=async n=>{const i=String.fromCharCode(...new Uint8Array(n.data));this.safeEmit("datachannel",e.channel,i)}}}}function YD(){if(typeof navigator=="object"&&navigator.product==="ReactNative"){if(typeof RTCPeerConnection=="undefined"){l.warn("Device::this._detectDevice() | unsupported ReactNative without RTCPeerConnection");return}return l.debug("Device::this._detectDevice() | ReactNative handler chosen"),"Chrome74"}if(typeof navigator=="object"&&typeof navigator.userAgent=="string"){const s=navigator.userAgent,t=Rm.getParser(s),e=t.getEngine();if(t.satisfies({chrome:">=74",chromium:">=74","microsoft edge":">=88"}))return"Chrome74";if(t.satisfies({chrome:">=70",chromium:">=70"}))return"Chrome70";if(t.satisfies({chrome:">=67",chromium:">=67"}))return"Chrome67";if(t.satisfies({chrome:">=55",chromium:">=55"}))return"Chrome55";if(t.satisfies({firefox:">=110"}))return"Firefox110";if(t.satisfies({firefox:">=60"}))return"Firefox60";if(t.satisfies({ios:{OS:">=14.3",firefox:">=30.0"}})||t.satisfies({safari:">=12.0"})&&typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(t.satisfies({safari:">=11"}))return"Safari11";if(t.satisfies({"microsoft edge":">=11"})&&t.satisfies({"microsoft edge":"<=18"}))return"Edge11";if(e.name&&e.name.toLowerCase()==="blink"){const r=s.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);if(r){const n=Number(r[1]);return n>=74?"Chrome74":n>=70?"Chrome70":n>=67?"Chrome67":"Chrome55"}return"Chrome74"}if(e.name.toLowerCase()==="webkit"&&t.getOS().name.toLowerCase()==="ios")return typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection")?"Safari12":"Safari11";l.warn("Device::this._detectDevice() | browser not supported");return}l.warn("Device::this._detectDevice() | unknown device")}class qg{constructor({handlerName:t,handlerFactory:e}={}){m(this,"handlerFactory");m(this,"_handlerName");m(this,"_observer");if(l.debug("constructor()"),t&&e)throw new TypeError("just one of handlerName or handlerInterface can be given");if(e)this.handlerFactory=e;else{if(t)l.debug(`Device::constructor() | handler given: ${t}`);else if(t=YD(),t)l.debug(`Device::constructor() | detected handler: ${t}`);else throw new Error("device not supported");switch(t){case"Chrome74":this.handlerFactory=Iu.createFactory();break;case"Safari12":this.handlerFactory=Au.createFactory();break;case"Firefox60":this.handlerFactory=ed.createFactory({supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=ed.createFactory({supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${t}"`)}}const r=this.handlerFactory();this._handlerName=r.name,r.close(),this._observer=new de}get handlerName(){return this._handlerName}createSendTransport({iceServers:t,iceTransportPolicy:e,additionalSettings:r,proprietaryConstraints:n,appData:i,config:a}){return l.debug("Device::createSendTransport()"),this.createTransport({direction:"send",iceServers:t,iceTransportPolicy:e,additionalSettings:r,proprietaryConstraints:n,appData:i,config:a})}createRecvTransport({iceServers:t,iceTransportPolicy:e,additionalSettings:r,proprietaryConstraints:n,appData:i}){return l.debug("Device::createRecvTransport()"),this.createTransport({direction:"recv",iceServers:t,iceTransportPolicy:e,additionalSettings:r,proprietaryConstraints:n,appData:i})}}let QD=class extends qg{createTransport({direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:a,config:o}){const d=Xs(),u=new zD({id:d,direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:a,handlerFactory:this.handlerFactory,config:o});return this._observer.emit("newtransport",u),u}};class XD{constructor(t){S(this,_t,void 0);y(this,_t,t)}async joinRoom(t,e,r=!1,n=null){const i={roomUuid:t,displayName:e,prejoined:r};return n&&(i.location=n),(await c(this,_t).sendMessagePromiseWithTimeout({event:se.joinRoom,protobuf:af.toBinary(i),timeout:5e3})).payload}async connectTransport(t){const e=(await c(this,_t).sendMessagePromise(se.createWebRTCTransport,Zm.toBinary(t))).payload,{transportId:r,description:n}=Hl.fromBinary(e),i={sdp:n==null?void 0:n.sdp,type:n.type};return{transportId:r,answer:i}}async produce(t){var i,a;const e=(await c(this,_t).sendMessagePromise(se.produce,lf.toBinary(t))).payload,r=Ef.fromBinary(e);return{answer:{sdp:(i=r==null?void 0:r.description)==null?void 0:i.sdp,type:(a=r==null?void 0:r.description)==null?void 0:a.type},producerId:r.producerId}}async consume(t){const e=(await c(this,_t).sendMessagePromise(se.consume,df.toBinary(t))).payload,{consumerIdsMap:{map:r}}=Sf.fromBinary(e);return r}async closeProducer(t){const e=(await c(this,_t).sendMessagePromise(se.closeProducer,hf.toBinary(t))).payload,{description:r}=wf.fromBinary(e);return r}async closeConsumer(t){return(await c(this,_t).sendMessagePromise(se.closeConsumer,pf.toBinary(t))).payload}async hostControlForPeer(t,e){const r={audio:e==="audio",screeShare:!1,video:e==="video",participantId:t},n=(await c(this,_t).sendMessagePromise(se.hostControlPeer,gf.toBinary(r))).payload;if(!n)return!1;const{status:i}=Pf.fromBinary(n);return i==="success"}async hostControlForAll(t){const e={audio:t==="audio",screenShare:!1,video:t==="video"},r=(await c(this,_t).sendMessagePromise(se.hostControlAllPeers,vf.toBinary(e))).payload;if(!r)return!1;const{status:n}=Rf.fromBinary(r);return n==="success"}async kickAll(){const t={},e=(await c(this,_t).sendMessagePromise(se.kickAll,ql.toBinary(t))).payload;if(!e)return!1;const{status:r}=bf.fromBinary(e);return r==="success"}async kickPeer(t){const e=(await c(this,_t).sendMessagePromise(se.kickPeer,mf.toBinary(t))).payload;if(!e)return!1;const{status:r}=Cf.fromBinary(e);return r==="success"}async changeDisplayName(t){const e=(await c(this,_t).sendMessagePromise(se.changeDisplayName,ff.toBinary(t))).payload;if(!e)return!1;const{status:r}=kf.fromBinary(e);return r==="success"}async notifySelfJoinComplete(){const t={},e=(await c(this,_t).sendMessagePromise(se.selfJoinComplete,of.toBinary(t))).payload;return Rc.fromBinary(e)}}_t=new WeakMap;var Rt=(s=>(s.NEW="new",s.CONNECTING="connecting",s.RECONNECTING="reconnecting",s.DISCONNECTED="disconnected",s.CONNECTED="connected",s.FAILED="failed",s))(Rt||{}),li=(s=>(s[s.HIVE=1]="HIVE",s[s.ROOM_NODE=2]="ROOM_NODE",s[s.CF=3]="CF",s))(li||{});const ZD=2e3;class eO extends Fg{constructor(e,r){super();S(this,Vn);m(this,"_device");m(this,"_sendTransport");m(this,"_recvTransport");m(this,"_consumers");m(this,"_producers");m(this,"_producerStatus");m(this,"_producerIdToConsumerIdMap");m(this,"_socket");m(this,"_socketHandler");m(this,"_totalTransportReconnectionCount");m(this,"_transportReconnectFailureCount");m(this,"_consumerCreationFailureCount");m(this,"_producerNotReadyFailureCount");m(this,"_consumerNotBoundFailureCount");m(this,"_transportDisconnectedTimer");m(this,"_iceTransportPolicy","all");m(this,"_transportConnectionFailCount",0);m(this,"lastConnectionTime",0);m(this,"transportConnectionStatus");m(this,"transportState");m(this,"transportDisconnected");S(this,Ar,void 0);y(this,Ar,e),this._device=new QD({}),this._socket=r,c(this,Vn,No).mediaState={consuming:{state:Rt.NEW,reconnected:!1},producing:{state:Rt.NEW,reconnected:!1}},this.transportDisconnected={consuming:!1,producing:!1},this._socketHandler=new XD(r),this.reset()}get socket(){return this._socket}get producers(){return this._producers}get consumers(){return this._consumers}get producerIdToConsumerIdMap(){return this._producerIdToConsumerIdMap}get hiveSocketHandler(){return this._socketHandler}get sendTransport(){return this._sendTransport}get recvTransport(){return this._recvTransport}reset(){this._producers=new Map,this._consumers=new Map,this._producerStatus=new Map,this._producerIdToConsumerIdMap=new Map,this._transportReconnectFailureCount=0,this._consumerCreationFailureCount=0,this._totalTransportReconnectionCount=0,this._producerNotReadyFailureCount=0,this._consumerNotBoundFailureCount=0,this._transportDisconnectedTimer={consuming:void 0,producing:void 0}}async setupTransports(e){var a,o,d,u,h,p,f,v;const n=await We().getICEServers().catch(T=>(l.warn(`failed to get iceservers from server: ${T.message}`),[])),i=[];if(e.send){const T=this.createSendTransport({iceServers:n,additionalSettings:{encodedInsertableStreams:(a=c(this,Ar).getValue("modules").e2ee)==null?void 0:a.enabled},config:{enableHighBitrate:(u=(d=(o=c(this,Ar).getValue("defaults").mediaConfiguration)==null?void 0:o.audio)==null?void 0:d.enableHighBitrate)!=null?u:!1,enableStereo:(f=(p=(h=c(this,Ar).getValue("defaults").mediaConfiguration)==null?void 0:h.audio)==null?void 0:p.enableStereo)!=null?f:!1},iceTransportPolicy:this._iceTransportPolicy});i.push(T)}if(e.recv){const T=this.createRecvTransport({iceServers:n,additionalSettings:{encodedInsertableStreams:(v=c(this,Ar).getValue("modules").e2ee)==null?void 0:v.enabled},iceTransportPolicy:this._iceTransportPolicy});i.push(T)}await Promise.all(i)}stopAllTransports(){var e,r,n,i;l.info("closing all the transports"),(e=this._sendTransport)==null||e.close(),(r=this._sendTransport)==null||r.removeAllListeners(),(n=this._recvTransport)==null||n.close(),(i=this._recvTransport)==null||i.removeAllListeners(),this._sendTransport=void 0,this._recvTransport=void 0,this.reset()}async createSendTransport(e){var n,i,a,o;if(this._sendTransport&&this._sendTransport.connected){l.info("sendTransport::already_exists_in_connected_state",{transport:{id:(n=this._sendTransport)==null?void 0:n.id,serverId:(i=this._sendTransport)==null?void 0:i.serverId,type:"send"}});return}l.info("sendTransport::initializing_transport",{transport:{id:(a=this._sendTransport)==null?void 0:a.id,serverId:(o=this._sendTransport)==null?void 0:o.serverId,type:"send"}});const r=this._device.createSendTransport(e);this._transportDisconnectedTimer.producing=void 0,l.info("sendTransport::initialized_transport",{transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"send"}}),this.handleTransport(r,!1),l.info("sendTransport::connecting_transport",{transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"send"}});try{await br(async(d,u)=>{this.socket.isConnected||u(new Error("socket is not connected")),r.connectionState==="closed"&&u(new Error("transport is closed")),d>0&&l.debug(`retrying transport connect, count: ${d}`,{transport:{id:r.id,serverId:r.serverId,type:"send"}});try{await r.connect()}catch(h){throw l.error(`failed to connect send transport: ${r.id}`,{error:h,transport:{id:r.id,serverId:r.serverId,type:"send"}}),h.message==="ice connection failed"&&u(h),h}},{delayTime:100,strategy:"exponential",maxRetryCount:J.hasFeature(X.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3}),l.info("sendTransport::connected_transport",{transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"send"}}),this._transportReconnectFailureCount=Math.max(0,this._transportReconnectFailureCount-1),this._producerNotReadyFailureCount=0,this._sendTransport=r,U.onSafeInitialization(()=>{U.configureSendTransport(r)})}catch(d){throw l.error(`failed to connect send transport after retry:${r.id}`,{error:d,transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"send"}}),r.close(),r.removeAllListeners(),this._transportReconnectFailureCount+=1,this.handleFailure(),d}}async createRecvTransport(e){var n,i,a,o,d;if(this._recvTransport&&this._recvTransport.connected){l.info("recvTransport::already_exists_in_connected_state",{transport:{id:(n=this._recvTransport)==null?void 0:n.id,serverId:(i=this._recvTransport)==null?void 0:i.serverId,type:"recv"}});return}l.info("recvTransport::initializing_transport",{transport:{id:(a=this._recvTransport)==null?void 0:a.id,serverId:(o=this._recvTransport)==null?void 0:o.serverId,type:"recv"}});const r=this._device.createRecvTransport({...e,additionalSettings:{...(d=e.additionalSettings)!=null?d:{},rtcAudioJitterBufferMaxPackets:25,rtcAudioJitterBufferFastAccelerate:!0,rtcAudioJitterBufferMinDelayMs:20}});this._transportDisconnectedTimer.consuming=void 0,l.info("recvTransport::initialized_transport",{transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"recv"}}),this.handleTransport(r,!0),l.info("recvTransport::connecting_transport",{transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"recv"}});try{await br(async(u,h)=>{this.socket.isConnected||h(new Error("socket is not connected")),r.connectionState==="closed"&&h(new Error("transport is closed")),u>0&&l.debug(`retrying transport connect, count: ${u}`,{transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"recv"}});try{await r.connect()}catch(p){throw l.error(`fail to connect recv transport: ${r.id}`,{error:p,transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"recv"}}),p.message==="ice connection failed"&&h(p),p}},{delayTime:100,strategy:"exponential",maxRetryCount:J.hasFeature(X.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3}),l.info("recvTransport::connected_transport",{transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"recv"}}),this._transportReconnectFailureCount=Math.max(0,this._transportReconnectFailureCount-1),this._consumerCreationFailureCount=0,this._consumerNotBoundFailureCount=0,this.producerIdToConsumerIdMap.clear(),this._recvTransport=r,U.onSafeInitialization(()=>{U.configureRecvTransport(r)})}catch(u){throw l.error(`failed to connect recv transport after retry:${r.id}`,{error:u,transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"recv"}}),r.close(),r.removeAllListeners(),this._transportReconnectFailureCount+=1,this.handleFailure(),u}}handleTransport(e,r){if(e.on("connect",async({offer:n},i,a)=>{try{const o={consuming:r,description:{sdp:n.sdp,type:n.type,target:r?qt.SUBSCRIBER:qt.PUBLISHER}},{transportId:d,answer:u}=await this._socketHandler.connectTransport(o);e.setServerId(d),i({answer:u})}catch(o){l.error(`${r?"consumer":"producer"} transport connection error:`,{error:o,transport:{id:e==null?void 0:e.id,serverId:e==null?void 0:e.serverId,type:r?"recv":"send"}}),a(o)}}),e.on("connectionstatechange",async n=>{this.updateTransportState({state:n,direction:r?"consuming":"producing"}),l.info(`${r?"consumer":"producer"} transport connectionState:`,{transport:{id:e==null?void 0:e.id,serverId:e==null?void 0:e.serverId,type:r?"recv":"send",status:n}});const i=()=>{this._transportDisconnectedTimer[r?"consuming":"producing"]!==void 0&&(clearTimeout(this._transportDisconnectedTimer[r?"consuming":"producing"]),this._transportDisconnectedTimer[r?"consuming":"producing"]=void 0)};switch(n){case"connected":i(),this.lastConnectionTime=performance.now();break;case"disconnected":this._transportDisconnectedTimer[r?"consuming":"producing"]=setTimeout(()=>{this.triggerTransportReconnection(e,r)},ZD);break;case"failed":if(e.closed)return;i(),this.triggerTransportReconnection(e,r);break}}),e.on("icecandidate",async n=>{l.debug("sending icecandidate:",{iceCandidate:n})}),e.on("datachannel:events",async(n,i)=>{var a,o;l.debug("got data channel message on event:",{rtcChannel:{label:n,message:i}});try{switch(i.type){case"negotiation":{e.awaitQueue.push(async()=>this.negotiateOverDC(i,Zc(i),n,e));break}case"handshake":{const d={type:"handshake",payload:{message:"pong"}};e.sendResponseOverDC(n,Zc(i),d);break}case"consumer_toggle":{this.handleConsumerToggle(i.payload);break}case"hub-disconnect":{l.debug(`media hub disconnected, full_reconnect: ${(a=i.payload)==null?void 0:a.full_reconnect}`),((o=i.payload)==null?void 0:o.full_reconnect)===!0&&this.emit("rejoin");break}case"error":{this.handleErrorOverDC(i.payload,e.id);break}default:l.warn(`unknown event received from hive node, event: ${i.type}`);break}}catch(d){l.error(`Unable to handle the incoming datachannel message on channel ${n}`)}}),e.on("dc_error",()=>{e.direction==="recv"&&(l.warn("events datachannel did not open in 5s"),this.handleFailure())}),e.on("negotiate",async({description:n},i,a)=>{try{const o={sdp:n==null?void 0:n.sdp,type:n==null?void 0:n.type},d=await this.negotiate(e,o);i({answer:d})}catch(o){l.error("negotiate error:",{transport:{id:e.id,serverId:e.serverId,type:e.direction},error:o}),a(o)}}),!r){e.on("produce",async({offer:n,kind:i,paused:a,appData:o},d,u)=>{var v;const p=bu(n.sdp).media.filter(T=>i==="video"?T.type==="video":T.type==="audio").at(-1).msid,f={description:{sdp:n.sdp,type:n.type,target:qt.PUBLISHER},paused:a,kind:i,msid:p,appData:JSON.stringify(o),screenShare:(v=o.screenShare)!=null?v:!1};try{const{answer:T,producerId:P}=await this._socketHandler.produce(f);d({answer:T,producerId:P})}catch(T){l.error("create producer error:",T),u(T)}});return}e.on("consume_peer",async({producingPeerId:n,producerId:i},a,o)=>{l.info("consumePeer:",n);const d={producingPeerId:n,producerId:i};try{const u=await this._socketHandler.consume(d);l.debug(`consumePeer response for ${n}:`,{consumerStateMap:u});const h=new Map;Object.entries(u).forEach(([p,f])=>{var T,P,k;let v={};try{v=JSON.parse(f.producerState.appData)}catch(I){}h.set(p,{consumerId:f.consumerId,trackId:(T=f.producerTrack)==null?void 0:T.trackId,streamId:f.producerTrack.streamId,kind:f.producerState.kind===Nt.VIDEO?"video":"audio",appData:v,screenShare:(P=f.producerState)==null?void 0:P.screenShare,paused:(k=f.producerState)==null?void 0:k.pause,producingPeerId:n})}),a({consumersMap:h})}catch(u){l.error("consumePeer error:",{error:u}),o(u)}}),e.on("consume",async({producerId:n,producingPeerId:i},a,o)=>{var u,h,p,f,v,T,P,k,I;const d={producingPeerId:i,producerId:n};try{const V=(await this._socketHandler.consume(d))[n];let O={};try{O=JSON.parse((u=V.producerState)==null?void 0:u.appData)}catch(W){}l.info("consumer create response:",{consumer:{remotelyPaused:(h=V.producerState)==null?void 0:h.pause,producerId:(p=V.producerState)==null?void 0:p.producerId,kind:(v=(f=V.producerState)==null?void 0:f.kind)==null?void 0:v.toString(),appData:{...O,screenShare:(T=V.producerState)==null?void 0:T.screenShare},id:V.consumerId},consumerState:V}),a({consumerId:V.consumerId,screenShare:(P=V.producerState)==null?void 0:P.screenShare,trackId:(k=V.producerTrack)==null?void 0:k.trackId,streamId:V.producerTrack.streamId,kind:V.producerState.kind===Nt.VIDEO?"video":"audio",paused:(I=V.producerState)==null?void 0:I.pause,appData:O})}catch(x){l.error("error during consuming on server:",x),o(x)}})}async createProducer(e,r,n){var a;if(this._sendTransport===void 0||this._sendTransport.closed)return null;l.info("createProducer::initializing_producer",{producer:{id:"TO_BE_CREATED",kind:e,status:"initializing",appData:r==null?void 0:r.appData}});const i=this._producerStatus.get(e);if((i==null?void 0:i.trackId)===r.track.id&&(i==null?void 0:i.status)===Jr.INITIALIZING)return l.info("createProducer::producer getting initializing",{producer:{id:"GETTING_CREATED",status:"initializing",kind:e,appData:r==null?void 0:r.appData}}),null;this._producerStatus.set(e,{trackId:r.track.id,status:Jr.INITIALIZING});try{const o=await this._sendTransport.produce(r);return(a=r.appData)!=null&&a.e2ee&&w.emit(C.E2EE_ACTIVE_PRODUCER,o),l.info("createProducer::initialized_producer",{producer:{id:o==null?void 0:o.id,kind:e,status:"producing",appData:r==null?void 0:r.appData}}),o.on("close",async({offer:d,reason:u},h)=>{l.info("producer::closing",{debuggingHint:u,producer:{id:o==null?void 0:o.id,kind:e,status:"closing",appData:r==null?void 0:r.appData}});const p={producerId:o.id,description:{sdp:d.sdp,type:d.type,target:qt.PUBLISHER}};try{const f=await this._socketHandler.closeProducer(p),v={sdp:f==null?void 0:f.sdp,type:f==null?void 0:f.type};l.info("producer::closed",{producer:{id:o==null?void 0:o.id,kind:e,status:"closed",appData:r==null?void 0:r.appData}}),h({answer:v})}catch(f){l.error("producer close error",f)}this._producerStatus.delete(e),this._producers.delete(e),n(),this.reconfigureWebcamLayers()}),o.on("trackended",()=>{l.info("producer::trackended",{producer:{id:o==null?void 0:o.id,kind:e,status:"UNKNOWN",appData:o==null?void 0:o.appData}}),[Y.MIC,Y.WEBCAM].includes(e)||n()}),this._producers.set(e,o),this._producerStatus.set(e,{trackId:r.track.id,status:Jr.INITIALIZED}),this.reconfigureWebcamLayers(),o.track}catch(o){throw this._producerStatus.set(e,{status:Jr.NOT_INITIALIZED,trackId:r.track.id}),l.error("createProducer::transport_initialization_failed",{producer:{id:"FAILED_TO_CREATE",kind:e,status:"failed",appData:r==null?void 0:r.appData,error:o}}),o}}async reconfigureWebcamLayers(){if(!J.hasFeature(X.DISABLE_WEBCAM_LAYERS_ON_SCREENSHARE))return;const e=this.producers.get(Y.WEBCAM);e&&await this._switchProducerSpatialLayer(e,this.producers.get(Y.SCREENSHARE_VIDEO)?0:3)}async _switchProducerSpatialLayer(e,r){try{l.debug("switching layer of webcam producer to:",{media:{video:{layer:r}},producer:{id:e.id,kind:e.kind,appData:e.appData}}),await e.setMaxSpatialLayer(r)}catch(n){l.error("failed to switch spatial layer",{error:n})}}_initConsumer(e){e&&(e.observer.on("close",async r=>{l.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),this._consumers.delete(e.id),w.emit(C.CONSUMER_CLOSED,{id:e.id})}),this._consumers.set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),w.emit(C.NEW_CONSUMER,{id:e.id,appData:e.appData,peerId:e.peerId}))}async createConsumers(e){if(this._recvTransport===void 0||this._recvTransport.closed||!this._recvTransport.connected)return;if(e.every(n=>this.getProducer(n.producerId))){l.warn("why are you creating a consumer for local producer?");return}await br(async n=>{n>0&&l.debug(`retrying consume call, retryCount: ${n}`),(await this._recvTransport.consume(e).catch(a=>{throw l.error("failed to consume:",{error:a}),a})).forEach(a=>{a.status==="rejected"?(l.error("consumer creation task is failing",a.reason),this._consumerCreationFailureCount+=1,setTimeout(this.handleFailure.bind(this),0)):this._initConsumer(a.value)})}).catch(n=>{l.error("create consumer failed after retries",{error:n}),this._consumerCreationFailureCount+=1,this.handleFailure()})}async pauseProducer(e){const r=this._producers.get(e);if(!r){l.warn(`producer type: ${e} not found`);return}r.pause(),r.appData.e2ee&&w.emit(C.E2EE_INACTIVE_PRODUCER,r),l.info(`Paused the producer of type: ${r.kind}`,{producer:{id:r.id,kind:r.kind,appData:r.appData}})}async resumeProducer(e){const r=this._producers.get(e);if(!r){l.warn(`producer type: ${e} not found`);return}r.resume(),l.info(`Resumed the producer of type: ${r.kind}`,{producer:{id:r.id,kind:r.kind,appData:r.appData}})}async replaceTrack(e,r){const n=this._producers.get(e);if(!n){l.warn(`producer type: ${e} not found`);return}await n.replaceTrack({track:r}),l.info(`Replaced track for the producer of type: ${n.kind}`,{producer:{id:n.id,kind:n.kind,appData:n.appData,trackId:r.id}})}async removeProducer(e,r){const n=this._producers.get(e);if(!n){l.warn(`producer type: ${e} not found`);return}r&&n.track.stop(),await this.sendTransport.awaitQueue.push(n.close.bind(n),"producer").then(()=>{c(this,Ar).getValue("modules").e2ee.enabled&&w.emit(C.E2EE_INACTIVE_PRODUCER,n)}).catch(i=>{l.error("failed to close producer on server",i)})}async pauseConsumer(e){const r=this._consumers.get(e);if(!r){l.warn(`consumer with id: ${e} not found`);return}this.toggleConsumerOverDC(e,!0),l.info(`Paused the consumer of type: ${r.kind}`,{consumer:{id:r.id,kind:r.kind,appData:r.appData}})}async pauseConsumerOverSocket(e){try{const r={consumerId:e.id,pause:!0};await this.socket.sendMessagePromise(se.toggleConsumer,Pc.toBinary(r)),e.pause(),w.emit(C.CONSUMER_PAUSED,{id:e.id}),l.info(`Paused the consumer of type: ${e.kind} over socket`,{consumer:{id:e.id,kind:e.kind,appData:e.appData}})}catch(r){l.error("error on pausing consumer",{error:r,consumer:{id:e.id,kind:e.kind,appData:e.appData}})}}async toggleConsumerOverDC(e,r){const n={type:"consumer_toggle",payload:{consumerId:e,mute:r}},i=this._recvTransport.getDatachannel("events");if(!i){l.warn("recvTransport:: events datachannel not found");return}await i.request(n),l.info(`HiveSFUHandler::consumer toggled, consumerId: ${e}, muted: ${r}`)}async resumeConsumer(e){const r=this._consumers.get(e);if(!r){l.warn(`consumer with id: ${e} not found`);return}if(!r.paused){l.warn(`consumer with id:${e} is not paused so not resuming`);return}try{const n={consumerId:e,pause:!1};await this.socket.sendMessagePromise(se.toggleConsumer,Pc.toBinary(n)),r.resume(),w.emit(C.CONSUMER_RESUMED,{id:r.id}),l.info(`Resumed the consumer of type: ${r.kind}`,{consumer:{id:r.id,kind:r.kind,appData:r.appData}})}catch(n){l.error("error on resuming consumer",n)}}async closeConsumer(e,r){return this.closeConsumers([e],r)}async closeConsumers(e,r=!1){l.info(`Closing consumers: ${JSON.stringify(e)} with force: ${r}`);let n=!0;const i=e.filter(d=>this._consumers.get(d)?!0:(l.warn(`consumer with id: ${d} not found`),!1));if(!i.length)return;const a={consumerIds:i},o=async()=>{var d;return(d=this._recvTransport)==null?void 0:d.awaitQueue.push(async()=>{await this._socketHandler.closeConsumer(a)},"close_consumer").catch(u=>{l.warn("error on closing consumer:",{error:u}),n=r})};r?o():await o(),n&&i.forEach(d=>{const u=this.consumers.get(d);u&&(this.producerIdToConsumerIdMap.delete(u.producerId),u.close(r?"force closed":void 0))})}async cleanupConsumers(e){l.debug("cleaning up all consumers");const r=[];this._consumers.forEach(n=>{e?n.peerId===e&&r.push(n.id):r.push(n.id)}),this.closeConsumers(r,!0)}async stopAllProducers(){l.info("stopping all available producers"),this._producers.forEach((e,r)=>{l.debug(`closing producer type: ${r}`,{producer:{id:e==null?void 0:e.id,kind:e.kind,appData:e.appData}}),e.close()})}getProducer(e){return Array.from(this.producers.values()).filter(r=>r.id===e).at(0)}hasProducer(e){return this.getProducer(e)!==void 0}async negotiate(e,r){l.debug(`setting remote offer : ${JSON.stringify(r)} on ${e.direction} transport`,{transport:{id:e.id,serverId:e.serverId,type:e.direction}});const n=await e.setRemoteOffer(r),i={transportId:e.serverId,description:{sdp:n.sdp,type:n.type,target:qt.SUBSCRIBER}};return l.debug(`sending renegotiate request: ${JSON.stringify(i)} on ${e.direction} transport`,{transport:{id:e.id,serverId:e.serverId,type:e.direction}}),await this.socket.sendMessagePromise(se.renegotiateSessionDescription,ef.toBinary(i)),l.info("renegotiation done",{transport:{id:e.id,serverId:e.serverId,type:e.direction}}),n}async negotiateOverDC(e,r,n,i){const{sdp:a}=e.payload,o={sdp:a,type:"offer"};try{l.debug(`got offer over dc: ${a} for transport: ${i.id}`);const d=await i.setRemoteOffer(o),u={type:"answer",payload:{type:d.type,sdp:d.sdp}};l.debug(`datachannel answer: ${JSON.stringify(u)}`),i.sendResponseOverDC(n,r,u)}catch(d){l.error("datachannel:events::Error:",d),d.code!=="DC_NOT_FOUND"&&i.sendErrorOverDC(n,r,d)}}handleConsumerToggle(e){const{mute:r,trackId:n}=e;l.info(`consumer toggled for trackId: ${n} muted: ${r}`);const i=this.consumers.get(n);if(!i){l.warn(`consumer with trackId: ${n} not found`);return}i.paused!==r&&(l.debug("consumer state is not same",{consumer:{id:i.id,remotelyPaused:i.paused}}),r?(i.pause(),w.emit(C.CONSUMER_PAUSED,{id:i.id})):(i.resume(),w.emit(C.CONSUMER_RESUMED,{id:i.id})))}async handleErrorOverDC(e,r){l.error(`got error over dc: ${JSON.stringify(e)} for transport: ${r}`);const{type:n,error:i,id:a}=e;if(n==="consumer"){if(i==="bind-fail"){if(J.hasFeature(X.CONSUMER_BIND_NO_RETRY))return;if(this._consumerNotBoundFailureCount>=2){this.handleFailure();return}this._consumerNotBoundFailureCount+=1;const o=this.consumers.get(a);if(!o)return;try{await this.closeConsumer(o.id),await this.createConsumers([{kind:o.kind,pause:o.paused,producerId:o.producerId,producingTransportId:o.producingTransportId,screenShare:o.appData.screenShare,producingPeerId:o.peerId}])}catch(d){l.error("failed to recreate consumer on downtrack bound failure,",{consumer:{id:o.id,producerId:o.producerId,kind:o.kind,appData:o.appData}})}}}else if(n==="producer")if(i==="ready-fail"){if(this._producerNotReadyFailureCount>=2){this.handleFailure();return}this._producerNotReadyFailureCount+=1;const[o]=Array.from(this.producers.entries()).find(d=>d[1].id===a);if(!o)return;await this.removeProducer(o).catch(d=>{l.error("failed to remove ready-fail producer:",{error:d,producer:{id:a,kind:o,appData:null}})})}else i==="general-failure"&&(this.updateTransportState({state:Rt.RECONNECTING,direction:"producing"}),this.emit("reconnect_transport",this._sendTransport))}async handleFailure(){if(this._transportReconnectFailureCount>0||this._totalTransportReconnectionCount>3){l.warn("transport failure detected"),J.hasFeature(X.ENABLE_HIVE_EXPERIMENTAL_FAIL_RECOVERY)&&(l.debug("rejoining room"),this.emit("rejoin"));return}(this._consumerCreationFailureCount>0||this._consumerNotBoundFailureCount>=2)&&(l.warn("consumer creation failure detected or consumer not bound failure increased"),J.hasFeature(X.ENABLE_HIVE_EXPERIMENTAL_FAIL_RECOVERY)&&(l.debug("reconnecting recv transport"),this._totalTransportReconnectionCount+=1,this.updateTransportState({state:Rt.RECONNECTING,direction:"consuming"}),this.emit("reconnect_transport",this._recvTransport))),this._producerNotReadyFailureCount>=2&&(l.warn("producer receiver not getting added needs to reconnect send transport"),this._totalTransportReconnectionCount+=1,this.updateTransportState({state:Rt.RECONNECTING,direction:"producing"}),this.emit("reconnect_transport",this._sendTransport))}triggerTransportReconnection(e,r){l.info("triggerTransportReconnection:: reconnecting transport",{transport:{type:e.direction,id:e.id,serverId:e.serverId}});const n=J.hasFeature(X.ENABLE_HIVE_TRANSPORT_RECONNECTION_ON_ICE_FAILED),i=J.hasFeature(X.HIVE_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED);n&&(i&&this._socket.isConnected&&(performance.now()-this.lastConnectionTime>2e4&&(this._transportConnectionFailCount=0),this._transportConnectionFailCount>2&&(l.warn("Multiple disconnections, forcing relay"),this._iceTransportPolicy="relay"),this._transportConnectionFailCount+=1),this.updateTransportState({state:Rt.RECONNECTING,direction:r?"consuming":"producing"}),this.emit("reconnect_transport",e))}async switchConsumersToLayer(e,r){const n=this._recvTransport.getDatachannel("events");if(!n){l.warn("events datachannel not found");return}const i={type:"switch_consumer_layer",payload:{consumerIds:e,layer:r}};await n.request(i),l.info(`HiveSFUHandler::consumer id: ${e} layer switched to ${r}`)}updateTransportState(e){const{state:r,direction:n}=e;r==="disconnected"&&(this.transportDisconnected[n]=!0),c(this,Vn,No).mediaState[n]={state:r,reconnected:r==="connected"?this.transportDisconnected[n]:c(this,Vn,No).mediaState[n].reconnected},r==="connected"&&(this.transportDisconnected[n]=!1),w.emit(C.TRANSPORT_STATE_UPDATE,{transport:n,...c(this,Vn,No).mediaState[n]})}}Vn=new WeakSet,No=function(){return c(this,Ar).getValue("connectionHandler")},Ar=new WeakMap;var tO=Object.defineProperty,rO=Object.getOwnPropertyDescriptor,ue=(s,t,e,r)=>{for(var n=r>1?void 0:r?rO(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&tO(t,e,n),n};const jg=(Lv=class extends Og{constructor(t,e){var d,u;super();S(this,Dr);S(this,St,void 0);S(this,me,void 0);S(this,Mr,void 0);S(this,$n,void 0);S(this,Bn,void 0);S(this,$s,void 0);S(this,ro,void 0);S(this,so,void 0);S(this,no,void 0);S(this,ns,void 0);S(this,ji,void 0);m(this,"legacyMode");m(this,"roomNodeUrl");m(this,"peerDisplayName");m(this,"e2ee");m(this,"partialJoinRoomPromise");this.context=t;const{roomName:r,authToken:n,legacyMode:i,socketClient:a,meetingTitle:o}=e;this.roomJoined=!1,this.roomName=r,this.authToken=n,this.legacyMode=i,this.meetingTitle=o,y(this,St,a),y(this,Mr,!1),y(this,me,new eO(t,a)),this.maxPreferredStreams=6,y(this,ns,new Set),y(this,$n,!1),y(this,Bn,0),y(this,$s,new di),this.e2ee=(u=(d=t.getValue("modules").e2ee)==null?void 0:d.enabled)!=null?u:!1,U.legacySwitch(i),this.handleSocketEvents(),this.handleSFUEvents(),this.handleCallstatsEvents(),y(this,ro,Vr(async()=>{if(!c(this,Dr,Ys).mediaJoinAttempted)return;const{roomJoined:h}=await this.joinRoom(this.peerDisplayName,this.roomUUID,{},!0,!0);h&&(w.emit(C.RESET_PRODUCER_STATE),w.emit(C.ROOM_NODE_RECONNECTED))},5e3,{leading:!0,maxWait:1e3})),y(this,so,Vr(async h=>{h.close(),h.removeAllListeners(),await this.sfuHandler.setupTransports({send:!0}),l.info("send transport reconected!"),w.emit(C.RESET_PRODUCER_STATE)},1e3)),y(this,no,Vr(async h=>{h.close(),h.removeAllListeners(),await this.sfuHandler.setupTransports({recv:!0}),l.info("recv transport reconnected!"),w.emit(C.UPDATE_ACTIVE,{createAllConsumers:!0})},1e3))}get mediaState(){return c(this,Dr,Ys).mediaState}static async init(t,e){const{legacyMode:r=!0,meetingId:n,authToken:i,meetingTitle:a,socket:o}=e;return new jg(t,{legacyMode:r,authToken:i,socketClient:o,roomName:n,meetingTitle:a})}get sfuHandler(){return c(this,me)}get rejoinRoom(){return c(this,ro)}get roomJoined(){return c(this,Dr,Ys).roomJoined}set roomJoined(t){c(this,Dr,Ys).roomJoined=t}reset(t=!0){var e,r,n,i;(r=(e=c(this,me))==null?void 0:e.cleanupConsumers)==null||r.call(e),(i=(n=c(this,me))==null?void 0:n.stopAllProducers)==null||i.call(n),c(this,ns).clear(),t&&(c(this,$s).stop(),this.sfuHandler.stopAllTransports(),this.sfuHandler.reset(),y(this,$s,new di))}async reconnectTransport(t){l.info(`HiveNodeClient::Room joining state: ${c(this,Mr)}`),!(!t||c(this,Mr))&&(t.direction==="send"?await c(this,so).call(this,t):await c(this,no).call(this,t))}async setupTransports(){await c(this,me).setupTransports({send:!0,recv:!0})}async stopAllProducers(){await c(this,me).stopAllProducers()}async joinRoom(t,e,r={},n=!1,i=!1){c(this,Dr,Ys).mediaJoinAttempted=!0,y(this,Mr,!0),this.reset(n);const a=We().ipInfo;if(a!=null&&a.loc&&!c(this,ji)){const d=a.loc.split(",");y(this,ji,{latitude:parseFloat(d[0]),longitude:parseFloat(d[1])})}let o;try{return o=await c(this,$s).push(()=>this._joinRoom(t,e,r,i,c(this,ji)),"joinRoom"),o}catch(d){o={roomJoined:!1}}return o.roomJoined||w.emit(C.ROOM_NODE_FAILED),o}async _partialJoinRoom(t,e,r=!1,n=void 0){const{ipInfo:i}=We();let a=n;if(i!=null&&i.loc&&!n){const[o,d]=i.loc.split(",").map(parseFloat);a={latitude:o,longitude:d}}await br((o,d)=>(c(this,St).isConnected||d(new Error("socket is not connected")),o>0&&l.warn(`retrying sending join room request, count: ${o}`),this.sfuHandler.hiveSocketHandler.joinRoom(e,t,r,a).catch(u=>{throw l.error("failed to send join room request, error:",{error:u}),u})),{delayTime:1e3,strategy:"exponential",maxRetryCount:J.hasFeature(X.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3}),await this.setupTransports()}async partialJoinRoom(t,e,r=!1,n=void 0){this.partialJoinRoomPromise=c(this,$s).push(()=>this._partialJoinRoom(t,e,r,n))}async _joinRoom(t,e,r={},n=!1,i=null){this.peerDisplayName=t;try{return this.partialJoinRoomPromise?await this.partialJoinRoomPromise:await this._partialJoinRoom(t,e,n,i),navigator.product!=="ReactNative"&&setTimeout(async()=>{const d={userId:this.context.getValue("userId"),peerId:this.peerId,displayName:t,roomUUID:e,roomViewType:"groupCall",roomName:this.roomName,deviceInfo:{...Se.getDeviceInfo(),userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency},sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};U.onSafeInitialization(()=>{U.roomJoined(d),r!=null&&r.audio?U.audioOn():U.audioOff(),r!=null&&r.video?U.videoOn():U.videoOff()})}),{roomJoined:await this.completeJoinRoom()}}catch(a){return l.error("error on sending join room request",{error:a}),{roomJoined:!1}}finally{this.partialJoinRoomPromise=void 0}}async completeJoinRoom(){try{this.roomJoined=!0;const{maxPreferredStreams:t,roomState:e}=await this.sfuHandler.hiveSocketHandler.notifySelfJoinComplete();return this.roomUUID=e.roomUuid,y(this,$n,!0),y(this,Mr,!1),this.maxPreferredStreams=t!=null?t:6,w.emit(C.UPDATE_ACTIVE,{createAllConsumers:!0}),!0}catch(t){return l.error("error on completing join room:",{error:t}),this.roomJoined=!1,!1}}async leaveRoom(){c(this,me).stopAllTransports(),y(this,$n,!1),c(this,Dr,Ys).mediaJoinAttempted=!1;const t={closeRoom:!1};c(this,St).sendMessagePromise(se.leaveRoom,cf.toBinary(t)).then(e=>{var n;((n=_f.fromBinary(e.payload))==null?void 0:n.closed)||l.warn("weird state on peer closed and should not happen")}).catch(e=>{l.error("error on sending leave room request",{error:e})}),U.callEnded(),g.destruct()}getConsumers(){return c(this,me).consumers}async activatePeers(t){return this.createConsumers(t)}async deactivatePeers(t,e="default"){const r=new Set;t.forEach(i=>{i.screenShare&&i.kind==="video"&&r.add(i.producingPeerId)});const n=e==="default"?t.filter(i=>!r.has(i.producingPeerId)).filter(i=>i.kind!=="audio"):t;await Promise.all(n.map(i=>{const a=this.sfuHandler.producerIdToConsumerIdMap.get(i.producerId);if(!a){l.warn(`consumer not found in deactivate producers: ${i.producerId}`);return}return this.sfuHandler.closeConsumer(a)}))}async createConsumers(t){return t.length===0?Promise.resolve():this.sfuHandler.createConsumers(t)}async pauseConsumers(t){t.forEach(e=>{this.sfuHandler.pauseConsumer(e)})}async resumeConsumers(t){t.forEach(e=>{this.sfuHandler.resumeConsumer(e)})}async closeConsumers(t){const e=t.reduce((r,n)=>{const i=this.sfuHandler.producerIdToConsumerIdMap.get(n.producerId);return i?(r.push(i),r):(l.warn(`consumer not found in deactivate producers: ${n.producerId}`),r)},[]);await this.sfuHandler.closeConsumers(e)}async shareWebcam(t){if(t===void 0)return null;if(c(this,me).producers.has(Y.WEBCAM)){const n=c(this,me).producers.get(Y.WEBCAM);if(!n.closed&&!navigator.isReactNative)return await n.replaceTrack({track:t}),await this.resumeWebcam(),t;await c(this,me).removeProducer(Y.WEBCAM)}const e={track:t,codecOptions:{name:"VP8"},appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1};if(J.hasFeature(X.ENABLE_HIVE_SIMULCAST)){let n=t.getConstraints().width;n in wg||(n=320),e.encodings=wg[n]}const r=()=>{l.info("Disabling video due to the producer closure"),this.disableWebcam()};return c(this,me).createProducer(Y.WEBCAM,e,r)}async shareScreen(t){const{video:e,audio:r}=t;if(e===void 0)return;const n={track:e,codecOptions:{name:"VP8"},appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Se.isElectron()},stopTracks:!1};let i=()=>{l.info("Disabling screenShare due to the producer closure"),this.disableScreenShare()};if(await c(this,me).createProducer(Y.SCREENSHARE_VIDEO,n,i),r){const a={track:r,codecOptions:{name:"opus"},appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Se.isElectron()},stopTracks:!1,zeroRtpOnPause:!0};i=()=>{},await c(this,me).createProducer(Y.SCREENSHARE_AUDIO,a,i)}U.screenShareStart()}async shareMic(t){try{if(t===void 0)throw new lt("track undefined");if(c(this,me).producers.has(Y.MIC)){const n=c(this,me).producers.get(Y.MIC);if(!n.closed&&!navigator.isReactNative){await n.replaceTrack({track:t}),await this.resumeMic();return}await c(this,me).removeProducer(Y.MIC,!1)}const e={track:t,encodings:[{priority:"high"}],codecOptions:{name:"opus"},appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!0},r=()=>{l.info("Disabling audio due to the producer closure"),this.disableMic()};await c(this,me).createProducer(Y.MIC,e,r)}catch(e){throw new b(e)}}pauseMic(){const t=c(this,me).producers.get(Y.MIC);if(!t){l.error("pauseMic::could_not_find_mic_producer");return}if(t.paused){l.info("pauseMic::mic_producer_already_paused");return}t.pause();const e={producerId:t.id,pause:!0};c(this,St).sendMessage(se.toggleProducer,fs.toBinary(e))}async pauseWebcam(){const t=c(this,me).producers.get(Y.WEBCAM);if(!t){l.error("pauseWebcam::could_not_find_webcam_producer");return}t.pause();const e={producerId:t.id,pause:!0};c(this,St).sendMessage(se.toggleProducer,fs.toBinary(e))}async resumeMic(){const t=c(this,me).producers.get(Y.MIC);if(!t){l.error("resumeMic::could_not_find_mic_producer");return}if(!t.pause){l.info("resumeMic::mic_producer_already_resumed");return}t.resume(),t.appData.e2ee&&w.emit(C.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,St).sendMessage(se.toggleProducer,fs.toBinary(e))}async resumeWebcam(){const t=c(this,me).producers.get(Y.WEBCAM);if(!t){l.error("resumeWebcam::could_not_find_webcam_producer");return}t.resume(),t.appData.e2ee&&w.emit(C.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,St).sendMessage(se.toggleProducer,fs.toBinary(e))}async disableWebcam(){await c(this,me).removeProducer(Y.WEBCAM)}async disableMic(){await c(this,me).removeProducer(Y.MIC)}async disableScreenShare(){l.info("screen_sharing_stopped"),U.screenShareStop(),await c(this,me).removeProducer(Y.SCREENSHARE_VIDEO),await c(this,me).removeProducer(Y.SCREENSHARE_AUDIO),c(this,ns).clear()}async muteSelf(){this.pauseMic()}async unmuteSelf(){}async resetVideoProducers(t,e){t&&(await c(this,me).removeProducer(Y.WEBCAM,!1),this.shareWebcam(t)),e&&(await c(this,me).removeProducer(Y.SCREENSHARE_VIDEO,!1),this.shareScreen({video:e}))}async changeDisplayName(t,e){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!await this.sfuHandler.hiveSocketHandler.changeDisplayName(r))throw new Error("failed to change display name!")}async kick(t){const e={participantId:t};if(!await this.sfuHandler.hiveSocketHandler.kickPeer(e))throw new Error("failed to kickout the participant!")}async kickAll(){if(!await this.sfuHandler.hiveSocketHandler.kickAll())throw new Error("failed to kickout all participant!")}async muteAll(t){if(!await this.sfuHandler.hiveSocketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await this.sfuHandler.hiveSocketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(t){if(!await this.sfuHandler.hiveSocketHandler.hostControlForPeer(t,"audio"))throw new Error("failed to mute given participant")}async disableVideo(t){if(!await this.sfuHandler.hiveSocketHandler.hostControlForPeer(t,"video"))throw new Error("failed to mute video of given participant")}async pinPeer(t){const e={participantId:t!=null?t:""};try{await c(this,St).sendMessagePromise(se.globalPinPeer,uf.toBinary(e))}catch(r){l.error("Error in pinning peer:",{error:r})}}validateScreenShare(t){return this.peerId===t.peerId&&this.sfuHandler.hasProducer(t.producerId)&&c(this,ns).add(t.consumerPeerId),c(this,ns).size}async switchConsumersToLayer(t,e){this.sfuHandler.switchConsumersToLayer(t,e)}async handleSocketEvents(){c(this,St).on(se.peerProducerCreateBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:r}=Mf.fromBinary(t);if(e===this.peerId)return;l.info(`producer created broadcast: ${e}, producer state: ${r}`),w.emit(C.NEW_PRODUCER,{peerId:e,producer:{...r,kind:r.kind===Nt.AUDIO?"audio":"video",producingPeerId:e}})}catch(e){l.error("error in peer-producer-create-broadcast",{error:e})}}),c(this,St).on(se.peerProducerToggleBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:{kind:r,pause:n,producerId:i}}=Df.fromBinary(t),a=r===Nt.AUDIO?"audio":"video";if(l.info(`producer toggle broadcast: ${e}, producerId: ${i}, kind:${a}, paused:${n}`),e===this.peerId&&n){w.emit(a==="audio"?C.MUTE_SELF:C.MUTE_SELF_VIDEO);return}w.emit(C.PRODUCER_TOGGLE,{peerId:e,producerId:i,paused:n,kind:a}),Array.from(this.getConsumers().values()).filter(d=>d.producerId===i).forEach(d=>{d.paused!==n&&(l.debug(`consumer state mismatched for ${d.id}. updating consumer pause state ${d.paused} to ${n}`),n?(d.pause(),w.emit(C.CONSUMER_PAUSED,{id:d.id})):(d.resume(),w.emit(C.CONSUMER_RESUMED,{id:d.id})))})}catch(e){l.error("error in producer toggle broadcast handler",{error:e})}}),c(this,St).on(se.peerLeaveBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e}=kc.fromBinary(t);if(e===this.peerId)return;l.info(`peer left broadcast:${e}`),c(this,ns).delete(e),this.sfuHandler.cleanupConsumers(e),w.emit(C.PEER_CLOSED,{id:e})}catch(e){l.error("error in peer left broadcast",{error:e})}}),c(this,St).on(se.peerProducerCloseBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:{producerId:r}}=Of.fromBinary(t);if(e===this.peerId)return;l.info(`producer closed broadcast:${e}`),w.emit(C.PRODUCER_CLOSED,{peerId:e,producerId:r});const n=this.sfuHandler.producerIdToConsumerIdMap.get(r);if(!n){l.warn(`no consumer found for producer:${r}`);return}l.info(`closing consumer ${n}, producer id: ${r}`),this.sfuHandler.closeConsumer(n).then(()=>{l.info(`closed consumer: ${n}`),this.sfuHandler.producerIdToConsumerIdMap.delete(r),w.emit(C.CONSUMER_CLOSED,{id:n})}).catch(i=>{l.error("error closing consumer",{error:i})})}catch(e){l.error("error on producer close broadcast",{error:e})}}),c(this,St).on(se.mediaRoomTerminationBroadcastResponse,()=>{!this.roomJoined&&!c(this,Mr)&&!c(this,$n)||(l.warn("media hub termination broadcast received, rejoining room"),w.emit(C.ROOM_NODE_DISCONNECTED),this.rejoinRoom())})}handleSFUEvents(){c(this,me).on("reconnect_transport",async t=>{try{await this.reconnectTransport(t),l.info(`transport reconnected [id:${t.id}]`)}catch(e){l.error("error on reconnection transports",{error:e})}}),c(this,me).on("rejoin",t=>{var e;if(((e=c(this,Dr,Ys).socketState)==null?void 0:e.state)!=="connected"){l.warn("Ignoring rejoin attempt because socket is not connected");return}if(c(this,Bn)>3&&!t){l.warn("cannot rejoin more already rejoined 3 times");return}if(c(this,Mr)&&!t){l.warn("room joining in progress, cannot start rejoining");return}y(this,Bn,c(this,Bn)+1),l.warn(`rejoining the room because transports are failing. [rejoinCount: ${c(this,Bn)}]`),this.roomJoined=!1,w.emit(C.ROOM_NODE_DISCONNECTED),this.rejoinRoom()})}handleCallstatsEvents(){U.onSafeInitialization(()=>{U.onConsumerScore(t=>{t.forEach((e,r)=>{const n=this.sfuHandler.consumers.get(r);n&&w.emit(C.CONSUMER_SCORE_UPDATE,{id:r,kind:n.kind,peerId:n.peerId,score:e.score,scoreStats:e})})}),U.onProducerScore(t=>{t.forEach((e,r)=>{const n=Array.from(this.sfuHandler.producers.values()).find(i=>i.id===r);n&&w.emit(C.PRODUCER_SCORE_UPDATE,{id:r,kind:n.kind,appData:n.appData,score:e.score,scoreStats:e})})})})}},St=new WeakMap,me=new WeakMap,Mr=new WeakMap,$n=new WeakMap,Bn=new WeakMap,$s=new WeakMap,ro=new WeakMap,so=new WeakMap,no=new WeakMap,ns=new WeakMap,ji=new WeakMap,Dr=new WeakSet,Ys=function(){return this.context.getValue("connectionHandler")},Lv);let ie=jg;ue([g.trace("HiveNodeClient.reset")],ie.prototype,"reset",1),ue([g.trace("HiveNodeClient.reconnect")],ie.prototype,"reconnectTransport",1),ue([g.trace("HiveNodeClient.setupTransport")],ie.prototype,"setupTransports",1),ue([g.trace("HiveNodeClient.stopAllProducers")],ie.prototype,"stopAllProducers",1),ue([g.trace("HiveNodeClient.joinRoom")],ie.prototype,"joinRoom",1),ue([g.trace("HiveNodeClient.completeJoinRoom")],ie.prototype,"completeJoinRoom",1),ue([g.trace("HiveNodeClient.leaveRoom")],ie.prototype,"leaveRoom",1),ue([g.trace("HiveNodeClient.activatePeers")],ie.prototype,"activatePeers",1),ue([g.trace("HiveNodeClient.deactivatePeers")],ie.prototype,"deactivatePeers",1),ue([g.trace("HiveNodeClient.createConsumers")],ie.prototype,"createConsumers",1),ue([g.trace("HiveNodeClient.pauseConsumers")],ie.prototype,"pauseConsumers",1),ue([g.trace("HiveNodeClient.resumeConsumers")],ie.prototype,"resumeConsumers",1),ue([g.trace("HiveNodeClient.closeConsumers")],ie.prototype,"closeConsumers",1),ue([g.trace("HiveNodeClient.shareWebcam")],ie.prototype,"shareWebcam",1),ue([g.trace("HiveNodeClient.shareScreen")],ie.prototype,"shareScreen",1),ue([g.trace("HiveNodeClient.shareMic")],ie.prototype,"shareMic",1),ue([g.trace("HiveNodeClient.pauseMic")],ie.prototype,"pauseMic",1),ue([g.trace("HiveNodeClient.pauseWebcam")],ie.prototype,"pauseWebcam",1),ue([g.trace("HiveNodeClient.resumeMic")],ie.prototype,"resumeMic",1),ue([g.trace("HiveNodeClient.resumeWebcam")],ie.prototype,"resumeWebcam",1),ue([g.trace("HiveNodeClient.disableWebcam")],ie.prototype,"disableWebcam",1),ue([g.trace("HiveClient.disableMic")],ie.prototype,"disableMic",1),ue([g.trace("HiveClient.disableScreenShare")],ie.prototype,"disableScreenShare",1),ue([g.trace("HiveNodeClient.muteSelf")],ie.prototype,"muteSelf",1),ue([g.trace("HiveNodeClient.resetVideoProducers")],ie.prototype,"resetVideoProducers",1),ue([g.trace("HiveNodeClient.changeDisplayName")],ie.prototype,"changeDisplayName",1),ue([g.trace("HiveNodeClient.kickPeer")],ie.prototype,"kick",1),ue([g.trace("HiveNodeClient.kickAllPeers")],ie.prototype,"kickAll",1),ue([g.trace("HiveNodeClient.muteAll")],ie.prototype,"muteAll",1),ue([g.trace("HiveNodeClient.muteAllVideo")],ie.prototype,"muteAllVideo",1),ue([g.trace("HiveNodeClient.disableAudio")],ie.prototype,"disableAudio",1),ue([g.trace("HiveNodeClient.disableVideo")],ie.prototype,"disableVideo",1),ue([g.trace("HiveNodeClient.pinPeer")],ie.prototype,"pinPeer",1),ue([g.trace("HiveNodeClient.validateScreenShare")],ie.prototype,"validateScreenShare",1),ue([g.trace("HiveNodeClient.init")],ie,"init",1);class sO{constructor(){m(this,"_orderedArray");m(this,"_map");this._map=new Map,this._orderedArray=[]}add(t,e){if(!this._map.has(t))return this._map.set(t,{peerId:t,priority:e}),this._orderedArray.splice(Math.max(e-1,0),0,t),this.index(t);const r=this.index(t);this.delete(t);const n=this.add(t,e);return r!==n?n:-1}delete(t){if(this._map.has(t)){const e=this.index(t);this._map.delete(t),this._orderedArray.splice(e,1)}}index(t){return this._map.has(t)?this._orderedArray.indexOf(t):-1}[Symbol.iterator](){return this._orderedArray[Symbol.iterator]()}}class Mu{constructor(){m(this,"_activeSpeakerPeers");m(this,"_compulsoryPeers");this._activeSpeakerPeers=new sO,this._compulsoryPeers=new Set}add(t,e){if(e<0)return this._compulsoryPeers.add(t),0;if(this.compulsoryPeers.includes(t)&&(e>0||e===246267631)){if(l.info("DyteSelectedPeer::removing_compulsory_peer",{selectedPeer:{peerId:t}}),this._removeFromCompulsoryPeer(t),e===246267631)return-1}else if(e===229490415)return this.delete(t),-1;return this._activeSpeakerPeers.add(t,e)}delete(t){l.info("DyteSelectedPeer::deleting_peer_from_selectedPeer",{selectedPeer:{peerId:t}}),this._removeFromCompulsoryPeer(t),this._activeSpeakerPeers.delete(t)}index(t){return this._activeSpeakerPeers.index(t)}get peers(){return Array.from(new Set(this.compulsoryPeers.concat(this.activeSpeakerPeers)))}get compulsoryPeers(){return Array.from(this._compulsoryPeers.values())}get peerPriorities(){return Array.from(this._activeSpeakerPeers).map((t,e)=>e)}get activeSpeakerPeers(){return Array.from(this._activeSpeakerPeers)}_removeFromCompulsoryPeer(t){this._compulsoryPeers.delete(t)}}var nO=Object.defineProperty,iO=Object.getOwnPropertyDescriptor,Jt=(s,t,e,r)=>{for(var n=r>1?void 0:r?iO(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&nO(t,e,n),n};const aO=["ACTIVE_GRID","PAGINATED","MANUAL"];let kt=(Fv=class extends Ht{constructor(t,e,r){super();S(this,vr);m(this,"waitlisted");m(this,"joined");m(this,"active");m(this,"videoSubscribed");m(this,"audioSubscribed");m(this,"pinned");m(this,"all");S(this,Bs,void 0);S(this,Hs,void 0);S(this,zt,void 0);m(this,"viewMode");m(this,"currentPage");m(this,"lastActiveSpeaker");m(this,"selectedPeers",new Mu);y(this,Bs,t),y(this,Hs,e),y(this,zt,r),this.waitlisted=new Sa,this.joined=new Sa,this.videoSubscribed=new Sa,this.audioSubscribed=new Sa,this.active=this.videoSubscribed,this.pinned=new Sa,this.selectedPeers=new Mu,this.all=new RD,this.viewMode="ACTIVE_GRID",this.currentPage=0,this.setupEvents()}get pip(){return c(this,Bs).getValue("pip")}get roomJoined(){var t;return((t=c(this,vr,ds))==null?void 0:t.roomJoined)===!0}setupEvents(){w.on(C.E2EE_ACTIVE_CONSUMER,({peerId:t})=>{var e;((e=c(this,Bs).getValue("modules").e2ee)==null?void 0:e.enabled)!==!0&&this.emit("media_decode_error",{reason:`Got encrypted media for participantId ${t}, but encryption wasn't enabled in init.defaults`,code:"1702"})})}get count(){return this.joined.size}get maxActiveParticipantsCount(){return c(this,vr,ds).maxPreferredStreams}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new b("0 <= Max active participants count limit <= 24");c(this,vr,ds).maxPreferredStreams=t,c(this,Hs).roomJoined&&w.emit(C.UPDATE_ACTIVE)}get pageCount(){if(this.viewMode==="PAGINATED"){const t=this.joined.toArray().filter(e=>e.stageStatus==="ON_STAGE");return Math.ceil(t.length/this.maxActiveParticipantsCount)}return 0}acceptWaitingRoomRequest(t){var r,n;if(!this.roomJoined)throw new b("Can`t accept waiting room request without joining room");const e=(n=(r=this.waitlisted.get(t))==null?void 0:r.userId)!=null?n:t;return c(this,zt).acceptWaitingRoomRequest([e])}async acceptAllWaitingRoomRequest(t){const e=t.map(r=>{var n,i;return(i=(n=this.waitlisted.get(r))==null?void 0:n.userId)!=null?i:r});return c(this,zt).acceptWaitingRoomRequest(e)}async rejectWaitingRoomRequest(t){var r,n;if(!this.roomJoined)throw new b("Can`t reject waiting room request without joining room");const e=(n=(r=this.waitlisted.get(t))==null?void 0:r.userId)!=null?n:t;c(this,zt).rejectWaitingRoomRequest([e])}async setViewMode(t){if(l.info("DyteParticipants::set_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),!(r=>aO.includes(r))(t))throw l.error("DyteParticipants::setViewMode::invalid_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),new b(`Invalid view mode: ${t}. Try ACTIVE_GRID, PAGINATED or MANUAL.`);if(this.viewMode===t){l.info("DyteParticipants::setViewMode::view_mode_same_as_previous");return}if(t==="MANUAL"&&!(c(this,vr,ds)instanceof ie))throw new b("Manual Subscription is not enabled for your Organization. Please contact support.");this.viewMode=t,t==="PAGINATED"?(this.currentPage=1,w.emit(C.UPDATE_ACTIVE,{page:this.currentPage})):t==="ACTIVE_GRID"&&(this.currentPage=0,w.emit(C.UPDATE_ACTIVE)),this.emit("viewModeChanged",{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount})}async subscribe(t,e=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new b("MANUAL subscription mode was not activated.");const r=[];t.forEach(n=>{const i=this.joined.get(n);if(i){if(e.includes("audio")){i.manualProducerConfig={...i.manualProducerConfig,audio:!0},this.videoSubscribed.add(i);const a=i.producers.find(o=>o.kind==="audio"&&!o.screenShare);a&&r.push(a)}if(e.includes("video")){i.manualProducerConfig={...i.manualProducerConfig,video:!0},this.audioSubscribed.add(i);const a=i.producers.find(o=>o.kind==="video"&&!o.screenShare);a&&r.push(a)}if(e.includes("screenshareAudio")){i.manualProducerConfig={...i.manualProducerConfig,screenshareAudio:!0};const a=i.producers.find(o=>o.kind==="audio"&&o.screenShare);r.push(a)}if(e.includes("screenshareVideo")){i.manualProducerConfig={...i.manualProducerConfig,screenshareVideo:!0};const a=i.producers.find(o=>o.kind==="video"&&o.screenShare);r.push(a)}}}),await c(this,vr,ds).createConsumers(r)}async unsubscribe(t,e=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new b("MANUAL subscription mode was not activated.");const r=[];t.forEach(n=>{const i=this.joined.get(n);if(i){if(e.includes("audio")){i.manualProducerConfig={...i.manualProducerConfig,audio:!1};const a=i.producers.find(o=>o.kind==="audio"&&!o.screenShare);a&&r.push(a)}if(e.includes("video")){i.manualProducerConfig={...i.manualProducerConfig,video:!1};const a=i.producers.find(o=>o.kind==="video"&&!o.screenShare);a&&r.push(a)}if(e.includes("screenshareAudio")){i.manualProducerConfig={...i.manualProducerConfig,screenshareAudio:!1};const a=i.producers.find(o=>o.kind==="audio"&&o.screenShare);r.push(a)}if(e.includes("screenshareVideo")){i.manualProducerConfig={...i.manualProducerConfig,screenshareVideo:!1};const a=i.producers.find(o=>o.kind==="video"&&o.screenShare);r.push(a)}}}),await c(this,vr,ds).closeConsumers(r)}getPeerIdsForCurrentPage(){l.info("DyteParticipants::getPeerIdsForCurrentPage()",{pageNavigation:{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}});const{compulsoryPeers:t}=this.selectedPeers,e=t.filter(o=>this.joined.has(o)),r=Array.from(this.pinned.keys()).filter(o=>!e.includes(o)),n=Array.from(this.joined.toArray().filter(o=>o.stageStatus==="ON_STAGE").map(o=>o.id)),i=Math.max((this.currentPage-1)*(this.maxActiveParticipantsCount-e.length-r.length)),a=this.currentPage*(this.maxActiveParticipantsCount-e.length-r.length);return e.concat(r,n.slice(i,a))}async setPage(t){if(l.info("DyteParticipants::set_page",{pageNavigation:{settingPage:t,viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),this.viewMode==="PAGINATED"){if(!Number.isInteger(t))throw l.error("DyteParticipants::invalid_page_number"),new b(`Invalid page: ${t}. Page must be an integer and greater than 0 and less than or equal to .pageCount`);this.currentPage=t,w.emit(C.UPDATE_ACTIVE,{page:t}),this.emit("pageChanged",{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount})}}async disableAllAudio(t){if(l.info("DyteParticipants::disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),!this.roomJoined)throw new b("Can`t disable all audio without joining room");if(c(this,Hs).permissions.canAllowParticipantAudio)return c(this,vr,ds).muteAll(t);throw l.error("DyteParticipants::unauthorized_disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),new b("Unauthorized: User does not have permission to disable peer audio.")}async disableAllVideo(){if(l.info("DyteParticipants::disable_all_video"),!this.roomJoined)throw new b("Can`t disable all video without joining room");if(c(this,Hs).permissions.canAllowParticipantVideo)return c(this,vr,ds).muteAllVideo();throw l.error("DyteParticipants::unauthorized_disable_all_video"),new b("Unauthorized: User does not have permission to disable peer video.")}async disableAudio(t){this.joined.get(t).disableAudio()}async disableVideo(t){this.joined.get(t).disableVideo()}async kick(t){await w.emitAsync(C.KICK_PEER,{peerId:t})}async kickAll(){if(l.info("DyteParticipants::kick_all"),c(this,Bs).getValue("viewType")!=="LIVESTREAM"&&!this.roomJoined)throw new b("Can`t kick all without joining room");if(!c(this,Hs).permissions.kickParticipant)throw l.error("DyteParticipants::unauthorized_kick_all"),new b("Unauthorized: User does not have permission to kick peers.");const e=J.hasFeature(X.PROPAGATE_KICK_ALL);c(this,zt).kickAll(e)}async broadcastMessage(t,e,r){if(l.info("DyteParticipants::broadcastMessage"),!this.roomJoined)throw new b("Can`t broadcast message without joining room");if(!(t!=null&&t.trim()))throw new b("`type` must be a non-empty string.");if(r){let n=[];"participantIds"in r?n=r.participantIds:n=this.joined.toArray().filter(i=>{var a;return(a=r.presetNames)==null?void 0:a.includes(i.presetName)}).map(i=>i.id),c(this,zt).broadcastToPeers(t,n,e)}else c(this,zt).broadcastMessage(t,e)}async getAllJoinedPeers(t,e,r){return(await c(this,zt).getRoomPeers(t,e,r)).peers.map(Wr.formatSocketServiceMessage)}async updatePermissions(t,e){const r=this.joined.toArray().filter(i=>t.includes(i.id)).map(i=>i.userId),n=[...new Set(r)];if(!n.length)throw new b("Cannot update permissions, no valid userIDs found");c(this,zt).updatePermissions(n,e)}async getParticipantsInMeetingPreJoin(){return c(this,zt).getRoomPeersNonPaginated()}},Bs=new WeakMap,vr=new WeakSet,ds=function(){return c(this,Bs).getValue("roomNodeClient")},Hs=new WeakMap,zt=new WeakMap,Fv);Jt([g.trace("DyteParticipants.setViewMode")],kt.prototype,"setViewMode",1),Jt([g.trace("DyteParticipants.setPage")],kt.prototype,"setPage",1),Jt([g.trace("DyteParticipants.disableAllAudio")],kt.prototype,"disableAllAudio",1),Jt([g.trace("DyteParticipants.disableAllVideo")],kt.prototype,"disableAllVideo",1),Jt([g.trace("DyteParticipants.disablePeerAudio")],kt.prototype,"disableAudio",1),Jt([g.trace("DyteParticipants.disablePeerVideo")],kt.prototype,"disableVideo",1),Jt([g.trace("DyteParticipants.kickPeer")],kt.prototype,"kick",1),Jt([g.trace("DyteParticipants.kickAll")],kt.prototype,"kickAll",1),Jt([g.trace("DyteParticipants.broadcastMessage"),Lt({maxInvocations:500,period:60})],kt.prototype,"broadcastMessage",1),Jt([g.trace("DyteParticipants.getAllJoinedPeers"),Lt({maxInvocations:10,period:60})],kt.prototype,"getAllJoinedPeers",1),Jt([g.trace("DyteParticipant.updatePermissions"),Lt({maxInvocations:1e3,period:60})],kt.prototype,"updatePermissions",1),Jt([g.trace("DyteParticipants.getParticipantsInMeetingPreJoin")],kt.prototype,"getParticipantsInMeetingPreJoin",1),kt=Jt([pt("1200")],kt);var oO=Object.defineProperty,cO=Object.getOwnPropertyDescriptor,ui=(s,t,e,r)=>{for(var n=r>1?void 0:r?cO(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&oO(t,e,n),n};const Gg=class{constructor(s,t,e){m(this,"participants");m(this,"self");m(this,"selectedPeers",new Mu);m(this,"maxSpatialLayerUpdates",new Map);m(this,"consumerPeerMap");m(this,"roomSocketHandler");m(this,"context");m(this,"videoPeerConsumerMap",new Map);m(this,"updateConsumerSpatialLayers",Vr(()=>{const s={},t=new Map(this.maxSpatialLayerUpdates);this.maxSpatialLayerUpdates.clear(),Array.from(t.entries()).forEach(([e,r])=>{s[r]===void 0&&(s[r]={layer:r,consumerIds:[]}),s[r].consumerIds.push(e)}),Object.keys(s).forEach(e=>{const r=s[e];l.log(`Switching max spatial layer to ${r.layer}`,{consumerIds:r.consumerIds}),this.roomNodeClient.switchConsumersToLayer(r.consumerIds,r.layer)})},2e3));m(this,"updateConsumers",Vr((s,t)=>{this.roomNodeClient.closeConsumers(t).then(()=>{this.roomNodeClient.createConsumers(s).catch(e=>l.error("Error activating peers",{error:e}))}).catch(e=>l.error("Error deactivating peers",{error:e}))},2e3,{trailing:!0}));this.context=s,this.roomSocketHandler=e,this.participants=new kt(s,t,this.roomSocketHandler),this.self=t,this.consumerPeerMap=new Map,t.config.viewType!=="CHAT"&&this.setupEventsGlobal()}get roomJoined(){var s;return((s=this.roomNodeClient)==null?void 0:s.roomJoined)===!0}get pip(){return this.context.getValue("pip")}waitingRoomRequestHandler(s){const t=s.requests.filter(r=>!this.participants.waitlisted.toArray().find(n=>n.userId===r.userId)),e=this.participants.waitlisted.toArray().filter(r=>!s.requests.find(n=>n.userId===r.userId));t.forEach(r=>this.participants.waitlisted.add(new Gr(this.context,{id:r.peerId,displayName:r.displayName,audioMuted:!0,videoEnabled:!1,audioTrack:void 0,videoTrack:void 0,stageStatus:"OFF_STAGE",userId:r.userId,flags:{},isHost:!1,customParticipantId:r.customParticipantId,picture:r.picture,metadata:{preset_name:r.presetName}},this.self,this.roomSocketHandler))),e.forEach(r=>this.participants.waitlisted.delete(r.id))}get maxPreferredStreams(){return this.participants.maxActiveParticipantsCount}async selectPagePeers(s){const{compulsoryPeers:t}=this.selectedPeers,e=t.filter(d=>this.participants.joined.has(d)),r=Array.from(this.participants.pinned.keys()).filter(d=>!e.includes(d)),n=Array.from(this.participants.joined.toArray().filter(d=>d.stageStatus==="ON_STAGE").map(d=>d.id)),i=Math.max((s-1)*(this.roomNodeClient.maxPreferredStreams-e.length-r.length)),a=s*(this.roomNodeClient.maxPreferredStreams-e.length-r.length);return e.concat(r,n.slice(i,a))}async selectActivePeers(){const s=new Map,t=Array.from(this.participants.joined.toArray().filter(u=>u.stageStatus==="ON_STAGE").map(u=>(s.set(u.id,!0),u.id))),e=this.selectedPeers.peers,r=this.participants.pinned.toArray().reduce((u,h)=>(h.stageStatus!=="ON_STAGE"?this.participants.pinned.delete(h.id):u.push(h.id),u),[]),n=this.self.stageStatus==="ON_STAGE"?1:0,i=this.participants.maxActiveParticipantsCount-n,a=new Set(e.concat(r).filter(u=>u!==this.self.id&&s.has(u)));let o=Array.from(a);const d=i-a.size;if(d>=0){const u=t.filter(h=>!a.has(h)&&h!==this.self.id).slice(0,d);o=Array.from(a).concat(u)}else o=o.slice(0,i);return o}async updateActive(s,t){const{page:e,createAllConsumers:r}=t!=null?t:{};let{strategies:n}=t!=null?t:{},i;switch(s){case"PAGINATED":{if(!e)return;i=await this.selectPagePeers(e),l.info("ParticipantController::updateActive::updating_current_page_peers",{peerIds:i}),n!=null||(n={video:this.updateParticipantsMap.bind(this),audio:this.updateParticipantsMap.bind(this)});break}case"ACTIVE_GRID":{i=await this.selectActivePeers(),l.info("ParticipantController::updateActive::updating_current_selected_peers",{peerIds:i}),n!=null||(n={video:this.updateParticipantsMapMinReplacement.bind(this),audio:this.updateParticipantsMap.bind(this)});break}default:throw new Error(`View mode ${s} not supported`)}let a,o;const d=this.updateGrid(i,n);r?(a=this.mapPeerIdsToProducers(i,["audio","video","screenshare"]),o=[]):(a=[...this.mapPeerIdsToProducers([...d.video.add],["video"]),...this.mapPeerIdsToProducers([...d.audio.add],["audio"])],o=[...this.mapPeerIdsToProducers([...d.video.remove],["video"]),...this.mapPeerIdsToProducers([...d.audio.remove],["audio"])]),this.updateConsumers(a,o)}computeActivateParticipants(s,t){const e=s.map((n,i)=>({peerId:n,priority:i+1})),r=t==null?void 0:t.map((n,i)=>({peerId:n,priority:-(i+1)}));e.push(...r!=null?r:[]),e.length>0&&this.updateActiveParticipantsWithPriorities(e)}fromSocketService(s){const t=Gg.formatSocketServiceMessage(s);return new Gr(this.context,{...t,isHost:!1,videoEnabled:!1,audioMuted:!0,videoTrack:void 0,audioTrack:void 0},this.self,this.roomSocketHandler)}updatePipSource(s,t){var e,r;t?(e=this.pip)==null||e.enableSource(s):(r=this.pip)==null||r.disableSource(s)}onMediaJoined(s,t){if(!this.roomJoined||s===this.self.id)return;const e=this.participants.joined.get(s);if(!e){l.warn(`Recieved media.peerJoinedBroadcast for non-existent peer ${s}`);return}t.forEach(r=>{r.kind===Nt.AUDIO&&!r.screenShare?e.setAudioEnabled(!r.pause):r.kind===Nt.VIDEO&&!r.screenShare&&(e.setVideoEnabled(!r.pause),this.updatePipSource(e.id,!r.pause)),e.producers.push({...r,producingTransportId:r.producingTransportId,kind:r.kind===Nt.AUDIO?"audio":"video",producingPeerId:s})})}updateParticipantsMapMinReplacement(s,t){const e=Array.from(s.keys()),r=new Map(s),n=[],i=[],a=new Set(t),o=[];return e.forEach((d,u)=>{(!a.has(d)||!this.participants.joined.get(d))&&o.push(u)}),t.forEach(d=>{if(s.get(d))return;if(e.length{a.has(d)||i.concat(e.splice(u,1))}),Array.from(s.keys()).forEach(d=>{s.delete(d,!a.has(d))}),e.forEach(d=>{if(!this.participants.joined.get(d)){l.warn("updateActiveParticipants::participant_not_in_joined_list",{dyteParticipant:{id:d}});return}s.add(this.participants.joined.get(d),!r.get(d)),n.push(d)}),s.emit("participantsUpdate"),[n,i]}updateParticipantsMap(s,t){const e=Array.from(s.keys()),r=[],n=[];return e.forEach(i=>{t.includes(i)||(s.delete(i,!0),n.push(i))}),t.forEach(i=>{s.get(i)||(s.add(this.participants.joined.get(i)),r.push(i))}),s.emit("participantsUpdate"),[r,n]}updatePinnedParticipants(){this.participants.pinned.forEach(s=>{s.setIsPinned(!1),this.participants.pinned.delete(s.id)})}setupEventsGlobal(){this.roomSocketHandler.on($.joinRoom,({peer:s})=>{if(!s.waitlisted){const t=J.hasFeature(X.DEBUG_SOCKET_JOIN);t&&l.info("Processing socket join",{peers:s.peerId}),this.onParticipantJoined(this.fromSocketService(s)),t&&l.info("Processed socket join",{peers:s.peerId})}}),this.roomSocketHandler.on($.leaveRoom,s=>{this.selectedPeers.delete(s.peer.peerId),this.onParticipantLeave(s.peer.peerId)}),w.on(C.SOCKET_SERVICE_ROOM_JOINED,()=>{this.self.permissions.acceptWaitingRequests&&this.roomSocketHandler.getWaitingRoomRequests()}),this.self.permissions.on("permissionsUpdate",s=>{const{acceptWaitingRequests:t}=s;t!==void 0&&(t?this.roomSocketHandler.getWaitingRoomRequests():this.participants.waitlisted.clear())}),w.on(C.SOCKET_SERVICE_DISCONNECTED,()=>{this.participants.joined.clear(),this.participants.videoSubscribed.clear(),this.participants.audioSubscribed.clear(),this.participants.pinned.clear(),this.participants.currentPage=0,this.participants.viewMode="ACTIVE_GRID",this.participants.emit("viewModeChanged",{viewMode:"ACTIVE_GRID",currentPage:this.participants.currentPage,pageCount:this.participants.pageCount})}),w.on(C.CONSUMER_PAUSED,({id:s})=>{this.processConsumerPaused(s)}),w.on(C.CONSUMER_RESUMED,({id:s})=>{this.processConsumerResumed(s)}),w.on(C.NEW_CONSUMER,({id:s})=>{this.processNewConsumer(s)}),w.on(C.CONSUMER_CLOSED,({id:s})=>{this.processConsumerClosed(s)}),w.on(C.ROOM_MESSAGE,async({payload:s,type:t,timestamp:e})=>{this.participants.emit("broadcastedMessage",{type:t,payload:s,timestamp:e})}),w.on(C.MESSAGE,async({payload:s,type:t,timestamp:e})=>{t!=="spotlight"&&this.participants.emit("broadcastedMessage",{type:t,payload:s,timestamp:e})}),w.on(C.LOW_CONSUMER_SCORE,({peerId:s,score:t,kind:e})=>{const r=this.participants.joined.get(s);r&&(r.emit("poorConnection",{score:t,kind:e}),this.participants.emit("poorConnection",{participantId:s,score:t,kind:e}))}),w.on(C.CONSUMER_SCORE_UPDATE,({score:s,kind:t,appData:e,peerId:r,scoreStats:n})=>{var o;const i=t==="video"&&((o=e==null?void 0:e.screenShare)!=null?o:!1),a=this.participants.joined.get(r);a&&(a.emit("mediaScoreUpdate",{kind:t,isScreenshare:i,score:s,participantId:r,scoreStats:n}),this.participants.emit("mediaScoreUpdate",{kind:t,isScreenshare:i,score:s,participantId:r,scoreStats:n}))}),w.onAsync(C.KICK_PEER,async({peerId:s})=>{const t=this.participants.joined.get(s);await this.roomNodeClient.kick(s),await this.roomSocketHandler.kick(s),t?t.emit("kicked"):this.participants.joined.emit("kicked",{id:s})}),w.on(C.UPDATE_ACTIVE,async({page:s,createAllConsumers:t}={})=>{await this.updateActive(s?"PAGINATED":"ACTIVE_GRID",{page:s,createAllConsumers:t})})}async onParticipantPinned(s){if(!s){this.self.isPinned&&this.self.setIsPinned(!1),this.participants.pinned.size!==0&&this.updatePinnedParticipants();return}if(s===this.self.id){this.participants.pinned.size!==0&&this.updatePinnedParticipants(),this.self.setIsPinned(!0);return}const t=this.participants.joined.get(s);this.self.isPinned&&this.self.setIsPinned(!1),this.updatePinnedParticipants(),t.setIsPinned(!0),this.participants.pinned.add(t)}async onParticipantJoined(s){var e,r,n;if(this.self.id!==s.id&&!((e=s.flags)!=null&&e.recorder)&&!((r=s.flags)!=null&&r.hidden_participant)&&!((n=s.flags)!=null&&n.hiddenParticipant)&&(this.participants.videoSubscribed.delete(s.id),this.participants.audioSubscribed.delete(s.id),this.participants.joined.add(s),this.participants.waitlisted.delete(s.id),s.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&w.emit(C.UPDATE_STAGE_REQUESTS,{request:{displayName:s.name,userId:s.userId,peerId:s.id},add:!0})),w.emit(C.PEER_JOINED_INTERNAL,s),this.self.config.viewType===Xe.Webinar&&s.stageStatus!=="ON_STAGE"||this.roomNodeClient===void 0||this.participants.videoSubscribed.size>=this.roomNodeClient.maxPreferredStreams)return;const t=this.participants.currentPage;this.updateActive(t?"PAGINATED":"ACTIVE_GRID",{page:t})}async onParticipantLeave(s){const t=this.participants.joined.get(s);this.participants.joined.delete(s,!0,!0),this.participants.pinned.delete(s,!0,!0),this.participants.waitlisted.delete(s,!0,!0),t&&t.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&w.emit(C.UPDATE_STAGE_REQUESTS,{request:{displayName:t.name,userId:t.userId,peerId:t.id},add:!1});const{currentPage:e}=this.participants,r=this.maxPreferredStreams*(e-1),n=this.participants.videoSubscribed.get(s);r===0?this.participants.setViewMode("ACTIVE_GRID"):this.participants.joined.size<=r?e===2?this.participants.setViewMode("ACTIVE_GRID"):this.participants.setPage(e-1):n&&this.updateActive(e?"PAGINATED":"ACTIVE_GRID",{page:e})}processMedia(s){var h;const t=this.roomNodeClient.getConsumers(),{peerId:e,kind:r,appData:n,remotelyPaused:i,track:a,producerId:o,rtpReceiver:d}=(h=t.get(s))!=null?h:{};if(!e)return l.warn("processMedia::Peer ID is undefined",{consumer:{id:s,kind:r,peerId:e,appData:{supportsRemoteControl:n==null?void 0:n.supportsRemoteControl,screenShare:n==null?void 0:n.screenShare},remotelyPaused:i,producerId:o}}),{};const u=n;return r==="video"&&u.screenShare!==!0&&this.videoPeerConsumerMap.set(e,s),l.info("ParticipantController::processMedia",{consumer:{id:s,peerId:e,kind:r,appData:u,remotelyPaused:i,producerId:o}}),this.consumerPeerMap.set(s,{type:r,peerId:e,appData:u,remotelyPaused:i,producerId:o}),{peerId:e,kind:r,appData:u,remotelyPaused:i,track:a,producerId:o,rtpReceiver:d}}processConsumerClosed(s){const{peerId:t,type:e,appData:r,remotelyPaused:n,producerId:i}=this.consumerPeerMap.get(s)||{},a=this.participants.joined.get(t);if(l.info("ParticipantController::processConsumerClosed",{consumer:{id:s,peerId:t,appData:r,kind:e,remotelyPaused:n,producerId:i}}),this.consumerPeerMap.delete(s),e==="video"&&r.screenShare!==!0&&this.videoPeerConsumerMap.delete(t),!a)return;const o=[];r&&r.screenShare?(a.setScreenShareEnabled(!1),U.consumerSharedMediaState(s,{screen:!1}),a.screenShareTracks.video&&o.push(a.screenShareTracks.video.id),a.screenShareTracks.audio&&o.push(a.screenShareTracks.audio.id),a.screenShareTracks={audio:void 0,video:void 0}):e==="audio"?(a.setAudioEnabled(!1),a.audioTrack&&o.push(a.audioTrack.id),U.consumerSharedMediaState(s,{audio:!1}),a.audioTrack=void 0):e==="video"&&(a.setVideoEnabled(!1),this.updatePipSource(a.id,!1),a.videoTrack&&o.push(a.videoTrack.id),U.consumerSharedMediaState(s,{video:!1}),a.videoTrack=void 0),r.e2ee&&o.forEach(d=>{w.emit(C.E2EE_INACTIVE_CONSUMER,{peerId:t,trackId:d})})}processConsumerResumed(s){const{peerId:t,kind:e,appData:r,track:n,remotelyPaused:i,producerId:a,rtpReceiver:o}=this.processMedia(s);if(!t)return;l.info("ParticipantController::processConsumerResumed",{consumer:{id:s,peerId:t,kind:e,appData:r,remotelyPaused:i,producerId:a}});const d=this.participants.joined.get(t);if(d){if(r.e2ee&&w.emit(C.E2EE_ACTIVE_CONSUMER,{peerId:t,rtpReceiver:o,track:n}),r.screenShare){e==="video"?d.screenShareTracks.video=n:e==="audio"&&(d.screenShareTracks.audio=n),d.setScreenShareEnabled(!0),U.consumerSharedMediaState(s,{screen:!0});return}e==="video"?(d.videoTrack=n,d.setVideoEnabled(!0),this.updatePipSource(d.id,!0),U.consumerSharedMediaState(s,{video:!0})):e==="audio"&&(d.audioTrack=n,d.setAudioEnabled(d.audioEnabled),U.consumerSharedMediaState(s,{audio:d.audioEnabled}))}}processConsumerPaused(s){l.info(`ParticipantController::processConsumerPaused called for consumerId: ${s}`);const{peerId:t,kind:e,track:r,appData:n,remotelyPaused:i,producerId:a}=this.processMedia(s);if(!t)return;l.info("ParticipantController::processConsumerPaused",{consumer:{id:s,peerId:t,kind:e,appData:n,remotelyPaused:i,producerId:a}});const o=this.participants.joined.get(t);o&&(r&&n.e2ee&&w.emit(C.E2EE_INACTIVE_CONSUMER,{peerId:t,trackId:r.id}),e==="video"?(o.videoTrack=r,o.setVideoEnabled(!1),this.updatePipSource(o.id,!1),U.consumerSharedMediaState(s,{video:!1})):e==="audio"&&(o.audioTrack=r,o.setAudioEnabled(o.audioEnabled),U.consumerSharedMediaState(s,{audio:o.audioEnabled})))}processNewConsumer(s){const{peerId:t,kind:e,remotelyPaused:r,track:n,appData:i,producerId:a,rtpReceiver:o}=this.processMedia(s);if(!t)return;l.info("ParticipantController::processNewConsumer",{consumer:{id:s,peerId:t,kind:e,remotelyPaused:r,appData:i,producerId:a}});const d=this.participants.joined.get(t);if(d){if(i.screenShare){e==="video"?d.screenShareTracks.video=n:e==="audio"&&(d.screenShareTracks.audio=n),(!r||this.self.permissions.isRecorder||J.hasFeature(X.SCREEENSHARE_ERR_HACK))&&d.setScreenShareEnabled(!0),i.supportsRemoteControl&&(d.supportsRemoteControl=!0),this.participants.broadcastMessage("screenshareConsumerCreated",{producerId:a,peerId:t,screenShare:!0,consumerId:s,consumerPeerId:this.self.id}),l.info("ParticipantController::newScreenshareConsumer::screenshareConsumerCreated",{consumer:{id:s,peerId:t,kind:e,remotelyPaused:r,appData:i,producerId:a}});return}e==="video"?(d.videoTrack=n,r||(d.setVideoEnabled(!0),this.updatePipSource(d.id,!0)),U.consumerSharedMediaState(s,{video:!r})):e==="audio"&&(d.audioTrack=n,r||d.setAudioEnabled(!0),U.consumerSharedMediaState(s,{audio:!r})),!r&&i.e2ee&&w.emit(C.E2EE_ACTIVE_CONSUMER,{peerId:t,rtpReceiver:o,track:n})}}static formatSocketServiceMessage(s){var e,r,n,i,a,o;if(!s)return;const t=lu(s.stageType);return{id:s.peerId,userId:s.userId,name:s.displayName,displayName:s.displayName,stageType:t,customParticipantId:s.customParticipantId,presetId:s.presetId,picture:s.displayPictureUrl,waitlisted:s.waitlisted,stageStatus:t,metadata:{preset_name:(e=s.flags)==null?void 0:e.presetName},recorderType:(r=s.flags)==null?void 0:r.recorderType,flags:{hiddenParticipant:(n=s.flags)==null?void 0:n.hiddenParticipant,hidden_participant:(i=s.flags)==null?void 0:i.hiddenParticipant,recorder:((a=s.flags)==null?void 0:a.recorderType)!==void 0&&((o=s.flags)==null?void 0:o.recorderType)!=="NONE"}}}mapPeerIdsToProducers(s,t){const e=(n,i)=>n.filter(({kind:a,screenShare:o})=>i.includes(a)||o&&i.includes("screenshare"));return s.flatMap(n=>{const i=this.participants.joined.get(n);if(i)return e(i.producers,t)}).filter(n=>!!n)}updateGrid(s,t){const[e,r]=t.video(this.participants.videoSubscribed,s),[n,i]=t.audio(this.participants.audioSubscribed,s);return{video:{add:e,remove:r},audio:{add:n,remove:i}}}async onSelectedPeers(s,t){if(this.participants.viewMode!=="ACTIVE_GRID")return;const e=s.map((n,i)=>({peerId:n,priority:i+1})),r=t==null?void 0:t.map((n,i)=>({peerId:n,priority:-(i+1)}));e.push(...r!=null?r:[]),e.length>0&&this.updateActiveParticipantsWithPriorities(e)}updateActiveParticipantsWithPriorities(s,t=!1){if(!this.roomJoined){l.warn("Skipped::ParticipantController::updateActiveParticipantsWithPriorities",{roomJoined:this.roomJoined});return}let e=null;s.forEach(r=>{this.selectedPeers.add(r.peerId,r.priority),(e===null||r.priority{for(var n=r>1?void 0:r?lO(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&dO(t,e,n),n};class Jg extends Wr{get roomNodeClient(){return this.context.getValue("roomNodeClient")}constructor(t,e,r){super(t,e,r),this.setupEvents()}setupEvents(){this.roomSocketHandler.on($.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),w.on(C.SOCKET_PEERS,async t=>{t==null||t.forEach(e=>this.onParticipantJoined(this.fromSocketService(e)))}),this.roomSocketHandler.on(ne.peerJoinedBroadcast,({participant:t})=>this.onMediaJoined(t.peerId,t.producerStates)),this.roomSocketHandler.on(ne.selfJoinComplete,({participants:t,selectedPeers:e,roomState:r})=>{t.forEach(a=>this.onMediaJoined(a.peerId,a.producerStates));const{audioPeers:n,compulsoryPeers:i}=e!=null?e:{};r.pinnedPeerIds.length!==0&&this.onParticipantPinned(r.pinnedPeerIds[0]),this.computeActivateParticipants(n!=null?n:[],i),w.emit(C.UPDATE_ACTIVE,{createAllConsumers:!0})}),w.on(C.MAX_SPATIAL_LAYER_CHANGE,({peerId:t,maxSpatialLayer:e})=>{const r=this.videoPeerConsumerMap.get(t);r&&(this.maxSpatialLayerUpdates.set(r,e),this.updateConsumerSpatialLayers())}),w.on(C.NEW_PRODUCER,({peerId:t,producer:e})=>{const r=this.participants.joined.get(t);if(!r){l.warn("ParticipantController::NEW_PRODUCER::participant not found",{producer:{id:e==null?void 0:e.producerId,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}},dyteParticipant:{id:t}});return}r.producers.push(e),l.info("ParticipantController::NEW_PRODUCER::producer_added_to_participant",{producer:{id:e==null?void 0:e.producerId,peerId:t,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}}}),(e==null?void 0:e.kind)==="audio"||e!=null&&e.screenShare||this.currentActiveGridParticipants.has(t)?this.roomNodeClient.createConsumers([e]).catch(n=>{l.error("ParticipantController::createConsumer failed",{error:n})}):l.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:e==null?void 0:e.producerId,peerId:t,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}}})}),w.on(C.PRODUCER_CLOSED,({peerId:t,producerId:e})=>{const r=this.participants.joined.get(t);if(!r){l.warn("ParticipantController::NEW_PRODUCER::participant not found",{dyteParticipant:{id:t}});return}r.producers=r.producers.filter(n=>n.producerId!==e)}),w.on(C.PRODUCER_TOGGLE,({peerId:t,producerId:e,paused:r,kind:n})=>{const i=this.participants.joined.get(t);if(i){n==="audio"&&i.setAudioEnabled(!r);const a=i.producers.find(o=>o.producerId===e);a&&(a.pause=r)}}),this.roomSocketHandler.on(ne.globalPeerPinBroadcast,({participantId:t})=>{if(!this.roomJoined)return;const e=t;this.onParticipantPinned(e);const r=this.participants.joined.get(e);this.roomNodeClient.activatePeers(r.producers).catch(n=>{l.error("unable to create consumers",{error:n})})}),this.roomSocketHandler.on(ne.selectedPeer,({audioPeers:t,compulsoryPeers:e})=>{this.roomJoined&&this.onSelectedPeers(e.concat(t))}),this.roomSocketHandler.on(ne.selectedPeerDiff,({entries:t})=>{if(!this.roomJoined||this.participants.viewMode!=="ACTIVE_GRID")return;const e=t.map(r=>({peerId:r.peerId,priority:r.priority}));this.updateActiveParticipantsWithPriorities(e,!0)})}}uO([g.trace("ParticipantController.setupEvents")],Jg.prototype,"setupEvents",1);var hO=Object.defineProperty,pO=Object.getOwnPropertyDescriptor,mO=(s,t,e,r)=>{for(var n=r>1?void 0:r?pO(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&hO(t,e,n),n};class Wg extends Wr{get roomNodeClient(){return this.context.getValue("roomNodeClient")}constructor(t,e,r){super(t,e,r),this.setupEvents()}setupEvents(){this.roomSocketHandler.on($.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),w.on(C.SOCKET_PEERS,async t=>{const e=J.hasFeature(X.DEBUG_SOCKET_JOIN);if(e){const r=t&&(t==null?void 0:t.length)<20?{peers:JSON.stringify(t.map(n=>n.peerId))}:void 0;l.info("Processing socket peers",r)}t==null||t.forEach(r=>{r.waitlisted||this.onParticipantJoined(this.fromSocketService(r))}),e&&l.info("Processed socket peers")}),this.roomSocketHandler.on(se.peerJoinedBroadcast,({participant:t})=>{J.hasFeature(X.DEBUG_SOCKET_JOIN)&&l.info("mediaEvents.peerJoinedBroadcast",{peers:t.peerId}),this.onMediaJoined(t.peerId,t.producerStates)}),this.roomSocketHandler.on(se.selfJoinComplete,({participants:t,selectedPeers:e,roomState:r})=>{if(J.hasFeature(X.DEBUG_SOCKET_JOIN)){const a=t&&(t==null?void 0:t.length)<20?{peers:JSON.stringify(t.map(o=>o.peerId))}:void 0;l.info("mediaEvents.selfJoinComplete",a)}t.forEach(a=>this.onMediaJoined(a.peerId,a.producerStates));const{audioPeers:n,compulsoryPeers:i}=e!=null?e:{};r.pinnedPeerIds.length!==0&&this.onParticipantPinned(r.pinnedPeerIds[0]),this.computeActivateParticipants(n!=null?n:[],i),w.emit(C.UPDATE_ACTIVE,{createAllConsumers:!0})}),w.on(C.MAX_SPATIAL_LAYER_CHANGE,({peerId:t,maxSpatialLayer:e})=>{const r=this.videoPeerConsumerMap.get(t);r&&(this.maxSpatialLayerUpdates.set(r,e),this.updateConsumerSpatialLayers())}),w.on(C.NEW_PRODUCER,({peerId:t,producer:e})=>{const r=this.participants.joined.get(t);if(!r){l.warn("ParticipantController::NEW_PRODUCER::participant not found",{producer:{id:e==null?void 0:e.producerId,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}},dyteParticipant:{id:t}});return}if(r.producers.push(e),l.info("ParticipantController::NEW_PRODUCER::producer_added_to_participant",{producer:{id:e==null?void 0:e.producerId,peerId:t,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}}}),this.participants.viewMode==="MANUAL"){let n=!1;const i=e.kind==="audio",a=e.kind==="video",o=r.manualProducerConfig;(i&&(o.audio&&!e.screenShare||o.screenshareAudio&&e.screenShare)||a&&(o.video&&!e.screenShare||o.screenshareVideo&&e.screenShare))&&(n=!0),n?this.roomNodeClient.createConsumers([e]):l.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:e==null?void 0:e.producerId,peerId:t,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}}});return}(e==null?void 0:e.kind)==="audio"&&this.participants.audioSubscribed.get(t)||(e==null?void 0:e.kind)==="video"&&this.participants.videoSubscribed.get(t)||e!=null&&e.screenShare?this.roomNodeClient.createConsumers([e]).catch(n=>{l.error("ParticipantController::createConsumer failed",{error:n})}):l.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:e==null?void 0:e.producerId,peerId:t,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}}})}),w.on(C.PRODUCER_CLOSED,({peerId:t,producerId:e})=>{const r=this.participants.joined.get(t);if(!r){l.warn("ParticipantController::PRODUCER_CLOSED::participant not found",{dyteParticipant:{id:t}});return}r.producers=r.producers.filter(n=>n.producerId!==e)}),w.on(C.PRODUCER_TOGGLE,({peerId:t,producerId:e,paused:r,kind:n})=>{const i=this.participants.joined.get(t);if(i){n==="audio"&&i.setAudioEnabled(!r);const a=i.producers.find(o=>o.producerId===e);a&&(a.pause=r)}}),this.roomSocketHandler.on(se.globalPeerPinBroadcast,t=>{let e;if(t&&(e=t.participantId),!this.roomJoined)return;const r=e;this.onParticipantPinned(r);const n=this.participants.joined.get(r);n&&this.roomNodeClient.activatePeers(n.producers).catch(i=>{l.error("unable to create consumers",{error:i})})}),this.roomSocketHandler.on(se.selectedPeer,({audioPeers:t,compulsoryPeers:e})=>{this.roomJoined&&this.onSelectedPeers(e.concat(t))}),this.roomSocketHandler.on(se.selectedPeerDiff,({entries:t})=>{if(!this.roomJoined||this.participants.viewMode!=="ACTIVE_GRID")return;const e=t.map(r=>({peerId:r.peerId,priority:r.priority}));this.updateActiveParticipantsWithPriorities(e,!0)})}}mO([g.trace("ParticipantController.setupEvents")],Wg.prototype,"setupEvents",1);const we=wr(Rl().permissions),Wi=class extends Ht{constructor(e,r,n,i=!1){super();S(this,At);S(this,q,void 0);S(this,Gi,void 0);S(this,Ji,void 0);S(this,Ad,e=>{var u,h,p;const{chat:r,connectedMeetings:n,plugins:i,polls:a,media:o,...d}=e;if(r&&(r.private&&ps(c(this,q).chat.private,r.private),r.public&&ps(c(this,q).chat.public,r.public),this.emit("chatUpdate")),n&&ps(c(this,q).connectedMeetings,n),o){const f=T=>{switch(T){case gs.NONE:return H.Allowed;case gs.ALLOWED:return H.Allowed;case gs.NOT_ALLOWED:return H.NotAllowed;case gs.CAN_REQUEST:return H.CanRequest;default:return}},v={audio:void 0,video:void 0,screenshare:void 0};(u=o.audio)!=null&&u.canProduce&&(v.audio={canProduce:f(o.audio.canProduce)}),(h=o.video)!=null&&h.canProduce&&(v.video={canProduce:f(o.video.canProduce)}),(p=o.screenshare)!=null&&p.canProduce&&(v.screenshare={canProduce:f(o.screenshare.canProduce)}),ps(c(this,q).media,v)}i&&(ps(c(this,q).plugins,i),this.emit("pluginsUpdate")),a&&(ps(c(this,q).polls,a),this.emit("pollsUpdate")),Object.keys(d).length!==0&&ps(c(this,q),d),this.emit("permissionsUpdate",e)});if(!r)throw l.error("DytePermissionsPreset::load_preset_permissions_failed"),new b("Could not load preset permissions.");y(this,Ji,e),y(this,Gi,n),y(this,q,r),i&&this.setupEvents()}setupEvents(){w.on(C.UPDATE_PERMISSIONS,c(this,Ad))}static fromResponse(e,r,n){return new Wi(n,e,r,!0)}static default(e,r){return new Wi(e,we,r)}static init(e,r,n){let i;return n?i=new Wi(e,n,r,!0):i=new Wi(e,we,r),i}get mediaRoomType(){const{sfu:e}=c(this,Ji).getValue("roomNodeOptions");return e===li.CF?"CF":"HIVE"}get stageEnabled(){var e;return((e=c(this,q))==null?void 0:e.stageEnabled)||c(this,Gi)===Xe.Webinar||c(this,Gi)===Xe.Livestream}get acceptStageRequests(){var e,r;return this.stageEnabled?((e=c(this,q))==null?void 0:e.acceptStageRequests)||((r=c(this,q))==null?void 0:r.canAcceptProductionRequests):!1}get stageAccess(){var e,r,n;return((e=c(this,q))==null?void 0:e.stageAccess)===H.NotAllowed?H.NotAllowed:((r=c(this,q))==null?void 0:r.stageAccess)===H.CanRequest?H.CanRequest:((n=c(this,q))==null?void 0:n.stageAccess)===H.Allowed||c(this,q).media.audio.canProduce===H.Allowed||c(this,q).media.video.canProduce===H.Allowed||c(this,q).media.screenshare.canProduce===H.Allowed?H.Allowed:c(this,q).media.audio.canProduce===H.CanRequest||c(this,q).media.video.canProduce===H.CanRequest||c(this,q).media.screenshare.canProduce===H.CanRequest?H.CanRequest:H.NotAllowed}get acceptWaitingRequests(){var e,r;return(r=(e=c(this,q))==null?void 0:e.acceptWaitingRequests)!=null?r:we.acceptWaitingRequests}get requestProduceVideo(){var e,r,n;return((n=(r=(e=c(this,q))==null?void 0:e.media)==null?void 0:r.video)==null?void 0:n.canProduce)===H.CanRequest}get requestProduceAudio(){var e,r,n;return((n=(r=(e=c(this,q))==null?void 0:e.media)==null?void 0:r.audio)==null?void 0:n.canProduce)===H.CanRequest}get requestProduceScreenshare(){var e,r,n;return((n=(r=(e=c(this,q))==null?void 0:e.media)==null?void 0:r.screenshare)==null?void 0:n.canProduce)===H.CanRequest}get canAllowParticipantAudio(){var e,r;return(r=(e=c(this,q))==null?void 0:e.disableParticipantAudio)!=null?r:we.disableParticipantAudio}get canAllowParticipantScreensharing(){var e,r;return(r=(e=c(this,q))==null?void 0:e.canAcceptProductionRequests)!=null?r:we.canAcceptProductionRequests}get canAllowParticipantVideo(){var e,r;return(r=(e=c(this,q))==null?void 0:e.disableParticipantVideo)!=null?r:we.disableParticipantVideo}get canDisableParticipantAudio(){return this.canAllowParticipantAudio}get canDisableParticipantVideo(){return this.canAllowParticipantVideo}get kickParticipant(){var e,r;return(r=(e=c(this,q))==null?void 0:e.kickParticipant)!=null?r:we.kickParticipant}get pinParticipant(){var e,r;return(r=(e=c(this,q))==null?void 0:e.pinParticipant)!=null?r:we.pinParticipant}get canRecord(){var e,r;return(r=(e=c(this,q))==null?void 0:e.canRecord)!=null?r:we.canRecord}get waitingRoomType(){var e,r;return(r=(e=c(this,q))==null?void 0:e.waitingRoomType)!=null?r:we.waitingRoomType}get waitingRoomBehaviour(){var e,r;return(r=(e=c(this,q))==null?void 0:e.waitingRoomType)!=null?r:we.waitingRoomType}get plugins(){var e,r;return(r=(e=c(this,q))==null?void 0:e.plugins)!=null?r:we.plugins}get polls(){var e,r;return(r=(e=c(this,q))==null?void 0:e.polls)!=null?r:we.polls}get produceVideo(){return this.canProduceVideo}get requestProduce(){return c(this,q).media.audio.canProduce===H.CanRequest||c(this,q).media.video.canProduce===H.CanRequest||c(this,q).media.screenshare.canProduce===H.CanRequest}get canProduceVideo(){var r;const e=(r=c(this,q).media.video.canProduce)!=null?r:we.media.video.canProduce;return this.stageEnabled&&(c(this,At,Yt)==="ACCEPTED_TO_JOIN_STAGE"||c(this,At,Yt)==="ON_STAGE")&&e===H.CanRequest?H.Allowed:this.stageEnabled&&(c(this,At,Yt)==="OFF_STAGE"||c(this,At,Yt)==="REQUESTED_TO_JOIN_STAGE")&&e===H.Allowed?H.NotAllowed:e}get produceScreenshare(){return this.canProduceScreenshare}get canProduceScreenshare(){var r;const e=(r=c(this,q).media.screenshare.canProduce)!=null?r:we.media.screenshare.canProduce;return this.stageEnabled&&(c(this,At,Yt)==="ACCEPTED_TO_JOIN_STAGE"||c(this,At,Yt)==="ON_STAGE")&&e===H.CanRequest?H.Allowed:this.stageEnabled&&(c(this,At,Yt)==="OFF_STAGE"||c(this,At,Yt)==="REQUESTED_TO_JOIN_STAGE")&&e===H.Allowed?H.NotAllowed:e}get produceAudio(){return this.canProduceAudio}get canProduceAudio(){var r;const e=(r=c(this,q).media.audio.canProduce)!=null?r:we.media.audio.canProduce;return this.stageEnabled&&(c(this,At,Yt)==="ACCEPTED_TO_JOIN_STAGE"||c(this,At,Yt)==="ON_STAGE")&&e===H.CanRequest?H.Allowed:this.stageEnabled&&(c(this,At,Yt)==="OFF_STAGE"||c(this,At,Yt)==="REQUESTED_TO_JOIN_STAGE")&&e===H.Allowed?H.NotAllowed:e}get chatPublic(){var e,r,n;return(n=(r=(e=c(this,q))==null?void 0:e.chat)==null?void 0:r.public)!=null?n:we.chat.public}get chatPrivate(){var e,r,n;return(n=(r=(e=c(this,q))==null?void 0:e.chat)==null?void 0:r.private)!=null?n:we.chat.private}get chatChannel(){var e,r,n;return(n=(r=(e=c(this,q))==null?void 0:e.chat)==null?void 0:r.channel)!=null?n:we.chat.channel}get chatMessage(){var e,r,n;return(n=(r=(e=c(this,q))==null?void 0:e.chat)==null?void 0:r.message)!=null?n:we.chat.message}get connectedMeetings(){var e,r;return(r=(e=c(this,q))==null?void 0:e.connectedMeetings)!=null?r:we==null?void 0:we.connectedMeetings}get hiddenParticipant(){var e,r;return(r=(e=c(this,q))==null?void 0:e.hiddenParticipant)!=null?r:we.hiddenParticipant}get showParticipantList(){var e;return(e=c(this,q).showParticipantList)!=null?e:we.showParticipantList}get canChangeParticipantRole(){var e,r;return(r=(e=c(this,q))==null?void 0:e.canChangeParticipantPermissions)!=null?r:we.canChangeParticipantPermissions}get canChangeParticipantPermissions(){var e,r;return(r=(e=c(this,q))==null?void 0:e.canChangeParticipantPermissions)!=null?r:we.canChangeParticipantPermissions}get canChangeTheme(){return!1}get canPresent(){return c(this,q).media.audio.canProduce===H.Allowed||c(this,q).media.video.canProduce===H.Allowed||c(this,q).media.screenshare.canProduce===H.Allowed}get acceptPresentRequests(){return this.acceptStageRequests}get canEditDisplayName(){var e;return(e=c(this,q).canEditDisplayName)!=null?e:!1}get maxScreenShareCount(){return 1}get isRecorder(){return c(this,q).isRecorder}get canSpotlight(){return c(this,q).canSpotlight}get canLivestream(){return c(this,q).canLivestream}get transcriptionEnabled(){return c(this,q).transcriptionEnabled}};let Du=Wi;q=new WeakMap,Gi=new WeakMap,Ji=new WeakMap,Ad=new WeakMap,At=new WeakSet,Yt=function(){return c(this,Ji).getValue("stageStatus")};class fO extends Ht{constructor(){super(...arguments);m(this,"localMediaHandler");S(this,Gu,void 0)}async updatePermission(){var d,u;const e=(h,p)=>{this.mediaPermissions[h]=p;const f={message:this.mediaPermissions[h],kind:h};p==="DENIED"?w.emit(C.MEDIA_PERMISSION_ERROR,f):w.emit(C.MEDIA_PERMISSION_UPDATE,f)};if(Se.getName()==="firefox")return;const r="microphone",n="camera",i=await((d=navigator==null?void 0:navigator.permissions)==null?void 0:d.query({name:r})),a=await((u=navigator==null?void 0:navigator.permissions)==null?void 0:u.query({name:n})),o=(h,p)=>{switch(p){case"granted":e(h,"ACCEPTED");break;case"denied":e(h,"DENIED");break;case"prompt":e(h,"NOT_REQUESTED");break}this.localMediaHandler.repopulateAvailableDevices()};i&&(i.onchange=()=>o("audio",i.state)),a&&(a.onchange=()=>o("video",a.state))}async populateMediaPermissionsInCallstats({message:e,kind:r}){U.onSafeInitialization(()=>{switch(r){case"audio":{U.mediaPermission("AUDIO",e),U.mediaPermission("SPEAKER",e);break}case"video":{U.mediaPermission("VIDEO",e);break}case"screenshare":{U.mediaPermission("SCREENSHARE",e);break}}})}async init(e={},r=!1,n=null){var i,a,o,d,u;if(Se.init(),!this.localMediaHandler)try{let h=!0;if(n!=null&&n.getValue("defaults").mediaHandler)h=!1,this.localMediaHandler=n.getValue("defaults").mediaHandler.localMediaHandler;else if(navigator.RNLocalMediaHandlerImpl){const{RNLocalMediaHandlerImpl:p}=navigator;this.localMediaHandler=await p.init()}else this.localMediaHandler=new Ft(n,e.constraints,(i=n==null?void 0:n.getValue("defaults"))==null?void 0:i.isNonPreferredDevice,(a=n==null?void 0:n.getValue("defaults"))==null?void 0:a.autoSwitchAudioDevice);if(w.on(C.MEDIA_PERMISSION_UPDATE,async p=>{if(this.populateMediaPermissionsInCallstats({message:p.message,kind:p.kind}),p.message==="NOT_REQUESTED")switch(p==null?void 0:p.kind){case"audio":this.rawAudioTrack&&(l.info("Disabling audio due to media permission update"),this.disableAudio());break;case"video":this.rawVideoTrack&&(l.info("Disabling video due to media permission update"),this.disableVideo());break;default:break}this.emit("mediaPermissionUpdate",p)}),w.on(C.MEDIA_PERMISSION_ERROR,async p=>{const{kind:f,message:v,constraints:T}=p;this.populateMediaPermissionsInCallstats({message:v,kind:f}),f==="audio"?(l.info(`Disabling audio due to media permission error skipping: ${this.localMediaHandler.audioUpdateInProgress}`),this.localMediaHandler.audioUpdateInProgress===!1&&this.disableAudio()):f==="video"&&(l.info(`Disabling video due to media permission error skipping: ${this.localMediaHandler.videoUpdateInProgress}`),this.localMediaHandler.videoUpdateInProgress===!1&&this.disableVideo()),l.error("SelfController::mediaPermissionError",{error:{message:v},constraints:T,mediaPermissionsErrors:{kind:f,message:v}}),this.emit("mediaPermissionError",p),this.emit("mediaPermissionUpdate",{message:v,kind:f})}),h){l.info(`Setting up DyteSelfMedia streams using media handler. audio:${!!(e!=null&&e.audio)} video:${(o=e==null?void 0:e.video)!=null?o:!0}`);const p=this.localMediaHandler.setupStreams({video:(d=e==null?void 0:e.video)!=null?d:!0,audio:(u=e==null?void 0:e.audio)!=null?u:!0});r||await p}}catch(h){l.error("DyteSelf::init::Failed To Setup Streams",{error:{name:h.name,message:h.message}})}}get audioTrack(){return this.localMediaHandler.audioTrack}get rawAudioTrack(){return this.localMediaHandler.rawAudioTrack}get mediaPermissions(){return this.localMediaHandler.permissions}async addAudioMiddleware(e){return this.localMediaHandler.addAudioMiddleware(e)}async removeAudioMiddleware(e){return this.localMediaHandler.removeAudioMiddleware(e)}get videoTrack(){return this.localMediaHandler.videoTrack}get rawVideoTrack(){return this.localMediaHandler.rawVideoTrack}async addVideoMiddleware(e){return this.localMediaHandler.addVideoMiddleware(e)}async setVideoMiddlewareGlobalConfig(e={disablePerFrameCanvasRendering:!1}){return this.localMediaHandler.setVideoMiddlewareGlobalConfig(e)}async removeVideoMiddleware(e){return this.localMediaHandler.removeVideoMiddleware(e)}get screenShareTracks(){return this.localMediaHandler.screenShareTracks}get audioEnabled(){return this.localMediaHandler.audioEnabled}get videoEnabled(){return this.localMediaHandler.videoEnabled}get screenShareEnabled(){return this.localMediaHandler.screenShareEnabled}async enableAudio(){await this.localMediaHandler.enableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}async enableVideo(){await this.localMediaHandler.enableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}async disableAudio(){this.localMediaHandler.disableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}async enableScreenShare(){await this.localMediaHandler.enableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}async disableScreenShare(){await this.localMediaHandler.disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}async disableVideo(){await this.localMediaHandler.disableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}getCurrentDevices(){return this.localMediaHandler.getCurrentDevices()}async getAudioDevices(){return await this.localMediaHandler.getAudioDevices()}async getVideoDevices(){return await this.localMediaHandler.getVideoDevices()}async getSpeakerDevices(){return await this.localMediaHandler.getSpeakerDevices()}getDeviceById(e,r){let n;return r==="audio"?n="audioinput":r==="video"?n="videoinput":r==="speaker"&&(n="audiooutput"),this.localMediaHandler.getDeviceById(e,n)}async setDevice(e){switch(e.kind){case"audioinput":try{await this.localMediaHandler.setAudioDevice(e)}catch(r){}finally{this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}break;case"audiooutput":await this.localMediaHandler.setSpeakerDevice(e);break;case"videoinput":try{await this.localMediaHandler.setVideoDevice(e)}catch(r){}finally{this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}this.emit("deviceUpdate",{device:e})}}Gu=new WeakMap;const wa={},_s={executeWithLock({methodName:s,lockName:t,timeout:e}){return(r,n,i)=>{const a=i.value;return i.value=function(...d){if(wa[t]){const p=new Error(`Unsupported concurrent calls on Dyte method: ${s}.`);throw p.name="UnsupportedConcurrentMethodExecution",l.error("DyteLocker::UnsupportedConcurrentMethodExecution",{error:{stack:p.stack},dyteLocker:{methodName:s,lockName:t}}),p}wa[t]=!0;const u=setTimeout(()=>delete wa[t],e),h=a.apply(this,d);return Promise.resolve(h).then(()=>{delete wa[t],clearTimeout(u)}).catch(()=>{delete wa[t],clearTimeout(u)}),h},i}}};var gO=Object.defineProperty,vO=Object.getOwnPropertyDescriptor,xt=(s,t,e,r)=>{for(var n=r>1?void 0:r?vO(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&gO(t,e,n),n};let ut=(xv=class extends fO{constructor(t,e,r,n,i){var a;super();S(this,js);S(this,Ye);S(this,ao);m(this,"name");m(this,"picture");m(this,"customParticipantId");m(this,"waitlistStatus");S(this,io,void 0);S(this,Ut,void 0);S(this,Ki,void 0);m(this,"role");m(this,"userId");m(this,"organizationId");m(this,"supportsRemoteControl",!1);m(this,"device");S(this,qs,void 0);m(this,"presetName");m(this,"roomState","init");S(this,zi,new Set);S(this,Yi,new Set);y(this,qs,t),this.userId=e.id,this.name=e.name,this.picture=e.picture,this.customParticipantId=(a=e.customParticipantId)!=null?a:e.clientSpecificId,this.waitlistStatus="none",y(this,Ut,r),y(this,io,n),y(this,Ki,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=Se.isElectron(),this.device=Se.getDeviceInfo(),this.presetName=i,n.viewType!==Xe.Chat&&this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),je(this,ao,Zu).call(this)}get stageStatus(){return c(this,qs).getValue("stageStatus")}get id(){return c(this,qs).getValue("peerId")}static async __init__(t,e,r,n,i,a=!1){var p,f,v,T,P;let o=(f=(p=t.getValue("defaults"))==null?void 0:p.audio)!=null?f:!0,d=(T=(v=t.getValue("defaults"))==null?void 0:v.video)!=null?T:!0;r.canProduceAudio!=="ALLOWED"&&(o=!1),r.canProduceVideo!=="ALLOWED"&&(d=!1);const u=new ut(t,e,r,n,i);if(n.viewType===Xe.Chat)return u;const h=G0(n.mediaConstraints);return ps(h,(P=t.getValue("defaults"))==null?void 0:P.mediaConfiguration),await u.init({audio:o,video:d,constraints:h},a,t),u.setupEvents(),u}setupEvents(){this.on("videoUpdate",je(this,ao,Zu)),this.localMediaHandler.on("AUDIO_TRACK_CHANGE",async()=>{if(l.info("DyteSelf::setupEvents::AUDIO_TRACK_CHANGE",{...pn(this)}),this.roomJoined&&this.audioEnabled)try{await c(this,Ye,it).shareMic(this.audioTrack)}catch(t){l.error("DyteSelf::setupEvents::Error while sharing mic",{error:t}),this.localMediaHandler.disableAudio()}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}),this.localMediaHandler.on("VIDEO_TRACK_CHANGE",async()=>{if(l.info("DyteSelf::setupEvents::VIDEO_TRACK_CHANGE",{...pn(this)}),this.roomJoined&&this.rawVideoTrack===void 0)l.info("DyteSelf::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&this.roomJoined)try{const t=await c(this,Ye,it).shareWebcam(this.videoTrack);t&&t.id!==this.videoTrack.id&&J.hasFeature(X.EXP_RESHARE)&&await c(this,Ye,it).shareWebcam(this.videoTrack)}catch(t){l.error("DyteSelf::setupEvents::failed shareWebcam",{error:t}),this.videoEnabled&&await this.localMediaHandler.disableVideo()}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}),this.localMediaHandler.on("DEVICE_CHANGE",async({device:t})=>{this.emit("deviceUpdate",{device:t})}),this.localMediaHandler.on("DEVICE_LIST_UPDATED",t=>{this.emit("deviceListUpdate",t)}),this.localMediaHandler.on("SCREENSHARE_TRACK_CHANGE",async()=>{if(!this.roomJoined){l.error("DyteSelf.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{await c(this,Ye,it).shareScreen(this.screenShareTracks)}catch(t){l.error("DyteSelf::setupEvents::Error while sharing screen",{error:t}),this.screenShareEnabled&&await this.localMediaHandler.disableScreenShare()}l.info("DyteSelf::setupEvents::SCREENSHARE_TRACK_CHANGE",{...pn(this)}),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}),this.localMediaHandler.on("SCREENSHARE_ENDED",async()=>{l.log("Disabling screenshare due to SCREENSHARE_ENDED"),await this.disableScreenShare(),l.info("DyteSelf::setupEvents::SCREENSHARE_ENDED",{...pn(this)})}),this.localMediaHandler.on("AUDIO_TRACK_SILENT",()=>{U.mediaTrackMuted("AUDIO")}),this.localMediaHandler.on("FORCE_MUTE_AUDIO",()=>{this.disableAudio()}),this.localMediaHandler.on("FORCE_MUTE_VIDEO",async()=>{this.roomJoined&&await c(this,Ye,it).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),U.videoOff()}),c(this,Ut).on("permissionsUpdate",t=>{var e,r,n;(e=t==null?void 0:t.media)!=null&&e.audio&&c(this,Ut).canProduceAudio!==H.Allowed&&(this.disableAudio(),l.info(`Disabled audio due to dynamic preset change: canProduceAudio: ${this.permissions.canProduceAudio}`)),(r=t==null?void 0:t.media)!=null&&r.video&&c(this,Ut).canProduceVideo!==H.Allowed&&(this.disableVideo(),l.info(`Disabled video due to dynamic preset change: canProduceVideo: ${this.permissions.canProduceVideo}`)),(n=t==null?void 0:t.media)!=null&&n.screenshare&&c(this,Ut).canProduceScreenshare!==H.Allowed&&(this.disableScreenShare(),l.info(`Disabled screenshare due to dynamic preset change: canProduceScreenshare: ${this.permissions.canProduceScreenshare}`))})}get permissions(){return c(this,Ut)}get config(){return c(this,io)}get roomJoined(){var t;return((t=c(this,Ye,it))==null?void 0:t.roomJoined)===!0}setName(t){if(!t)throw new b("Name cannot be empty.");this.name=t}async setupTracks(t={}){var e,r;return t.forceReset&&(c(this,Ye,it).stopAllProducers(),this.localMediaHandler.removeAllTracks()),this.localMediaHandler.setupStreams({video:(e=t.video)!=null?e:!0,audio:(r=t.audio)!=null?r:!0})}async destructMediaHandler(){return this.localMediaHandler.destruct()}async removeDocumentEventListeners(){return this.localMediaHandler.removeDocumentEventListeners()}async enableAudio(){if(this.permissions.canProduceAudio!==H.NotAllowed&&!(c(this,Ut).canProduceAudio===H.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.audioEnabled){if(await this.localMediaHandler.enableAudio(),this.roomJoined&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{await c(this,Ye,it).shareMic(this.audioTrack)}catch(t){l.error("DyteSelf::enableAudio::Error while sharing mic",{error:t}),this.localMediaHandler.disableAudio()}if(!this.audioEnabled)return;c(this,Ye,it).unmuteSelf()}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),U.audioOn()}}async enableVideo(){if(c(this,Ut).canProduceVideo!==H.NotAllowed&&!(c(this,Ut).canProduceVideo===H.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.videoEnabled){if(await this.localMediaHandler.enableVideo(),this.roomJoined&&this.stageStatus==="ON_STAGE")try{await c(this,Ye,it).shareWebcam(this.videoTrack)}catch(t){l.error("DyteSelf::enableVideo::Error while sharing video",{error:t}),this.videoEnabled&&await this.localMediaHandler.disableVideo()}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),l.info("DyteSelf.enableVideo",{...pn(this)}),U.videoOn()}}async updateVideoConstraints(t){if(!this.localMediaHandler.updateVideoConstraints)throw new b("Unsupported");await this.localMediaHandler.updateVideoConstraints(t)}async enableScreenShare(){if(!this.roomJoined)throw new b("Can`t enable screenshare without joining room");if(c(this,Ut).canProduceScreenshare!==H.NotAllowed&&!(c(this,Ut).canProduceScreenshare===H.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.screenShareEnabled&&(await this.localMediaHandler.enableScreenShare(),this.screenShareTracks.audio||this.screenShareTracks.video)){try{await c(this,Ye,it).shareScreen(this.screenShareTracks)}catch(t){l.error("DyteSelf::enableScreenShare::Error while sharing screen",{error:t}),this.screenShareEnabled&&await this.localMediaHandler.disableScreenShare()}this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}}async updateScreenshareConstraints(t){if(!this.localMediaHandler.updateScreenshareConstraints)throw new b("Unsupported");await this.localMediaHandler.updateScreenshareConstraints(t)}async disableAudio(){this.audioEnabled&&(this.localMediaHandler.disableAudio(),this.roomJoined&&c(this,Ye,it).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),U.audioOff())}async disableVideo(){this.videoEnabled&&(await this.localMediaHandler.disableVideo(),this.roomJoined&&await c(this,Ye,it).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),U.videoOff())}async disableScreenShare(){this.screenShareEnabled&&(await this.localMediaHandler.disableScreenShare(),this.roomJoined&&await c(this,Ye,it).disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var n;y(this,Ki,t);const r=t?"pinned":"unpinned";(n=c(this,js,ea))==null||n.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}get isPinned(){return c(this,Ki)}async pin(){if(!this.roomJoined)throw new b("Can`t pin participants without joining room");return c(this,Ye,it).pinPeer(this.id)}async unpin(){if(!this.roomJoined)throw new b("Can`t unpin participants without joining room");return c(this,Ye,it).pinPeer(null)}async setDevice(t){var r,n,i;if(!t)throw new b("No device selected");const e=this.getCurrentDevices();if(t.deviceId&&(((r=e==null?void 0:e.audio)==null?void 0:r.deviceId)===t.deviceId||((n=e==null?void 0:e.video)==null?void 0:n.deviceId)===t.deviceId||((i=e==null?void 0:e.speaker)==null?void 0:i.deviceId)===t.deviceId)&&(l.warn("DyteSelf.setDevice.setting_to_in_use_device",{devices:[t]}),J.hasFeature(X.SKIP_SETTING_IN_USE_DEVICE)))throw new b("Cannot set device currently in use");switch(t.kind){case"audioinput":try{await this.localMediaHandler.setAudioDevice(t)}catch(a){this.roomJoined&&await c(this,Ye,it).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}break;case"audiooutput":await this.localMediaHandler.setSpeakerDevice(t);break;case"videoinput":try{await this.localMediaHandler.setVideoDevice(t)}catch(a){this.roomJoined&&await c(this,Ye,it).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}}cleanUpTracks(){var t,e,r,n;(t=this.audioTrack)==null||t.stop(),(e=this.rawAudioTrack)==null||e.stop(),(r=this.videoTrack)==null||r.stop(),(n=this.rawVideoTrack)==null||n.stop()}registerVideoElement(t,e=!1){var r;e?c(this,zi).add(t):c(this,Yi).add(t),this.updateVideo(t),e||c(this,js,ea).addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(r=this.raised)!=null?r:!1)}deregisterVideoElement(t,e=!1){t.srcObject=void 0,e?c(this,zi).delete(t):(c(this,Yi).delete(t),c(this,js,ea).removeSource(this.id))}updateVideo(t,e=!1){var r,n,i;if(this.videoEnabled){if(this.videoTrack==null)return;const a=(r=t.srcObject)==null?void 0:r.getTracks()[0];if((a==null?void 0:a.id)===this.videoTrack.id)return;const o=new MediaStream;o.addTrack(this.videoTrack),t.srcObject=o,e||(n=c(this,js,ea))==null||n.enableSource(this.id)}else t.srcObject=void 0,e||(i=c(this,js,ea))==null||i.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},io=new WeakMap,Ut=new WeakMap,Ki=new WeakMap,qs=new WeakMap,js=new WeakSet,ea=function(){return c(this,qs).getValue("pip")},Ye=new WeakSet,it=function(){return c(this,qs).getValue("roomNodeClient")},zi=new WeakMap,Yi=new WeakMap,ao=new WeakSet,Zu=function(){Array.from(c(this,Yi)).forEach(t=>this.updateVideo(t,!1)),Array.from(c(this,zi)).forEach(t=>this.updateVideo(t,!0))},xv);xt([g.trace("DyteSelf.setupEvents")],ut.prototype,"setupEvents",1),xt([g.trace("DyteSelf.setupTracks")],ut.prototype,"setupTracks",1),xt([g.trace("DyteSelf.destructMediaHandler")],ut.prototype,"destructMediaHandler",1),xt([g.trace("DyteSelf.removeDocumentEventListeners")],ut.prototype,"removeDocumentEventListeners",1),xt([_s.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),g.trace("DyteSelf.enableAudio")],ut.prototype,"enableAudio",1),xt([_s.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),g.trace("DyteSelf.enableVideo")],ut.prototype,"enableVideo",1),xt([g.trace("DyteSelf.updateVideoConstraints")],ut.prototype,"updateVideoConstraints",1),xt([g.trace("DyteSelf.enableScreenShare"),_s.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3})],ut.prototype,"enableScreenShare",1),xt([g.trace("DyteSelf.updateScreenshareConstraints")],ut.prototype,"updateScreenshareConstraints",1),xt([_s.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),g.trace("DyteSelf.disableAudio")],ut.prototype,"disableAudio",1),xt([_s.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),g.trace("DyteSelf.disableVideo")],ut.prototype,"disableVideo",1),xt([_s.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3}),g.trace("DyteSelf.disableScreenShare")],ut.prototype,"disableScreenShare",1),xt([g.trace("DyteSelf.setDevice")],ut.prototype,"setDevice",1),ut=xt([pt("1100")],ut);class yO extends xg{constructor(e){super(e);m(this,"sessionDescription");this.sessionDescription=e.sessionDescription}}class TO extends Hg{}class _O extends Bg{async retryFailedConsumerCreationTasks(t){return Qc(t.map(async e=>br(async r=>(r>0&&l.warn(`retrying failed consumer creation task: ${JSON.stringify(e)}`),this.consumerCreationTask({...e})))))}async consumerCreationTask({consumerId:t,producerId:e,producingPeerId:r,producingTransportId:n,streamId:i,trackId:a,paused:o,screenShare:d,appData:u,kind:h,sessionDescription:p}){const f=`${i}:${h}`,v={consumerId:t,producerId:e,producingPeerId:r,producingTransportId:n,streamId:i,trackId:a,sessionDescription:p,appData:u,kind:h,paused:o,screenShare:d,name:"consumer creation task error",message:"consumer creation failed"};return new Promise(async(P,k)=>{const I=setTimeout(()=>{this.consumerTrackEvents.delete(f),v.isTimedout=!0,k(v)},5e3),x=(W,Q)=>{try{if(W.readyState==="ended")clearTimeout(I),k(v);else{const oe=W;oe.enabled=!0,this.handler.midTransceiverMap.set(Q.mid,Q);const ve=new yO({id:t,localId:Q.mid,track:oe,paused:o,producerId:e,producingPeerId:r,handler:this.handler,appData:{...u,screenShare:d,peerId:r},reuseTrack:!0,rtpReceiver:Q.receiver,producingTransportId:n,sessionDescription:p});this.consumers.set(t,ve),ve.once("close",()=>{this.consumers.delete(ve.id),this.handler.midTransceiverMap.delete(Q.mid)}),l.info("consumer created for ",{consumer:{id:t,kind:h,appData:{screenShare:d},peerId:r,producerId:e}}),this.observer.emit("newconsumer",ve),clearTimeout(I),P(ve)}}catch(oe){l.warn("error while creating consumer:",oe),clearTimeout(I),k(v)}},V=this.consumerTrackPool.get(t);if((V==null?void 0:V.length)===2){x(V[0],V[1]);return}const O=this.unknownTracksMap.get(f);O?(this.unknownTracksMap.delete(f),x(O.track,O.transceiver)):this.consumerTrackEvents.set(f,x),p&&await this.safeEmitAsPromise("negotiate",{description:p})})}async connect(){try{const{offerSdp:t,callback:e}=await this.handler.connect(),{answer:r}=await this.safeEmitAsPromise("connect",{offer:t});if(await e(r),!await this.isConnected)throw new Error("ice connection failed")}catch(t){throw l.error("transport failed to connect:",t),t}}_ontrack(t){const{track:e,transceiver:r}=t;l.info(`track event received [trackId: ${e.id}]`);const n=`${r.mid}:${e.kind}`;e.addEventListener("ended",()=>{l.info(`rtc consumer track ended [trackId: ${e.id}]`),this.consumerTrackPool.delete(e.id),this.unknownTracksMap.delete(n)}),this.consumerTrackPool.set(e.id,[e,r]);const i=this.consumerTrackEvents.get(n);i?(i(e,r),this.consumerTrackEvents.delete(n)):(l.warn(`track event handler not found ${n}`),this.unknownTracksMap.set(n,t))}async consume(t){if(l.debug(`consume() producers: ${JSON.stringify(t)}`),this.closed)throw new lt("closed");if(this.direction!=="recv")throw new vn("not a receiving Transport");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(!await this.isConnected)return Promise.reject(new Error("Transport not connected"));const e=[],r=new Map;return t.forEach(n=>{var a;const i=(a=r.get(n.producingPeerId))!=null?a:[];r.set(n.producingPeerId,i.concat([n]))}),r.forEach(async(n,i)=>{const{consumersMap:a}=await this.safeEmitAsPromise("consume_peer",{producingPeerId:i});a.forEach((o,d)=>{const{consumerId:u,trackId:h,screenShare:p,paused:f,streamId:v,kind:T,appData:P,producingTransportId:k,sessionDescription:I}=o;e.push(this.consumerCreationTask({consumerId:u,trackId:h,streamId:v,kind:T,producerId:d,producingPeerId:i,producingTransportId:k,paused:f,screenShare:p,appData:P,sessionDescription:I}))})}),Qc(e)}async produce({track:t,encodings:e,codecOptions:r,stopTracks:n=!0,disableTrackOnPause:i=!0,zeroRtpOnPause:a=!1,appData:o={}}={}){if(l.debug(`produce() [track:${t.id}]`),t){if(this.direction!=="send")throw new vn("not a sending Transport");if(t.readyState==="ended")throw new lt("track ended");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(this.listenerCount("produce")===0)throw new TypeError('no "produce" listener set into this transport');if(o&&typeof o!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!await this.isConnected)return Promise.reject(new Error("Transport not connected"));const{producerId:d,localId:u,rtpSender:h}=await this.awaitQueue.push(async()=>{const{offerSdp:f,callback:v,sender:T,mid:P}=await this.handler.send({track:t,encodings:e,codecOption:r,screenShare:o==null?void 0:o.screenShare}),{answer:k,producerId:I}=await this.safeEmitAsPromise("produce",{offer:f,kind:t.kind,paused:i?!t.enabled:!1,appData:{...o||{},mid:P}}),x=await v(k);return{producerId:I,localId:x,rtpSender:T}},"producer"),p=new TO({id:d,localId:u,track:t,stopTracks:n,disableTrackOnPause:i,zeroRtpOnPause:a,appData:o,handler:this.handler,rtpSender:h});return this.producers.set(d,p),p.observer.on("close",()=>{this.producers.delete(p.id)}),this.emit("newproducer",p),this.observer.emit("newproducer",p),p}}class SO extends qg{createTransport({direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:a,config:o}){const d=Xs(),u=new _O({id:d,direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:a,handlerFactory:this.handlerFactory,config:o});return this._observer.emit("newtransport",u),u}}class EO{constructor(t){S(this,Et,void 0);y(this,Et,t)}async joinRoom(t,e,r=!1,n=null){const i={roomUuid:t,displayName:e,prejoined:r};return n&&(i.location=n),(await c(this,Et).sendMessagePromiseWithTimeout({event:ne.joinRoom,protobuf:af.toBinary(i),timeout:5e3})).payload}async connectTransport(t){const e=(await c(this,Et).sendMessagePromise(ne.createWebRTCTransport,Zm.toBinary(t))).payload,{transportId:r,description:n}=Hl.fromBinary(e),i={sdp:n==null?void 0:n.sdp,type:n.type};return{transportId:r,answer:i}}async produce(t){var i,a;const e=(await c(this,Et).sendMessagePromise(ne.produce,lf.toBinary(t))).payload,r=Ef.fromBinary(e);return{answer:{sdp:(i=r==null?void 0:r.description)==null?void 0:i.sdp,type:(a=r==null?void 0:r.description)==null?void 0:a.type},producerId:r.producerId}}async consume(t){const e=(await c(this,Et).sendMessagePromise(ne.consume,df.toBinary(t))).payload,{consumerIdsMap:{map:r},description:n}=Sf.fromBinary(e);return{consumerStateMap:r,sessionDescription:n}}async closeProducer(t){const e=(await c(this,Et).sendMessagePromise(ne.closeProducer,hf.toBinary(t))).payload,{description:r}=wf.fromBinary(e);return r}async closeConsumer(t){return(await c(this,Et).sendMessagePromise(ne.closeConsumer,pf.toBinary(t))).payload}async hostControlForPeer(t,e){const r={audio:e==="audio",screeShare:!1,video:e==="video",participantId:t},n=(await c(this,Et).sendMessagePromise(ne.hostControlPeer,gf.toBinary(r))).payload;if(!n)return!1;const{status:i}=Pf.fromBinary(n);return i==="success"}async hostControlForAll(t){const e={audio:t==="audio",screenShare:!1,video:t==="video"},r=(await c(this,Et).sendMessagePromise(ne.hostControlAllPeers,vf.toBinary(e))).payload;if(!r)return!1;const{status:n}=Rf.fromBinary(r);return n==="success"}async kickAll(){const t={},e=(await c(this,Et).sendMessagePromise(ne.kickAll,ql.toBinary(t))).payload;if(!e)return!1;const{status:r}=bf.fromBinary(e);return r==="success"}async kickPeer(t){const e=(await c(this,Et).sendMessagePromise(ne.kickPeer,mf.toBinary(t))).payload;if(!e)return!1;const{status:r}=Cf.fromBinary(e);return r==="success"}async changeDisplayName(t){const e=(await c(this,Et).sendMessagePromise(ne.changeDisplayName,ff.toBinary(t))).payload;if(!e)return!1;const{status:r}=kf.fromBinary(e);return r==="success"}async notifySelfJoinComplete(){const t={},e=(await c(this,Et).sendMessagePromise(ne.selfJoinComplete,of.toBinary(t))).payload;return Rc.fromBinary(e)}}Et=new WeakMap;const wO=Error("task execution aborted");class CO{constructor(t,e){m(this,"id");m(this,"executor");m(this,"cancel");this.id=t,this.executor=e}async execute(){return new Promise((t,e)=>{this.cancel=()=>e(wO),this.executor.then(r=>t(r))})}}let Kg=0;const td=new Map;class Ou{static execute(t){const e=Kg;Kg+=1;const r=new CO(e,t);return td.set(e,r),{id:e,value:r.execute().finally(()=>td.delete(e))}}static stop(t){const e=td.get(t);e&&(e.cancel(),td.delete(t))}}const bO=2e3;class PO extends Fg{constructor(e,r){super();S(this,Hn);m(this,"_device");m(this,"_sendTransport");m(this,"_recvTransport");m(this,"_consumers");m(this,"_producers");m(this,"_producerStatus");m(this,"_producerIdToConsumerIdMap");m(this,"_socket");m(this,"_socketHandler");m(this,"_totalTransportReconnectionCount");m(this,"_transportReconnectFailureCount");m(this,"_consumerCreationFailureCount");m(this,"_producerNotReadyFailureCount");m(this,"_consumerNotBoundFailureCount");m(this,"_transportDisconnectedTimer");m(this,"_iceTransportPolicy","all");m(this,"_transportConnectionFailCount",0);m(this,"lastConnectionTime",0);m(this,"transportConnectionStatus");m(this,"transportDisconnected");S(this,Or,void 0);y(this,Or,e),this._device=new SO({}),this._socket=r,c(this,Hn,Lo).mediaState={consuming:{state:Rt.NEW,reconnected:!1},producing:{state:Rt.NEW,reconnected:!1}},this.transportDisconnected={consuming:!1,producing:!1},this._socketHandler=new EO(r),this.reset()}get socket(){return this._socket}get producers(){return this._producers}get consumers(){return this._consumers}get producerIdToConsumerIdMap(){return this._producerIdToConsumerIdMap}get cfSocketHandler(){return this._socketHandler}get sendTransport(){return this._sendTransport}get recvTransport(){return this._recvTransport}reset(){this._producers=new Map,this._consumers=new Map,this._producerStatus=new Map,this._producerIdToConsumerIdMap=new Map,this.transportConnectionStatus=new Map,this._transportReconnectFailureCount=0,this._consumerCreationFailureCount=0,this._totalTransportReconnectionCount=0,this._producerNotReadyFailureCount=0,this._consumerNotBoundFailureCount=0,this._transportDisconnectedTimer={consuming:void 0,producing:void 0}}async setupTransports(e,r){const i=await We().getICEServers().catch(o=>(l.warn(`failed to get iceservers from server: ${o.message}`),[])),a=e.map(o=>{var u,h,p,f,v,T,P,k;const d=this.transportConnectionStatus.get(o);if(d&&!r)return d;switch(d&&r&&Ou.stop(d.id),o){case"send":{const I=Ou.execute(this.createSendTransport({iceServers:i,additionalSettings:{encodedInsertableStreams:(u=c(this,Or).getValue("modules").e2ee)==null?void 0:u.enabled},config:{enableHighBitrate:(f=(p=(h=c(this,Or).getValue("defaults").mediaConfiguration)==null?void 0:h.audio)==null?void 0:p.enableHighBitrate)!=null?f:!1,enableStereo:(P=(T=(v=c(this,Or).getValue("defaults").mediaConfiguration)==null?void 0:v.audio)==null?void 0:T.enableStereo)!=null?P:!1},iceTransportPolicy:this._iceTransportPolicy}));return this.transportConnectionStatus.set(o,I),I.value}case"recv":{const I=Ou.execute(this.createRecvTransport({iceServers:i,additionalSettings:{encodedInsertableStreams:(k=c(this,Or).getValue("modules").e2ee)==null?void 0:k.enabled},iceTransportPolicy:this._iceTransportPolicy}));return this.transportConnectionStatus.set(o,I),I.value}default:return l.warn(`What are you thinking when passing this transportType: ${o}?`,{transport:{type:o}}),Promise.reject(Error("TYPE_OF_TRANSPORT_UNKNOWN"))}});return Promise.all(a).finally(()=>{e.forEach(o=>{this.transportConnectionStatus.delete(o)})})}stopAllTransports(){var e,r,n,i;l.info(" closing all the transports"),(e=this._sendTransport)==null||e.close(),(r=this._sendTransport)==null||r.removeAllListeners(),(n=this._recvTransport)==null||n.close(),(i=this._recvTransport)==null||i.removeAllListeners(),this._sendTransport=void 0,this._recvTransport=void 0,this.reset()}async createSendTransport(e){var n,i,a,o;if(this._sendTransport&&this._sendTransport.connected){l.info("sendTransport::already_exists_in_connected_state",{transport:{id:(n=this._sendTransport)==null?void 0:n.id,serverId:(i=this._sendTransport)==null?void 0:i.serverId,type:"send"}});return}l.info("sendTransport::initializing_transport",{transport:{id:(a=this._sendTransport)==null?void 0:a.id,serverId:(o=this._sendTransport)==null?void 0:o.serverId,type:"send"}});const r=this._device.createSendTransport(e);this._transportDisconnectedTimer.producing=void 0,l.info("sendTransport::initialized_transport",{transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"send"}}),this.handleTransport(r,!1),l.info("sendTransport::connecting_transport",{transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"send"}});try{await br(async(d,u)=>{this.socket.isConnected||u(new Error("socket is not connected")),r.connectionState==="closed"&&u(new Error("transport is closed")),d>0&&l.debug(`retrying transport connect, count: ${d}`,{transport:{id:r.id,serverId:r.serverId,type:"send"}});try{await r.connect()}catch(h){throw l.error(`failed to connect send transport: ${r.id}`,{error:h,transport:{id:r.id,serverId:r.serverId,type:"send"}}),h.message==="ice connection failed"&&u(h),h}},{delayTime:100,strategy:"exponential",maxRetryCount:J.hasFeature(X.ENABLE_CF_INFINITE_RETRIES)?1/0:3}),l.info("sendTransport::connected_transport",{transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"send"}}),this._transportReconnectFailureCount=Math.max(0,this._transportReconnectFailureCount-1),this._producerNotReadyFailureCount=0,this._sendTransport=r,U.onSafeInitialization(()=>{U.configureSendTransport(r)})}catch(d){throw l.error(`failed to connect send transport after retry:${r.id}`,{error:d,transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"send"}}),r.close(),r.removeAllListeners(),this._transportReconnectFailureCount+=1,this.handleFailure(),d}}async createRecvTransport(e){var n,i,a,o,d;if(this._recvTransport&&this._recvTransport.connected){l.info("recvTransport::already_exists_in_connected_state",{transport:{id:(n=this._recvTransport)==null?void 0:n.id,serverId:(i=this._recvTransport)==null?void 0:i.serverId,type:"recv"}});return}l.info("recvTransport::initializing_transport",{transport:{id:(a=this._recvTransport)==null?void 0:a.id,serverId:(o=this._recvTransport)==null?void 0:o.serverId,type:"recv"}});const r=this._device.createRecvTransport({...e,additionalSettings:{...(d=e.additionalSettings)!=null?d:{},rtcAudioJitterBufferMaxPackets:25,rtcAudioJitterBufferFastAccelerate:!0,rtcAudioJitterBufferMinDelayMs:20}});this._transportDisconnectedTimer.consuming=void 0,l.info("recvTransport::initialized_transport",{transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"recv"}}),this.handleTransport(r,!0),l.info("recvTransport::connecting_transport",{transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"recv"}});try{await br(async(u,h)=>{this.socket.isConnected||h(new Error("socket is not connected")),r.connectionState==="closed"&&h(new Error("transport is closed")),u>0&&l.debug(`retrying transport connect, count: ${u}`,{transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"recv"}});try{await r.connect()}catch(p){throw l.error(`fail to connect recv transport: ${r.id}`,{error:p,transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"recv"}}),p.message==="ice connection failed"&&h(p),p}},{delayTime:100,strategy:"exponential",maxRetryCount:J.hasFeature(X.ENABLE_CF_INFINITE_RETRIES)?1/0:3}),l.info("recvTransport::connected_transport",{transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"recv"}}),this._transportReconnectFailureCount=Math.max(0,this._transportReconnectFailureCount-1),this._consumerCreationFailureCount=0,this._consumerNotBoundFailureCount=0,this.producerIdToConsumerIdMap.clear(),this._recvTransport=r,U.onSafeInitialization(()=>{U.configureRecvTransport(r)})}catch(u){throw l.error(`failed to connect recv transport after retry:${r.id}`,{error:u,transport:{id:r==null?void 0:r.id,serverId:r==null?void 0:r.serverId,type:"recv"}}),r.close(),r.removeAllListeners(),this._transportReconnectFailureCount+=1,this.handleFailure(),u}}handleTransport(e,r){if(e.on("connect",async({offer:n},i,a)=>{try{const o={consuming:r,description:{sdp:n.sdp,type:n.type,target:r?qt.SUBSCRIBER:qt.PUBLISHER}},{transportId:d,answer:u}=await this._socketHandler.connectTransport(o);e.setServerId(d),i({answer:u})}catch(o){l.error(`${r?"consumer":"producer"} transport connection error:`,{error:o,transport:{id:e==null?void 0:e.id,serverId:e==null?void 0:e.serverId,type:r?"recv":"send"}}),a(o)}}),e.on("connectionstatechange",async n=>{this.updateTransportState({state:n,direction:r?"consuming":"producing"}),l.info(`${r?"consumer":"producer"} transport connectionState:`,{transport:{id:e==null?void 0:e.id,serverId:e==null?void 0:e.serverId,type:r?"recv":"send",status:n}});const i=()=>{this._transportDisconnectedTimer[r?"consuming":"producing"]!==void 0&&(clearTimeout(this._transportDisconnectedTimer[r?"consuming":"producing"]),this._transportDisconnectedTimer[r?"consuming":"producing"]=void 0)};switch(n){case"connected":i(),this.lastConnectionTime=performance.now();break;case"disconnected":this._transportDisconnectedTimer[r?"consuming":"producing"]=setTimeout(()=>{this.triggerTransportReconnection(e,r)},bO);break;case"failed":if(e.closed)return;i(),this.triggerTransportReconnection(e,r);break}}),e.on("icecandidate",async n=>{l.debug("sending icecandidate:",{iceCandidate:n})}),e.on("datachannel:events",async(n,i)=>{var a,o;l.debug("got data channel message on event:",{rtcChannel:{label:n,message:i}});try{switch(i.type){case"negotiation":{this.negotiateOverDC(i,Zc(i),n,e);break}case"handshake":{const d={type:"handshake",payload:{message:"pong"}};e.sendResponseOverDC(n,Zc(i),d);break}case"consumer_toggle":{this.handleConsumerToggle(i.payload);break}case"hub-disconnect":{l.debug(`media hub disconnected, full_reconnect: ${(a=i.payload)==null?void 0:a.full_reconnect}`),((o=i.payload)==null?void 0:o.full_reconnect)===!0&&this.emit("rejoin");break}case"error":{this.handleErrorOverDC(i.payload,e.id);break}default:l.warn(`unknown event received from cf node, event: ${i.type}`);break}}catch(d){l.error(`Unable to handle the incoming datachannel message on channel ${n}`)}}),e.on("dc_error",()=>{e.direction==="recv"&&(l.warn("events datachannel did not open in 5s"),this.handleFailure())}),e.on("negotiate",async({description:n},i,a)=>{try{const o={sdp:n==null?void 0:n.sdp,type:n==null?void 0:n.type},d=await this.negotiate(e,o);i({answer:d})}catch(o){l.error("negotiate error:",{transport:{id:e.id,serverId:e.serverId,type:e.direction},error:o}),a(o)}}),!r){e.on("produce",async({offer:n,kind:i,paused:a,appData:o},d,u)=>{var v;const p=bu(n.sdp).media.filter(T=>i==="video"?T.type==="video":T.type==="audio").at(-1).msid,f={description:{sdp:n.sdp,type:n.type,target:qt.PUBLISHER},paused:a,kind:i,msid:p,appData:JSON.stringify(o),screenShare:(v=o.screenShare)!=null?v:!1};try{const{answer:T,producerId:P}=await this._socketHandler.produce(f);d({answer:T,producerId:P})}catch(T){l.error("create producer error:",{error:T}),u(T)}});return}e.on("consume_peer",async({producingPeerId:n},i,a)=>{l.info("consumePeer:",n);const o={producingPeerId:n};try{const d=await this._socketHandler.consume(o);l.debug(`consumePeer response for ${n}:`,{consumerStateMap:d.consumerStateMap});const u=new Map;Object.entries(d.consumerStateMap).forEach(([h,p])=>{var v,T,P;let f={};try{f=JSON.parse(p.producerState.appData)}catch(k){}u.set(h,{consumerId:p.consumerId,trackId:(v=p.producerTrack)==null?void 0:v.trackId,streamId:p.producerTrack.streamId,kind:p.producerState.kind===Nt.VIDEO?"video":"audio",appData:f,screenShare:(T=p.producerState)==null?void 0:T.screenShare,paused:(P=p.producerState)==null?void 0:P.pause,sessionDescription:d.sessionDescription,producingPeerId:n})}),i({consumersMap:u})}catch(d){l.error("consumePeer error:",{error:d}),a(d)}}),e.on("consume",async({producerId:n,producingPeerId:i},a,o)=>{var u,h,p,f,v,T,P,k,I;const d={producingPeerId:i,producerId:n};try{const x=await this._socketHandler.consume(d),V=x.consumerStateMap[n];let O={};try{O=JSON.parse((u=V.producerState)==null?void 0:u.appData)}catch(W){}l.info("consumer create response:",{consumer:{remotelyPaused:(h=V.producerState)==null?void 0:h.pause,producerId:(p=V.producerState)==null?void 0:p.producerId,kind:(v=(f=V.producerState)==null?void 0:f.kind)==null?void 0:v.toString(),appData:{...O,screenShare:(T=V.producerState)==null?void 0:T.screenShare},id:V.consumerId,sessionDescription:x.sessionDescription},consumerState:V}),a({consumerId:V.consumerId,screenShare:(P=V.producerState)==null?void 0:P.screenShare,trackId:(k=V.producerTrack)==null?void 0:k.trackId,streamId:V.producerTrack.streamId,kind:V.producerState.kind===Nt.VIDEO?"video":"audio",paused:(I=V.producerState)==null?void 0:I.pause,appData:O,sessionDescription:x.sessionDescription})}catch(x){l.error("error during consuming on server:",x),o(x)}})}async createProducer(e,r,n){var a;if(this._sendTransport===void 0||this._sendTransport.closed)return null;l.info("createProducer::initializing_producer",{producer:{id:"TO_BE_CREATED",kind:e,status:"initializing",appData:r==null?void 0:r.appData}});const i=this._producerStatus.get(e);if((i==null?void 0:i.trackId)===r.track.id&&(i==null?void 0:i.status)===Jr.INITIALIZING)return l.info("createProducer::producer getting initializing",{producer:{id:"GETTING_CREATED",status:"initializing",kind:e,appData:r==null?void 0:r.appData}}),null;this._producerStatus.set(e,{trackId:r.track.id,status:Jr.INITIALIZING});try{const o=await this._sendTransport.produce(r);return(a=r.appData)!=null&&a.e2ee&&w.emit(C.E2EE_ACTIVE_PRODUCER,o),l.info("createProducer::initialized_producer",{producer:{id:o==null?void 0:o.id,kind:e,status:"producing",appData:r==null?void 0:r.appData}}),o.on("close",async({offer:d,reason:u},h)=>{l.info("producer::closing",{debuggingHint:u,producer:{id:o==null?void 0:o.id,kind:e,status:"closing",appData:r==null?void 0:r.appData}});const p={producerId:o.id,description:{sdp:d.sdp,type:d.type,target:qt.PUBLISHER}};try{const f=await this._socketHandler.closeProducer(p),v={sdp:f==null?void 0:f.sdp,type:f==null?void 0:f.type};l.info("producer::closed",{producer:{id:o==null?void 0:o.id,kind:e,status:"closed",appData:r==null?void 0:r.appData}}),h({answer:v})}catch(f){l.error("producer close error",f)}this._producerStatus.delete(e),this._producers.delete(e),n(),this.reconfigureWebcamLayers()}),o.on("trackended",()=>{l.info("producer::trackended",{producer:{id:o==null?void 0:o.id,kind:e,status:"UNKNOWN",appData:o==null?void 0:o.appData}}),[Y.MIC,Y.WEBCAM].includes(e)||n()}),this._producers.set(e,o),this._producerStatus.set(e,{trackId:r.track.id,status:Jr.INITIALIZED}),this.reconfigureWebcamLayers(),o.track}catch(o){throw this._producerStatus.set(e,{status:Jr.NOT_INITIALIZED,trackId:r.track.id}),l.error("createProducer::transport_initialization_failed",{producer:{id:"FAILED_TO_CREATE",kind:e,status:"failed",appData:r==null?void 0:r.appData,error:o}}),o}}async reconfigureWebcamLayers(){if(!J.hasFeature(X.DISABLE_WEBCAM_LAYERS_ON_SCREENSHARE))return;const e=this.producers.get(Y.WEBCAM);e&&await this._switchProducerSpatialLayer(e,this.producers.get(Y.SCREENSHARE_VIDEO)?0:3)}async _switchProducerSpatialLayer(e,r){try{l.debug("switching layer of webcam producer to:",{media:{video:{layer:r}},producer:{id:e.id,kind:e.kind,appData:e.appData}}),await e.setMaxSpatialLayer(r)}catch(n){l.error("failed to switch spatial layer",{error:n})}}_initConsumer(e){e&&(e.observer.on("close",async r=>{l.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),this._consumers.delete(e.id),w.emit(C.CONSUMER_CLOSED,{id:e.id})}),this._consumers.set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),w.emit(C.NEW_CONSUMER,{id:e.id,appData:e.appData,peerId:e.peerId}))}async createConsumers(e){if(this._recvTransport===void 0||this._recvTransport.closed||!this._recvTransport.connected)return;if(e.every(n=>this.getProducer(n.producerId))){l.warn("why are you creating a consumer for local producer?");return}await br(async n=>{n>0&&l.debug(`retrying consume call, retryCount: ${n}`),(await this._recvTransport.consume(e).catch(a=>{throw l.error("failed to consume:",{error:a}),a})).forEach(a=>{a.status==="rejected"?(l.error("consumer creation task is failing",a.reason),this._consumerCreationFailureCount+=1,setTimeout(this.handleFailure.bind(this),0)):this._initConsumer(a.value)})}).catch(n=>{l.error("create consumer failed after retries",{error:n}),this._consumerCreationFailureCount+=1,this.handleFailure()})}async pauseProducer(e){const r=this._producers.get(e);if(!r){l.warn(`producer type: ${e} not found`);return}r.pause(),r.appData.e2ee&&w.emit(C.E2EE_INACTIVE_PRODUCER,r),l.info(`Paused the producer of type: ${r.kind}`,{producer:{id:r.id,kind:r.kind,appData:r.appData}})}async resumeProducer(e){const r=this._producers.get(e);if(!r){l.warn(`producer type: ${e} not found`);return}r.resume(),l.info(`Resumed the producer of type: ${r.kind}`,{producer:{id:r.id,kind:r.kind,appData:r.appData}})}async replaceTrack(e,r){const n=this._producers.get(e);if(!n){l.warn(`producer type: ${e} not found`);return}await n.replaceTrack({track:r}),l.info(`Replaced track for the producer of type: ${n.kind}`,{producer:{id:n.id,kind:n.kind,appData:n.appData,trackId:r.id}})}async removeProducer(e,r){const n=this._producers.get(e);if(!n){l.warn(`producer type: ${e} not found`);return}r&&n.track.stop(),await this.sendTransport.awaitQueue.push(n.close.bind(n),"producer").then(()=>{c(this,Or).getValue("modules").e2ee.enabled&&w.emit(C.E2EE_INACTIVE_PRODUCER,n)}).catch(i=>{l.error("failed to close producer on server",i)})}async pauseConsumer(e){const r=this._consumers.get(e);if(!r){l.warn(`consumer with id: ${e} not found`);return}this.toggleConsumerOverDC(e,!0),l.info(`Paused the consumer of type: ${r.kind}`,{consumer:{id:r.id,kind:r.kind,appData:r.appData}})}async pauseConsumerOverSocket(e){try{const r={consumerId:e.id,pause:!0};await this.socket.sendMessagePromise(ne.toggleConsumer,Pc.toBinary(r)),e.pause(),w.emit(C.CONSUMER_PAUSED,{id:e.id}),l.info(`Paused the consumer of type: ${e.kind} over socket`,{consumer:{id:e.id,kind:e.kind,appData:e.appData}})}catch(r){l.error("error on pausing consumer",{error:r,consumer:{id:e.id,kind:e.kind,appData:e.appData}})}}async toggleConsumerOverDC(e,r){const n={type:"consumer_toggle",payload:{consumerId:e,mute:r}},i=this._recvTransport.getDatachannel("events");if(!i){l.warn("recvTransport:: events datachannel not found");return}await i.request(n),l.info(`HiveSFUHandler::consumer toggled, consumerId: ${e}, muted: ${r}`)}async resumeConsumer(e){const r=this._consumers.get(e);if(!r){l.warn(`consumer with id: ${e} not found`);return}if(!r.paused){l.warn(`consumer with id:${e} is not paused so not resuming`);return}try{const n={consumerId:e,pause:!1};await this.socket.sendMessagePromise(ne.toggleConsumer,Pc.toBinary(n)),r.resume(),w.emit(C.CONSUMER_RESUMED,{id:r.id}),l.info(`Resumed the consumer of type: ${r.kind}`,{consumer:{id:r.id,kind:r.kind,appData:r.appData}})}catch(n){l.error("error on resuming consumer",n)}}async closeConsumer(e,r){return this.closeConsumers([e],r)}async closeConsumers(e,r=!1){l.info(`Closing consumers: ${JSON.stringify(e)} with force: ${r}`);let n=!0;const i=e.filter(d=>this._consumers.get(d)?!0:(l.warn(`consumer with id: ${d} not found`),!1));if(!i.length)return;const a={consumerIds:i},o=async()=>{var d;return(d=this._recvTransport)==null?void 0:d.awaitQueue.push(async()=>{await this._socketHandler.closeConsumer(a)},"close_consumer").catch(u=>{l.warn("error on closing consumer:",{error:u}),n=r})};r?o():await o(),n&&i.forEach(d=>{const u=this.consumers.get(d);this.producerIdToConsumerIdMap.delete(u.producerId),u.close(r?"force closed":void 0)})}async cleanupConsumers(e){l.debug("cleaning up all consumers");const r=[];this._consumers.forEach(n=>{e?n.peerId===e&&r.push(n.id):r.push(n.id)}),this.closeConsumers(r,!0)}async stopAllProducers(){l.info("stopping all available producers"),this._producers.forEach((e,r)=>{l.debug(`closing producer type: ${r}`,{producer:{id:e==null?void 0:e.id,kind:e.kind,appData:e.appData}}),e.close()})}getProducer(e){return Array.from(this.producers.values()).filter(r=>r.id===e).at(0)}hasProducer(e){return this.getProducer(e)!==void 0}async negotiate(e,r){l.debug(`setting remote offer : ${JSON.stringify(r)} on ${e.direction} transport`,{transport:{id:e.id,serverId:e.serverId,type:e.direction}});const n=await e.setRemoteOffer(r),i={transportId:e.serverId,description:{sdp:n.sdp,type:n.type,target:qt.SUBSCRIBER}};return l.debug(`sending renegotiate request: ${JSON.stringify(i)} on ${e.direction} transport`,{transport:{id:e.id,serverId:e.serverId,type:e.direction}}),await this.socket.sendMessagePromise(ne.renegotiateSessionDescription,ef.toBinary(i)),l.info("renegotiation done",{transport:{id:e.id,serverId:e.serverId,type:e.direction}}),n}async negotiateOverDC(e,r,n,i){const{sdp:a}=e.payload,o={sdp:a,type:"offer"};try{l.debug(`got offer over dc: ${a} for transport: ${i.id}`);const d=await i.setRemoteOffer(o),u={type:"answer",payload:{type:d.type,sdp:d.sdp}};l.debug(`datachannel answer: ${JSON.stringify(u)}`),i.sendResponseOverDC(n,r,u)}catch(d){l.error("datachannel:events::Error:",d),d.code!=="DC_NOT_FOUND"&&i.sendErrorOverDC(n,r,d)}}handleConsumerToggle(e){const{mute:r,trackId:n}=e;l.info(`consumer toggled for trackId: ${n} muted: ${r}`);const i=this.consumers.get(n);if(!i){l.warn(`consumer with trackId: ${n} not found`);return}i.paused!==r&&(l.debug("consumer state is not same",{consumer:{id:i.id,remotelyPaused:i.paused}}),r?(i.pause(),w.emit(C.CONSUMER_PAUSED,{id:i.id})):(i.resume(),w.emit(C.CONSUMER_RESUMED,{id:i.id})))}async handleErrorOverDC(e,r){l.error(`got error over dc: ${JSON.stringify(e)} for transport: ${r}`);const{type:n,error:i,id:a}=e;if(n==="consumer"){if(i==="bind-fail"){if(this._consumerNotBoundFailureCount>=2){this.handleFailure();return}this._consumerNotBoundFailureCount+=1;const o=this.consumers.get(a);if(!o)return;try{await this.closeConsumer(o.id),await this.createConsumers([{kind:o.kind,pause:o.paused,producerId:o.producerId,producingTransportId:o.producingTransportId,screenShare:o.appData.screenShare,producingPeerId:o.peerId}])}catch(d){l.error("failed to recreate consumer on downtrack bound failure,",{consumer:{id:o.id,producerId:o.producerId,kind:o.kind,appData:o.appData}})}}}else if(n==="producer")if(i==="ready-fail"){if(this._producerNotReadyFailureCount>=2){this.handleFailure();return}this._producerNotReadyFailureCount+=1;const[o]=Array.from(this.producers.entries()).find(d=>d[1].id===a);if(!o)return;await this.removeProducer(o).catch(d=>{l.error("failed to remove ready-fail producer:",{error:d,producer:{id:a,kind:o,appData:null}})})}else i==="general-failure"&&(this.updateTransportState({state:Rt.RECONNECTING,direction:"producing"}),this.emit("reconnect_transport",this._sendTransport))}async handleFailure(){if(this._transportReconnectFailureCount>0||this._totalTransportReconnectionCount>3){l.warn("transport failure detected"),J.hasFeature(X.ENABLE_CF_EXPERIMENTAL_FAIL_RECOVERY)&&(l.debug("rejoining room"),this.emit("rejoin"));return}(this._consumerCreationFailureCount>0||this._consumerNotBoundFailureCount>=2)&&(l.warn("consumer creation failure detected or consumer not bound failure increased"),J.hasFeature(X.ENABLE_CF_EXPERIMENTAL_FAIL_RECOVERY)&&(l.debug("reconnecting recv transport"),this._totalTransportReconnectionCount+=1,this.updateTransportState({state:Rt.RECONNECTING,direction:"consuming"}),this.emit("reconnect_transport",this._recvTransport))),this._producerNotReadyFailureCount>=2&&(l.warn("producer receiver not getting added needs to reconnect send transport"),this._totalTransportReconnectionCount+=1,this.updateTransportState({state:Rt.RECONNECTING,direction:"producing"}),this.emit("reconnect_transport",this._sendTransport))}triggerTransportReconnection(e,r){l.info("triggerTransportReconnection:: reconnecting transport",{transport:{type:e.direction,id:e.id,serverId:e.serverId}});const n=J.hasFeature(X.ENABLE_CF_TRANSPORT_RECONNECTION_ON_ICE_FAILED),i=J.hasFeature(X.CF_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED);n&&(i&&this._socket.isConnected&&(performance.now()-this.lastConnectionTime>2e4&&(this._transportConnectionFailCount=0),this._transportConnectionFailCount>2&&(l.warn("Multiple disconnections, forcing relay"),this._iceTransportPolicy="relay"),this._transportConnectionFailCount+=1),this.updateTransportState({state:Rt.RECONNECTING,direction:r?"consuming":"producing"}),this.emit("reconnect_transport",e))}async switchConsumersToLayer(e,r){const n=this._recvTransport.getDatachannel("events");if(!n){l.warn("events datachannel not found");return}const i={type:"switch_consumer_layer",payload:{consumerIds:e,layer:r}};await n.request(i),l.info(`CFSFUHandler::consumer id: ${e} layer switched to ${r}`)}updateTransportState(e){const{state:r,direction:n}=e;r==="disconnected"&&(this.transportDisconnected[n]=!0),c(this,Hn,Lo).mediaState[n]={state:r,reconnected:r==="connected"?this.transportDisconnected[n]:c(this,Hn,Lo).mediaState[n].reconnected},r==="connected"&&(this.transportDisconnected[n]=!1),w.emit(C.TRANSPORT_STATE_UPDATE,{transport:n,...c(this,Hn,Lo).mediaState[n]})}}Hn=new WeakSet,Lo=function(){return c(this,Or).getValue("connectionHandler")},Or=new WeakMap;var RO=Object.defineProperty,kO=Object.getOwnPropertyDescriptor,le=(s,t,e,r)=>{for(var n=r>1?void 0:r?kO(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&RO(t,e,n),n};const zg=(Uv=class extends Og{constructor(t,e){var d,u;super();S(this,Lr);S(this,wt,void 0);S(this,pe,void 0);S(this,Nr,void 0);S(this,qn,void 0);S(this,jn,void 0);S(this,Gs,void 0);S(this,oo,void 0);S(this,co,void 0);S(this,lo,void 0);S(this,is,void 0);S(this,Qi,void 0);m(this,"legacyMode");m(this,"roomNodeUrl");m(this,"peerDisplayName");m(this,"activatedProducingPeerIds");m(this,"e2ee");m(this,"partialJoinRoomPromise");this.context=t;const{roomName:r,authToken:n,legacyMode:i,socketClient:a,meetingTitle:o}=e;this.roomJoined=!1,this.roomName=r,this.authToken=n,this.legacyMode=i,this.meetingTitle=o,y(this,wt,a),y(this,Nr,!1),y(this,pe,new PO(t,a)),this.maxPreferredStreams=6,this.activatedProducingPeerIds=new Set,y(this,is,new Set),y(this,qn,!1),y(this,jn,0),y(this,Gs,new di),this.e2ee=(u=(d=t.getValue("modules").e2ee)==null?void 0:d.enabled)!=null?u:!1,U.legacySwitch(i),this.handleSocketEvents(),this.handleSFUEvents(),this.handleCallstatsEvents(),y(this,oo,Vr(async()=>{if(!c(this,Lr,Qs).mediaJoinAttempted)return;const{roomJoined:h}=await this.joinRoom(this.peerDisplayName,this.roomUUID,{},!0,!0);h&&(w.emit(C.RESET_PRODUCER_STATE),w.emit(C.ROOM_NODE_RECONNECTED))},5e3,{leading:!0,maxWait:1e3})),y(this,co,Vr(async h=>{h.close(),h.removeAllListeners(),await this.sfuHandler.setupTransports(["send"]),l.info("send transport reconected!"),w.emit(C.RESET_PRODUCER_STATE)},1e3)),y(this,lo,Vr(async h=>{h.close(),h.removeAllListeners(),await this.sfuHandler.setupTransports(["recv"]),l.info("recv transport reconnected!"),this.activatedProducingPeerIds=new Set,w.emit(C.UPDATE_ACTIVE,{createAllConsumers:!0})},1e3))}get mediaState(){return c(this,Lr,Qs).mediaState}get roomJoined(){return c(this,Lr,Qs).roomJoined}set roomJoined(t){c(this,Lr,Qs).roomJoined=t}static async init(t,e){const{legacyMode:r=!0,meetingId:n,authToken:i,meetingTitle:a,socket:o}=e;return new zg(t,{legacyMode:r,authToken:i,socketClient:o,roomName:n,meetingTitle:a})}get sfuHandler(){return c(this,pe)}get rejoinRoom(){return c(this,oo)}reset(t=!0){var e,r,n,i;(r=(e=c(this,pe))==null?void 0:e.cleanupConsumers)==null||r.call(e),(i=(n=c(this,pe))==null?void 0:n.stopAllProducers)==null||i.call(n),c(this,is).clear(),this.activatedProducingPeerIds.clear(),t&&(c(this,Gs).stop(),this.sfuHandler.stopAllTransports(),this.sfuHandler.reset(),y(this,Gs,new di))}async reconnectTransport(t){l.info(`CFNodeClient::Room joining state: ${c(this,Nr)}`),!(!t||c(this,Nr))&&(t.direction==="send"?await c(this,co).call(this,t):await c(this,lo).call(this,t))}async setupTransports(t=!1){await c(this,pe).setupTransports(["recv","send"],t)}async stopAllProducers(){await c(this,pe).stopAllProducers()}async joinRoom(t,e,r={},n=!1,i=!1){c(this,Lr,Qs).mediaJoinAttempted=!0,y(this,Nr,!0),this.reset(n);const a=We().ipInfo;if(a!=null&&a.loc&&!c(this,Qi)){const d=a.loc.split(",");y(this,Qi,{latitude:parseFloat(d[0]),longitude:parseFloat(d[1])})}let o;try{return o=await c(this,Gs).push(()=>this._joinRoom(t,e,r,i,c(this,Qi)),"joinRoom"),o}catch(d){o={roomJoined:!1}}return o.roomJoined||w.emit(C.ROOM_NODE_FAILED),o}async _partialJoinRoom(t,e,r=!1,n=void 0){const i=We().ipInfo;let a=n;if(i!=null&&i.loc&&!n){const o=i.loc.split(",");a={latitude:parseFloat(o[0]),longitude:parseFloat(o[1])}}await br((o,d)=>(c(this,wt).isConnected||d(new Error("socket is not connected")),o>0&&l.warn(`retrying sending join room request, count: ${o}`),this.sfuHandler.cfSocketHandler.joinRoom(e,t,r,a).catch(u=>{throw l.error("failed to send join room request, error:",{error:u}),u})),{delayTime:1e3,strategy:"exponential",maxRetryCount:J.hasFeature(X.ENABLE_CF_INFINITE_RETRIES)?1/0:3}),await this.setupTransports(!0)}async partialJoinRoom(t,e,r=!1,n=void 0){this.partialJoinRoomPromise=c(this,Gs).push(()=>this._partialJoinRoom(t,e,r,n))}async _joinRoom(t,e,r={},n=!1,i=null){this.peerDisplayName=t;try{return this.partialJoinRoomPromise?await this.partialJoinRoomPromise:await this._partialJoinRoom(t,e,n,i),navigator.product!=="ReactNative"&&setTimeout(async()=>{const d={userId:this.context.getValue("userId"),peerId:this.peerId,displayName:t,roomUUID:e,roomViewType:"groupCall",roomName:this.roomName,deviceInfo:{...Se.getDeviceInfo(),userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency},sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};U.onSafeInitialization(()=>{U.roomJoined(d),r!=null&&r.audio?U.audioOn():U.audioOff(),r!=null&&r.video?U.videoOn():U.videoOff()})}),{roomJoined:await this.completeJoinRoom()}}catch(a){return l.error("error on sending join room request",{error:a}),{roomJoined:!1}}finally{this.partialJoinRoomPromise=void 0}}async completeJoinRoom(){try{const{maxPreferredStreams:t,roomState:e}=await this.sfuHandler.cfSocketHandler.notifySelfJoinComplete();return this.roomUUID=e.roomUuid,this.maxPreferredStreams=t!=null?t:6,y(this,Nr,!1),y(this,qn,!0),this.roomJoined=!0,w.emit(C.UPDATE_ACTIVE,{createAllConsumers:!0}),!0}catch(t){return l.error("error on completing join room:",{error:t}),!1}}async leaveRoom(){c(this,pe).stopAllTransports(),y(this,qn,!1),c(this,Lr,Qs).mediaJoinAttempted=!1;const t={closeRoom:!1};c(this,wt).sendMessagePromise(ne.leaveRoom,cf.toBinary(t)).then(e=>{var n;((n=_f.fromBinary(e.payload))==null?void 0:n.closed)||l.warn("weird state on peer closed and should not happen")}).catch(e=>{l.error("error on sending leave room request",{error:e})}),U.callEnded(),g.destruct()}getConsumers(){return c(this,pe).consumers}async activatePeers(t){return this.createConsumers(t)}async deactivatePeers(t,e="default"){const r=new Set;t.forEach(i=>{i.screenShare&&i.kind==="video"&&r.add(i.producingPeerId)});const n=e==="default"?t.filter(i=>!r.has(i.producingPeerId)).filter(i=>i.kind!=="audio"):t;await Promise.all(n.map(i=>{const a=this.sfuHandler.producerIdToConsumerIdMap.get(i.producerId);if(!a){l.warn(`consumer not found in deactivate producers: ${i.producerId}`);return}return this.sfuHandler.closeConsumer(a)}))}async createConsumers(t){return this.sfuHandler.createConsumers(t)}async pauseConsumers(t){t.forEach(e=>{this.sfuHandler.pauseConsumer(e)})}async resumeConsumers(t){t.forEach(e=>{this.sfuHandler.resumeConsumer(e)})}async closeConsumers(t){await Promise.all(t.map(e=>{const r=this.sfuHandler.producerIdToConsumerIdMap.get(e.producerId);if(!r){l.warn(`consumer not found in deactivate producers: ${e.producerId}`);return}return this.sfuHandler.closeConsumer(r)}))}async consumePeer(t,e,r){if(l.info(`current activated Peer ids: ${JSON.stringify(Array.from(this.activatedProducingPeerIds.values()))}, forced?:${r}`),!this.activatedProducingPeerIds.has(t)||r)try{await c(this,pe).createConsumers(e),this.activatedProducingPeerIds.add(t)}catch(n){l.error("consumePeer failed in CFNodeClient.ts",{error:n})}else l.info(`not creating consumer for this peerId: ${t}`)}async shareWebcam(t){if(t===void 0)return null;if(c(this,pe).producers.has(Y.WEBCAM)){const i=c(this,pe).producers.get(Y.WEBCAM);if(!i.closed&&!navigator.isReactNative)return await i.replaceTrack({track:t}),await this.resumeWebcam(),t;await c(this,pe).removeProducer(Y.WEBCAM)}const e={track:t,codecOptions:{name:"VP8"},appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1};let r=t.getConstraints().width;r in Cg||(r=640),e.encodings=q0[r],J.hasFeature(X.ENABLE_CF_SIMULCAST)&&(e.encodings=Cg[r]);const n=()=>{l.info("Disabling video due to the producer closure"),this.disableWebcam()};return c(this,pe).createProducer(Y.WEBCAM,e,n)}async shareScreen(t){const{video:e,audio:r}=t;if(e===void 0)return;const n={track:e,codecOptions:{name:"VP8"},appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Se.isElectron()},stopTracks:!1};let i=()=>{l.info("Disabling screenShare due to the producer closure"),this.disableScreenShare()};if(await c(this,pe).createProducer(Y.SCREENSHARE_VIDEO,n,i),r){const a={track:r,codecOptions:{name:"opus"},appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Se.isElectron()},stopTracks:!1,zeroRtpOnPause:!0};i=()=>{},await c(this,pe).createProducer(Y.SCREENSHARE_AUDIO,a,i)}U.screenShareStart()}async shareMic(t){try{if(t===void 0)throw new lt("track undefined");if(c(this,pe).producers.has(Y.MIC)){const n=c(this,pe).producers.get(Y.MIC);if(!n.closed&&!navigator.isReactNative){await n.replaceTrack({track:t}),await this.resumeMic();return}await c(this,pe).removeProducer(Y.MIC,!1)}const e={track:t,encodings:[{priority:"high"}],codecOptions:{name:"opus"},appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!0},r=()=>{l.info("Disabling audio due to the producer closure"),this.disableMic()};await c(this,pe).createProducer(Y.MIC,e,r)}catch(e){throw new b(e)}}pauseMic(){const t=c(this,pe).producers.get(Y.MIC);if(!t){l.error("pauseMic::could_not_find_mic_producer");return}if(t.paused){l.info("pauseMic::mic_producer_already_paused");return}t.pause();const e={producerId:t.id,pause:!0};c(this,wt).sendMessage(ne.toggleProducer,fs.toBinary(e))}async pauseWebcam(){const t=c(this,pe).producers.get(Y.WEBCAM);if(!t){l.error("pauseWebcam::could_not_find_webcam_producer");return}t.pause();const e={producerId:t.id,pause:!0};c(this,wt).sendMessage(ne.toggleProducer,fs.toBinary(e))}async resumeMic(){const t=c(this,pe).producers.get(Y.MIC);if(!t){l.error("resumeMic::could_not_find_mic_producer");return}if(!t.pause){l.info("resumeMic::mic_producer_already_resumed");return}t.resume(),t.appData.e2ee&&w.emit(C.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,wt).sendMessage(ne.toggleProducer,fs.toBinary(e))}async resumeWebcam(){const t=c(this,pe).producers.get(Y.WEBCAM);if(!t){l.error("resumeWebcam::could_not_find_webcam_producer");return}t.resume(),t.appData.e2ee&&w.emit(C.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,wt).sendMessage(ne.toggleProducer,fs.toBinary(e))}async disableWebcam(){await c(this,pe).removeProducer(Y.WEBCAM)}async disableMic(){await c(this,pe).removeProducer(Y.MIC)}async disableScreenShare(){l.info("screen_sharing_stopped"),U.screenShareStop(),await c(this,pe).removeProducer(Y.SCREENSHARE_VIDEO),await c(this,pe).removeProducer(Y.SCREENSHARE_AUDIO),c(this,is).clear()}async muteSelf(){this.pauseMic()}async unmuteSelf(){}async resetVideoProducers(t,e){t&&(await c(this,pe).removeProducer(Y.WEBCAM,!1),this.shareWebcam(t)),e&&(await c(this,pe).removeProducer(Y.SCREENSHARE_VIDEO,!1),this.shareScreen({video:e}))}async changeDisplayName(t,e){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!await this.sfuHandler.cfSocketHandler.changeDisplayName(r))throw new Error("failed to change display name!")}async kick(t){const e={participantId:t};if(!await this.sfuHandler.cfSocketHandler.kickPeer(e))throw new Error("failed to kickout the participant!")}async kickAll(){if(!await this.sfuHandler.cfSocketHandler.kickAll())throw new Error("failed to kickout all participant!")}async muteAll(t){if(!await this.sfuHandler.cfSocketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await this.sfuHandler.cfSocketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(t){if(!await this.sfuHandler.cfSocketHandler.hostControlForPeer(t,"audio"))throw new Error("failed to mute given participant")}async disableVideo(t){if(!await this.sfuHandler.cfSocketHandler.hostControlForPeer(t,"video"))throw new Error("failed to mute video of given participant")}async pinPeer(t){const e={participantId:t!=null?t:""};try{await c(this,wt).sendMessagePromise(ne.globalPinPeer,uf.toBinary(e))}catch(r){l.error("Error in pinning peer:",{error:r})}}validateScreenShare(t){return this.peerId===t.peerId&&this.sfuHandler.hasProducer(t.producerId)&&c(this,is).add(t.consumerPeerId),c(this,is).size}async switchConsumersToLayer(t,e){this.sfuHandler.switchConsumersToLayer(t,e)}async handleSocketEvents(){c(this,wt).on(ne.peerProducerCreateBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:r}=Mf.fromBinary(t);if(e===this.peerId)return;l.info(`producer created broadcast: ${e}, producer state: ${r}`),w.emit(C.NEW_PRODUCER,{peerId:e,producer:{...r,kind:r.kind===Nt.AUDIO?"audio":"video"}})}catch(e){l.error("error in peer-producer-create-broadcast",{error:e})}}),c(this,wt).on(ne.peerProducerToggleBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:{kind:r,pause:n,producerId:i}}=Df.fromBinary(t),a=r===Nt.AUDIO?"audio":"video";l.info(`producer toggle broadcast: ${e}, producerId: ${i}, kind:${a}, paused:${n}`),w.emit(C.PRODUCER_TOGGLE,{peerId:e,producerId:i,paused:n,kind:a}),Array.from(this.getConsumers().values()).filter(d=>d.producerId===i).forEach(d=>{d.paused!==n&&(l.debug(`consumer state mismatched for ${d.id}. updating consumer pause state ${d.paused} to ${n}`),n?(d.pause(),w.emit(C.CONSUMER_PAUSED,{id:d.id})):(d.resume(),w.emit(C.CONSUMER_RESUMED,{id:d.id})))})}catch(e){l.error("error in producer toggle broadcast handler",{error:e})}}),c(this,wt).on(ne.peerLeaveBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e}=kc.fromBinary(t);if(e===this.peerId)return;l.info(`peer left broadcast:${e}`),c(this,is).delete(e),this.sfuHandler.cleanupConsumers(e)}catch(e){l.error("error in peer left broadcast",{error:e})}}),c(this,wt).on(ne.peerProducerCloseBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:{producerId:r}}=Of.fromBinary(t);if(e===this.peerId)return;l.info(`producer closed broadcast:${e}`),w.emit(C.PRODUCER_CLOSED,{peerId:e,producerId:r});const n=this.sfuHandler.producerIdToConsumerIdMap.get(r);if(!n){l.warn(`no consumer found for producer:${r}`);return}l.info(`closing consumer ${n}, producer id: ${r}`),this.sfuHandler.closeConsumer(n).then(()=>{l.info(`closed consumer: ${n}`),this.sfuHandler.producerIdToConsumerIdMap.delete(r),w.emit(C.CONSUMER_CLOSED,{id:n})}).catch(i=>{l.error("error closing consumer",{error:i})})}catch(e){l.error("error on producer close broadcast",{error:e})}}),c(this,wt).on(ne.mediaRoomTerminationBroadcastResponse,()=>{!this.roomJoined&&!c(this,Nr)&&!c(this,qn)||(l.warn("media hub termination broadcast received, rejoining room"),w.emit(C.ROOM_NODE_DISCONNECTED),this.rejoinRoom())})}handleSFUEvents(){c(this,pe).on("reconnect_transport",async t=>{try{await this.reconnectTransport(t),l.info(`transport reconnected [id:${t.id}]`)}catch(e){l.error("error on reconnection transports",{error:e})}}),c(this,pe).on("rejoin",t=>{var e;if(((e=c(this,Lr,Qs).socketState)==null?void 0:e.state)!=="connected"){l.warn("Ignoring rejoin attempt because socket is not connected");return}if(c(this,jn)>3&&!t){l.warn("cannot rejoin more already rejoined 3 times");return}if(c(this,Nr)&&!t){l.warn("room joining in progress, cannot start rejoining");return}y(this,jn,c(this,jn)+1),l.warn(`rejoining the room because transports are failing. [rejoinCount: ${c(this,jn)}]`),this.roomJoined=!1,w.emit(C.ROOM_NODE_DISCONNECTED),this.rejoinRoom()})}handleCallstatsEvents(){U.onSafeInitialization(()=>{U.onConsumerScore(t=>{t.forEach((e,r)=>{const n=this.sfuHandler.consumers.get(r);n&&w.emit(C.CONSUMER_SCORE_UPDATE,{id:r,kind:n.kind,peerId:n.peerId,score:e.score,scoreStats:e})})}),U.onProducerScore(t=>{t.forEach((e,r)=>{const n=Array.from(this.sfuHandler.producers.values()).find(i=>i.id===r);n&&w.emit(C.PRODUCER_SCORE_UPDATE,{id:r,kind:n.kind,appData:n.appData,score:e.score,scoreStats:e})})})})}},wt=new WeakMap,pe=new WeakMap,Nr=new WeakMap,qn=new WeakMap,jn=new WeakMap,Gs=new WeakMap,oo=new WeakMap,co=new WeakMap,lo=new WeakMap,is=new WeakMap,Qi=new WeakMap,Lr=new WeakSet,Qs=function(){return this.context.getValue("connectionHandler")},Uv);let ae=zg;le([g.trace("CFNodeClient.reset")],ae.prototype,"reset",1),le([g.trace("CFNodeClient.reconnect")],ae.prototype,"reconnectTransport",1),le([g.trace("CFNodeClient.setupTransport")],ae.prototype,"setupTransports",1),le([g.trace("CFNodeClient.stopAllProducers")],ae.prototype,"stopAllProducers",1),le([g.trace("CFNodeClient.joinRoom")],ae.prototype,"joinRoom",1),le([g.trace("CFNodeClient.completeJoinRoom")],ae.prototype,"completeJoinRoom",1),le([g.trace("CFNodeClient.leaveRoom")],ae.prototype,"leaveRoom",1),le([g.trace("CFNodeClient.activatePeers")],ae.prototype,"activatePeers",1),le([g.trace("CFNodeClient.deactivatePeers")],ae.prototype,"deactivatePeers",1),le([g.trace("CFNodeClient.createConsumers")],ae.prototype,"createConsumers",1),le([g.trace("CFNodeClient.pauseConsumers")],ae.prototype,"pauseConsumers",1),le([g.trace("CFNodeClient.resumeConsumers")],ae.prototype,"resumeConsumers",1),le([g.trace("CFNodeClient.closeConsumers")],ae.prototype,"closeConsumers",1),le([g.trace("CFNodeClient.consumePeer")],ae.prototype,"consumePeer",1),le([g.trace("CFNodeClient.shareWebcam")],ae.prototype,"shareWebcam",1),le([g.trace("CFNodeClient.shareScreen")],ae.prototype,"shareScreen",1),le([g.trace("CFNodeClient.shareMic")],ae.prototype,"shareMic",1),le([g.trace("CFNodeClient.pauseMic")],ae.prototype,"pauseMic",1),le([g.trace("CFNodeClient.pauseWebcam")],ae.prototype,"pauseWebcam",1),le([g.trace("CFNodeClient.resumeMic")],ae.prototype,"resumeMic",1),le([g.trace("CFNodeClient.resumeWebcam")],ae.prototype,"resumeWebcam",1),le([g.trace("CFNodeClient.disableWebcam")],ae.prototype,"disableWebcam",1),le([g.trace("CFClient.disableMic")],ae.prototype,"disableMic",1),le([g.trace("CFClient.disableScreenShare")],ae.prototype,"disableScreenShare",1),le([g.trace("CFNodeClient.muteSelf")],ae.prototype,"muteSelf",1),le([g.trace("CFNodeClient.resetVideoProducers")],ae.prototype,"resetVideoProducers",1),le([g.trace("CFNodeClient.changeDisplayName")],ae.prototype,"changeDisplayName",1),le([g.trace("CFNodeClient.kickPeer")],ae.prototype,"kick",1),le([g.trace("CFNodeClient.kickAllPeers")],ae.prototype,"kickAll",1),le([g.trace("CFNodeClient.muteAll")],ae.prototype,"muteAll",1),le([g.trace("CFNodeClient.muteAllVideo")],ae.prototype,"muteAllVideo",1),le([g.trace("CFNodeClient.disableAudio")],ae.prototype,"disableAudio",1),le([g.trace("CFNodeClient.disableVideo")],ae.prototype,"disableVideo",1),le([g.trace("CFNodeClient.pinPeer")],ae.prototype,"pinPeer",1),le([g.trace("CFNodeClient.validateScreenShare")],ae.prototype,"validateScreenShare",1),le([g.trace("CFNodeClient.init")],ae,"init",1);async function IO(s,t){const e=s.getValue("roomNodeClient");if(e){if(e instanceof ie)return e;throw new Error("Room Node Client already setup")}const r=await ie.init(s,t);return s.setValue("roomNodeClient",r),r}async function AO(s,t){const e=s.getValue("roomNodeClient");if(e){if(e instanceof ae)return e;throw new Error("Room Node Client already setup")}const r=await ae.init(s,t);return s.setValue("roomNodeClient",r),r}async function Yg(s,t,e=li.HIVE){return e===li.CF?AO(s,t):IO(s,t)}function Qg(s){const t=s.getValue("roomNodeClient");try{t==null||t.leaveRoom()}catch(e){l.error("roomNodeClient::cleanupRoomNodeClient")}s.setValue("roomNodeClient",void 0)}var MO=Object.defineProperty,DO=Object.getOwnPropertyDescriptor,OO=(s,t,e,r)=>{for(var n=r>1?void 0:r?DO(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&MO(t,e,n),n};let Tn;const Xg=class{constructor(s){m(this,"socket");this.socket=s,this.handleSocketEvents()}static create(s){return Tn||(Tn=new Xg(s)),Tn}static cleanup(){var s;try{(s=Tn==null?void 0:Tn.socket)==null||s.disconnect()}catch(t){l.error("roomSocketHandler::cleanup")}Tn=void 0}async joinRoom(s,t){var n;this.socket.joinAttempted=!0;const e={capabilities:[],peer:{displayName:(n=s.name)!=null?n:"Participant",customParticipantId:s.customParticipantId,peerId:s.id,userId:s.userId,displayPictureUrl:s.picture,waitlisted:!1},roomUuid:""},r=this.socket.sendMessagePromise($.joinRoom,KR.toBinary(e));try{const{peer:i}=ei.fromBinary((await r).payload);w.emit(C.SOCKET_SERVICE_ROOM_JOINED,{peer:i});const a=this.getRoomState();let o=()=>new Promise(h=>{h({peers:[]})});t!==Xe.Livestream&&(o=this.getRoomPeersNonPaginated()),t===Xe.Livestream&&i.stageType===1&&(o=this.getStagePeers());const[{room:d},{peers:u}]=await Promise.all([a,o]);return w.emit(C.ROOM_STATE,d),w.emit(C.SOCKET_PEERS,u),{peer:i}}catch(i){throw l.error("RoomSocketHandler.joinRoom.failed",{error:i}),new b("Error: RoomSocketHandler.joinRoom failed.","0002",i)}}async getAllAddedParticipants(){try{return Dk.fromBinary((await this.socket.sendMessagePromise($.getAllAddedParticipants)).payload).participants.map(({id:t,...e})=>({...e,userId:t}))}catch(s){return[]}}async getRoomPeers(s,t,e){let r;try{const n={seachQuery:s,limit:t,offset:e},i=await this.socket.sendMessagePromise($.getRoomPeersInfo,UR.toBinary(n));r=Wl.fromBinary(i.payload)}catch(n){l.error("getRoomPeers::binary_decode_error",{error:n})}return r}async getRoomPeersNonPaginated(){let s;try{const t=await this.socket.sendMessagePromise($.getRoomPeersInfo);s=Wl.fromBinary(t.payload)}catch(t){l.error("getRoomJoinedPeers::binary_decode_error",{error:t})}return s}async getStagePeers(){let s;try{const t=await this.socket.sendMessagePromise($.getRoomPeersInfo);s=Wl.fromBinary(t.payload)}catch(t){l.error("getRoomJoinedPeers::binary_decode_error",{error:t})}return s}async getPeerInfo(s){let t;try{const e=await this.socket.sendMessagePromise($.getPeerInfo,Vf.toBinary({peerId:s}));t=ei.fromBinary(e.payload)}catch(e){l.error("getPeerInfo::binary_decode_error",{error:e})}return t}async getRoomState(){let s=Uf.create();try{const t=await this.socket.sendMessagePromise($.getRoomInfo);s=Uf.fromBinary(t.payload)}catch(t){l.error("getRoomState::binary_decode_error",{error:t})}return s}async getRoomStageState(){let s=jf.create();try{const t=await this.socket.sendMessagePromise($.getRoomStageState);s=jf.fromBinary(t.payload)}catch(t){l.error("getRoomStageState::binary_decode_error",{error:t})}return s}async broadcastMessage(s,t){const e={type:s,payload:new TextEncoder().encode(JSON.stringify(t)),timestamp:Date.now(),peerIds:[]};return this.socket.sendMessagePromise($.broadcastMessage,Mc.toBinary(e))}async broadcastToPeers(s,t,e){const r={type:s,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),peerIds:t};return this.socket.sendMessage($.broadcastToPeers,Mc.toBinary(r))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise($.leaveRoom,YR.toBinary({}))}async kick(s){const t={peerIds:[s]};this.socket.sendMessage($.kick,Fk.toBinary(t))}async kickAll(s=!1){const t={propagateKickAcrossRooms:s};this.socket.sendMessage($.kickAll,ql.toBinary(t))}getWaitingRoomRequests(){this.socket.sendMessage($.getWaitingRoomRequests)}acceptWaitingRoomRequest(s){const t={userIds:s};this.socket.sendMessage($.acceptWaitingRoomRequests,Vk.toBinary(t))}rejectWaitingRoomRequest(s){const t={userIds:s};this.socket.sendMessage($.denyWaitingRoomRequests,Bk.toBinary(t))}async updatePermissions(s,t){const e={updatePeersPresets:[]};return s.forEach(r=>{e.updatePeersPresets.push({userIds:r,patch:t})}),this.socket.sendMessagePromise(Lc.updateUserPreset,gI.toBinary(e))}handleSocketEvents(){this.socket.on($.broadcastMessage,({payload:s})=>{try{const t=Mc.fromBinary(s);w.emit(C.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(t.payload)),type:t.type,timestamp:t.timestamp})}catch(t){l.error("failed to decode broadcast message:",t)}}),this.socket.on($.broadcastToPeers,({payload:s})=>{try{const t=Mc.fromBinary(s);w.emit(C.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(t.payload)),type:t.type,timestamp:t.timestamp})}catch(t){l.error("failed to decode peer broadcast message:",t)}})}on(s,t){let e,r;switch(s){case $.joinRoom:case $.leaveRoom:case $.kick:case $.kickAll:{e=ei.fromBinary.bind(ei),r=ei.create();break}case $.getWaitingRoomRequests:{e=(n,i)=>n?qf.fromBinary(n,i):{requests:[]},r=qf.create();break}case $.recordingPaused:case $.recordingStarted:case $.recordingStopped:{e=rg.fromBinary.bind(rg);break}case Lc.updateUserPreset:{e=Jf.fromBinary.bind(Jf);break}case ne.peerJoinedBroadcast:case se.peerJoinedBroadcast:{e=If.fromBinary.bind(If);break}case ne.selfJoinComplete:case se.selfJoinComplete:{e=Rc.fromBinary.bind(Rc);break}case ne.globalPeerPinBroadcast:case se.globalPeerPinBroadcast:{e=Nf.fromBinary.bind(Nf);break}case ne.selectedPeer:case se.selectedPeer:{e=jl.fromBinary.bind(jl);break}case ne.selectedPeerDiff:case se.selectedPeerDiff:{e=Tf.fromBinary.bind(Tf);break}case ne.leaveRoom:case se.leaveRoom:{e=kc.fromBinary.bind(kc);break}}this.socket.on(s,({payload:n})=>{let i=r;if(!e)return t(void 0);try{i=e(n)}catch(a){l.error("roomSocketHandler::on::binary_decode_error",{error:a})}return t(i)})}async getUserPermissions(s){const t={userIds:[s]};try{const e=await this.socket.sendMessagePromise(Lc.getUserPresets,dI.toBinary(t)),r=pI.fromBinary(e.payload).peerPresets[0],n=new TextDecoder().decode(r.preset),i=JSON.parse(n).permissions;return{chat:i.chat,polls:i.polls,plugins:i.plugins}}catch(e){throw l.error("Error in getting user preset",{error:e}),e}}};let rd=Xg;OO([g.trace("RoomSocketHandler.joinRoom")],rd.prototype,"joinRoom",1);var NO=Object.defineProperty,LO=Object.getOwnPropertyDescriptor,_n=(s,t,e,r)=>{for(var n=r>1?void 0:r?LO(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&NO(t,e,n),n};const Zg=(Vv=class{constructor(s,t,e,r){S(this,Vt);m(this,"self");m(this,"authToken");S(this,Js,void 0);m(this,"viewType");S(this,yr,void 0);S(this,Ct,void 0);const{socket:n}=e,i=s.getValue("authToken");this.self=t,y(this,Ct,s),this.viewType=r,this.authToken=i,y(this,Js,n),y(this,yr,e),t.config.viewType!==Xe.Chat&&this.setupEvents()}get peerId(){return c(this,Ct).getValue("peerId")}static async init(s,t,e,r,n){const i=We(),a=s.getValue("peerId"),o=!!s.getValue("cachedUserDetails"),d=await ut.__init__(s,e,r,n,n.name,o);if(navigator.product!=="ReactNative"){const u=!J.hasFeature(X.PRECALL_BANDWIDTH_TEST);setTimeout(async()=>{const h=await d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(h)}),U.onSafeInitialization(async()=>{U.devices("AUDIO",h==null?void 0:h.filter(p=>p.kind==="audioinput")),U.devices("VIDEO",h==null?void 0:h.filter(p=>p.kind==="videoinput")),U.devices("SPEAKER",h==null?void 0:h.filter(p=>p.kind==="audiooutput"))}),l.info("Callstats:: initializing");try{await U.initialize({peerId:a,engineName:Se.getDeviceInfo().engineName,env:s.getValue("env"),iceServers:await i.getICEServers(),apiBase:s.getValue("apiBase"),flags:J.getAllFlags(),logger:l,apiHostnames:Lm(s),skipConnectivityChecks:u}),l.info("Callstats:: initialized")}catch(p){l.error("Callstats:: initialization failed",{error:p})}},0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new Zg(s,d,t,n.viewType)}async shareMediaTracks(){var o;const{audioTrack:s,videoTrack:t,permissions:e,audioEnabled:r,videoEnabled:n,screenShareEnabled:i,screenShareTracks:a}=this.self;if(e.canProduceAudio&&r)try{await c(this,Vt,ir).shareMic(s)}catch(d){this.self.disableAudio()}if(e.canProduceVideo&&n)try{const d=await c(this,Vt,ir).shareWebcam(t);d&&d.id!==t.id&&J.hasFeature(X.EXP_RESHARE)&&await c(this,Vt,ir).shareWebcam(d)}catch(d){this.self.disableVideo()}if(e.canProduceScreenshare&&i)try{await((o=c(this,Vt,ir))==null?void 0:o.shareScreen({video:a.video,audio:a.audio}))}catch(d){this.self.disableScreenShare()}}async kickHandler(s){let t="kicked";(s==null?void 0:s.kickType)==="kickAll"&&(t="ended"),this.leaveRoom(t)}waitlistedHandler(){l.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(l.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){l.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(l.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){l.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}async resetSelf(s){U.callEnded(),c(this,Vt,ir).reset(),s&&await this.joinRoom(s)}setupEvents(){w.on(C.RESET_PRODUCER_STATE,async()=>{this.self.roomJoined&&this.shareMediaTracks()}),w.on(C.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),w.on(C.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),w.on(C.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),w.on(C.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),w.on(C.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;let{peerId:t}=this;s&&J.hasFeature(X.REFRESH_ID_ON_DISCONNECTION)&&(t=Xs()),c(this,Js).updateURL(t),g.resetPeerId(t),We().setHeader("dyte-tracing-id",t),pa.remapContext(t,c(this,Ct)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),w.on(C.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),c(this,yr).on($.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),c(this,yr).on(Lc.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&w.emit(C.UPDATE_PERMISSIONS,t.patch)})}),c(this,yr).on($.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),c(this,yr).on($.kick,()=>{this.kickHandler({kickType:"kick"})}),c(this,yr).on($.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),w.onAsync(C.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),w.on(C.PRODUCER_SCORE_UPDATE,({score:s,kind:t,appData:e,scoreStats:r})=>{var i;const n=(i=e==null?void 0:e.screenShare)!=null?i:!1;this.self.emit("mediaScoreUpdate",{kind:t,isScreenshare:n,score:s,participantId:this.self.id,scoreStats:r})}),w.on(C.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),U.audioOff())}),w.on(C.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),U.videoOff())}),w.onAsync(C.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),w.on(C.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{const{peer:t}=await c(this,yr).joinRoom(this.self,this.self.config.viewType);c(this,yr).socket.flush();const e=lu(t.stageType);if(c(this,Ct).setValue("stageStatus",e,!1),t.waitlisted){this.waitlistedHandler();return}await this.joinMediaRoom(s),c(this,Ct).notify("stageStatus")}catch(t){throw l.error("Error in joinRoom",{error:t}),t}}async leaveRoom(s="left"){var t,e;if(s==="rejected"){try{(t=c(this,Js))==null||t.disconnect()}catch(r){l.error("SelfController::leaveRoom::socketDisconnect")}this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),c(this,Ct).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),c(this,Ct).notify("stageStatus");try{(e=c(this,Js))==null||e.disconnect()}catch(r){l.error("SelfController::leaveRoom::socketDisconnect")}Qg(c(this,Ct)),rd.cleanup(),this.self.roomState=s,this.self.emit("roomLeft",{state:s})}partialMediaRoom(){var s;(s=c(this,Vt,ir))==null||s.partialJoinRoom(this.self.name,c(this,Ct).getValue("meetingId"),void 0)}async joinMediaRoom(s=!1){var h,p;const{peerId:t,viewType:e,meetingId:r,authToken:n,stageStatus:i,roomNodeOptions:a}=c(this,Ct).getAllValues(),{sfu:o,roomNodeUrl:d,meetingTitle:u}=a;try{if(e===Xe.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}await Yg(c(this,Ct),{socket:c(this,Js),peerId:t,meetingId:r,authToken:n,roomNodeUrl:d,meetingTitle:u},o)}const{roomJoined:f}=(p=await((h=c(this,Vt,ir))==null?void 0:h.joinRoom(this.self.name,r,{audio:this.self.audioEnabled,video:this.self.videoEnabled,screen:this.self.screenShareEnabled},s,s)))!=null?p:{};if(!f)return;i==="ON_STAGE"&&await this.shareMediaTracks(),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s})}catch(f){throw l.error("Error:SelfController.mediaRoomJoin",f),new b("Error: could not join media room",f)}}async leaveMediaRoom(s){const t=c(this,Ct).getValue("viewType");await this.cleanupSelf(),!(s==="stageLeft"&&t===Xe.Webinar)&&c(this,Vt,ir)&&(c(this,Vt,ir).roomJoined&&s!=="disconnected"&&await c(this,Vt,ir).leaveRoom(),!(s==="stageLeft"&&t===Xe.Livestream)&&(c(this,Vt,ir).roomJoined=!1))}async cleanupSelf(){await this.self.disableAudio(),await this.self.disableVideo(),await this.self.disableScreenShare(),this.self.cleanUpTracks(),this.self.destructMediaHandler(),navigator.isReactNative||this.self.removeDocumentEventListeners()}},Js=new WeakMap,yr=new WeakMap,Ct=new WeakMap,Vt=new WeakSet,ir=function(){return c(this,Ct).getValue("roomNodeClient")},Vv);let Ss=Zg;_n([g.trace("SelfController.resetSelf")],Ss.prototype,"resetSelf",1),_n([g.trace("SelfController.setupEvents")],Ss.prototype,"setupEvents",1),_n([g.trace("SelfController.joinRoom")],Ss.prototype,"joinRoom",1),_n([g.trace("SelfController.leaveRoom")],Ss.prototype,"leaveRoom",1),_n([g.trace("SelfController.joinMediaRoom")],Ss.prototype,"joinMediaRoom",1),_n([g.trace("SelfController.leaveMediaRoom")],Ss.prototype,"leaveMediaRoom",1),_n([g.trace("SelfController.init")],Ss,"init",1);class FO{constructor(t){S(this,uo,void 0);y(this,uo,t)}on(t,e){let r;t===$.roomPeerCount?r=Ff.fromBinary.bind(Ff):r=Xf.fromBinary.bind(Xf),c(this,uo).on(t,({payload:n})=>{const i=r(n);return e(i)})}}uo=new WeakMap;class xO{constructor(t){S(this,ho,void 0);y(this,ho,t)}on(t,e){let r,n;switch(t){case $.transcript:{r=Gl.fromBinary.bind(Gl),n=Gl.create();break}default:{l.debug("AISocketHandler switch case hit default, event not accounted for.");break}}c(this,ho).on(t,({payload:i})=>{let a=n;try{a=r(i)}catch(o){l.error("chatSocketHandler::on::binary_decode_error",{error:o})}return e(a)})}}ho=new WeakMap;var UO=Object.defineProperty,VO=Object.getOwnPropertyDescriptor,Nu=(s,t,e,r)=>{for(var n=r>1?void 0:r?VO(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&UO(t,e,n),n};class sd{constructor(t){S(this,as,void 0);y(this,as,t)}getPolls(){return c(this,as).sendMessagePromise(qr.getPolls)}createPoll(t,e,r=!1,n=!1){const i={anonymous:r,hideVotes:n,question:t,options:e};return c(this,as).sendMessage(qr.createPoll,cM.toBinary(i))}votePoll(t,e){const r={index:e,pollId:t};return c(this,as).sendMessage(qr.votePoll,lM.toBinary(r))}on(t,e){let r,n;switch(t){case qr.updatePoll:case qr.createPoll:case qr.votePoll:{r=su.fromBinary.bind(su),n=su.create();break}}c(this,as).on(t,({payload:i})=>{let a=n;try{a=r(i)}catch(o){l.error("pollSocketHandler::on::binary_decode_error",{error:o})}return e(a)})}removeListeners(t){c(this,as).removeListeners(t)}}as=new WeakMap,Nu([g.trace("PollSocketHandler.getPolls")],sd.prototype,"getPolls",1),Nu([g.trace("PollSocketHandler.createPoll")],sd.prototype,"createPoll",1),Nu([g.trace("PollSocketHandler.votePoll")],sd.prototype,"votePoll",1);class $O{constructor(t){S(this,$t,void 0);y(this,$t,t)}async getStageRequests(){const{payload:t}=await c(this,$t).sendMessagePromise($.getStageRequests);return t?ru.fromBinary(t):{stageRequests:[]}}requestAccess(){c(this,$t).sendMessage($.requestStageAccess)}cancelRequestAccess(){c(this,$t).sendMessage($.cancelStageRequest)}async grantAccess(t){const e={userIds:t};c(this,$t).sendMessage($.grantStageAccess,XA.toBinary(e))}async denyAccess(t){const e={userIds:t};c(this,$t).sendMessage($.denyStageAccess,eM.toBinary(e))}joinStage(){return c(this,$t).sendMessagePromise($.joinStage,void 0,void 0,$.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return c(this,$t).sendMessagePromise($.leaveStage,eg.toBinary(e),void 0,$.peerStageStatusUpdate)}kick(t){const e={userIds:t};return c(this,$t).sendMessagePromise($.leaveStage,eg.toBinary(e))}on(t,e){let r;switch(t){case $.grantStageAccess:case $.denyStageAccess:{r=void 0;break}case $.getStagePeers:{r=Zf.fromBinary.bind(Zf);break}case $.getStageRequests:case $.requestStageAccess:case $.cancelStageRequest:{r=ru.fromBinary.bind(ru);break}case $.peerStageStatusUpdate:{r=Lf.fromBinary.bind(Lf);break}}c(this,$t).on(t,({payload:n,id:i})=>{if(!n||!r)return e(void 0,i);const a=r(n);return e(a,i)})}async getPeerInfo(t){const e=await c(this,$t).sendMessagePromise($.getPeerInfo,Vf.toBinary({peerId:t}));return ei.fromBinary(e.payload)}}$t=new WeakMap;class BO{constructor(t){S(this,nt,void 0);y(this,nt,t)}addPlugin(t,e){c(this,nt).sendMessage(j.addPlugin,fA.toBinary({pluginId:t,staggered:e}))}removePlugin(t){c(this,nt).sendMessage(j.removePlugin,vA.toBinary({pluginId:t,staggered:!1}))}async getActivePlugins(){const{payload:t}=await c(this,nt).sendMessagePromise(j.getPlugins);return t?$A.fromBinary(t):{plugins:[]}}customPluginEventToRoom(t,e,r){const n={pluginId:t,pluginData:new TextEncoder().encode(JSON.stringify(e))};c(this,nt).sendMessage(j.customPluginEventToRoom,RA.toBinary(n),r)}customPluginEventToPeers(t,e,r,n){const i={pluginId:t,peerIds:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};c(this,nt).sendMessage(j.customPluginEventToPeers,IA.toBinary(i),n)}enablePluginForRoom(t,e){c(this,nt).sendMessage(j.enablePluginForRoom,TA.toBinary({pluginId:t}),e)}enablePluginForPeers(t,e,r){c(this,nt).sendMessage(j.enablePluginForPeers,wA.toBinary({pluginId:t,peerIds:e}),r)}disablePluginForRoom(t,e){c(this,nt).sendMessage(j.disablePluginForRoom,SA.toBinary({pluginId:t}),e)}disablePluginForPeers(t,e,r){c(this,nt).sendMessage(j.disablePluginForPeers,bA.toBinary({pluginId:t,peerIds:e}),r)}storeInsertKeys(t,e,r,n){const i={pluginId:t,storeName:e,insertKeys:r.map(a=>({storeKey:a.key,payload:new TextEncoder().encode(JSON.stringify(a.payload))}))};c(this,nt).sendMessage(j.storeInsertKeys,Kf.toBinary(i),n)}storeGetKeys(t,e,r,n){const i={pluginId:t,storeName:e,getKeys:r.map(a=>({storeKey:a.key}))};c(this,nt).sendMessage(j.storeGetKeys,OA.toBinary(i),n)}storeDeleteKeys(t,e,r,n){const i={pluginId:t,storeName:e,deleteKeys:r.map(a=>({storeKey:a.key}))};c(this,nt).sendMessage(j.storeDeleteKeys,LA.toBinary(i),n)}storeDelete(t,e,r){c(this,nt).sendMessage(j.storeDelete,xA.toBinary({pluginId:t,storeName:e}),r)}getPluginDataOld(t,e){l.info("getPluginDataOld",{plugin:{id:t,storeName:e}})}storePluginDataOld(t,e,r){const n={pluginId:t,storeName:e,insertKeys:[{storeKey:r.key,payload:new TextEncoder().encode(JSON.stringify(r))}]};c(this,nt).sendMessage(j.storeInsertKeys,Kf.toBinary(n))}on(t,e){let r;switch(t){case j.addPlugin:case j.enablePluginForPeers:case j.enablePluginForRoom:{r=tu.fromBinary.bind(tu);break}case j.removePlugin:case j.disablePluginForPeers:case j.disablePluginForRoom:{r=zf.fromBinary.bind(zf);break}case j.customPluginEventToPeers:case j.customPluginEventToRoom:{r=Qf.fromBinary.bind(Qf);break}case j.storeInsertKeys:case j.storeGetKeys:case j.storeDeleteKeys:case j.storeDelete:{r=Yf.fromBinary.bind(Yf);break}}c(this,nt).on(t,({payload:n,id:i})=>{const a=r(n);return e(a,i)})}}nt=new WeakMap;var HO=Object.defineProperty,qO=(s,t,e)=>t in s?HO(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,jO=(s,t,e)=>(qO(s,typeof t!="symbol"?t+"":t,e),e),Lu=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},L=(s,t,e)=>(Lu(s,t,"read from private field"),e?e.call(s):t.get(s)),Ie=(s,t,e)=>{if(t.has(s))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(s):t.set(s,e)},ge=(s,t,e,r)=>(Lu(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),Ne=(s,t,e)=>(Lu(s,t,"access private method"),e),Es,Sn,En,He,wn,Le,Ke,ws,ot,Kr,Cs,pr,hi,zr,Fu,ev,Ca,nd,xu,tv,Uu,rv,id,Vu,$u,sv,ba,ad,Pa,od,cd,Bu,pi,Ra,ka,dd,Hu={exports:{}},mi=typeof Reflect=="object"?Reflect:null,nv=mi&&typeof mi.apply=="function"?mi.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},ld;mi&&typeof mi.ownKeys=="function"?ld=mi.ownKeys:Object.getOwnPropertySymbols?ld=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:ld=function(t){return Object.getOwnPropertyNames(t)};function GO(s){console&&console.warn&&console.warn(s)}var iv=Number.isNaN||function(t){return t!==t};function Te(){Te.init.call(this)}Hu.exports=Te,Hu.exports.once=zO,Te.EventEmitter=Te,Te.prototype._events=void 0,Te.prototype._eventsCount=0,Te.prototype._maxListeners=void 0;var av=10;function ud(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(Te,"defaultMaxListeners",{enumerable:!0,get:function(){return av},set:function(s){if(typeof s!="number"||s<0||iv(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");av=s}}),Te.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Te.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||iv(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function ov(s){return s._maxListeners===void 0?Te.defaultMaxListeners:s._maxListeners}Te.prototype.getMaxListeners=function(){return ov(this)},Te.prototype.emit=function(t){for(var e=[],r=1;r0&&(a=e[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var d=i[t];if(d===void 0)return!1;if(typeof d=="function")nv(d,this,e);else for(var u=d.length,h=hv(d,u),r=0;r0&&a.length>n&&!a.warned){a.warned=!0;var o=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");o.name="MaxListenersExceededWarning",o.emitter=s,o.type=t,o.count=a.length,GO(o)}return s}Te.prototype.addListener=function(t,e){return cv(this,t,e,!1)},Te.prototype.on=Te.prototype.addListener,Te.prototype.prependListener=function(t,e){return cv(this,t,e,!0)};function JO(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function dv(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},n=JO.bind(r);return n.listener=e,r.wrapFn=n,n}Te.prototype.once=function(t,e){return ud(e),this.on(t,dv(this,t,e)),this},Te.prototype.prependOnceListener=function(t,e){return ud(e),this.prependListener(t,dv(this,t,e)),this},Te.prototype.removeListener=function(t,e){var r,n,i,a,o;if(ud(e),n=this._events,n===void 0)return this;if(r=n[t],r===void 0)return this;if(r===e||r.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete n[t],n.removeListener&&this.emit("removeListener",t,r.listener||e));else if(typeof r!="function"){for(i=-1,a=r.length-1;a>=0;a--)if(r[a]===e||r[a].listener===e){o=r[a].listener,i=a;break}if(i<0)return this;i===0?r.shift():WO(r,i),r.length===1&&(n[t]=r[0]),n.removeListener!==void 0&&this.emit("removeListener",t,o||e)}return this},Te.prototype.off=Te.prototype.removeListener,Te.prototype.removeAllListeners=function(t){var e,r,n;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[t]),this;if(arguments.length===0){var i=Object.keys(r),a;for(n=0;n=0;n--)this.removeListener(t,e[n]);return this};function lv(s,t,e){var r=s._events;if(r===void 0)return[];var n=r[t];return n===void 0?[]:typeof n=="function"?e?[n.listener||n]:[n]:e?KO(n):hv(n,n.length)}Te.prototype.listeners=function(t){return lv(this,t,!0)},Te.prototype.rawListeners=function(t){return lv(this,t,!1)},Te.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):uv.call(s,t)},Te.prototype.listenerCount=uv;function uv(s){var t=this._events;if(t!==void 0){var e=t[s];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}Te.prototype.eventNames=function(){return this._eventsCount>0?ld(this._events):[]};function hv(s,t){for(var e=new Array(t),r=0;r{setTimeout(e,t)})}getAttempts(){return L(this,Es)}reset(){ge(this,Es,0)}}Es=new WeakMap;const bs={debug:0,info:1,warn:2,error:3};class tN{constructor(t){Ie(this,Sn,void 0),Ie(this,En,void 0),ge(this,Sn,console),ge(this,En,t)}debug(...t){bs[L(this,En)]>bs.debug||L(this,Sn).debug("[Sockrates]:",...t)}info(...t){bs[L(this,En)]>bs.info||L(this,Sn).info("[Sockrates]:",...t)}warn(...t){bs[L(this,En)]>bs.warn||L(this,Sn).warn("[Sockrates]:",...t)}error(...t){bs[L(this,En)]>bs.error||L(this,Sn).error("[Sockrates]:",...t)}}Sn=new WeakMap,En=new WeakMap;var gv=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(gv||{});const rN="2",sN="3";class nN{constructor(t,e){Ie(this,Fu),Ie(this,Ca),Ie(this,xu),Ie(this,Uu),Ie(this,id),Ie(this,$u),Ie(this,ba),Ie(this,Pa),Ie(this,cd),Ie(this,pi),Ie(this,ka),Ie(this,He,void 0),Ie(this,wn,void 0),Ie(this,Le,void 0),Ie(this,Ke,void 0),Ie(this,ws,void 0),Ie(this,ot,void 0),Ie(this,Kr,void 0),Ie(this,Cs,void 0),Ie(this,pr,void 0),Ie(this,hi,void 0),Ie(this,zr,void 0);var r,n,i,a,o,d,u,h,p,f,v,T,P,k,I,x,V,O,W;ge(this,wn,t),ge(this,ws,[]),ge(this,ot,new QO),ge(this,Kr,!0),ge(this,pr,!1),ge(this,Le,e!=null?e:{}),(n=(r=L(this,Le)).autoReconnect)!=null||(r.autoReconnect=!0),(a=(i=L(this,Le)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(d=(o=L(this,Le)).pingTimeout)!=null||(o.pingTimeout=3e4),(h=(u=L(this,Le)).connectionTimeout)!=null||(u.connectionTimeout=5e3),(f=(p=L(this,Le)).debug)!=null||(p.debug=!0),(T=(v=L(this,Le)).maxReconnectionAttempts)!=null||(v.maxReconnectionAttempts=10),(k=(P=L(this,Le)).disconnectOnPingTimeout)!=null||(P.disconnectOnPingTimeout=!0),(x=(I=L(this,Le)).queueOnDisconnect)!=null||(I.queueOnDisconnect=!1),(O=(V=L(this,Le)).flushOnReconnect)!=null||(V.flushOnReconnect=!1),ge(this,Cs,{code:void 0,reason:void 0}),ge(this,Ke,(W=L(this,Le).logger)!=null?W:new tN(L(this,Le).debug?"debug":"info")),ge(this,zr,new eN)}get readyState(){var t;return(t=L(this,He))==null?void 0:t.readyState}get url(){return L(this,wn)}updateURL(t){ge(this,wn,t),Ne(this,$u,sv).call(this)}get config(){return L(this,Le)}get sendQueue(){return L(this,ws)}flush(){if(!L(this,Le).queueOnDisconnect)return!1;const t=[];return L(this,ws).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),ge(this,ws,t),L(this,ws)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){L(this,Ke).debug("Websocket was already connecting or connected.");return}if(L(this,Kr)!==!1)return new Promise((e,r)=>{Ne(this,pi,Ra).call(this),Ne(this,ka,dd).call(this);try{ge(this,He,new WebSocket(Ne(this,Fu,ev).call(this,L(this,wn)))),L(this,He).binaryType="arraybuffer",L(this,Ke).debug("Connecting to",L(this,wn));const n=setTimeout(()=>{L(this,Ke).debug("Connection timeout. Closing socket"),ge(this,Kr,!0),Ne(this,ka,dd).call(this),L(this,He).close(3001,"Connection Timeout"),L(this,Le).autoReconnect&&!L(this,pr)&&(L(this,ot).emit("reconnecting"),Ne(this,ba,ad).call(this)),r(new Error("Connection timed out!"))},L(this,Le).connectionTimeout);L(this,He).onopen=()=>{L(this,Ke).debug(`Ready State: ${gv[L(this,He).readyState]}`),n&&clearTimeout(n),Ne(this,cd,Bu).call(this),ge(this,Cs,{code:void 0,reason:void 0}),L(this,ot).emit("connected"),L(this,Le).flushOnReconnect&&this.flush(),e()},L(this,He).onclose=i=>{try{n&&clearTimeout(n);const{code:a,reason:o}=i;r(o),L(this,Ke).debug("Socket closed. Close event:",i),L(this,Ke).debug("Connection closed code:",a),L(this,Ke).debug("Connection closed reason:",o),L(this,pr)||Ne(this,id,Vu).call(this,a,o)}catch(a){Ne(this,Ca,nd).call(this,a)}},L(this,He).onerror=i=>{Ne(this,Ca,nd).call(this,i)},L(this,He).onmessage=i=>Ne(this,xu,tv).call(this,i)}catch(n){Ne(this,Ca,nd).call(this,n,r)}})}send(t,e,r,n){const i={event:t,id:e,payload:r,metadata:n};if(L(this,Le).queueOnDisconnect&&(!L(this,He)||L(this,He).readyState!==1))return L(this,Ke).debug("Queuing message since socket is not connected!",i),L(this,ws).push(i),!1;const a=fv.encode(i);return Ne(this,Pa,od).call(this,a)}emit(t,e,r,n){return this.send(t,e,r,n)}sendRaw(t){return Ne(this,Pa,od).call(this,t)}receive(t,e){return L(this,ot).on(t.toString(),e)}on(t,e){if(typeof t=="string"&&(t==="connected"||t==="disconnected"||t==="errored"||t==="reconnected"||t==="reconnecting"||t==="reconnectAttempt"||t==="reconnectFailure"||t==="failed")){L(this,ot).on(t,e);return}this.receive(t,e)}removeAllListeners(){L(this,ot).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){L(this,ot).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){L(this,ot).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){ge(this,Kr,!1),Ne(this,pi,Ra).call(this),this.removeAllListeners(),ge(this,Cs,{code:1e3,reason:"Sockrates disconnect method called"}),L(this,He).close(1e3,"Sockrates disconnect method called.")}}He=new WeakMap,wn=new WeakMap,Le=new WeakMap,Ke=new WeakMap,ws=new WeakMap,ot=new WeakMap,Kr=new WeakMap,Cs=new WeakMap,pr=new WeakMap,hi=new WeakMap,zr=new WeakMap,Fu=new WeakSet,ev=function(s){if(s.startsWith("ws://")||s.startsWith("wss://"))return s;if(s.startsWith("https://"))return`wss://${s.substring(8)}`;if(s.startsWith("http://"))return`ws://${s.substring(7)}`;throw new Error("Invalid URL. URL must start with http(s):// or ws(s)://.")},Ca=new WeakSet,nd=function(s,t){L(this,Ke).error("Error:",{error:s}),L(this,ot).emit("errored",{error:s}),t==null||t(s)},xu=new WeakSet,tv=function(s){if(Ne(this,cd,Bu).call(this),s.data===rN){L(this,Ke).debug("Received ping from server"),Ne(this,Pa,od).call(this,sN);return}const t=fv.decode(s.data),{id:e,payload:r}=t;L(this,Ke).debug("Received message",{event:t.event,messageID:e}),L(this,ot).emit(t.event.toString(),{id:e,payload:r})},Uu=new WeakSet,rv=function(){return L(this,He).readyState===1},id=new WeakSet,Vu=function(s,t){ge(this,Cs,{reason:t,code:s}),L(this,ot).emit("disconnected",{code:s,reason:t})},$u=new WeakSet,sv=function(){const{reason:s,code:t}=L(this,Cs);t&&t!==1e3&&L(this,Kr)&&L(this,Le).autoReconnect&&!L(this,pr)&&(L(this,Ke).debug(`Triggering reconnection due to ${s}.`),L(this,ot).emit("reconnecting"),Ne(this,ba,ad).call(this))},ba=new WeakSet,ad=async function(s=!0){if(s&&L(this,pr)){L(this,Ke).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(L(this,pr)||L(this,zr).reset(),L(this,Le).maxReconnectionAttempts!==null&&L(this,zr).getAttempts()>=L(this,Le).maxReconnectionAttempts){L(this,ot).emit("failed"),ge(this,pr,!1);return}ge(this,pr,!0),Ne(this,ka,dd).call(this),Ne(this,pi,Ra).call(this);try{if(await L(this,zr).wait(),L(this,Kr)===!1)return;if(L(this,Ke).debug(`Reconnection attempt ${L(this,zr).getAttempts()}`),L(this,ot).emit("reconnectAttempt",{attempt:L(this,zr).getAttempts()}),await this.connect(),!Ne(this,Uu,rv).call(this))throw Error("Reconnect Failed");ge(this,pr,!1),ge(this,Cs,{code:void 0,reason:void 0}),L(this,ot).emit("reconnected")}catch(t){L(this,Ke).debug("Failed to reconnect."),L(this,ot).emit("reconnectFailure",{attempt:L(this,zr).getAttempts()}),Ne(this,ba,ad).call(this,!1)}},Pa=new WeakSet,od=function(s){try{return L(this,He).send(s),!0}catch(t){return L(this,Ke).error(t.message),!1}},cd=new WeakSet,Bu=function(){this.config.disconnectOnPingTimeout&&(L(this,Ke).debug("Resetting ping timeout"),Ne(this,pi,Ra).call(this),ge(this,hi,setTimeout(()=>{var s;L(this,Ke).debug("Disconnecting the socket due to ping timeout"),ge(this,Kr,!0);const t=3002,e="Ping timeout";(s=L(this,He))==null||s.close(t,e),Ne(this,id,Vu).call(this,t,e)},L(this,Le).pingTimeout)))},pi=new WeakSet,Ra=function(){L(this,hi)&&(clearTimeout(L(this,hi)),ge(this,hi,void 0))},ka=new WeakSet,dd=function(){L(this,He)&&(L(this,He).onopen=void 0,L(this,He).onerror=void 0,L(this,He).onmessage=void 0,L(this,He).onclose=void 0)};var iN=Object.defineProperty,aN=Object.getOwnPropertyDescriptor,hd=(s,t,e,r)=>{for(var n=r>1?void 0:r?aN(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&iN(t,e,n),n};const vv=65535,oN=3e3,yv=($v=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:n}){S(this,Me);S(this,po);S(this,mo);S(this,Ws,void 0);S(this,Ve,void 0);m(this,"roomName");m(this,"authToken");m(this,"capabilities");S(this,nr,void 0);S(this,os,void 0);var i;if(!t||!e||!r)throw new b("peerId, roomName, or authToken can not be empty");y(this,nr,void 0),y(this,os,s),this.capabilities=n,this.roomName=e,this.authToken=r,y(this,Ws,je(this,po,eh).call(this,t)),y(this,Ve,new nN(c(this,Ws),{autoReconnect:!0,disconnectOnPingTimeout:(i=n.includes("PING"))!=null?i:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:l})),this.handleSocketConnectionEvents()}get joinAttempted(){return c(this,Me,$e).socketJoinAttempted}set joinAttempted(s){c(this,Me,$e).socketJoinAttempted=s}get peerId(){return c(this,os).getValue("peerId")}updateURL(s){s!==this.peerId&&(y(this,Ws,je(this,po,eh).call(this,s)),l.debug("SocketService:: Connection URL updated.")),c(this,Ve).updateURL(c(this,Ws))}static getSocketEdgeDomain(s){return Xn({servicePrefix:"socket-edge",baseURI:s})}get url(){return c(this,Ws)}async connect(){c(this,Me,$e).socketJoinAttempted=!0,await c(this,Ve).connect(),c(this,Me,$e).socketJoinAttempted=!0,c(this,Me,$e).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}async disconnect(){c(this,Me,$e).socketJoinAttempted=!1,c(this,Ve).disconnect(),c(this,Me,$e).socketJoinAttempted=!0,c(this,Me,$e).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return c(this,Ve).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return g.injectContext(r),c(this,Ve).send(s,e!=null?e:je(this,mo,th).call(this),t,new TextEncoder().encode(JSON.stringify(r)))}sendMessagePromise(s,t,e,r){const n=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:s,timeout:n,protobuf:t,messageId:e,resp:r})}sendMessagePromiseWithTimeout({event:s,timeout:t,protobuf:e,messageId:r,resp:n}){const i=n!=null?n:s;return new Promise((a,o)=>{const d=(v,T)=>{c(this,Ve).removeListener(i,v),c(this,Ve).removeListener(vv,T),c(this,Ve).removeListener(se.errorResponse,T),c(this,Ve).removeListener(ne.errorResponse,T)},u=r!=null?r:je(this,mo,th).call(this),h={};g.injectContext(h);const p=({id:v,payload:T})=>{if(u===v){let P;try{const k=$P.fromBinary(T);P=new Error(k.errorMessage)}catch(k){P=new Error("failed to parse error message",{cause:k});try{const I=MR.fromBinary(T);P=new Error(I.message)}catch(I){P=new Error("failed to parse error message",{cause:I})}}o(P),d(f,p)}},f=({id:v,payload:T})=>{u===v&&(a({id:v,payload:T}),d(f,p))};c(this,Ve).on(i,f),c(this,Ve).on(vv,p),c(this,Ve).on(se.errorResponse,p),c(this,Ve).on(ne.errorResponse,p),setTimeout(()=>{d(f,p),o(new Error(`request timeout for callback eventId:${s}`))},t),c(this,Ve).send(s,u,e,new TextEncoder().encode(JSON.stringify(h)))})}on(s,t){c(this,Ve).on(s,t)}onStateEvent(s,t){c(this,Ve).on(s,t)}removeListener(s,t){c(this,Ve).removeListener(s,t)}removeListeners(s){c(this,Ve).removeListeners(s)}flush(){return c(this,Ve).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{l.info("SocketService::Connected to socket-edge"),c(this,nr)&&(clearTimeout(c(this,nr)),y(this,nr,void 0)),c(this,Me,$e).updateSocketConnectionState("connected")}),this.onStateEvent("disconnected",({code:s,reason:t})=>{var n;l.info("SocketService::Disconnected from socket-edge",{error:{code:s,reason:t}});const{consuming:e,producing:r}=(n=c(this,Me,$e).mediaState)!=null?n:{};e!=null&&e.state&&(e==null?void 0:e.state)!==Rt.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==Rt.CONNECTED?w.emit(C.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:c(this,Me,$e).joinAttempted}):y(this,nr,setTimeout(()=>{w.emit(C.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:c(this,Me,$e).joinAttempted}),y(this,nr,void 0)},oN)),c(this,Me,$e).updateSocketConnectionState("disconnected"),c(this,Me,$e).roomJoined=!1}),this.onStateEvent("reconnecting",async()=>{l.info("SocketService::Reconnecting to socket-edge"),c(this,Me,$e).updateSocketConnectionState("reconnecting")}),this.onStateEvent("reconnectAttempt",async({attempt:s})=>{l.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),c(this,Me,$e).updateSocketConnectionState("reconnectAttempt",s)}),this.onStateEvent("reconnectFailure",({attempt:s})=>{l.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),c(this,Me,$e).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",async()=>{l.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:c(this,Me,$e).joinAttempted}}),c(this,nr)&&(clearTimeout(c(this,nr)),y(this,nr,void 0)),w.emit(C.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:c(this,Me,$e).joinAttempted}),c(this,Me,$e).updateSocketConnectionState("reconnected")}),this.onStateEvent("failed",async()=>{l.info("SocketService::Failed to connect to socket-edge"),w.emit(C.SOCKET_SERVICE_FAILED),c(this,Me,$e).updateSocketConnectionState("failed"),c(this,Me,$e).roomJoined=!1})}},Ws=new WeakMap,Ve=new WeakMap,Me=new WeakSet,$e=function(){return c(this,os).getValue("connectionHandler")},nr=new WeakMap,os=new WeakMap,po=new WeakSet,eh=function(s){let t=yv.getSocketEdgeDomain(c(this,os).getValue("baseURI"));typeof Nl(c(this,os),"socket_server_base")=="string"&&(t=Nl(c(this,os),"socket_server_base"));const e=`wss://${t}`,r=new URL(`${e}/ws`),n=this.peerId,i={roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0,...n!==s&&{oldPeerID:n},ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(a=>Ic[a]).join(" "),joinWithDetails:!0};return Object.entries(i).forEach(([a,o])=>{r.searchParams.append(a,o.toString())}),r.href},mo=new WeakSet,th=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},$v);let Ia=yv;hd([g.trace("SocketService.connect")],Ia.prototype,"connect",1),hd([g.trace("SocketService.disconnect")],Ia.prototype,"disconnect",1),hd([g.trace("SocketService.sendMessagePromise")],Ia.prototype,"sendMessagePromise",1),hd([g.trace("SocketService.sendMessagePromiseWithTimeout")],Ia.prototype,"sendMessagePromiseWithTimeout",1);const Ks=class{static handleConnectedRoomsDumpRaw({payload:t}){var i;const e=nk.fromBinary(t),r=e.meetings.map(a=>{var o;return{id:a.id,title:a.title,participants:(o=a.participants)!=null?o:[]}});return{parentMeeting:{id:e.parentMeeting.id,title:e.parentMeeting.title,participants:(i=e.parentMeeting.participants)!=null?i:[]},meetings:r}}static handleTransferPeerRaw({payload:t}){const e=Ak.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}static handleMovedPeerRaw({payload:t}){const e=Hf.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}static handleConnectedRoomsUpdatedRaw({payload:t}){return Bf.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}static handleConnectedRoomsDeletedRaw({payload:t}){return _k.fromBinary(t).payloads}static async getConnectedRoomsDump(){const t=await Ks.socketService.sendMessagePromise($.getConnectedRoomsDump);return Ks.handleConnectedRoomsDumpRaw(t)}static async createConnectedRooms(t){const{payload:e}=await Ks.socketService.sendMessagePromise($.createConnectedRooms,ck.toBinary({payloads:t}));return Bf.fromBinary(e).payloads.map(n=>({id:n.id,title:n.title}))}static async updateConnectedRooms(t){}static async disableConnectedRooms(t){const e=t.map(n=>({id:n})),r=await Ks.socketService.sendMessagePromise($.deleteConnectedRooms,yk.toBinary({payloads:e}));return Ks.handleConnectedRoomsDeletedRaw(r)}static async movePeersBetweenRooms(t){try{const e=await Ks.socketService.sendMessagePromise($.movePeers,Pk.toBinary({sourceMeetingId:t.sourceMeetingId,destinationMeetingId:t.destinationMeetingId,participants:t.participants}));return new TextDecoder().decode(e.payload).includes("error")?{success:!1,error:"failed to move participants"}:{success:!0}}catch(e){return{success:!1,error:e}}}};let Ae=Ks;m(Ae,"socketService"),m(Ae,"currentMeetingId");var cN=Object.defineProperty,dN=Object.getOwnPropertyDescriptor,pd=(s,t,e,r)=>{for(var n=r>1?void 0:r?dN(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&cN(t,e,n),n};const Cn=class{constructor(s,t){m(this,"apiBase");m(this,"selfController");m(this,"pollController");m(this,"chatController");m(this,"metaController");m(this,"storesManager");m(this,"stageController");m(this,"pluginController");m(this,"internalsController");m(this,"recordingController");m(this,"livestreamController");m(this,"participantController");this.apiBase=s,this.storesManager=t.storesManager,this.metaController=t.metaController,this.selfController=t.selfController,this.chatController=t.chatController,this.pollController=t.pollController,this.stageController=t.stageController,this.pluginController=t.pluginController,this.recordingController=t.recordingController,this.internalsController=t.internalsController,this.participantController=t.participantController,this.livestreamController=t.livestreamController}static async init(s){var x;const{peerId:t,apiBase:e,authToken:r,meetingId:n,organizationId:i,cachedUserDetails:a}=s.getAllValues();if(w.reset(),rd.cleanup(),Qg(s),Se.isSupported()===!1)throw new b("Browser not supported","0010",!0);const o=HM(s,{authToken:r,baseURL:e,cachedUserDetails:a});o.setRoomName(n),o.setRoomUUID(n),o.setOrganizationId(i),o.setHeader("dyte-tracing-id",t),s.setValue("apiClient",o);const d=new C0;s.setValue("connectionHandler",d);const u=Cn.createSocketService(s),h=u.connect(),p=o.getPlugins(),[{sfu:f,userResponse:v,meetingTitle:T,roomNodeUrl:P}]=await Promise.all([Cn.getRoomMetadata(),Cn.setupFlagsmith(s)]);g.location.country=(x=o.ipInfo)==null?void 0:x.country,s.setValue("roomNodeOptions",{sfu:f,meetingTitle:T,roomNodeUrl:P});const{theme:k,controllers:I}=await Cn.setupControllers(u,s,v,p);p0(k)&&Cn.createRoomNodeClient(s,u),vb();try{await h,I.selfController.partialMediaRoom()}catch(V){throw l.error("[Socket Service] Failed to connect to socket server:",{error:V}),new b("Failed to connect to websocket","0012")}return new Cn(e,I)}static async getRoomMetadata(){const s=We(),[{roomNodeUrl:t,meetingTitle:e,sfu:r=li.HIVE},n]=await Promise.all([s.getRoomNodeData(),s.getUserDetails()]);return{sfu:r,roomNodeUrl:t,meetingTitle:e,userResponse:n}}static async setupFlagsmith(s){const{peerId:t,baseURI:e,overrides:r,meetingId:n,organizationId:i}=s.getAllValues(),a=fb(n),o={entity:Dl.PEER,clientId:i,isAnonUser:!i,sdkVersion:s.getValue("sdkVersion"),meetingHash:a,roomName:n,...Se.getDeviceInfo(),isReactNative:navigator.isReactNative};try{const d=r!=null&&r.whitelabelled_flags_endpoint?Xn({servicePrefix:"flags",baseURI:e}):"edge.api.flagsmith.com";await J.identify(`${Dl.PEER}_${t}`,JSON.parse(JSON.stringify(o)),!1,5e3,d),l.info("flagsmith::allFlags",{flags:JSON.stringify(J.getAllFlags())},!0)}catch(d){l.error("Failed to fetch flagsmith flags")}}static async setupControllers(s,t,e,r){var G,A,rt;const n=t.getValue("modules"),{preset:i,participant:a}=e,o=t.getValue("defaults"),{sfu:d,meetingTitle:u}=t.getValue("roomNodeOptions"),h=_u.init(i,!n.theme),{viewType:p,mediaConstraints:{audio:f}}=h;t.setValue("viewType",p),t.setValue("defaults",{mediaConfiguration:{audio:{enableHighBitrate:(G=f.enableHighBitrate)!=null?G:!1,enableStereo:(A=f.enableStereo)!=null?A:!1}},...o});const v=Du.init(t,p,i.permissions);let T,P,k,I,x,V,O,W;const Q=new xO(s);Ae.socketService=s;const oe=new sd(s),ve=new Xt(s),Mt=new $O(s),Fe=rd.create(s),Dt=new BO(s),M=new FO(s),E=new dn(s),R=await Ss.init(t,Fe,a,v,h),B=await lg.init(t,R.self,Fe,Q,u);if(n.participant&&(d===li.CF&&(W=new Jg(t,R.self,Fe)),W=new Wg(t,R.self,Fe)),(rt=n.e2ee)!=null&&rt.enabled&&n.e2ee.manager.init(l,w),n.chat&&(P=await ur.init(t,ve,E,R.self,W.participants)),n.internals&&(x=await pu.init()),n.livestream&&h.viewType===Xe.Livestream&&J.hasFeature(X.LIVESTREAM)&&(O=new Mg(R.self,M)),h.viewType!==Xe.Chat){if(n.poll&&(T=await ag.init(t,R.self,oe)),n.recording&&(V=new fg(t,R.self,Fe)),n.stage&&(k=new ug(t,Mt,Fe,R.self,W.participants)),n.plugin){if(!W)throw new b("The plugin module cannot be initialized without the `participant` module");const cs=await r;I=await ga.init(t,cs,Dt,ve,P==null?void 0:P.chat,R.self,W.participants)}if(n.pip){const cs=await Ll._init(t,R.self);t.setValue("pip",cs)}}const Qe={storesManager:new ED(t,Dt),pollController:T,selfController:R,metaController:B,chatController:P,stageController:k,pluginController:I,recordingController:V,internalsController:x,livestreamController:O,participantController:W};return{theme:h,permissions:v,controllers:Qe}}static async createRoomNodeClient(s,t){const{peerId:e,meetingId:r,authToken:n,roomNodeOptions:i}=s.getAllValues(),{sfu:a,roomNodeUrl:o,meetingTitle:d}=i;return Yg(s,{socket:t,peerId:e,meetingId:r,authToken:n,roomNodeUrl:o,meetingTitle:d},a)}static createSocketService(s){const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),n=["PING"];return new Ia(s,{peerId:t,meetingId:e,authToken:r,capabilities:n})}};let Aa=Cn;pd([g.trace("Controller.init")],Aa,"init",1),pd([g.trace("setupFlagsmith")],Aa,"setupFlagsmith",1),pd([g.trace("Controller.createSocketServiceAndRoomNodeClient")],Aa,"createRoomNodeClient",1),pd([g.trace("Controller.createSocketService")],Aa,"createSocketService",1);var lN=Object.defineProperty,uN=Object.getOwnPropertyDescriptor,hN=(s,t,e,r)=>{for(var n=r>1?void 0:r?uN(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&lN(t,e,n),n};class Tv extends Ht{constructor(e,r){super();S(this,fo,void 0);m(this,"meetings",[]);m(this,"parentMeeting",null);S(this,Md,void 0);y(this,Md,e),y(this,fo,r.self)}get supportsConnectedMeetings(){return c(this,fo).id!==""}get isActive(){return this.meetings.length!==0}get currentMeetingId(){return Ae.currentMeetingId}validateConnectedMeetingsAction(){if(!this.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action. Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`)}async getConnectedMeetings(){return this.validateConnectedMeetingsAction(),await Ae.getConnectedRoomsDump()}async createMeetings(e){return this.validateConnectedMeetingsAction(),(await Ae.createConnectedRooms(e)).map(n=>({id:n.id,title:n.title}))}async updateMeetings(e){this.validateConnectedMeetingsAction(),await Ae.updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title})))}async deleteMeetings(e){this.validateConnectedMeetingsAction();const r=this.meetings.map(i=>e.includes(i.id)&&i.participants.length!==0?this.moveParticipants(i.id,this.parentMeeting.id,i.participants.map(a=>a.id)):Promise.resolve());return await Promise.all(r),await Ae.disableConnectedRooms(e)}async moveParticipants(e,r,n){this.validateConnectedMeetingsAction();const i=await Ae.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:n.map(a=>({id:a}))});return i.success&&this.moveSuccessHandler(e,r,n),i}async moveParticipantsWithCustomPreset(e,r,n){this.validateConnectedMeetingsAction();const i=await Ae.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:n});return i.success&&this.moveSuccessHandler(e,r,n.map(a=>a.id)),i}moveSuccessHandler(e,r,n){const i=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(a=>a.participants)].forEach(a=>i.set(a.id,a)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(n.map(a=>i.get(a)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(a=>!n.includes(a.id))),this.meetings=this.meetings.map(a=>{if(r===a.id){const o=a.participants.concat(n.map(d=>i.get(d)));return{...a,participants:o}}if(e===a.id){const o=a.participants.filter(d=>!n.includes(d.id));return{...a,participants:o}}return a})}}fo=new WeakMap,Md=new WeakMap,hN([Lt({maxInvocations:60,period:60})],Tv.prototype,"getConnectedMeetings",1);var pN=Object.defineProperty,mN=Object.getOwnPropertyDescriptor,qu=(s,t,e,r)=>{for(var n=r>1?void 0:r?mN(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&pN(t,e,n),n};const Ps=(Ju=class{constructor(s,t,e){m(this,"connectedMeetings");S(this,Xi,void 0);S(this,zs,void 0);S(this,Dd,void 0);y(this,Dd,s),y(this,Xi,e),this.connectedMeetings=new Tv(s,t),this.setCurrentMeeting(t)}static init(s,t,e){return Ps.instance||(Ps.instance=new Ps(s,t,e)),Ps.instance.connectedMeetings.supportsConnectedMeetings&&(Ps.instance.setupEvents(),t.self.once("roomJoined",()=>Ps.instance.getConnectedMeetings())),Ps.instance}setCurrentMeeting(s){y(this,zs,s),Ae.currentMeetingId=s.meta.meetingId}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){Ae.socketService&&(Ae.socketService.on($.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),Ae.socketService.on($.transferPeer,this.handleTransferPeer.bind(this)),Ae.socketService.on($.movedPeer,this.handleMovedPeer.bind(this)),Ae.socketService.on($.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),Ae.socketService.on($.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this)))}handleTransferPeer(s){const t=Ae.handleTransferPeerRaw(s);return this.switchMeeting(t)}async switchMeeting({authToken:s,meetingId:t}){if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action. Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`);this.connectedMeetings.emit("changingMeeting",t),await c(this,zs).leave("connected-meeting"),Ae.socketService=void 0;const e=await Sv.init({...c(this,Xi),cachedUserDetails:null,defaults:{...c(this,Xi).defaults,video:c(this,zs).self.videoEnabled,audio:c(this,zs).self.audioEnabled},authToken:s});e.self.setName(c(this,zs).self.name);try{await e.join()}catch(r){g.addLogInCurrentSpan("error","ConnectedMeetingsController.joinRoom",{error:r})}return this.connectedMeetings.emit("meetingChanged",e),this.setCurrentMeeting(e),e}handleConnectedRoomsDump(s){const t=Ae.handleConnectedRoomsDumpRaw(s);this.connectedMeetings.meetings=t.meetings.map(e=>({id:e.id,title:e.title,participants:e.participants||[]})),this.connectedMeetings.parentMeeting={id:t.parentMeeting.id,title:t.parentMeeting.title,participants:t.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(s){return Ae.handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=Ae.handleConnectedRoomsUpdatedRaw(s),e=new Map;this.connectedMeetings.meetings.forEach(r=>{e.set(r.id,r)}),t.forEach(r=>{e.has(r.id)?e.get(r.id).title=r.title:e.set(r.id,{...r,participants:[]})}),this.connectedMeetings.meetings=Array.from(e.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(s){const e=Ae.handleConnectedRoomsDeletedRaw(s).map(r=>r.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(r=>!e.includes(r.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},Xi=new WeakMap,zs=new WeakMap,Dd=new WeakMap,m(Ju,"instance"),Ju);let md=Ps;qu([g.trace("ConnectedMeetingsController.getConnectedMeetings")],md.prototype,"getConnectedMeetings",1),qu([g.trace("ConnectedMeetingsController.setupEvents")],md.prototype,"setupEvents",1),qu([g.trace("ConnectedMeetingsController.switchMeeting")],md.prototype,"switchMeeting",1);class fN{constructor(){m(this,"battery");m(this,"init",async()=>{try{"getBattery"in navigator&&(this.battery=await navigator.getBattery(),this.battery.addEventListener("chargingchange",this.updateChargeInfo),this.battery.addEventListener("levelchange",this.updateLevelInfo),this.updateLevelInfo(),this.updateChargeInfo())}catch(t){l.error("Error getting battery",t)}});m(this,"updateChargeInfo",()=>{var t;l.log(`Battery charging? ${(t=this.battery)!=null&&t.charging?"Yes":"No"}`)});m(this,"updateLevelInfo",()=>{if(!this.battery){l.log("Battery level: Not known");return}l.log(`Battery level: ${this.battery.level*100}%`)});m(this,"cleanup",()=>{var t,e;"getBattery"in navigator&&((t=this.battery)==null||t.removeEventListener("chargingchange",this.updateChargeInfo),(e=this.battery)==null||e.removeEventListener("levelchange",this.updateLevelInfo))})}}const _v=new fN;function gN(s,t){try{const{meetingId:e,orgId:r,participantId:n}=JSON.parse(atob(s.split(".")[1]));if(!e)throw Error(`Received V1 auth token ${s}`);let i="dyte.io";t&&(i=t);const a=`https://api.${i}`;return{meetingId:e,orgId:r,participantId:n,baseURI:i,apiBase:a}}catch(e){throw l.error("constants::decodeAuthToken",{error:e,debuggingHint:`Unable to decode auth token: ${s}`},!0),new b("Invalid auth token")}}var vN=Object.defineProperty,yN=Object.getOwnPropertyDescriptor,fd=(s,t,e,r)=>{for(var n=r>1?void 0:r?yN(t,e):t,i=s.length-1,a;i>=0;i--)(a=s[i])&&(n=(r?a(t,e,n):a(n))||n);return r&&n&&vN(t,e,n),n};let Rs=(Bv=class{constructor(t,e){S(this,Od);S(this,ct,void 0);S(this,go,void 0);S(this,vo,void 0);y(this,vo,t),y(this,ct,e)}static async init(t){var h,p,f,v,T;hb(),Se.init();const e=Xs();_v.init();const{authToken:r,baseURI:n}=t,{meetingId:i,...a}=gN(r,n);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const o=Rs.setupContext(e,t,i,a);g.meetingMetadata.roomName=i,g.meetingMetadata.userId=a.participantId,g.meetingMetadata.organizationId=a.orgId,g.init(o,(p=(h=t.modules)==null?void 0:h.tracing)!=null?p:!0),l.info("DyteClient::init::options",{dyteClientInitOptions:{...t,authToken:`${(f=t.authToken)==null?void 0:f.slice(0,10)}... -${(v=t.authToken)==null?void 0:v.slice(-10)}`}});const d=await Aa.init(o),u=new Rs(o,d);return je(T=u,Od,zv).call(T,t),u}static setupContext(t,e,r,n){var o;const i=pa.createContext(t,e),a={...ab,...e==null?void 0:e.modules};return i.setValue("peerId",t),i.setValue("modules",a),i.setValue("sdkName","web-core"),i.setValue("meetingId",r),i.setValue("apiBase",n.apiBase),i.setValue("baseURI",n.baseURI),i.setValue("userId",n.participantId),i.setValue("organizationId",n.orgId),i.setValue("authToken",e.authToken),i.setValue("overrides",(o=e.overrides)!=null?o:{}),i.setValue("env",ob({baseURI:n.baseURI})),i.setValue("defaults",e.defaults||{audio:!0,video:!0}),i.setValue("cachedUserDetails",wr(e.cachedUserDetails)),i.setValue("sdkVersion","2.1.10-staging.6"),i}async join(){const{selfController:t}=c(this,ct);return t.self.roomJoined?null:t.joinRoom()}async leave(t){_v.cleanup();const{selfController:e}=c(this,ct);return e.leaveRoom(t)}get participants(){var t;return(t=c(this,ct).participantController)==null?void 0:t.participants}get self(){var t;return(t=c(this,ct).selfController)==null?void 0:t.self}get meta(){var t;return(t=c(this,ct).metaController)==null?void 0:t.meta}get ai(){var t;return(t=c(this,ct).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=c(this,ct).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=c(this,ct).chatController)==null?void 0:t.chat}get polls(){var t;return(t=c(this,ct).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=c(this,go))==null?void 0:t.connectedMeetings}get recording(){var t;return(t=c(this,ct).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=c(this,ct).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=c(this,ct).stageController)==null?void 0:t.stage}get stores(){return c(this,ct).storesManager}get __internals__(){var t;return(t=c(this,ct).internalsController)==null?void 0:t.internals}async joinRoom(){return this.join()}async leaveRoom(t){return this.leave(t)}},ct=new WeakMap,go=new WeakMap,vo=new WeakMap,Od=new WeakSet,zv=function(t){y(this,go,md.init(c(this,vo),this,t))},Bv);fd([pt("0002"),_s.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],Rs.prototype,"join",1),fd([pt("0003")],Rs.prototype,"leave",1),fd([pt("0001"),_s.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],Rs,"init",1),Rs=fd([pt("0000")],Rs);const Sv=Rs;return Sv}(); +${(v=t.authToken)==null?void 0:v.slice(-10)}`}});const d=await Aa.init(o),u=new Rs(o,d);return je(T=u,Od,zv).call(T,t),u}static setupContext(t,e,r,n){var o;const i=pa.createContext(t,e),a={...ab,...e==null?void 0:e.modules};return i.setValue("peerId",t),i.setValue("modules",a),i.setValue("sdkName","web-core"),i.setValue("meetingId",r),i.setValue("apiBase",n.apiBase),i.setValue("baseURI",n.baseURI),i.setValue("userId",n.participantId),i.setValue("organizationId",n.orgId),i.setValue("authToken",e.authToken),i.setValue("overrides",(o=e.overrides)!=null?o:{}),i.setValue("env",ob({baseURI:n.baseURI})),i.setValue("defaults",e.defaults||{audio:!0,video:!0}),i.setValue("cachedUserDetails",wr(e.cachedUserDetails)),i.setValue("sdkVersion","2.1.10-staging.7"),i}async join(){const{selfController:t}=c(this,ct);return t.self.roomJoined?null:t.joinRoom()}async leave(t){_v.cleanup();const{selfController:e}=c(this,ct);return e.leaveRoom(t)}get participants(){var t;return(t=c(this,ct).participantController)==null?void 0:t.participants}get self(){var t;return(t=c(this,ct).selfController)==null?void 0:t.self}get meta(){var t;return(t=c(this,ct).metaController)==null?void 0:t.meta}get ai(){var t;return(t=c(this,ct).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=c(this,ct).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=c(this,ct).chatController)==null?void 0:t.chat}get polls(){var t;return(t=c(this,ct).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=c(this,go))==null?void 0:t.connectedMeetings}get recording(){var t;return(t=c(this,ct).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=c(this,ct).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=c(this,ct).stageController)==null?void 0:t.stage}get stores(){return c(this,ct).storesManager}get __internals__(){var t;return(t=c(this,ct).internalsController)==null?void 0:t.internals}async joinRoom(){return this.join()}async leaveRoom(t){return this.leave(t)}},ct=new WeakMap,go=new WeakMap,vo=new WeakMap,Od=new WeakSet,zv=function(t){y(this,go,md.init(c(this,vo),this,t))},Bv);fd([pt("0002"),_s.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],Rs.prototype,"join",1),fd([pt("0003")],Rs.prototype,"leave",1),fd([pt("0001"),_s.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],Rs,"init",1),Rs=fd([pt("0000")],Rs);const Sv=Rs;return Sv}();