PageSourceSearch

https://app.parler.com/assets/LoungePageRoute-BnIxhUS4.js

js parler.com collected 2026-09-24 08:28:46 UTC 625,939 bytes, 98 lines download raw bytes

1import{u as Cr,gx as Uu,c as xt,gy as Ca,gz as Fu,gA as Vu,gB as Bu,gC as qu,gD as Hu,gE as Ta,gF as zu,gG as kc,gH as Ku,gI as Wu,j as c,ee as xc,ef as Gu,gJ as Ju,gK as $u,gL as Qu,gM as Yu,gN as Zu,bd as Xu,gO as Pn,bc as eh,gP as th,gQ as nh,b as ih,gR as sh,dw as rh,bj as Je,gS as ah,gT as yc,eN as oh,gU as ch,bo as Cc,ff as dh,ab as Tc,gV as Sc,gW as Nn,aQ as lh,bq as uh,gX as hh,gY as mh,ce as oi,gZ as $i,a3 as Et,bl as ph,g_ as wc,bm as fh,eM as gh,bp as vh,c2 as bh,g$ as kh,h0 as xh,gu as yh,h1 as Ch,h2 as Th,c7 as Sh,h3 as wh,ca as Rh,du as Eh,h4 as Ph,h5 as Nh,h6 as Rc,h7 as _h,h8 as Ih,h9 as Mh,ha as jh,hb as Un,hc as Ec,hd as Oh,he as Lh,hf as Ah,hg as Dh,hh as Pc,hi as Nc,hj as _c,hk as Uh,hl as Fh,hm as Sa,hn as Vh,ho as Bh,hp as qh,hq as Hh,hr as zh,a4 as Kh}from"./vendor-data-eBPZki-Z.js";import{aD as Wh,aI as Ic,fZ as Gh,ca as Mc,A as jc,f_ as Jh,f$ as $h,cJ as Qi,g0 as pt,g1 as Qh,g2 as Yh,g3 as Oc,g4 as Zh,g5 as Xh,y as vn,cB as Li,g6 as Lc,g7 as em,g8 as tm,g9 as Tr,dV as nm,z as Yi,ga as Ac,cE as im,ds as sm,dl as rm,eS as am,eU as om,dO as cm,gb as dm,gc as lm,gd as um,ge as hm,cK as mm,gf as wa,gg as Dc,gh as Ra,gi as pm,gj as fm,gk as gm,gl as Ts,aX as vm,gm as bm,gn as km,go as xm}from"./vendor-zod-Bei2Z9MS.js";import{r as p,f as lt,L as Pe,o as ci,u as Sr,n as ei,k as Uc}from"./vendor-react-BgtJhS2O.js";import{d6 as Fc,eA as Vc,eB as Bc,eC as ym,eD as Cm,cB as Tm,cA as Ea,eE as Pa,b6 as Sm,_ as Zi,aX as di,eF as wm,b9 as wr,b_ as $e,t as z,aZ as Rr,at as Ae,a_ as Xi,af as Gs,eG as Rm,ag as Em,eH as Pm,eI as Na,eJ as qc,u as De,m as je,X as Hc,ez as zc,bO as Er,bv as Kc,cD as Sn,Z as Ye,dI as rn,eK as Ft,eL as an,d0 as Pr,am as qt,an as Ht,ao as zt,ap as Kt,aq as Wt,dw as es,eM as Nm,bL as _m,eN as Im,eO as Mm,a8 as ts,eP as Wc,aN as Nr,bp as _a,cr as jm,cs as Om,ac as Lm,eQ as Gc,eR as ns,eS as ln,eT as Am,aY as _n,c_ as Dm,eU as Um,d3 as Fm,bg as Vm,eu as _r,cJ as Bm,eV as qm,aD as Ia,eW as Hm,eX as zm,ey as Km,aA as Jc,b8 as Wm,eY as Gm,bz as Ma,cc as Jm,bn as $c,eZ as $m,a6 as Qm,e_ as Ym,ab as Zm,e$ as Xm,en as ep,f0 as tp,es as Qc,f1 as np,f2 as ip,f3 as Yc,f4 as sp,f5 as rp,f6 as ap,f7 as op,f8 as cp}from"./index-DTQGL8n8.js";import{u as is}from"./useTrackScreen-BLOOZkQ_.js";import{f as dp,g as lp}from"./usePostComments-Dl6oiND2.js";import{c as up,P as Zc}from"./PostCard-BpLSQMtH.js";import{M as hp}from"./ModerationProfileLink-D-cfV-C2.js";import{I as mp}from"./InviteShareModal-CR2OXGVS.js";import{S as Xc,L as Ir,a as ed}from"./LoungeFeedOverlays-DK6u33yH.js";import{u as td}from"./useAdminViewActive-ugcL5nZn.js";import{S as pp}from"./lock-square-DNvVRpgy.js";import{u as ja}from"./useImageCropTarget-D4vTG1Mx.js";import{L as gi,a as fp,i as gp}from"./LoungePrivacyRadios-DMwsS6RQ.js";import{u as nd}from"./usePremiumGateAccess-_F9WRRYB.js";import{M as vp,a as bp}from"./loungeSlug-ziCyOWDO.js";import{F as Mr}from"./FeedSkeleton-BVp-FCQb.js";import{u as id}from"./usePostActions-B9V6JroX.js";import{u as kp,a as sd}from"./useParentPostHydration-Dkq7qC0q.js";import{P as xp}from"./PostSkeleton-BY0I-Fub.js";import{A as Oa}from"./ActionPill-DC9WWrRI.js";import{I as yp}from"./InviteByUsername-CD_UeCRV.js";import"./ExpandableBody-DWLBBjw0.js";import"./user-multiple-F5jephUU.js";import"./useFeedVideoAutoplayPref-B5Ho7cdm.js";import"./useUserSettingValue-BuB0sMd0.js";import"./UserAddIcon-C4dm3gP3.js";import"./CommentComposeModal-BRop2xNS.js";import"./useNestedOverlayDismissGate-Bdez5EoF.js";import"./CameraIcon-MwhCrT8M.js";import"./PostActionsPortals-Cu4g2GT7.js";const ht={RoomStarted:"App\\Events\\VoiceRoomStarted",RoomEnded:"App\\Events\\VoiceRoomEnded",RoomUpdated:"App\\Events\\VoiceRoomUpdated",ParticipantJoined:"App\\Events\\VoiceParticipantJoined",ParticipantLeft:"App\\Events\\VoiceParticipantLeft",ParticipantRoleChanged:"App\\Events\\VoiceParticipantRoleChanged",HandRaised:"App\\Events\\VoiceHandRaised",HandLowered:"App\\Events\\VoiceHandLowered",ChatMessage:"App\\Events\\VoiceChatMessage",ChatMessageRemoved:"App\\Events\\VoiceChatMessageRemoved"};function Cp(n,e,t,i=!0,s){const r=Cr(),o=Fc(),a=e?`private-lounge.${e}`:null,d=Vc(a),l=Bc(),u=i&&!!n&&n!==Mc&&!!t&&!!e,h=p.useRef(t);p.useEffect(()=>{h.current=t},[t]);const m=p.useRef(s);p.useEffect(()=>{m.current=s},[s]),p.useEffect(()=>{if(!u||!o||!a)return;ym(o,a);const x=g=>typeof g?.roomId=="string"&&g.roomId===h.current,S=()=>h.current?kc(r,h.current):void 0,v=[o.on(a,ht.RoomStarted,g=>{if(x(g)){if(typeof g.createdAt=="string"&&g.createdAt!==""){if(!Uu(r,g.roomId,g.createdAt))return;r.setQueryData(xt.voiceRoom(g.roomId),k=>k?.data?{...k,data:{...k.data,createdAt:g.createdAt,isLive:!0}}:k)}
1r.invalidateQueries({queryKey:xt.voiceRoom(g.roomId)}),typeof g.loungeId=="string"&&r.invalidateQueries({queryKey:xt.voiceRooms(g.loungeId)})}}),o.on(a,ht.RoomEnded,g=>{if(!x(g))return;const k=typeof g.createdAt=="string"&&g.createdAt!==""?g.createdAt:void 0;if(k){Ca(g.roomId,k);const T=S();if(T&&Wh(T,k))return}else{const T=S();T&&Ca(g.roomId,T)}Fu(g.roomId),Vu(r,g.roomId),r.resetQueries({queryKey:xt.voiceRoom(g.roomId)}),typeof g.loungeId=="string"&&r.invalidateQueries({queryKey:xt.voiceRooms(g.loungeId)}),m.current?.()}),o.on(a,ht.RoomUpdated,g=>{x(g)&&(r.setQueryData(xt.voiceRoom(g.roomId),k=>k?.data?{...k,data:{...k.data,topic:g.topic??null}}:k),typeof g.loungeId=="string"&&r.invalidateQueries({queryKey:xt.voiceRooms(g.loungeId)}))}),o.on(a,ht.ParticipantJoined,g=>{!x(g)||typeof g.userUlid!="string"||Bu(r,g.roomId,{ulid:g.userUlid,username:typeof g.username=="string"?g.username:"",...typeof g.avatar=="string"?{avatar:g.avatar}:{},joinedAt:new Date().toISOString(),...g.role==="host"||g.role==="speaker"||g.role==="listener"?{role:g.role}:{}})}),o.on(a,ht.ParticipantLeft,g=>{!x(g)||typeof g.userUlid!="string"||qu(r,g.roomId,g.userUlid)}),o.on(a,ht.ParticipantRoleChanged,g=>{!x(g)||typeof g.userUlid!="string"||g.role!=="host"&&g.role!=="speaker"&&g.role!=="listener"||(Hu(r,g.roomId,g.userUlid,g.role),g.role!=="listener"&&Ta(r,g.roomId,g.userUlid))}),o.on(a,ht.HandRaised,g=>{!x(g)||typeof g.userUlid!="string"||Ic(S(),g.createdAt)&&zu(r,g.roomId,{userUlid:g.userUlid,username:typeof g.username=="string"?g.username:"",createdAt:typeof g.createdAt=="string"?g.createdAt:""})}),o.on(a,ht.HandLowered,g=>{!x(g)||typeof g.userUlid!="string"||Ta(r,g.roomId,g.userUlid)})];return()=>{v.forEach(g=>g()),Cm(o,a)}},[u,o,a,r]);const f=p.useRef(d),C=p.useRef(!1);return p.useEffect(()=>{if(!u){f.current=d;return}f.current&&!d?C.current=!0:!f.current&&d&&C.current&&(h.current&&r.invalidateQueries({queryKey:xt.voiceRoom(h.current)}),C.current=!1),f.current=d},[u,d,r]),{realtimeHealthy:u&&l&&d}}function Tp(n,e,t=!0){const i=Cr(),s=Fc(),r=e?`private-voice-room.${e}`:null,o=Vc(r),a=Bc(),d=t&&!!n&&n!==Mc&&!!e;return p.useEffect(()=>{if(!d||!s||!r||!e)return;s.subscribe(r);const l=[s.on(r,ht.ChatMessage,u=>{const h=Gh.safeParse(u);h.success&&h.data.roomId===e&&Ic(kc(i,e),h.data.createdAt)&&Ku(i,e,h.data)}),s.on(r,ht.ChatMessageRemoved,u=>{u?.roomId!==e||typeof u?.messageUlid!="string"||Wu(i,e,u.messageUlid)})];return()=>{l.forEach(u=>u()),s.unsubscribe(r)}},[d,s,r,e,i]),{realtimeHealthy:d&&a&&o}}const La="bottom-1.5 right-1.5 rounded px-1.5 py-0.5 text-[11px] font-semibold text-white bg-black/60 tabular-nums",Sp={sm:{disk:"h-7 w-7",icon:12,duration:"bottom-1 left-1 rounded bg-black/70 px-1 text-[10px] font-semibold text-white"},md:{disk:"h-11 w-11 backdrop-blur-sm",icon:20,duration:La},lg:{disk:"h-14 w-14 backdrop-blur-sm",icon:28,duration:La}};function rd({duration:n,size:e="md"}){const t=Sp[e],i=(n??0)>0;return c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:c.jsx("span",{className:`flex items-center justify-center rounded-full bg-black/60 text-white ${t.disk}`,children:c.jsx(Tm,{width:t.icon,height:t.icon,className:"ml-0.5"})})}),i&&c.jsx("span",{className:`pointer-events-none absolute ${t.duration}`,children:jc(n)})]})}const wp=16/9,Rp=320;function ad(n){return n.width>0&&n.height>0}function Aa(n){return ad(n)?n.width/n.height:wp}function Da(n){return{width:"100%",maxWidth:Jh(n,Rp,$h),aspectRatio:String(n)}}function Ep({attachments:n,isOwn:e}){const[t,i]=p.useState(!1),[s,r]=p.useState(0),[o,a]=p.useState(()=>new Set),{images:d,imagePosition:l}=p.useMemo(()=>{const v=[],g=new Map;return n.forEach((k,T)=>{k.type==="image"&&(g.set(T,v.length),v.push({url:k.url,width:k.width||void 0,height:k.height||void 0,alt:k.name||"Attachment"}))}),{images:v,imagePosition:g}},[n]),u=p.useCallback(v=>g=>{g.stopPropagation();const k=l.get(v);k!==void 0&&(r(k),i(!0))},[l]),h=p.useCallback(v=>g=>{g.stopPropagation(),a(k=>new Set(k).add(v))},[]),m=p.useCallback(v=>()=>{a(g=>{const k=new Set(g);return k.delete(v),k})},[]);if(n.length===0)return null;const f=n.length===1?n[0]:null,C=f?.type==="video"?f:null,x=f?.type==="image"&&ad(f)?f:null;if(C){const v=C.id||C.url,g=Da(Aa(C));return o.has(v)?c.jsx("div",{className:`mt-1 ${e?"self-end":""}`,style:g,children:c.jsx(Ea,{sources:Pa({videoUrl:C.url,hlsUrl:C.hlsUrl||null}),posterUri:C.thumbnailUrl||void 0,className:"rounded-lg h-full",onPlaybackFailed:m(v)})}):c.jsx("button",{type:"button",onClick:h(v),"aria-label":C.duration>0?`Play video, ${jc(C.duration)}`:"Play video",className:`mt-1 relative rounded-lg overflow-hidden bg-black ${e?"self-end":""}
1`,style:g,children:c.jsx(Fa,{attachment:C})})}const S=x?c.jsx(Ua,{attachment:x,onClick:u(0),className:`mt-1 rounded-lg overflow-hidden ${e?"self-end":""}`,style:Da(Aa(x))}):c.jsx("div",{className:`flex flex-wrap gap-1 mt-1 ${e?"justify-end":""}`,children:n.map((v,g)=>{const k=v.id||`${v.url}-${g}`;return v.type==="video"?o.has(k)?c.jsx("div",{className:"w-36 h-36 rounded-lg overflow-hidden bg-black",children:c.jsx(Ea,{sources:Pa({videoUrl:v.url,hlsUrl:v.hlsUrl||null}),posterUri:v.thumbnailUrl||void 0,className:"w-full h-full",onPlaybackFailed:m(k)})},k):c.jsx("button",{type:"button",onClick:h(k),"aria-label":v.name?`Play ${v.name}`:"Play video",className:"relative w-36 h-36 rounded-lg overflow-hidden bg-black",children:c.jsx(Fa,{attachment:v,compact:!0})},k):v.type==="image"?c.jsx(Ua,{attachment:v,onClick:u(g),className:"w-36 h-36 rounded-lg overflow-hidden"},k):c.jsx("a",{href:v.url,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-brand hover:underline",children:v.name||"Attachment"},k)})});return c.jsxs(c.Fragment,{children:[S,c.jsx(dp,{open:t,images:d,index:s,onIndexChange:r,onOpenChange:i})]})}function Ua({attachment:n,onClick:e,className:t,style:i}){return c.jsx("button",{type:"button",onClick:e,"aria-label":`View ${n.name||"attachment"}`,className:t,style:i,children:c.jsx("img",{src:n.url,alt:n.name||"Attachment",className:"w-full h-full object-cover"})})}function Fa({attachment:n,compact:e}){return c.jsxs(c.Fragment,{children:[n.thumbnailUrl&&c.jsx("img",{src:n.thumbnailUrl,alt:"",className:"absolute inset-0 w-full h-full object-cover"}),c.jsx(rd,{duration:n.duration,size:e?"md":"lg"})]})}function Pp({content:n,isOwn:e}){const t=p.useMemo(()=>xc(n??""),[n]);return t?c.jsx("div",{className:`mt-1 w-[320px] max-w-full ${e?"self-end":""}`,onClick:i=>i.stopPropagation(),children:c.jsx(up,{videoId:t.id,kind:t.kind})}):null}const Np={owner:"Owner",admin:"Admin",moderator:"Mod"};function _p({message:n,isOwn:e,showMenu:t,onOpenMenu:i,onAuthorPress:s,onToggleReaction:r}){const o=Np[n.authorRole]??null,a=n.attachments.length>0,d=p.useMemo(()=>{const g=n.content??"";return!a&&xc(g)?Gu(g).trim():g},[n.content,a]),l=lt(),u=p.useCallback(g=>l(`/${g}`),[l]),h=p.useCallback(g=>l(`/topic/${encodeURIComponent(g)}`),[l]),m=p.useCallback(g=>{g.stopPropagation(),i?.(n,g.currentTarget)},[n,i]),f=p.useCallback(()=>{s?.(n)},[n,s]),C=s?c.jsx("button",{type:"button",onClick:f,"aria-label":`View profile for ${n.authorName}`,className:"w-8 h-8 rounded-full overflow-hidden flex-shrink-0",children:c.jsx("img",{src:n.authorAvatar,alt:"",className:"w-full h-full rounded-full object-cover"})}):c.jsx("img",{src:n.authorAvatar,alt:"",className:"w-8 h-8 rounded-full object-cover flex-shrink-0"}),x=t?c.jsx("button",{type:"button",onClick:m,"aria-label":"Message actions",className:"self-center p-1 rounded-full text-text-secondary dark:text-text-secondary-dark hover:bg-border-light/40 dark:hover:bg-border-dark/40 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 transition-opacity flex-shrink-0",children:c.jsx(di,{width:16,height:16})}):null,S=c.jsxs(c.Fragment,{children:[d&&c.jsx("div",{className:`text-sm rounded-2xl px-3 py-2 min-w-0 [overflow-wrap:anywhere] ${e?"bg-brand text-white rounded-tr-sm":"bg-bg-elevated dark:bg-bg-elevated-dark text-text dark:text-text-dark rounded-tl-sm"}`,children:c.jsx(Sm,{tokenClassName:e?"text-white":"text-brand dark:text-brand-dark",linkClassName:e?"text-white":"text-info dark:text-info-dark",onMentionClick:u,onHashtagClick:h,children:d})}),!a&&c.jsx(Pp,{content:n.content,isOwn:e}),c.jsx(Ep,{attachments:n.attachments,isOwn:e})]}),v=c.jsxs("div",{className:`flex flex-col max-w-[70%] min-w-0 ${e?"items-end":"items-start"}`,children:[c.jsxs("div",{className:`flex items-baseline gap-1.5 mb-0.5 ${e?"flex-row-reverse":""}`,children:[c.jsxs("div",{className:"flex items-center gap-0.5 min-w-0",children:[s?c.jsx("button",{type:"button",onClick:f,className:"text-xs font-semibold text-text dark:text-text-dark truncate hover:underline",children:n.authorName}):c.jsx("span",{className:"text-xs font-semibold text-text dark:text-text-dark truncate",children:n.authorName}),c.jsx(Zi,{badges:n.authorBadges,size:12})]}),o&&c.jsx("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-brand/10 text-brand",children:o})]}),n.replyTo&&c.jsxs("div",{className:"min-w-0 max-w-full text-[10px] text-text-secondary dark:text-text-secondary-dark border-l-2 border-brand/40 pl-2 mb-1 truncate",children:[c.jsxs("span",{className:"font-medium",children:[n.replyTo.authorName,":"]})," ",n.replyTo.content]}
1),c.jsxs("div",{className:"flex items-end gap-1 max-w-full","data-testid":"message-bubble-menu-row",children:[c.jsx("div",{className:"min-w-0 flex flex-col gap-0",children:S}),x]}),n.reactions.length>0&&c.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1",children:n.reactions.map(g=>{const k=`inline-flex items-center gap-1 text-sm px-2 py-1 rounded-full border ${g.hasReacted?"border-brand/40 bg-brand/10":"border-border-light dark:border-border-dark"}`,T=`${g.emoji} ${g.count}${g.hasReacted?", your reaction":""}`,b=c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"text-base leading-none",children:g.emoji}),g.count>1?c.jsx("span",{className:"text-xs tabular-nums text-text-secondary dark:text-text-secondary-dark",children:g.count}):null]});return r?c.jsx("button",{type:"button",onClick:()=>r(n,g.emoji),"aria-label":T,"aria-pressed":g.hasReacted,className:`${k} hover:bg-bg-elevated dark:hover:bg-bg-elevated-dark transition-colors`,children:b},g.emoji):c.jsx("span",{className:k,"aria-label":T,children:b},g.emoji)})}),c.jsx("span",{className:"text-[10px] text-text-secondary dark:text-text-secondary-dark mt-0.5",children:Qi(n.createdAt)})]});return c.jsx("div",{className:`group flex items-end gap-2 py-1 ${e?"justify-end":"justify-start"}`,children:e?c.jsxs(c.Fragment,{children:[v,C]}):c.jsxs(c.Fragment,{children:[C,v]})})}function Ip(n){n.key==="Enter"&&!n.shiftKey&&(n.preventDefault(),n.currentTarget.form?.requestSubmit())}function od({value:n,onChange:e,onSubmit:t,sendDisabled:i,placeholder:s,maxLength:r=2e3,inputRef:o,leadingControl:a,children:d,layout:l="overlay"}){const u=l==="docked";return c.jsxs("div",{"data-composer-layout":l,className:u?"relative z-10 flex-none border-t border-nav-active bg-bg dark:border-nav-active-dark dark:bg-bg-dark":"pointer-events-none absolute inset-x-0 bottom-0 z-10",children:[!u&&c.jsxs(c.Fragment,{children:[c.jsx("div",{"aria-hidden":!0,className:"absolute inset-0 backdrop-blur-[5px] [mask-image:linear-gradient(to_bottom,transparent,black_45%)]"}),c.jsx("div",{"aria-hidden":!0,className:"absolute inset-0 bg-gradient-to-b from-transparent via-bg/70 via-[30%] to-bg to-[62%] dark:via-bg-dark/70 dark:to-bg-dark"})]}),c.jsxs("div",{className:u?"relative px-5 py-4":"pointer-events-auto relative px-5 pb-5 pt-10",children:[d,c.jsxs("form",{onSubmit:t,className:"flex items-center gap-2.5",children:[a,c.jsx("textarea",{ref:o,value:n,onChange:h=>e(h.target.value),onKeyDown:Ip,placeholder:s,rows:1,maxLength:r,className:"flex-1 h-11 resize-none rounded-xl pl-3.5 pr-2 py-3 text-[15px] leading-5 tracking-[-0.23px] bg-gradient-to-b from-bg to-bg-elevated dark:from-bg-elevated-dark dark:to-bg-elevated-dark shadow-glass text-text dark:text-text-dark placeholder:text-text-dim dark:placeholder:text-text-dim-dark focus:outline-none focus:ring-2 focus:ring-brand/30"}),c.jsx("button",{type:"submit",disabled:i,"aria-label":"Send message",className:"flex h-11 w-11 flex-none items-center justify-center rounded-full bg-brand-gradient text-white transition-opacity hover:opacity-90 disabled:opacity-20 disabled:cursor-not-allowed",children:c.jsx(wm,{width:22,height:22})})]})]})]})}function Mp({attachment:n,uploadProgress:e,onRemove:t}){const i=n.uploadedUrl==null,s=n.file.name||(n.type==="video"?"Video attachment":"Photo attachment");return c.jsxs("div",{className:"relative h-16 w-16 flex-none overflow-hidden rounded-lg bg-bg-elevated dark:bg-bg-elevated-dark",children:[n.type==="video"?c.jsxs(c.Fragment,{children:[c.jsx("video",{src:n.previewUrl,muted:!0,playsInline:!0,preload:"metadata",className:"h-full w-full object-cover","aria-label":s}),c.jsx(rd,{duration:n.duration,size:"sm"})]}):c.jsx("img",{src:n.previewUrl,alt:s,className:"h-full w-full object-cover"}),i&&c.jsx("span",{className:"absolute inset-0 flex items-center justify-center bg-black/40 text-[10px] font-semibold text-white",children:e!=null&&e>0?`${e}%`:"Uploading"}),c.jsx("button",{type:"button","aria-label":`Remove ${n.file.name||"attachment"}`,onClick:()=>t(n.id),className:"absolute right-1 top-1 flex h-5 w-5 items-center justify-center rounded-full bg-black/70 text-white",children:c.jsx(wr,{size:14})})]})}function jp({suggestions:n,onSelect:e}){return n.length===0?null:c.jsx("div",{className:"mb-2 max-h-[180px] overflow-y-auto rounded-xl bg-bg dark:bg-bg-elevated-dark shadow-glass",children:n.map(t=>c.jsxs("button",{type:"button",onClick:()=>e(t.username),className:"w-full flex items-center gap-2 px-4 py-2 text-left hover:bg-bg-elevated dark:hover:bg-bg-elevated-dark text-sm min-w-0",children:[c.jsx("img",{src:t.avatar,alt:"",className:"w-6 h-6 rounded-full object-cover flex-shrink-0"}),c.jsxs("span",{className:"font-medium text-text dark:text-text-dark truncate min-w-0",children:["@",t.username]}),c.jsx("span",{className:"text-text-secondary dark:text-text-secondary-dark text-xs truncate min-w-0",children:t.name})]},t.ulid))})}function cd(n,{currentUserId:e,isMod:t,isAdmin:i,canPost:s}){const r=[],o=n.authorUlid===e;!n.replyTo&&s&&r.push("reply"),!o&&s&&r.push("report"),(o&&s||t)&&r.push("delete");const a=i?pt("admin"):pt("moderator");return t&&!o&&n.authorRole!=="owner"&&pt(n.authorRole)<a&&r.push("remove"),t&&!o&&!(n.authorRole==="admin"&&!i)&&r.push("ban"),r}function Op(n,e){return cd(n,e).length>0}function Lp({menuMessage:n,menuContext:e,onReply:t,onReport:i,onDelete:s,onRemove:r,onBan:o,closeMenu:a}){const d={reply:{id:"reply",label:"Reply",onPress:()=>{t(n),a()}},report:{id:"report",label:"Report",onPress:()=>{i(n),a()}},delete:{id:"delete",label:"Delete",destructive:!0,onPress:()=>{s(n),a()}},remove:{id:"remove",label:"Remove from Lounge",onPress:()=>{r(n),a()}},ban:{id:"ban",label:"Ban Member",destructive:!0,onPress:()=>{o(n),a()}}};return cd(n,e).map(l=>d[l])}function Ap({selectedEmojis:n,onSelect:e}){return c.jsx("div",{className:"flex flex-nowrap gap-1.5 py-0.5",role:"group","aria-label":"Message reactions",children:Qh.map(t=>{const i=n.includes(t);return c.jsx("button",{type:"button",onClick:()=>e(t),"aria-label":i?`Remove your ${t} reaction`:`React with ${t}`,"aria-pressed":i,className:`w-9 h-9 flex-shrink-0 rounded-full text-lg leading-none flex items-center justify-center border transition-colors ${i?"border-brand/40 bg-brand/10":"border-border-light dark:border-border-dark hover:bg-bg-elevated dark:hover:bg-bg-elevated-dark"}`,children:t},t)})})}function Dp({spaceId:n,channelId:e,menuContext:t,isLoggedIn:i,canPost:s,onReply:r,onMessageHidden:o}){const a=Ju(),d=$u(),l=Qu(),u=Yu(),h=Zu(),[m,f]=p.useState(null),[C,x]=p.useState(null),[S,v]=p.useState(!1),[g,k]=p.useState(null),[T,b]=p.useState(null),[w,P]=p.useState(null),[E,_]=p.useState(null),N=p.useCallback((B,Q)=>{f(B),x(Q),v(!0)},[]),L=p.useCallback(()=>v(!1),[]),O=p.useCallback((B,Q)=>{h.mutate({spaceId:n,channelId:e,messageId:B.ulid,emoji:Q})},[n,e,h]),q=p.useCallback(B=>{m&&(O(m,B),L())},[m,O,L]),J=p.useMemo(()=>m?Lp({menuMessage:m,menuContext:t,onReply:r,onReport:b,onDelete:k,onRemove:_,onBan:P,closeMenu:L}):[],[m,t,r,L]),D=p.useCallback(B=>i&&(s||Op(B,t)),[i,s,t]),K=p.useCallback(async B=>{T&&(await d.mutateAsync({spaceId:n,channelId:e,messageId:T.ulid,violationType:B}),await o(T.ulid))},[T,d,n,e,o]),se=p.useCallback(B=>{B||k(null)},[]),re=p.useCallback(()=>
1{if(!g)return;const B=g.ulid;a.mutate({spaceId:n,channelId:e,messageId:B},{onError:Q=>{$e("delete-lounge-message",{spaceId:n,channelId:e,messageId:B},Q),z.error("Couldn't delete message. Try again.")}}),k(null)},[g,a,n,e]),F=p.useCallback(B=>{B||P(null)},[]),ie=p.useCallback(()=>{if(!w)return;const{authorUlid:B,authorName:Q}=w;l.mutate({spaceId:n,userId:B},{onError:fe=>{$e("ban-lounge-member",{spaceId:n,userId:B},fe),z.error(`Couldn't ban @${Q}. Try again.`)}}),P(null)},[w,l,n]),$=p.useCallback(B=>{B||_(null)},[]),ne=p.useCallback(()=>{if(!E)return;const{authorUlid:B,authorName:Q}=E;u.mutate({spaceId:n,userId:B},{onError:fe=>{$e("remove-lounge-member",{spaceId:n,userId:B},fe),z.error(`Couldn't remove @${Q}. They may have already left.`)}}),_(null)},[E,u,n]),he=p.useCallback(()=>b(null),[]),ke=c.jsxs(c.Fragment,{children:[c.jsx(Rr,{open:S,onOpenChange:v,options:J,triggerEl:C,header:s&&m?c.jsx(Ap,{selectedEmojis:Yh(m.reactions),onSelect:q}):void 0}),c.jsx(Ae,{open:!!g,onOpenChange:se,title:"Delete message?",description:"This cannot be undone.",confirmLabel:"Delete",onConfirm:re,isPending:a.isPending}),c.jsx(Ae,{open:!!w,onOpenChange:F,title:"Ban member?",description:w?`@${w.authorName} will be removed and blocked from rejoining this lounge.`:"",confirmLabel:"Ban",onConfirm:ie,isPending:l.isPending}),c.jsx(Ae,{open:!!E,onOpenChange:$,title:"Remove member?",description:E?`@${E.authorName} will be removed from the lounge. They can rejoin later.`:"",confirmLabel:"Remove",onConfirm:ne,isPending:u.isPending}),T&&c.jsx(Xi,{open:!!T,onClose:he,targetId:T.ulid,submitOverride:K,subjectLabel:"message",onReportSubmitted:he})]});return{showMenuForMessage:D,handleOpenMenu:N,overlays:ke,onToggleReaction:s?O:void 0}}async function Up(n,e=5e3){return Oc(n)!=="video"?{}:new Promise(t=>{const i=URL.createObjectURL(n),s=document.createElement("video");s.preload="metadata",s.muted=!0;let r=!1;const o=d=>{r||(r=!0,clearTimeout(a),URL.revokeObjectURL(i),s.removeAttribute("src"),t(d))};s.onloadedmetadata=()=>{const d=s.duration,l=s.videoWidth,u=s.videoHeight;o({...Number.isFinite(d)&&d>0?{duration:Math.ceil(d)}:{},...l>0?{width:l}:{},...u>0?{height:u}:{}})},s.onerror=()=>o({});const a=setTimeout(()=>o({}),e);s.src=i})}const Ss=4;function Fp(){const{upload:n,cancel:e,progress:t,isUploading:i}=Gs(),[s,r]=p.useState([]),[o,a]=p.useState(null),d=p.useRef(null),l=p.useRef(new Set),u=p.useRef([]);u.current=s;const h=p.useRef(0),m=p.useRef(!1),f=p.useRef(null),C=p.useRef(new Set),x=E=>C.current.has(E),S=p.useCallback(E=>{f.current=E,a(E)},[]),v=p.useCallback(()=>{d.current&&(d.current.value="")},[]),g=p.useCallback(E=>{URL.revokeObjectURL(E),l.current.delete(E)},[]);p.useEffect(()=>()=>{e();for(const E of l.current)URL.revokeObjectURL(E);l.current.clear()},[e]);const k=p.useCallback(E=>{C.current.add(E),f.current===E&&(e(),S(null));const _=u.current.find(N=>N.id===E);_&&(h.current=Math.max(0,h.current-1),g(_.previewUrl),u.current=u.current.filter(N=>N.id!==E),r(N=>{const L=N.filter(O=>O.id!==E);return u.current=L,L}))},[g,e,S]),T=p.useCallback(()=>{for(const E of u.current)g(E.previewUrl);u.current=[],r([]),C.current.clear(),h.current=0,S(null)},[g,S]),b=p.useCallback(async E=>{if(!E?.length)return;if(m.current||i){z.error("Please wait for the current upload to finish."),v();return}const _=Ss-h.current;if(_<=0){z.error(`You can attach up to ${Ss} items per message.`),v();return}const N=Array.from(E).flatMap(q=>{const J=Oc(q);return J?[{file:q,type:J}]:[]});if(N.length===0){z.error("Only photos and videos can be attached."),v();return}N.length<E.length&&z.error("Some files were skipped — only photos and videos are supported.");const L=N.slice(0,_);N.length>_&&z.error(`Only ${Ss} items can be attached per message.`);const O=[];for(const q of L){const J=Zh(q.file,q.type);if(J){z.error(J);continue}O.push(q)}if(O.length===0){v();return}m.current=!0;try{const q=O.map(({file:D,type:K},se)=>{const re=URL.createObjectURL(D);return l.current.add(re),{id:`${Date.now()}-${se}-${D.name}`,file:D,previewUrl:re,uploadedUrl:null,type:K}});u.current=[...u.current,...q],h.current+=q.length,r(D=>{const K=[...D,...q];return u.current=K,K});const J=(D,K)=>{r(se=>{const re=se.map(F=>F.id===D?{...F,...K}:F);return u.current=re,re})};await Promise.all(q.map(async D=>{if(x(D.id))return;if(D.type==="image"){try{const re=await Rm(D.file);if(x(D.id))return;re.width>0&&re.height>0&&J(D.id,{width:re.width,height:re.height})}catch{}return}if(D.type!=="video")return;const K=await Up(D.file);if(x(D.id))return;const se=Xh(K.duration);if(se){z.error(se),k(D.id);return}(K.width||K.height||K.duration)&&J(D.id,K)}));for(const D of q)if(!x(D.id)){S(D.id);try{const K=await n(D.file);if(x(D.id))continue;J(D.id,{uploadedUrl:K})}catch(K){if(x(D.id)||K instanceof Em)continue;k(D.id),z.error(K instanceof Error?K.message:"Could not upload media.")}finally{f.current===D.id&&S(null)}}}finally{m.current=!1,v()}},[n,i,k,v,S]),w=p.useCallback(()=>s.filter(E=>!!E.uploadedUrl).map(E=>({type:E.type,url:E.uploadedUrl,name:E.file.name,...E.width?{width:E.width}:{},...E.height?{height:E.height}:{},...E.duration?{duration:E.duration}:{}})),[s]),P=s.some(E=>!E.uploadedUrl);return{pendingAttachments:s,fileInputRef:d,handleMediaSelection:b,removeAttachment:k,clearAttachments:T,toMessageAttachments:w,hasUploadPending:P,uploadingAttachmentId:o,uploadProgress:t,isUploading:i}}const Va=new Map;function Vp(n,e){const t=p.useRef(null),i=p.useRef(0),s=p.useRef(!1);return p.useEffect(()=>{i.current=0,s.current=!1,t.current&&(t.current.scrollTop=0)},[n]),p.useEffect(()=>{const r=t.current;if(!r)return;const o=()=>{s.current&&Va.set(n,r.scrollTop)};return r.addEventListener("scroll",o,{passive:!0}),()=>r.removeEventListener("scroll",o)},[n]),p.useEffect(()=>{const r=t.current;if(!r||e===0)return;const o=i.current===0,d=r.scrollHeight-r.scrollTop-r.clientHeight<200;if(o){const l=Va.get(n);requestAnimationFrame(()=>{l!==void 0?r.scrollTop=l:r.scrollTo({top:r.scrollHeight,behavior:"auto"}),s.current=!0})}else d&&requestAnimationFrame(()=>{r.scrollTo({top:r.scrollHeight,behavior:"smooth"})});i.current=e},[e,n]),{scrollContainerRef:t}}function Bp({spaceId:n,input:e,setInput:t,inputRef:i,currentUserId:s}){const r=Xu(e),[o,a]=p.useState(null);p.useEffect(()=>{const h=window.setTimeout(()=>a(r),300);return()=>window.clearTimeout(h)},[r]);const d=Pn(n,o??void 0,{enabled:o!==null}),l=p.useMemo(()=>o===null?[]:(d.data?.pages.flatMap(m=>m.data)??[]).filter(m=>m.ulid!==s).slice(0,5),[o,d.data,s]),u=p.useCallback(h=>{t(m=>eh(m,h)??m),i.current?.focus()},[t,i]);return{mentionSuggestions:l,insertMention:u}}function ws(n,e){let t=n;for(const i of e)t=qc(t,i);return t}function qp(n){const[e,t]=p.useState(new Set),i=p.useRef(e),s=p.useRef(!1),r=p.useRef(!1);p.useEffect(()=>{let d=!1;return Pm().then(l=>{if(d)return;const u=ws(l,i.current);i.current=u,r.current&&(Na(u),r.current=!1),s.current=!0,t(h=>{const m=ws(i.current,h);return i.current=m,m})}),()=>{d=!0}},[]);const o=p.useMemo(()=>n.filter(d=>!e.has(d.ulid)),[n,e]),a=p.useCallback(async d=>{const l=i.current,u=qc(l,d);u!==l&&(s.current||(r.current=!0),i.current=u,t(h=>{const m=ws(h,i.current);return i.current=m,m}),await Na(i.current))},[]);return{visibleMessages:o,hideMessage:a}}const Hp=5e3;function zp({spaceId:n,channelId:e,isMod:t,isAdmin:i,shouldPoll:s=!1,canPost:r}){const o=lt(),a=De(ae=>ae.user?.id??null),d=De(ae=>ae.isLoggedIn),l=th(n,e,{refetchInterval:s?Hp:!1}),u=p.useMemo(()=>l.data?.pages.flatMap(ae=>ae.data)??[],[l.data]),{visibleMessages:h,hideMessage:m}=qp(u),f=p.useMemo(()=>[...h].reverse(),[h]),{scrollContainerRef:C}=Vp(e,f.length),x=nh(),S=ih(),v=sh(n),{pendingAttachments:g,fileInputRef:k,handleMediaSelection:T,removeAttachment:b,clearAttachments:w,toMessageAttachments:P,hasUploadPending:E,uploadingAttachmentId:_,uploadProgress:N}=Fp(),L=p.useRef(null);p.useEffect(()=>{!n||!e||!d||!r||L.current!==e&&(L.current=e,S.mutate({spaceId:n,channelId:e}),v(e))},[n,e,d,r]);const[O,q]=p.useState(null),[J,D]=p.useState(""),K=p.useRef(null);p.useEffect(()=>{O&&requestAnimationFrame(()=>K.current?.focus())},[O]);const se=p.useMemo(()=>({currentUserId:a,isMod:!!t,isAdmin:!!i,canPost:r}),[a,t,i,r]),{showMenuForMessage:re,handleOpenMenu:F,overlays:ie,onToggleReaction:$}=Dp({spaceId:n,channelId:e,menuContext:se,isLoggedIn:d,canPost:r,onReply:q,onMessageHidden:m}),ne=p.useMemo(()=>[...new Set(f.map(ae=>ae.authorUlid))].sort(),[f]),he=rh(ne),ke=p.useMemo(()=>{const ae=new Map;for(const Z of he.data??[])ae.set(Z.id,Z.username);return ae},[he.data]),B=p.useCallback(ae=>{const Z=ke.get(ae.authorUlid);Z&&o(`/${Z}`)},[o,ke]),{mentionSuggestions:Q,insertMention:fe}
1=Bp({spaceId:n,input:J,setInput:D,inputRef:K,currentUserId:a}),Ue=p.useCallback(ae=>{ae.preventDefault();const Z=J.trim(),Pt=P();if(!Z&&Pt.length===0||E||!n||!e)return;const kt=O;D(""),q(null),x.mutate({spaceId:n,channelId:e,content:Z,...kt&&{replyToId:kt.ulid},...Pt.length>0&&{attachments:Pt}},{onSuccess:()=>{w()},onError:tt=>{D(Z),kt&&q(kt),z.error(Je(tt,"Couldn't send message. Try again."))}})},[J,n,e,x,O,P,E,w]);return l.isLoading&&f.length===0?c.jsx("div",{className:"flex-1 flex items-center justify-center",children:c.jsx(je,{size:"md",label:"Loading messages"})}):c.jsxs("div",{className:"relative flex flex-col flex-1 min-h-0 min-w-0",children:[c.jsxs("div",{ref:C,className:"flex-1 overflow-y-auto px-4 pt-3 pb-36 space-y-1",children:[l.hasNextPage&&c.jsx("div",{className:"flex justify-center py-2",children:c.jsx("button",{type:"button",onClick:()=>l.fetchNextPage(),disabled:l.isFetchingNextPage,className:"text-xs text-brand hover:underline disabled:opacity-50",children:l.isFetchingNextPage?"Loading...":"Load older messages"})}),f.length===0&&!l.isLoading&&c.jsx("div",{className:"text-center text-sm text-text-secondary dark:text-text-secondary-dark py-8",children:"No messages yet. Start the conversation!"}),f.map(ae=>c.jsx(_p,{message:ae,isOwn:ae.authorUlid===a,showMenu:re(ae),onOpenMenu:F,onAuthorPress:he.isSuccess?B:void 0,onToggleReaction:$},ae.ulid))]}),d&&r&&c.jsxs(od,{value:J,onChange:D,onSubmit:Ue,sendDisabled:!J.trim()&&g.length===0||E||x.isPending,placeholder:"Message the room",inputRef:K,leadingControl:c.jsxs(c.Fragment,{children:[c.jsx("input",{ref:k,type:"file",accept:"image/*,video/*",multiple:!0,className:"sr-only","aria-label":"Choose photos and videos",onChange:ae=>void T(ae.target.files)}),c.jsx("button",{type:"button","aria-label":"Add photos and videos",onClick:()=>k.current?.click(),className:"flex h-11 w-11 flex-none items-center justify-center rounded-full text-text-secondary transition-colors hover:bg-bg-elevated hover:text-text dark:text-text-secondary-dark dark:hover:bg-bg-elevated-dark dark:hover:text-text-dark",children:c.jsx(zc,{size:24})})]}),children:[g.length>0&&c.jsx("div",{className:"mb-2 flex gap-2 overflow-x-auto rounded-xl bg-bg/90 p-2 shadow-glass dark:bg-bg-elevated-dark/90",children:g.map(ae=>c.jsx(Mp,{attachment:ae,uploadProgress:_===ae.id?N:null,onRemove:b},ae.id))}),O&&c.jsxs("div",{className:"mb-2 flex items-center gap-2 rounded-xl bg-bg dark:bg-bg-elevated-dark shadow-glass px-3.5 py-2 text-xs",children:[c.jsxs("span",{className:"text-brand font-medium",children:["Replying to ",O.authorName]}),c.jsx("span",{className:"text-text-secondary dark:text-text-secondary-dark truncate flex-1",children:O.content?.slice(0,60)}),c.jsx("button",{type:"button",onClick:()=>q(null),className:"text-text-secondary dark:text-text-secondary-dark hover:text-text dark:hover:text-text-dark p-0.5","aria-label":"Cancel reply",children:c.jsx(Hc,{width:12,height:12})})]}),c.jsx(jp,{suggestions:Q,onSelect:fe})]}),ie]})}function ss({loungeUlid:n,displayName:e,channelId:t,channelName:i,channelType:s,isOwner:r,visibility:o,membershipStatus:a,isTrendingExcluded:d,triggerClassName:l="text-text-secondary dark:text-text-secondary-dark hover:text-text dark:hover:text-text-dark p-1",extraOptions:u,triggerLabel:h="Lounge options"}){const[m,f]=p.useState(!1),[C,x]=p.useState(!1),[S,v]=p.useState(!1),[g,k]=p.useState(!1),[T,b]=p.useState(null),w=ah(),P=yc(),E=oh(),_=ch(),N=De(Z=>Z.user?.id??null),L=De(Z=>Z.user?.badges),O=!!L?.includes("employee")&&!!L?.includes("moderator"),q=Er(Z=>Z.open),J=p.useCallback(Z=>w.mutateAsync({loungeUlid:n,violationType:Z}),[w,n]),D=p.useCallback(()=>{N&&(f(!1),P.mutate({spaceId:n,userId:N},{onSuccess:()=>z.success("Request canceled"),onError:Z=>z.error(Je(Z,"Could not cancel your request. Try again."))}))},[P,n,N]),K=p.useCallback(()=>{N&&(f(!1),E.mutate({spaceId:n,userId:N},{onSuccess:()=>z.success("Invitation declined"),onError:Z=>z.error(Je(Z,"Could not decline the invitation. Try again."))}))},[E,n,N]),se=p.useCallback(()=>{f(!1),q({type:"space",spaceId:n,displayName:e??void 0,channelId:t,channelName:i,...s==="voice"?{channelType:"voice"}:{}})},[n,e,t,i,s,q]),re=p.useCallback(()=>{f(!1),x(!0)},[]),F=p.useCallback(Z=>{b(Z.currentTarget),f(!0)},[]),ie=p.useCallback(()=>{f(!1),v(!0)},[]),$=p.useCallback(Z=>{Z||v(!1)},[]),ne=p.useCallback(()=>{v(!1),k(!0)},[]),he=p.useCallback(Z=>{!Z&&!_.isPending&&k(!1)},[_.isPending]),ke=d?{label:"Restore to Trending",confirmLabel:"Restore",description:"Restore this lounge to Discover/recommendation surfaces?",successToast:"Restored to Trending"}:{label:"Remove from Trending",confirmLabel:"Remove",description:"Remove this lounge from Discover/recommendation surfaces? It stays searchable.",successToast:"Removed from Trending"},B=p.useCallback(()=>{_.mutate({loungeUlid:n,excluded:!d},{onSuccess:()=>{z.success(ke.successToast),k(!1)},onError:Z=>z.error(Je(Z,"Could not update Trending status. Try again."))})},[_,n,d,ke.successToast]),Q=[...vn(o)!=="hidden"?[{id:"share",label:"Share lounge",onPress:se}]:[],...a==="requested"&&N?[{id:"cancel-request",label:"Cancel request",onPress:D}]:[],...a==="invited"&&N?[{id:"decline-invitation",label:"Decline invitation",destructive:!0,onPress:K}]:[],...r?[]:[{id:"report",label:"Report lounge",onPress:re}],...O?[{id:"admin",label:"Admin",onPress:ie}]:[]],Ue=[...u?.length?[...u,...Q.length?[{type:"separator",id:"room"}]:[]]:[],...Q],ae=[{id:"admin-trending",label:ke.label,destructive:!d,onPress:ne}];return Ue.length===0?null:c.jsxs(c.Fragment,{children:[c.jsx("button",{type:"button",onClick:F,className:l,"aria-label":h,children:c.jsx(di,{width:20,height:20})}),c.jsx(Rr,{open:m,onOpenChange:f,options:Ue,triggerEl:T}),c.jsx(Xi,{open:C,onClose:()=>x(!1),targetId:n,targetType:"post",subjectLabel:"lounge",submitOverride:J}),c.jsx(Kc,{open:S,onOpenChange:$,title:"Admin",options:ae}),c.jsx(Ae,{open:g,onOpenChange:he,title:ke.label,description:ke.description,confirmLabel:ke.confirmLabel,de
1structive:!d,onConfirm:B,isPending:_.isPending})]})}function rs(){const n=lt();return c.jsx("div",{className:"flex items-center justify-center min-h-[60vh] p-8",children:c.jsxs("div",{className:"text-center",children:[c.jsx("h1",{className:"text-xl font-bold text-text dark:text-text-dark mb-2",children:"Lounge not found"}),c.jsx("p",{className:"text-text-secondary dark:text-text-secondary-dark mb-4",children:"This lounge may have been deleted or you don't have access."}),c.jsx("button",{type:"button",onClick:()=>n("/lounges"),className:"text-sm text-brand hover:underline",children:"Back to Lounges"})]})})}const Kp=5;function jr({member:n,ownerId:e}){return e&&n.ulid===e?c.jsx("span",{className:"rounded bg-brand-pale dark:bg-brand-pale-dark px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-[0.3px] text-brand",children:"Owner"}):pt(n.role)>=2?c.jsx("span",{className:"rounded bg-info/15 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-[0.3px] text-info",children:n.role==="admin"?"Admin":"Mod"}):null}function Wp({space:n,onOpenMembers:e,onSameTabProfile:t}){const i=Pn(n.ulid),s=n.ownerId??null,r=p.useMemo(()=>[...i.data?.pages[0]?.data??[]].sort((d,l)=>{const u=s&&d.ulid===s?1:0,h=s&&l.ulid===s?1:0;return u!==h?h-u:pt(l.role)-pt(d.role)}).slice(0,Kp),[i.data,s]);function o(a,d){t&&an(a,()=>t(d))}return i.isLoading||i.isError||r.length===0?null:c.jsxs("section",{className:"rounded-xl border border-border-light dark:border-border-dark bg-bg-elevated dark:bg-bg-elevated-dark",children:[e?c.jsxs("button",{type:"button",onClick:e,className:"flex w-full items-center justify-between px-4 pt-4 text-left",children:[c.jsx("h2",{className:"text-base font-bold text-text dark:text-text-dark",children:"Members"}),c.jsx(Sn,{size:16,className:"text-text-secondary dark:text-text-secondary-dark","aria-hidden":"true"})]}):c.jsxs(Pe,{to:`/lounges/${n.ulid}/members`,className:"flex items-center justify-between px-4 pt-4",children:[c.jsx("h2",{className:"text-base font-bold text-text dark:text-text-dark",children:"Members"}),c.jsx(Sn,{size:16,className:"text-text-secondary dark:text-text-secondary-dark","aria-hidden":"true"})]}),c.jsx("ul",{className:"px-4 pb-2 pt-1",children:r.map(a=>c.jsx("li",{children:c.jsxs(Pe,{to:Ft(a.username),...rn(!!t),onClick:d=>o(d,a.username),className:"flex items-center gap-2.5 rounded-md py-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand",children:[a.avatar?c.jsx("img",{src:a.avatar,alt:"",className:"h-9 w-9 flex-none rounded-full object-cover",loading:"lazy"}):c.jsx("span",{className:"flex h-9 w-9 flex-none items-center justify-center rounded-full bg-bg dark:bg-bg-dark font-semibold text-text-secondary dark:text-text-secondary-dark",children:(a.name||a.username)?.[0]?.toUpperCase()??"?"}),c.jsxs("span",{className:"min-w-0 flex-1",children:[c.jsxs("span",{className:"flex items-center gap-1.5",children:[c.jsx(Ye,{className:"truncate text-sm font-semibold text-text dark:text-text-dark",children:a.name||a.username}),c.jsx(jr,{member:a,ownerId:s})]}),c.jsxs(Ye,{as:"span",className:"block truncate text-xs text-text-secondary dark:text-text-secondary-dark",children:["@",a.username]})]})]})},a.ulid))})]})}function Gp(n){return n.split("-").map(e=>["ui","ux","qa"].includes(e.toLowerCase())?e.toUpperCase():e&&e[0].toUpperCase()+e.slice(1)).join(" ")}function Or({space:n,open:e,onOpenChange:t,onSameTabProfile:i}){const s=De(S=>S.user),r=n.displayName??n.name,o=Pr(n.iconUrl,n.ulid),a=Cc(n.ulid),d=Pn(n.ulid,void 0,{enabled:e}),l=dh(s?.username??"",e),u=(n.category??"").split(",").map(S=>S.trim()).filter(Boolean),h=a.data?.data??[],m=n.ownerId??null,f=p.useMemo(()=>[...d.data?.pages.flatMap(v=>v.data)??[]].sort((v,g)=>{const k=m&&v.ulid===m?1:0,T=m&&g.ulid===m?1:0;return k!==T?T-k:pt(g.role)-pt(v.role)}),[d.data,m]),C=p.useMemo(()=>{const S=new Set;for(const v of l.data??[])S.add(v.id),S.add(v.username);return S},[l.data]);function x(S,v){if(i){an(S,()=>i(v));return}Mm(S)||t(!1)}return c.jsx(qt,{open:e,onOpenChange:t,children:c.jsxs(Ht,{children:[c.jsx(zt,{className:"fixed inset-0 z-50 bg-scrim data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0"}),c.jsxs(Kt,{className:`
2            fixed z-50 bg-bg dark:bg-bg-dark text-text dark:text-text-dark
3            top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2
4            flex max-h-[85vh] w-[calc(100vw-32px)] max-w-md flex-col overflow-hidden rounded-2xl font-inter
5            border border-border-light dark:border-border-dark shadow-xl
6            data-[state=open]:animate-in data-[state=closed]:animate-out
7            data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0
8          `,"aria-describedby":void 0,children:[c.jsx("div",{className:"flex-none px-4 pt-4",children:o?c.jsx("img",{src:o,alt:"","data-testid":"lounge-logo",className:"h-[88px] w-[88px] rounded-xl object-cover"}):c.jsx("span",{className:"flex h-[88px] w-[88px] items-center justify-center rounded-xl bg-bg-elevated dark:bg-bg-elevated-dark text-2xl font-bold text-text-secondary dark:text-text-secondary-dark",children:r?.[0]?.toUpperCase()??"?"})}),c.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto px-4 pb-5",children:[c.jsx(Wt,{className:"mb-2 mt-4 text-lg font-extrabold",children:"About"}),c.jsx("p",{className:"whitespace-pre-wrap text-[15px] leading-6 text-text-secondary dark:text-text-secondary-dark",children:n.description||"This lounge has no description yet."}),u.length>0&&c.jsxs("section",{"aria-labelledby":"about-categories",children:[c.jsx("h2",{id:"about-categories",className:"mb-2.5 mt-6 text-lg font-extrabold",children:"Categories"}),c.jsx("div",{className:"flex flex-wrap gap-2",children:u.map(S=>c.jsx("span",{className:"rounded-full border border-border-light dark:border-border-dark px-3.5 py-2 text-sm font-medium text-text-secondary dark:text-text-secondary-dark",children:Gp(S)},S))})]}),h.length>0&&c.jsxs("section",{"aria-labelledby":"about-rules",children:[c.jsx("h2",{id:"about-rules",className:"mb-2.5 mt-6 text-lg font-extrabold",children:"Rules & Guidelines"}),c.jsx("ul",{children:h.map(S=>c.jsxs("li",{className:"mb-3 flex items-center gap-2.5",children:[c.jsx(es,{size:20,className:"flex-none text-brand","aria-hidden":"true"}),c.jsx("span",{className:"text-[15px] text-text-secondary dark:text-text-secondary-dark",children:S.title})]},S.id))}),c.jsx("p",{className:"mt-4 text-[13px] leading-[18px] text-text-secondary dark:text-text-secondary-dark",children:"Removal is lounge-scoped — the owner moderates here, never your Parler account."})]}),c.jsxs("section",{"aria-labelledby":"about-members",children:[c.jsxs("h2",{id:"about-members",className:"mb-1 mt-6 text-lg font-extrabold",children:["Members · ",Li(n.memberCount)]}),d.isLoading?c.jsx("div",{className:"flex justify-center py-10",children:c.jsx(je,{size:"lg",label:"Loading members"})}):d.isError?c.jsxs("div",{className:"py-8 text-center",children:[c.jsx("p",{className:"text-sm text-text-secondary dark:text-text-secondary-dark",children:"Unable to load members."}),c.jsx("button",{type:"button",onClick:()=>d.refetch(),className:"mt-3 rounded-full border border-border-light dark:border-border-dark px-5 py-2 text-sm font-semibold",children:"Retry"})]}):f.length===0?c.jsx("p",{className:"py-8 text-center text-sm text-text-secondary dark:text-text-secondary-dark",children:"No members yet."}):c.jsx("ul",{children:f.map(S=>c.jsxs("li",{className:"flex items-center gap-3 py-2",children:[c.jsxs(Pe,{to:Ft(S.username),...rn(!!i),onClick:v=>x(v,S.username),className:"flex min-w-0 flex-1 items-center gap-3 rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand",children:[S.avatar?c.jsx("img",{src:S.avatar,alt:"",loading:"lazy",className:"h-11 w-11 flex-none rounded-full object-cover"}):c.jsx("span",{className:"flex h-11 w-11 flex-none items-center justify-center rounded-full bg-bg-elevated dark:bg-bg-elevated-dark",children:c.jsx(Nm,{size:19,className:"text-text-secondary dark:text-text-secondary-dark","aria-hidden":"true"})}),c.jsxs("span",{className:"min-w-0 flex-1",children:[c.jsxs("span",{className:"flex items-center gap-1.5",children:[c.jsx(Ye,{className:"truncate text-[15px] font-bold",children:S.name||S.username}),c.jsx(jr,{member:S,ownerId:m})]}),c.jsxs(Ye,{as:"span",className:"block truncate text-[13px] text-text-secondary dark:text-text-secondary-dark",children:["@",S.username]})]})]}),S.ulid!==s?.id&&c.jsx(_m,{username:S.username,initialFollowing:C.has(S.ulid)||C.has(S.username),className:Im})]},S.ulid))}),d.hasNextPage&&c.jsx("button",{type:"button",onClick:()=>d.fetchNextPage(),disabled:d.isFetchingNextPage,className:"mt-3 w-full rounded-xl border border-border-light dark:border-border-dark py-2 text-sm font-semibold disabled:opacity-50",children:d.isFetchingNextPage?"Loading…":"Load more"})]})]})]})]})})}
8function Lr({space:n,open:e,onOpenChange:t,onSameTabProfile:i}){const s=De(k=>k.user),r=lt(),o=!!n.isOwner||n.myRole==="admin"||n.myRole==="moderator",[a,d]=p.useState(""),[l,u]=p.useState(null),h=Tc(a.trim(),400),m=Lc(a),f=Pn(n.ulid,h||void 0,{enabled:e}),C=n.ownerId??null,x=p.useMemo(()=>em(n,s?.id??null),[n,s?.id]),S=p.useCallback(k=>tm(x,k),[x]),v=p.useMemo(()=>[...f.data?.pages.flatMap(T=>T.data)??[]].sort((T,b)=>{const w=C&&T.ulid===C?1:0,P=C&&b.ulid===C?1:0;return w!==P?P-w:pt(b.role)-pt(T.role)}),[f.data,C]);function g(k,T){i&&an(k,()=>i(T))}return c.jsxs(c.Fragment,{children:[c.jsx(qt,{open:e,onOpenChange:t,children:c.jsxs(Ht,{children:[c.jsx(zt,{className:"fixed inset-0 z-50 bg-scrim data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0"}),c.jsxs(Kt,{className:`
9              fixed z-50 bg-bg dark:bg-bg-dark text-text dark:text-text-dark
10              top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2
11              flex max-h-[85vh] w-[90vw] max-w-md flex-col rounded-2xl font-inter
12              border border-border-light dark:border-border-dark shadow-xl
13              data-[state=open]:animate-in data-[state=closed]:animate-out
14              data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0
15            `,"aria-describedby":void 0,children:[c.jsx(Wt,{className:"flex-none pt-5 text-center text-lg font-bold",children:"Members"}),n.isBanned&&c.jsx("p",{className:"flex-none px-4 pt-3 text-center text-sm text-text-secondary dark:text-text-secondary-dark","data-testid":"lounge-members-banned-notice",children:Tr}),c.jsxs("div",{className:"flex-none px-4 pt-3",children:[c.jsxs("label",{className:"flex h-11 items-center gap-2 rounded-full border border-border-light dark:border-border-dark px-3",children:[c.jsx(ts,{size:18,className:"flex-none text-text-secondary dark:text-text-secondary-dark","aria-hidden":"true"}),c.jsx("input",{type:"search",value:a,onChange:k=>d(k.target.value),placeholder:"Search","aria-label":"Search members",className:"min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-text-placeholder dark:placeholder:text-text-placeholder-dark"})]}),m&&c.jsx("p",{className:"mt-1.5 text-xs text-text-secondary dark:text-text-secondary-dark","data-testid":"lounge-members-search-byte-cap-hint",children:"Search limited to 200 bytes"})]}),c.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto px-4 pb-4",children:[f.isLoading?c.jsx("div",{className:"flex justify-center py-10",children:c.jsx(je,{size:"lg",label:"Loading members"})}):f.isError?c.jsx("p",{className:"py-10 text-center text-sm text-text-secondary dark:text-text-secondary-dark",children:"Couldn't load members. Try refreshing."}):v.length===0?c.jsx("p",{className:"py-10 text-center text-sm text-text-secondary dark:text-text-secondary-dark",children:h?"No members match your search.":"No members found."}):c.jsx("ul",{className:"pt-2",children:v.map(k=>c.jsxs("li",{className:"flex items-center gap-3 py-2.5",children:[c.jsxs(hp,{to:k.username?Ft(k.username):null,className:"flex min-w-0 flex-1 items-center gap-3 rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand",ariaLabel:`@${k.username} profile`,onClick:T=>g(T,k.username),stay:!!i,children:[k.avatar?c.jsx("img",{src:k.avatar,alt:"",className:"h-11 w-11 flex-none rounded-full object-cover",loading:"lazy"}):c.jsx("span",{className:"flex h-11 w-11 flex-none items-center justify-center rounded-full bg-bg-elevated dark:bg-bg-elevated-dark font-semibold text-text-secondary dark:text-text-secondary-dark",children:(k.name||k.username)?.[0]?.toUpperCase()??"?"}),c.jsxs("span",{className:"min-w-0 flex-1",children:[c.jsxs("span",{className:"flex items-center gap-1.5",children:[c.jsx(Ye,{className:"truncate text-[15px] font-bold text-text dark:text-text-dark",children:k.name||k.username}),c.jsx(jr,{member:k,ownerId:C})]}),c.jsxs(Ye,{as:"span",className:"block truncate text-[13px] text-text-secondary dark:text-text-secondary-dark",children:["@",k.username]})]})]}),k.ulid!==s?.id&&!S(k)&&c.jsx("button",{type:"button",onClick:()=>u(k.ulid),"aria-label":`Report ${k.username}`,className:"flex-none rounded-md p-1.5 text-text-secondary dark:text-text-secondary-dark transition-colors hover:bg-bg-elevated dark:hover:bg-bg-elevated-dark hover:text-text dark:hover:text-text-dark",children:c.jsx(Wc,{size:18,"aria-hidden":"true"})})]},k.ulid))}),f.hasNextPage&&c.jsx("button",{type:"button",onClick:()=>f.fetchNextPage(),disabled:f.isFetchingNextPage,className:"mt-3 block w-full rounded-xl border border-border-light dark:border-border-dark py-2 text-center text-sm font-semibold text-text dark:text-text-dark transition-colors hover:bg-bg-elevated dark:hover:bg-bg-elevated-dark disabled:opacity-50",children:f.isFetchingNextPage?"Loading…":"Load more"})]}),o&&c.jsx("div",{className:"flex-none border-t border-border-light/60 dark:border-border-dark/60 px-4 py-3",children:c.jsx(Nr,{asChild:!0,children:c.jsx("button",{type:"button",onClick:()=>r(`/lounges/${n.ulid}/members`),className:"block w-full rounded-xl bg-bg-elevated dark:bg-bg-elevated-dark py-2 text-center text-sm font-semibold text-text dark:text-text-dark transition-colors hover:bg-bg-elevated/80 dark:hover:bg-bg-elevated-dark/80",children:"Manage members"})})})]})]})}),l&&c.jsx(Xi,{open:!0,onClose:()=>u(null),targetId:l,targetType:"user"})]})}function dd({item:n}){const e=n.images??[],t=n.videos??[];return e.length===0&&t.length===0?null:c.jsxs("div",{className:"mt-2 flex flex-col gap-2","data-testid":"lounge-report-media",children:[e.length>0&&c.jsx("div",{className:"flex flex-wrap gap-2",children:e.slice(0,4).map((i,s)=>c.jsx(_a,{src:i.url,alt:`Reported post image ${s+1}`,width:i.widthPx,height:i.heightPx,containerClassName:"h-40 w-40 rounded-lg",imageClassName:"w-full h-full object-cover"},`${n.ulid}-img-${s}`))}),t.map((i,s)=>i.url?c.jsx("video",{src:i.url,poster:i.thumbnailUrl,controls:!0,playsInl
15ine:!0,preload:"none",className:"max-h-64 w-full rounded-lg bg-black object-contain"},`${n.ulid}-vid-${s}`):i.thumbnailUrl?c.jsxs("div",{className:"relative overflow-hidden rounded-lg",children:[c.jsx(_a,{src:i.thumbnailUrl,alt:`Reported video thumbnail ${s+1}`,width:i.widthPx,height:i.heightPx,containerClassName:"h-48 w-full",imageClassName:"w-full h-full object-cover"}),c.jsx("span",{className:"absolute bottom-2 left-2 rounded bg-scrim px-2 py-0.5 text-xs font-semibold text-white",children:"Video"})]},`${n.ulid}-vid-${s}`):c.jsx("p",{className:"rounded-lg border border-border-light/60 dark:border-border-dark/60 px-3 py-2 text-xs text-text-secondary dark:text-text-secondary-dark",children:"Video attached (preview unavailable)"},`${n.ulid}-vid-${s}`))]})}function ld(n){return n==="post"||n==="channel_message"||n==="voice_message"}function ud(n){return n==="post"?{title:"Remove post",description:"Hides this post from the lounge for everyone. Does not assign moderation points.",success:"Post removed"}:{title:"Remove message",description:"Hides this message from the lounge for everyone.",success:"Message removed"}}function Jp(n){return n==="channel_message"||n==="voice_message"?"Message":n==="lounge"?"Lounge":n==="user"?"User":n.charAt(0).toUpperCase()+n.slice(1)}function hd(n){const e=n.violationType??n.channelMessageContext?.violationType??n.violations?.[0]?.name??null;return n.body?e?`"${n.body}" — flagged ${e}`:`"${n.body}"`:e?`Flagged: ${e}`:"Reported content"}function md(n){return n.reporterUsername??n.channelMessageContext?.reporterUsername??null}function Ar({loungeId:n,item:e}){const t=Sc(),[i,s]=p.useState(!1),r=md(e),o=ld(e.contentType),a=e.flagStatus==="kept",d=ud(e.contentType),l=(u,h)=>{t.mutate({loungeId:n,contentId:e.ulid,postFlagId:e.postFlagId,action:u,channelId:e.channelMessageContext?.channelId??null,roomId:e.roomId??null},{onSuccess:()=>{z.success(h),s(!1)},onError:()=>z.error("Couldn't apply moderation. Try again.")})};return c.jsxs("div",{children:[c.jsxs("div",{className:"flex items-center gap-2.5",children:[e.author?.avatarUrl?c.jsx("img",{src:e.author.avatarUrl,alt:"",className:"h-9 w-9 flex-none rounded-full object-cover",loading:"lazy"}):c.jsx("span",{className:"flex h-9 w-9 flex-none items-center justify-center rounded-full bg-notif-live text-xs font-bold uppercase text-white",children:(e.author?.displayName||e.username).slice(0,2)}),c.jsxs("span",{className:"min-w-0",children:[c.jsxs("span",{className:"block text-sm font-semibold text-text dark:text-text-dark",children:[Jp(e.contentType)," · reported"]}),c.jsxs(Ye,{as:"span",className:"block truncate text-xs text-text-secondary dark:text-text-secondary-dark",children:["@",e.username]})]})]}),c.jsx("p",{className:"mt-3 line-clamp-3 rounded-[10px] border border-border-light/60 dark:border-border-dark/60 px-3 py-2 text-sm text-text-secondary dark:text-text-secondary-dark",children:hd(e)}),c.jsx(dd,{item:e}),r&&c.jsxs("p",{className:"mt-2 text-xs text-text-dim dark:text-text-dim-dark",children:["Reported by ",c.jsxs("span",{children:["@",r]})]}),a?c.jsxs("p",{className:"mt-3 flex h-9 items-center gap-1.5 text-sm font-semibold text-text-secondary dark:text-text-secondary-dark",children:[c.jsx(es,{size:16,className:"text-success","aria-hidden":"true"}),"Kept"]}):c.jsxs("div",{className:"mt-3 flex gap-2",children:[c.jsxs("button",{type:"button",onClick:()=>l("dismiss-flag","Flag kept"),disabled:t.isPending,className:"flex h-9 flex-1 items-center justify-center gap-1.5 rounded-xl border border-border-light dark:border-border-dark text-sm font-semibold text-text dark:text-text-dark transition-colors hover:bg-bg-elevated dark:hover:bg-bg-elevated-dark disabled:opacity-50",children:[t.isPending&&t.variables?.action==="dismiss-flag"&&c.jsx("span",{className:"inline-block h-3.5 w-3.5 animate-spin rounded-full border-2 border-current border-t-transparent","aria-hidden":"true"}),"Keep"]}),o&&c.jsxs("button",{type:"button",onClick:()=>s(!0),disabled:t.isPending,className:"flex h-9 flex-1 items-center justify-center gap-1.5 rounded-xl bg-brand text-sm font-bold text-white transition-colors hover:bg-brand/90 disabled:opacity-50",children:[t.isPending&&t.variables?.action==="hide"&&c.jsx("span",{className:"inline-block h-3.5 w-3.5 animate-spin rounded-full border-2 border-current border-t-transparent","aria-hidden":"true"}),"Remove"]})]}
15),o&&c.jsx(Ae,{open:i,onOpenChange:s,title:d.title,description:d.description,confirmLabel:"Remove",destructive:!0,onConfirm:()=>l("hide",d.success),isPending:t.isPending&&t.variables?.action==="hide"})]})}function Dr({loungeId:n,enabled:e,open:t,onOpenChange:i}){const[s,r]=p.useState(""),o=Nn(n,e&&t),a=p.useMemo(()=>o.data?.pages.flatMap(u=>u.data)??[],[o.data]),d=s.trim().toLowerCase(),l=p.useMemo(()=>d?a.filter(u=>u.username?.toLowerCase().includes(d)||u.author?.displayName?.toLowerCase().includes(d)||md(u)?.toLowerCase().includes(d)||hd(u).toLowerCase().includes(d)):a,[a,d]);return c.jsx(qt,{open:t,onOpenChange:i,children:c.jsxs(Ht,{children:[c.jsx(zt,{className:"fixed inset-0 z-50 bg-scrim data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0"}),c.jsxs(Kt,{className:`
16            fixed z-50 bg-bg dark:bg-bg-dark text-text dark:text-text-dark
17            top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2
18            flex max-h-[85vh] w-[90vw] max-w-md flex-col rounded-2xl font-inter
19            border border-border-light dark:border-border-dark shadow-xl
20            data-[state=open]:animate-in data-[state=closed]:animate-out
21            data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0
22          `,"aria-describedby":void 0,children:[c.jsx(Wt,{className:"flex-none pt-5 text-center text-lg font-bold",children:"Moderation Reports"}),c.jsx("div",{className:"flex-none px-4 pt-3",children:c.jsxs("label",{className:"flex h-11 items-center gap-2 rounded-full border border-border-light dark:border-border-dark px-3",children:[c.jsx(ts,{size:18,className:"flex-none text-text-secondary dark:text-text-secondary-dark","aria-hidden":"true"}),c.jsx("input",{type:"search",value:s,onChange:u=>r(u.target.value),placeholder:"Search","aria-label":"Search reports",className:"min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-text-placeholder dark:placeholder:text-text-placeholder-dark"})]})}),c.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto px-4 pb-4",children:[o.isLoading&&a.length===0?c.jsx("div",{className:"flex justify-center py-10",children:c.jsx(je,{size:"lg",label:"Loading reports"})}):o.isError?c.jsx("p",{className:"py-10 text-center text-sm text-text-secondary dark:text-text-secondary-dark",children:"Couldn't load reports. Try refreshing."}):l.length===0?c.jsx("p",{className:"py-10 text-center text-sm text-text-secondary dark:text-text-secondary-dark",children:d?"No reports match your search.":"No open reports."}):c.jsx("ul",{className:"flex flex-col gap-5 pt-4",children:l.map(u=>c.jsx("li",{children:c.jsx(Ar,{loungeId:n,item:u})},`${u.postFlagId}-${u.ulid}`))}),!d&&o.hasNextPage&&c.jsx("button",{type:"button",onClick:()=>o.fetchNextPage(),disabled:o.isFetchingNextPage,className:"mt-4 block w-full rounded-xl border border-border-light dark:border-border-dark py-2 text-center text-sm font-semibold text-text dark:text-text-dark transition-colors hover:bg-bg-elevated dark:hover:bg-bg-elevated-dark disabled:opacity-50",children:o.isFetchingNextPage?"Loading…":"Load more"})]})]})]})})}function $p({space:n,onOpenAbout:e}){return n.description?c.jsxs("section",{className:"rounded-xl border border-border-light dark:border-border-dark bg-bg-elevated dark:bg-bg-elevated-dark",children:[c.jsxs("button",{type:"button",onClick:e,className:"flex w-full items-center justify-between px-4 pt-4 text-left",children:[c.jsx("h2",{className:"text-base font-bold text-text dark:text-text-dark",children:"About"}),c.jsx(Sn,{size:16,className:"text-text-secondary dark:text-text-secondary-dark","aria-hidden":"true"})]}),c.jsx("p",{className:"line-clamp-4 px-4 pb-4 pt-3 text-sm text-text-secondary dark:text-text-secondary-dark",children:n.description})]}):null}const Qp=n=>p.createElement("svg",{width:17,height:17,viewBox:"0 0 17 17",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n},p.createElement("path",{d:"M14.8216 2.83253C14.8216 2.83253 14.8216 2.83519 14.8216 2.84053C14.8216 2.84586 14.8216 2.84853 14.8216 2.84853L11.0921 15.1416C11.0281 15.3444 10.916 15.5124 10.756 15.6458C10.5959 15.7792 10.4092 15.8566 10.1957 15.8779C10.1637 15.8779 10.1317 15.8779 10.0997 15.8779C9.89694 15.8779 9.71286 15.8246 9.54746 15.7179C9.38206 15.6112 9.26201 15.4724 9.18731 15.301
227V15.2857L6.85035 10.5157C6.83967 10.4944 6.83167 10.4757 6.82633 10.4597C6.821 10.4437 6.81833 10.425 6.81833 10.4037C6.81833 10.361 6.82633 10.3236 6.84234 10.2916C6.85835 10.2596 6.87702 10.2329 6.89837 10.2116L10.6119 6.51405C10.6546 6.46069 10.6893 6.40467 10.7159 6.34598C10.7426 6.28729 10.756 6.22593 10.756 6.1619C10.756 6.01251 10.7053 5.88979 10.6039 5.79375C10.5025 5.69771 10.3825 5.64969 10.2438 5.64969C10.1691 5.64969 10.1024 5.66036 10.0437 5.68171C9.98498 5.70305 9.93429 5.73506 9.89161 5.77775L6.17807 9.49128C6.15672 9.51263 6.13005 9.5313 6.09803 9.54731C6.06602 9.56331 6.02867 9.57132 5.98599 9.57132C5.96464 9.57132 5.94597 9.56865 5.92996 9.56331C5.91396 9.55798 5.89528 9.54997 5.87394 9.5393L1.08796 7.21834C0.91722 7.13297 0.778496 7.00759 0.671785 6.84219C0.565074 6.67678 0.511719 6.49271 0.511719 6.28996C0.511719 6.05519 0.581081 5.84711 0.719805 5.6657C0.858529 5.48429 1.0346 5.36157 1.24802 5.29755L13.5571 1.58401C13.5998 1.56266 13.6425 1.54933 13.6852 1.54399C13.7279 1.53866 13.7759 1.53599 13.8292 1.53599C14.1067 1.53599 14.3468 1.63736 14.5495 1.84011C14.7523 2.04286 14.8537 2.28296 14.8537 2.56041C14.8537 2.61377 14.851 2.66446 14.8457 2.71247C14.8403 2.7605 14.827 2.80585 14.8056 2.84853L14.8216 2.83253Z",fill:"white"}));function Yp({loungeId:n}){const[e,t]=p.useState(!1),[i,s]=p.useState(!1),r=lh("parler",{enabled:!0,retry:!1});jm(r.error);const o=Om(r.data),a=o&&typeof window<"u"?nm(`${window.location.origin}/lounge/${n}`,o.code):null,d=uh(),l=p.useCallback(()=>{d.mutate()},[d]);return e?null:c.jsxs("section",{className:"relative rounded-xl border border-border-light bg-bg p-4 dark:border-border-dark dark:bg-bg-dark",children:[c.jsx("button",{type:"button",onClick:()=>t(!0),"aria-label":"Dismiss Invite & Earn",className:"absolute right-2.5 top-2.5 flex h-7 w-7 items-center justify-center rounded-full text-text-secondary transition-colors hover:bg-bg-elevated hover:text-text dark:text-text-secondary-dark dark:hover:bg-bg-elevated-dark dark:hover:text-text-dark",children:c.jsx(wr,{size:20})}),c.jsx("h2",{className:"pr-7 text-base font-bold text-text dark:text-text-dark",children:"Invite & Earn"}),c.jsx("p",{className:"mt-2 text-[13px] leading-[18px] text-text-secondary dark:text-text-secondary-dark",children:"Invite people you know, grow your network, and help bring more voices into the Parler community."}),c.jsxs("label",{className:"mt-3 block",children:[c.jsx("span",{className:"mb-2 block text-sm font-semibold text-text-secondary dark:text-text-secondary-dark",children:"Your Invite Link:"}),c.jsx("input",{type:"text",readOnly:!0,value:a??"",placeholder:r.isPending?"Loading invite link…":"Invite link unavailable",onClick:u=>u.currentTarget.select(),"aria-label":"Your invite link",className:"h-11 w-full truncate rounded-lg border border-border-light bg-bg-elevated px-3 text-sm text-text outline-none dark:border-border-dark dark:bg-bg-elevated-dark dark:text-text-dark"})]}),c.jsxs("button",{type:"button",onClick:()=>s(!0),disabled:!a,className:"mt-2.5 flex h-12 w-full items-center justify-center gap-2 rounded-xl bg-brand text-sm font-bold text-white transition-opacity hover:opacity-90 disabled:opacity-40",children:[c.jsx(Qp,{width:17,height:17,"aria-hidden":"true"}),"Share invite"]}),c.jsx(mp,{open:i,onOpenChange:s,shareUrl:a??"",onShared:l})]})}function Zp({loungeId:n,enabled:e,onViewAll:t}){const s=Nn(n,e).data?.pages.flatMap(o=>o.data)??[],r=s.find(o=>o.flagStatus!=="kept")??s[0]??null;return!e||!r?null:c.jsxs("section",{className:"rounded-xl border border-border-light dark:border-border-dark bg-bg-elevated dark:bg-bg-elevated-dark",children:[t?c.jsxs("button",{type:"button",onClick:t,className:"flex w-full items-center justify-between px-4 pt-4 text-left",children:[c.jsx("h2",{className:"text-base font-bold text-text dark:text-text-dark",children:"Moderation"}),c.jsx(Sn,{size:16,className:"text-text-secondary dark:text-text-secondary-dark","aria-hidden":"true"})]}):c.jsxs(Pe,{to:`/lounges/${n}/reports`,className:"flex items-center justify-between px-4 pt-4",children:[c.jsx("h2",{className:"text-base font-bold text-text dark:text-text-dark",children:"Moderation"}),c.jsx(Sn,{size:16,className:"text-text-secondary dark:text-text-secondary-dark","aria-hidden":"true"})]}),c.jsxs("div",{className:"px-4 pb-4 pt-3",children:[c.jsx(Ar,{loungeId:n,item:r}),t?c.jsx("button",{type:"button",onClick:t,className:"mt-3 block w-full rounded-xl border border-border-light dark:border-border-dark py-2 text-center text-sm font-semibold text-text dark:text-text-dark hover:bg-bg dark:hover:bg-bg-dark transition-colors",children:"View All"}):c.jsx(Pe,{to:`/lounges/${n}/reports`,className:"mt-3 block rounded-xl border border-border-light dark:border-border-dark py-2 text-center text-sm font-semibold text-text dark:text-text-dark hover:bg-bg dark:hover:bg-bg-dark transition-colors",children:"View All"})]})]})}function Xp({value:n,onChange:e}){return c.jsxs("div",{className:"flex h-12 w-full flex-none items-center gap-2 rounded-full bg-surface dark:bg-surface-dark pl-[11px] pr-[10px]",children:[c.jsx(ts,{size:20,className:"flex-none text-text-secondary dark:text-text-secondary-dark","aria-hidden":"true"}),c.jsx("input",{type:"search",value:n,onChange:t=>e(t.target.value),placeholder:"Search content","aria-label":"Search lounge content",className:"min-w-0 flex-1 bg-transparent text-sm text-text dark:text-text-dark outline-none placeholder:text-text-placeholder dark:placeholder:text-text-placeholder-dark"})]})}function as(n){return n.isSpeaking&&Yi(n.role)}function pd(n){return as(n)?"Speaking":n.role==="host"?"Host":n.role==="speaker"?"Speaker":"Listener"}function fd(n){return as(n)?"border-custom-blue":n.role==="host"?"border-custom-pink":"border-transparent"}const ef=6;function tf({participant:n}){const e=as(n),t=pd(n),i=e?"text-custom-blue":n.role==="host"?"text-custom-pink":n.role==="speaker"&&n.isMuted?"text-error":"text-text-secondary dark:text-text-secondary-dark";return c.jsxs("span",{className:`flex items-center gap-1 text-xs font-medium ${i}`,children:[n.role==="listener"?c.jsx(Gc,{size:12,"aria-hidden":"true"}):e?c.jsx(Xc,{width:14,height:9}):n.isMuted?c.jsx(ns,{size:12,"aria-hidden":"true"}):c.jsx(ln,{size:12,"aria-hidden":"true"}),t]})}function Ba({participant:n,onProfile:e}){const t=n.name||n.username||"Member",i=n.username?Ft(n.username):null,s=e&&n.username?()=>e(n):void 0,r=d=>{s&&an(d,s)},o=c.jsx("span",{className:`flex-none rounded-full border-2 ${fd(n)}`,children:c.jsx(Lm,{user:{avatarUrl:n.avatar||null,displayName:t,username:n.username},size:"row",fallbackClassName:"bg-bg dark:bg-bg-dark"})}),a=c.jsxs(c.Fragment,{children:[o,c.jsxs("span",{className:"min-w-0 flex-1",children:[c.jsxs("span",{className:"flex items-center gap-1.5",children:[c.jsx(Ye,{className:"truncate text-sm font-semibold text-text dark:text-text-dark",children:t}),c.jsx(Zi,{badges:n.badges,size:12})]}),c.jsx(tf,{participant:n})]})]});return i?c.jsx("li",{children:c.jsx(Pe,{to:i,...rn(!!s),onClick:r,"aria-label":`View profile for ${t}`,className:"flex w-full items-center gap-2.5 rounded-md py-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand",children:a})}):c.jsx("li",{className:"flex items-center gap-2.5 py-2",children:a})}function qa({title:n,children:e,footer:t}){return c.jsxs("section",{"aria-label":n,className:"rounded-xl border border-border-light dark:border-border-dark bg-bg-elevated dark:bg-bg-elevated-dark",children:[c.jsxs("div",{className:"flex items-center justify-between px-4 pt-4",children:[c.jsx("h2",{className:"text-base font-bold text-text dark:text-text-dark",children:n}),c.jsx(Sn,{size:16,className:"text-text-secondary dark:text-text-secondary-dark","aria-hidden":"true"})]}),c.jsx("ul",{className:"px-4 pb-2 pt-1",children:e}),t]})}function nf({roster:n,onParticipantProfile:e}){const[t,i]=p.useState(!1),{speakers:s,listeners:r}=p.useMemo(()=>Ac(n),[n]),o=t?r:r.slice(0,ef),a=r.length-o.length;return c.jsxs(c.Fragment,{children:[s.length>0&&c.jsx(qa,{title:"Speakers",children:s.map(d=>c.jsx(Ba,{participant:d,onProfile:e},d.ulid))}),r.length>
220&&c.jsx(qa,{title:"Listeners",footer:a>0?c.jsxs("button",{type:"button",onClick:()=>i(!0),className:"w-full px-4 pb-4 text-center text-sm font-medium text-text-secondary dark:text-text-secondary-dark hover:underline",children:["Show all (",r.length,")"]}):null,children:o.map(d=>c.jsx(Ba,{participant:d,onProfile:e},d.ulid))})]})}function Ur({space:n,isAdmin:e,isRestricted:t,isMember:i,onOpenAbout:s,onOpenMembers:r,onOpenReports:o,contentQuery:a,onContentQueryChange:d,onSameTabProfile:l,voiceRoster:u,onParticipantProfile:h}){return c.jsxs("aside",{className:"hidden md:flex sticky top-0 h-dvh w-[280px] lg:w-[320px] flex-none flex-col gap-4 overflow-y-auto px-4 py-4",children:[i&&!t&&d&&c.jsx(Xp,{value:a??"",onChange:d}),n.isOwner&&!t&&c.jsx(Yp,{loungeId:n.ulid}),c.jsx(Zp,{loungeId:n.ulid,enabled:e,onViewAll:o}),c.jsx($p,{space:n,onOpenAbout:s}),u&&u.length>0?c.jsx(nf,{roster:u,onParticipantProfile:h}):!t&&c.jsx(Wp,{space:n,onOpenMembers:r,onSameTabProfile:l}),c.jsxs("footer",{"data-testid":"lounge-rail-footer",className:"mt-auto flex flex-none flex-wrap items-center justify-start gap-x-3 gap-y-1 pt-2 font-inter text-[12px] font-medium leading-[16.56px] tracking-[0] text-[#8E8E93E5]",children:[c.jsx("a",{href:im,target:"_blank",rel:"noopener noreferrer",className:"hover:underline",children:"Terms"}),c.jsx("a",{href:sm,target:"_blank",rel:"noopener noreferrer",className:"hover:underline",children:"Privacy"}),c.jsx("a",{href:"https://www.parler.com/cookie-policy",target:"_blank",rel:"noopener noreferrer",className:"hover:underline",children:"Cookies"}),c.jsx("a",{href:"https://www.parler.com/about",target:"_blank",rel:"noopener noreferrer",className:"hover:underline",children:"About"})]})]})}const Ha="mt-1.5 w-full rounded-xl bg-bg-elevated dark:bg-bg-elevated-dark px-4 py-3 text-sm text-text dark:text-text-dark outline-none placeholder:text-text-placeholder dark:placeholder:text-text-placeholder-dark focus:ring-2 focus:ring-brand";function gd({name:n,onNameChange:e,description:t,onDescriptionChange:i}){return c.jsxs(c.Fragment,{children:[c.jsxs("label",{className:"block",children:[c.jsx("span",{className:"text-sm text-text-secondary dark:text-text-secondary-dark",children:"Room Name"}),c.jsx("input",{type:"text",value:n,onChange:s=>e(s.target.value),placeholder:"Name your room",className:`${Ha} font-semibold placeholder:font-normal`})]}),c.jsxs("label",{className:"mt-4 block",children:[c.jsx("span",{className:"text-sm text-text-secondary dark:text-text-secondary-dark",children:"Description"}),c.jsx("textarea",{value:t,onChange:s=>i(s.target.value),rows:3,placeholder:"What is this room about?",className:`${Ha} resize-none`})]})]})}const Js=2;function vd(n){return n.trim().toLowerCase().replace(/\s+/g,"-")}const $s="flex h-12 flex-1 items-center justify-center rounded-xl border border-border-light dark:border-border-dark text-sm font-semibold text-text dark:text-text-dark transition-colors hover:bg-bg-elevated dark:hover:bg-bg-elevated-dark",Qs="flex h-12 flex-1 items-center justify-center gap-2 rounded-xl bg-label-primary text-sm font-semibold text-white transition-opacity hover:opacity-90 disabled:opacity-50";function sf({spaceId:n,channel:e,open:t,onOpenChange:i}){const[s,r]=p.useState(e.name),[o,a]=p.useState(e.description??""),d=hh(),l=vd(s),u=e.type==="voice",h=()=>{d.mutate({spaceId:n,channelId:e.ulid,input:{name:l,description:o.trim()}},{onSuccess:()=>{z.success("Room updated"),i(!1)},onError:m=>z.error(Je(m,"Couldn't update the room. Try again."))})};return c.jsx(qt,{open:t,onOpenChange:i,children:c.jsxs(Ht,{children:[c.jsx(zt,{className:"fixed inset-0 z-50 bg-scrim data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0"}),c.jsxs(Kt,{className:`
23            fixed z-50 bg-bg dark:bg-bg-dark text-text dark:text-text-dark
24            top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2
25            w-[90vw] max-w-md rounded-2xl p-5 font-inter
26            border border-border-light dark:border-border-dark shadow-xl
27            data-[state=open]:animate-in data-[state=closed]:animate-out
28            data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0
29          `,"aria-describedby":void 0,children:[c.jsx(Wt,{className:"pb-4 text-center text-lg font-bold",children:u?"Edit Audio Room":"Edit Chat Room"}
29),c.jsx(gd,{name:s,onNameChange:r,description:o,onDescriptionChange:a}),c.jsxs("div",{className:"mt-5 flex gap-3",children:[c.jsx("button",{type:"button",onClick:()=>i(!1),className:$s,children:"Cancel"}),c.jsxs("button",{type:"button",onClick:h,disabled:d.isPending||l.length<Js,className:Qs,children:[d.isPending&&c.jsx("span",{className:"inline-block h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent","aria-hidden":"true"}),"Save"]})]})]})]})})}function Fr({spaceId:n,channel:e,canManage:t,onDeleted:i}){const[s,r]=p.useState(!1),[o,a]=p.useState(!1),d=mh(),l=p.useCallback(()=>r(!0),[]),u=p.useCallback(()=>a(!0),[]),h=p.useCallback(S=>{!S&&!d.isPending&&a(!1)},[d.isPending]),m=p.useCallback(()=>{e&&d.mutate({spaceId:n,channelId:e.ulid},{onSuccess:()=>{z.success("Room deleted"),a(!1),i?.()},onError:S=>z.error(Je(S,"Could not delete the room. Try again."))})},[e,n,d,i]),f=p.useMemo(()=>!t||!e?[]:[{id:"edit-room",label:"Edit room",onPress:l},{id:"delete-room",label:"Delete room",destructive:!0,onPress:u}],[t,e,l,u]),C=e?.type==="voice"?"audio room":"chat room",x=e?c.jsxs(c.Fragment,{children:[s&&c.jsx(sf,{spaceId:n,channel:e,open:!0,onOpenChange:r}),c.jsx(Ae,{open:o,onOpenChange:h,title:`Delete ${e.name}?`,description:`This ${C} and its history will be permanently removed. This can't be undone.`,confirmLabel:"Delete",onConfirm:m,isPending:d.isPending})]}):null;return{roomOptions:f,roomDialogs:x}}const za="flex h-9 w-9 flex-none items-center justify-center rounded-full bg-bg-elevated dark:bg-bg-elevated-dark text-text dark:text-text-dark hover:bg-border-light dark:hover:bg-border-dark transition-colors";function rf(){is("LoungeChatRoom");const{spaceId:n="",channelId:e=""}=ci(),{search:t}=Sr(),i=De(D=>D.user?.id??null),s=oi(n),r=s.data?.data??null,o=$i(n),a=(o.data?.data??[]).find(D=>D.ulid===e)??null,[d,l]=p.useState(!1),[u,h]=p.useState(!1),[m,f]=p.useState(!1),C=p.useCallback(()=>l(!0),[]),x=p.useCallback(()=>h(!0),[]),S=p.useCallback(()=>f(!0),[]),v=p.useCallback(D=>{D||h(!1)},[]),g=r?.myRole??null,k=!!r?.isOwner||g==="admin",T=k||g==="moderator",b=td(),w=!!r?.isJoined||!!r?.isOwner,P=w||b,{realtimeHealthy:E}=Am(i,n||null,a?.ulid??null,w),_=P&&!E,N=`/lounges/${n}?tab=rooms`,L=lt(),O=p.useCallback(()=>L(N,{replace:!0}),[L,N]),{roomOptions:q,roomDialogs:J}=Fr({spaceId:n,channel:a,canManage:T,onDeleted:O});return s.isLoading||o.isLoading?c.jsx("div",{className:"flex items-center justify-center min-h-[60vh]",children:c.jsx(je,{size:"lg",label:"Loading room"})}):s.isError||!r?c.jsx(rs,{}):o.isError?c.jsx("div",{className:"flex items-center justify-center min-h-[60vh]",children:c.jsx("p",{className:"text-sm text-text-secondary dark:text-text-secondary-dark",children:"Couldn't load this room. Try refreshing."})}):s.isSuccess&&a?.type==="voice"?c.jsx(ei,{to:`/lounges/${n}/voice/${encodeURIComponent(e)}${t}`,replace:!0}):s.isSuccess&&(!P||!a)?c.jsx(ei,{to:N,replace:!0}):c.jsxs("div",{className:"flex mx-auto font-inter",children:[c.jsxs("div",{className:"flex h-[calc(100dvh-3.5rem)] md:h-dvh min-w-0 max-w-[600px] flex-1 flex-col md:border-r border-border-light/60 dark:border-border-dark/60",children:[c.jsxs("header",{className:"sticky top-0 z-10 flex items-center justify-between gap-2 border-b border-border-light/60 dark:border-border-dark/60 bg-bg/90 dark:bg-bg-dark/90 px-3 py-2 backdrop-blur",children:[c.jsx(Pe,{to:N,"aria-label":"Back to rooms",className:za,children:c.jsx(_n,{width:18,height:18})}),c.jsxs("h1",{className:"flex min-w-0 items-center gap-1.5 text-[17px] font-bold text-text dark:text-text-dark",children:[c.jsx("span",{className:"font-normal text-text-secondary dark:text-text-secondary-dark",children:"#"}),c.jsx("span",{className:"truncate",children:a.name})]}),c.jsx(ss,{loungeUlid:r.ulid,displayName:r.displayName??r.name,channelId:a.ulid,channelName:a.name,isOwner:r.isOwner,visibility:r.visibility,membershipStatus:r.membershipStatus,isTrendingExcluded:r.isTrendingExcluded,triggerClassName:za,extraOptions:q,triggerLabel:"Room options"})]}),c.jsx("div",{className:"flex min-h-0 flex-1 flex-col",children:c.jsx(zp,{spaceId:n,channelId:e,isMod:T,isAdmin:k,shouldPoll:_,canPost:w})})]}),c.jsx(Ur,{space:r,isAdmin:k,isRestricted:!1,isMember:P,onOpenAbout:C,onOpenMembers:x,onOpenReports:S}),d&&c.jsx(Or,{space:r,open:!0,onOpenChange:l}),u&&c.jsx(Lr,{space:r,open:!0,onOpenChange:v}),c.jsx(Dr,{loungeId:r.ulid,enabled:T,open:m,onOpenChange:f}),J]})}function Vr(n){const e=lt(),t=Sr(),i=p.useRef(t.key!=="default");return p.useCallback(()=>{i.current?e(-1):e(n,{replace:!0})},[e,n])}function af(n,e){const t=Nn(n,e);return p.useMemo(()=>
29{if(!e)return null;let i=0;for(const s of t.data?.pages??[])for(const r of s.data)if(r.flagStatus!=="kept"&&(i+=1,i>9))return"9+";return t.hasNextPage?"9+":i===0?null:String(i)},[e,t.data,t.hasNextPage])}const Br=n=>p.createElement("svg",{width:24,height:24,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n},p.createElement("path",{d:"M12 1C15.0376 1 17.5 3.46243 17.5 6.5V8.25H18C19.5187 8.2501 20.75 9.48128 20.75 11V20C20.75 21.5187 19.5187 22.7499 18 22.75H6.00098C4.48229 22.75 3.25112 21.5187 3.25098 20L3.25 11C3.25 9.48123 4.4812 8.25 6 8.25H6.5V6.5C6.5 3.46243 8.96243 1 12 1ZM12 13.5C11.4477 13.5 11 13.9477 11 14.5V16.5C11 17.0523 11.4477 17.5 12 17.5C12.5523 17.5 13 17.0523 13 16.5V14.5C13 13.9477 12.5523 13.5 12 13.5ZM12 3C10.067 3 8.5 4.567 8.5 6.5V8.25H15.5V6.5C15.5 4.567 13.933 3 12 3Z",fill:"white"}),p.createElement("path",{d:"M17.5 8.25H17.25V8.5H17.5V8.25ZM18 8.25L18 8H18V8.25ZM18 22.75V23H18L18 22.75ZM6.00098 22.75V23V22.75ZM3.25098 20L3.50098 20V20L3.25098 20ZM3.25 11L3 11V11L3.25 11ZM6 8.25V8V8.25ZM6.5 8.25V8.5H6.75V8.25H6.5ZM12 13.5V13.25V13.5ZM12 17.5V17.75V17.5ZM8.5 8.25H8.25V8.5H8.5V8.25ZM15.5 8.25V8.5H15.75V8.25H15.5ZM12 1V1.25C14.8995 1.25 17.25 3.60051 17.25 6.5H17.5H17.75C17.75 3.32436 15.1756 0.75 12 0.75V1ZM17.5 6.5H17.25V8.25H17.5H17.75V6.5H17.5ZM17.5 8.25V8.5H18V8.25V8H17.5V8.25ZM18 8.25L18 8.5C19.3806 8.50009 20.5 9.61937 20.5 11H20.75H21C21 9.34319 19.6568 8.00011 18 8L18 8.25ZM20.75 11H20.5V20H20.75H21V11H20.75ZM20.75 20H20.5C20.5 21.3806 19.3806 22.4999 18 22.5L18 22.75L18 23C19.6568 22.9999 21 21.6568 21 20H20.75ZM18 22.75V22.5H6.00098V22.75V23H18V22.75ZM6.00098 22.75V22.5C4.62038 22.5 3.5011 21.3806 3.50098 20L3.25098 20L3.00098 20C3.00113 21.6567 4.3442 23 6.00098 23V22.75ZM3.25098 20L3.50098 20L3.5 11L3.25 11L3 11L3.00098 20L3.25098 20ZM3.25 11L3.5 11C3.5 9.6193 4.61928 8.5 6 8.5V8.25V8C4.34313 8 3 9.34317 3 11L3.25 11ZM6 8.25V8.5H6.5V8.25V8H6V8.25ZM6.5 8.25H6.75V6.5H6.5H6.25V8.25H6.5ZM6.5 6.5H6.75C6.75 3.60051 9.10051 1.25 12 1.25V1V0.75C8.82436 0.75 6.25 3.32436 6.25 6.5H6.5ZM12 13.5V13.25C11.3096 13.25 10.75 13.8096 10.75 14.5H11H11.25C11.25 14.0858 11.5858 13.75 12 13.75V13.5ZM11 14.5H10.75V16.5H11H11.25V14.5H11ZM11 16.5H10.75C10.75 17.1904 11.3096 17.75 12 17.75V17.5V17.25C11.5858 17.25 11.25 16.9142 11.25 16.5H11ZM12 17.5V17.75C12.6904 17.75 13.25 17.1904 13.25 16.5H13H12.75C12.75 16.9142 12.4142 17.25 12 17.25V17.5ZM13 16.5H13.25V14.5H13H12.75V16.5H13ZM13 14.5H13.25C13.25 13.8096 12.6904 13.25 12 13.25V13.5V13.75C12.4142 13.75 12.75 14.0858 12.75 14.5H13ZM12 3V2.75C9.92893 2.75 8.25 4.42893 8.25 6.5H8.5H8.75C8.75 4.70507 10.2051 3.25 12 3.25V3ZM8.5 6.5H8.25V8.25H8.5H8.75V6.5H8.5ZM8.5 8.25V8.5H15.5V8.25V8H8.5V8.25ZM15.5 8.25H15.75V6.5H15.5H15.25V8.25H15.5ZM15.5 6.5H15.75C15.75 4.42893 14.0711 2.75 12 2.75V3V3.25C13.7949 3.25 15.25 4.70507 15.25 6.5H15.5Z",fill:"white"})),vi="flex h-10 items-center justify-center rounded-lg border border-system-grey4 dark:border-system-grey4-dark px-3 py-1 text-text dark:text-text-dark hover:bg-bg-elevated dark:hover:bg-bg-elevated-dark transition-colors",of="flex h-10 items-center justify-center gap-2 rounded-lg bg-label-primary px-4 text-[15px] font-semibold leading-none tracking-[-0.23px] text-white transition-opacity disabled:opacity-50";function cf({space:n,isAdmin:e,onEdit:t}){const i=lt(),s=De(P=>P.user?.id??null),r=Et("hidden_lounges"),o=ph(),a=wc(),d=fh(),l=yc(),u=gh(),h=Dm(),m=Er(P=>P.open),f=()=>m({type:"space",spaceId:n.ulid,displayName:n.displayName??n.name}),C=vh(n,r),x=C?.intent==="request",S=()=>o.mutate(n.ulid,{onSuccess:()=>h.close(),onError:P=>z.error(rm(Je(P,"Could not join this lounge."),P))}),v=()=>d.mutate(n.ulid,{onSuccess:()=>h.close(),onError:P=>z.error(Je(P,"Could not send your request. Try again."))}),g=()=>h.promptJoin(n.ulid,x?v:S),k=()=>{a.mutate(n.ulid,{onSuccess:()=>i("/lounges"),onError:P=>z.error(Je(P,"Could not leave this lounge."))})},T=n.isJoined||n.isOwner||n.membershipStatus==="requested"||n.membershipStatus==="invited",b=(vn(n.visibility)!=="hidden"||T)&&c.jsx("button",{type:"button","aria-label":"Share lounge",onClick:f,className:`w-11 ${vi}`,children:c.jsx(Um,{size:18})});let w=null;if(e)w=c.jsxs("button",{type:"button",onClick:t??(()=>i(`/lounges/${n.ulid}
29/settings`)),className:`gap-1.5 text-sm font-semibold ${vi}`,children:[c.jsx(Vm,{size:16,"aria-hidden":"true"}),"Edit"]});else if(n.isJoined)w=c.jsxs("button",{type:"button",onClick:k,disabled:a.isPending,className:`gap-2 text-[15px] font-semibold leading-none tracking-[-0.23px] px-4 disabled:opacity-50 ${vi}`,children:[a.isPending&&c.jsx("span",{className:"inline-block w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin","aria-hidden":"true"}),"Leave"]});else if(!n.isBanned&&C){const P={join:g,request:g,requested:()=>{s&&l.mutate({spaceId:n.ulid,userId:s},{onSuccess:()=>z.success("Request canceled"),onError:N=>z.error(Je(N,"Could not cancel your request. Try again."))})},accept:()=>u.mutate(n.ulid,{onSuccess:()=>z.success("Invitation accepted"),onError:N=>z.error(Je(N,"Could not accept the invitation. Try again."))})},E=o.isPending||d.isPending||l.isPending||u.isPending||h.isChecking,_=C.intent==="requested";w=c.jsxs("button",{type:"button",onClick:P[C.intent],disabled:E||_&&!s,className:_?`gap-2 text-[15px] font-semibold leading-none tracking-[-0.23px] px-4 disabled:opacity-50 ${vi}`:of,children:[E?c.jsx("span",{className:"inline-block w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin","aria-hidden":"true"}):C.intent==="request"&&c.jsx(Br,{width:20,height:20,"aria-hidden":"true"}),C.label]})}return c.jsxs("div",{className:"flex items-center gap-2",children:[b,w,h.hasOpened&&c.jsx(Fm,{space:n,open:h.open,onOpenChange:h.onOpenChange,onConfirm:x?v:S,isPending:x?d.isPending:o.isPending,confirmLabel:x?"Request to Join":void 0,title:x?`Request to join ${n.displayName??n.name}`:void 0})]})}const $n="flex h-9 w-9 items-center justify-center rounded-full bg-bg/80 dark:bg-bg-dark/80 backdrop-blur text-text dark:text-text-dark hover:bg-bg dark:hover:bg-bg-dark transition-colors";function df({space:n,membersVisible:e,onOpenMembers:t}){const i=Pn(n.ulid,void 0,{enabled:e}),s=n.ownerId??null,r=(i.data?.pages[0]?.data??[]).filter(d=>d.avatar).sort((d,l)=>{const u=s&&d.ulid===s?1:0;return(s&&l.ulid===s?1:0)-u}).slice(0,3),o="mt-2 flex items-center gap-2 text-sm text-text-secondary dark:text-text-secondary-dark hover:underline",a=c.jsxs(c.Fragment,{children:[r.length>0&&c.jsx("span",{className:"flex -space-x-2",children:r.map(d=>c.jsx("img",{src:d.avatar,alt:"",className:"h-7 w-7 rounded-full object-cover ring-2 ring-bg dark:ring-bg-dark",loading:"lazy"},d.ulid))}),c.jsxs("span",{children:[c.jsx("span",{className:"font-bold text-text dark:text-text-dark",children:Li(n.memberCount)})," ",n.memberCount===1?"Member":"Members"]})]});return t?c.jsx("button",{type:"button",onClick:t,className:o,children:a}):c.jsx(Pe,{to:`/lounges/${n.ulid}/members`,className:o,children:a})}function lf({space:n,canModerate:e,isAdmin:t,isMember:i,onOpenReports:s,onOpenMembers:r,onEdit:o}){const a=Vr("/lounges"),d=De(S=>S.user?.badges),l=Et("voice_rooms",d),u=af(n.ulid,e),h=_r(n.bannerUrl,n.ulid),m=Pr(n.iconUrl,n.ulid),f=am(n),C=!f||i,x=n.createdAt?new Date(n.createdAt).toLocaleDateString(void 0,{month:"long",year:"numeric"}):null;return c.jsxs("header",{children:[c.jsxs("div",{className:"relative h-[200px] bg-bg-elevated dark:bg-bg-elevated-dark",children:[h&&c.jsx("img",{src:h,alt:"",className:"h-full w-full object-cover"}),c.jsx("button",{type:"button","aria-label":"Back",onClick:a,className:`absolute left-3 top-4 ${$n}`,children:c.jsx(_n,{width:18,height:18})}),c.jsxs("div",{className:"absolute right-6 top-4 flex items-center gap-3",children:[e&&c.jsxs("button",{type:"button","aria-label":u?`Reports (${u} open)`:"Reports",onClick:s,className:`relative ${$n}`,children:[c.jsx(Wc,{size:16}),u&&c.jsx("span",{className:"absolute -right-1 -top-1 flex h-4 min-w-[16px] items-center justify-center rounded-full bg-brand px-1 text-[10px] font-bold text-text-on-brand",children:u})]}),c.jsx(ss,{loungeUlid:n.ulid,displayName:n.displayName??n.name,isOwner:n.isOwner,visibility:n.visibility,membershipStatus:n.membershipStatus,isTrendingExcluded:n.isTrendingExcluded,triggerClassName:$n})]})]}),c.jsxs("div",{className:"px-4",children:[c.jsxs("div",{className:"flex items-end justify-between",children:[c.jsx("div",{className:"relative z-10 -mt-12 h-24 w-24 overflow-hidden rounded-2xl border-4 border-bg dark:border-bg-dark bg-bg-elevated dark:bg-bg-elevated-dark",children:m?c.jsx("img",{src:m,alt:"",className:"h-full w-full object-cover"}):c.jsx("span",{className:"flex h-full w-full items-center justify-center text-2xl font-bold text-text-secondary dark:text-text-secondary-dark",children:(n.displayName??n.name)?.[0]?.toUpperCase()??"?"})}),c.jsx("div",{className:"pb-1 pt-2",children:c.jsx(cf,{space:n,isAdmin:t,onEdit:o})})]}),c.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[c.jsx("h1",{className:"truncate text-xl font-bold text-text dark:text-text-dark",children:n.displayName??n.name}),f&&c.jsx(Bm,{as:pp,size:14,"aria-hidden":!1,"aria-label":om(n),className:"text-text-secondary dark:text-text-secondary-dark"}),n.isOwner&&c.jsx("span",{className:"rounded border border-brand-pale dark:border-brand-pale-dark bg-brand-pale dark:bg-brand-pale-dark px-2 py-0.5 text-xs font-semibold text-brand",children:"Owner"}),l&&n.hasLiveRoom&&c.jsx(Ir,{})]}),n.description&&c.jsx("p",{className:"mt-1 line-clamp-2 text-sm text-text dark:text-text-dark",children:n.description}),x&&c.jsxs("p",{className:"mt-2 flex items-center gap-1.5 text-sm text-text-secondary dark:text-text-secondary-dark",children:[c.jsx(qm,{size:15,"aria-hidden":"true"}),x]}),c.jsx(df,{space:n,membersVisible:C,onOpenMembers:r})]})]})}function Ka(n,e){return cm[n]?.label??e}function uf(n){return n.map(e=>({key:`rule-${e.id}
29`,id:e.id,title:e.title,description:e.description}))}function hf({loungeId:n,onClose:e}){const t=lt(),i=oi(n),s=i.data?.data??null,r=Cc(n),o=bh(),a=Et("hidden_lounges"),d=nd("lounge_private_hidden"),l=kh(),u=xh(),h=yh(),m=Ch(),f=Th(),C=Gs(),x=Gs(),S=ja(),v=ja(),g=S.onPick,k=v.onPick,T=Ia(S.file),b=Ia(v.file),w=p.useRef(null),P=p.useRef(null),E=p.useRef(1),_=p.useRef(!1),N=p.useRef(!1),[L,O]=p.useState(""),[q,J]=p.useState(""),[D,K]=p.useState("public"),se=W=>{if(W!==D){if(gp(W)&&!d.allowed){d.requestPaywall();return}K(W)}},[re,F]=p.useState(""),[ie,$]=p.useState(""),[ne,he]=p.useState([]),[ke,B]=p.useState(!1),[Q,fe]=p.useState(!1);p.useEffect(()=>{!s||_.current||(_.current=!0,O(s.displayName??s.name),J(s.description??""),K(vn(s.visibility)),F((s.category??"").toLowerCase().replace(/\s+/g,"-")))},[s]),p.useEffect(()=>{!r.data||N.current||(N.current=!0,he(uf(r.data.data)))},[r.data]);const Ue=o.data??[],ae=p.useMemo(()=>{const W=ie.trim().toLowerCase();return W?Ue.filter(ve=>Ka(ve.slug,ve.name).toLowerCase().includes(W)):Ue},[ie,Ue]),Z=r.data?.data??[],Pt=p.useMemo(()=>{if(!N.current)return!1;const W=ne.filter(ve=>ve.title.trim());return W.length!==Z.length?!0:W.some(ve=>{const Oe=Z.find(it=>it.id===ve.id);return!Oe||Oe.title!==ve.title.trim()})},[Z,ne]),tt=!!s&&(L.trim()!==(s.displayName??s.name)||q.trim()!==(s.description??"")||a&&D!==vn(s.visibility)||re!==(s.category??"").toLowerCase().replace(/\s+/g,"-")||!!S.file||!!v.file||Pt)&&L.trim().length>0&&q.trim().length>0,Qt=p.useCallback((W,ve)=>{he(Oe=>Oe.map(it=>it.key===W?{...it,title:ve}:it))},[]),gs=p.useCallback(()=>{const W=`draft-${E.current++}`;he(ve=>[...ve,{key:W,title:"",description:""}])},[]),In=p.useCallback(W=>{he(ve=>ve.filter(Oe=>Oe.key!==W))},[]),Yt=p.useCallback(async()=>{if(!(!s||!tt)){B(!0);try{const W={};L.trim()!==(s.displayName??s.name)&&(W.displayName=L.trim()),q.trim()!==(s.description??"")&&(W.description=q.trim()),a&&D!==vn(s.visibility)&&(W.visibility=D);const ve=(s.category??"").toLowerCase().replace(/\s+/g,"-");re!==ve&&(W.category=re);const[Oe,it]=await Promise.all([S.file?C.upload(S.file):Promise.resolve(null),v.file?x.upload(v.file):Promise.resolve(null)]);Oe&&(W.iconUrl=Oe,Hm(n)),it&&(W.bannerUrl=it,zm(n));const ze=ne.filter(Ce=>Ce.title.trim()),ui=new Set(ze.flatMap(Ce=>Ce.id?[Ce.id]:[])),Nt=[];for(const Ce of ze){if(!Ce.id){Nt.push(h.mutateAsync({spaceId:n,input:{title:Ce.title.trim(),description:Ce.description}}));continue}const _t=Z.find(On=>On.id===Ce.id);_t&&_t.title!==Ce.title.trim()&&Nt.push(m.mutateAsync({spaceId:n,ruleId:Ce.id,input:{title:Ce.title.trim(),description:Ce.description}}))}for(const Ce of Z)ui.has(Ce.id)||Nt.push(f.mutateAsync({spaceId:n,ruleId:Ce.id}));await Promise.all([Object.keys(W).length>0?l.mutateAsync({spaceId:n,input:W}):Promise.resolve(),...Nt]),z.success("Lounge settings updated"),e()}catch(W){z.error(W instanceof Error?W.message:"Failed to save changes")}finally{B(!1)}}},[v.file,x,tt,re,h,f,q,a,S.file,C,n,L,e,Z,ne,s,m,l,D]),Mn=p.useCallback(W=>{k(W.target.files?.[0]??null),W.target.value=""},[k]),jn=p.useCallback(W=>{g(W.target.files?.[0]??null),W.target.value=""},[g]);if(i.isLoading||!s)return c.jsx("div",{className:"flex min-h-[420px] items-center justify-center",children:c.jsx(je,{size:"lg",label:"Loading edit lounge"})});const nt=b??_r(s.bannerUrl,n),li=T??Pr(s.iconUrl,n);return c.jsxs("div",{className:"flex max-h-[90vh] min-h-0 flex-col",children:[c.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto px-4 pb-6 pt-4 sm:px-5",children:[c.jsxs("div",{className:"relative mb-14",children:[c.jsxs("button",{type:"button",onClick:()=>P.current?.click(),className:"relative flex h-40 w-full items-center justify-center overflow-hidden rounded-xl bg-surface text-text-secondary dark:bg-surface-dark dark:text-text-secondary-dark",children:[nt&&c.jsx("img",{src:nt,alt:"",className:"h-full w-full object-cover"}),c.jsxs("span",{className:"absolute right-3 top-3 flex items-center gap-1.5 rounded-md bg-black/55 px-2.5 py-1.5 text-xs font-semibold text-white",children:[c.jsx(Km,{size:16})," Cover photo"]})]}),c.jsx("input",{ref:P,type:"file",accept:"image/jpeg,image/png,image/webp",className:"sr-only","aria-label":"Choose cover photo",onChange:Mn}),c.jsx("button",{type:"button",onClick:()=>w.current?.click(),className:"absolute -bottom-9 left-3 flex h-[72px] w-[72px] items-center justify-center overflow-hidden rounded-xl border-4 border-bg bg-brand text-white shadow-sm dark:border-bg-dark","aria-label":"Choose lounge icon",children:li?c.jsx("img",{src:li,alt:"",className:"h-full w-full object-cover"}):c.jsx(zc,{size:30})}),c.jsx("input",{ref:w,type:"file",accept:"image/jpeg,image/png,image/webp",className:"sr-only",onChange:jn})]}),c.jsxs("div",{className:"space-y-5",children:[c.jsxs("label",{className:"block",children:[c.jsx("span",{className:"mb-2 block text-xs font-semibold text-text dark:text-text-dark",children:"Name"}),c.jsx("input",{value:L,onChange:W=>O(W.target.value),maxLength:vp,className:gi})]}),c.jsxs("label",{className:"block",children:[c.jsx("span",{className:"mb-2 block text-xs font-semibold text-text dark:text-text-dark",children:"About"}),c.jsx("textarea",{value:q,onChange:W=>J(W.target.value),maxLength:bp,rows:10,className:`${gi} min-h-56 resize-y leading-5`})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-3 text-xs font-semibold text-text dark:text-text-dark",children:"Rules & Guidelines"}),c.jsxs("div",{className:"space-y-2",children:[ne.map(W=>{const ve=W.title.trim().length>0;return c.jsxs("div",{className:"flex items-center gap-2",children:[ve?c.jsx(es,{className:"flex-none text-brand",size:19}):c.jsx("span",{className:"h-[19px] w-[19px] flex-none rounded-full border border-border-light dark:border-border-dark"}),c.jsx("input",{value:W.title,onChange:Oe=>Qt(W.key,Oe.target.value),placeholder:"Rule Title",maxLength:100,className:`${gi} min-w-0 flex-1 py-2.5`}),c.jsx("button",{type:"button",onClick:()=>In(W.key),"aria-label":"Remove rule",className:"flex h-8 w-8 flex-none items-center justify-center text-text-dim hover:text-error",children:c.jsx(wr,{size:20})})]},W.key)}),c.jsxs("button",{type:"button",onClick:gs,className:"flex w-full items-center justify-center gap-2 rounded-xl border border-dashed border-border-light py-3 text-sm font-semibold text-text hover:border-brand dark:border-border-dark dark:text-text-dark",children:[c.jsx(Jc,{size:17})," Add Rule"]})]})]}),a&&c.jsxs("section",{children:[c.jsx("h2",{className:"mb-3 text-xs font-semibold text-text dark:text-text-dark",children:"Privacy"}),c.jsx(fp,{value:D,onSelect:se,showPremiumCallout:!d.allowed})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-3 text-xs font-semibold text-text dark:text-text-dark",children:"Categories"}),c.jsxs("label",{className:"relative block",children:[c.jsx(Wm,{size:16,className:"pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-text-dim"}),c.jsx("input",{value:ie,onChange:W=>$(W.target.value),placeholder:"Search",className:`${gi} py-2.5 pl-9`})]}),o.isLoading?c.jsx("div",{className:"py-4",children:c.jsx(je,{size:"sm",label:"Loading c
29ategories"})}):c.jsx("div",{className:"mt-3 flex flex-wrap gap-2",role:"radiogroup","aria-label":"Category",children:ae.map(W=>{const ve=re===W.slug;return c.jsx("button",{type:"button",role:"radio","aria-checked":ve,onClick:()=>F(W.slug),className:`rounded-full border px-3.5 py-1.5 text-xs transition-colors ${ve?"border-brand bg-brand text-white":"border-border-light text-text-secondary hover:border-brand/60 dark:border-border-dark dark:text-text-secondary-dark"}`,children:Ka(W.slug,W.name)},W.slug)})})]}),s.isOwner&&c.jsx("section",{className:"rounded-xl border border-border-light p-3 dark:border-border-dark",children:c.jsxs("div",{className:"flex items-start gap-3",children:[c.jsx("span",{className:"flex h-8 w-8 flex-none items-center justify-center rounded-full border border-error/30 text-error",children:c.jsx(Gm,{size:16})}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("h2",{className:"text-sm font-semibold text-text dark:text-text-dark",children:"Delete this lounge"}),c.jsx("p",{className:"mt-1 text-xs leading-4 text-text-secondary dark:text-text-secondary-dark",children:"Permanently removes the lounge, its rooms, and all posts for everyone. This can't be undone."}),c.jsx("button",{type:"button",onClick:()=>fe(!0),className:"mt-3 rounded-lg border border-border-light px-5 py-2 text-xs font-semibold text-error hover:bg-error/5 dark:border-border-dark",children:"Delete Lounge"})]})]})})]})]}),c.jsxs("div",{className:"grid flex-none grid-cols-2 gap-2 border-t border-border-light bg-bg p-4 dark:border-border-dark dark:bg-bg-dark",children:[c.jsx("button",{type:"button",onClick:e,className:"h-12 rounded-xl border border-border-light text-sm font-semibold text-text hover:bg-bg-elevated dark:border-border-dark dark:text-text-dark dark:hover:bg-bg-elevated-dark",children:"Cancel"}),c.jsx("button",{type:"button",onClick:()=>void Yt(),disabled:!tt||ke,className:"h-12 rounded-xl bg-label-primary text-sm font-semibold text-white disabled:opacity-40",children:ke?"Saving…":"Save"})]}),c.jsx(Ae,{open:Q,onOpenChange:fe,title:"Delete this lounge?",description:"This permanently removes the lounge, its rooms, posts, and messages for everyone. This action cannot be undone.",confirmLabel:"Delete Lounge",onConfirm:()=>u.mutate(n,{onSuccess:()=>{fe(!1),e(),t("/lounges",{replace:!0})}}),isPending:u.isPending}),c.jsx(Ma,{open:S.isOpen,onOpenChange:S.setOpen,onCancel:S.cancel,file:S.dialogFile,aspect:1,lockAspect:!0,title:"Crop icon",onApply:S.onApply}),c.jsx(Ma,{open:v.isOpen,onOpenChange:v.setOpen,onCancel:v.cancel,file:v.dialogFile,aspect:3,lockAspect:!0,title:"Crop banner",onApply:v.onApply})]})}function mf({loungeId:n,open:e,onOpenChange:t}){return c.jsx(qt,{open:e,onOpenChange:t,children:c.jsxs(Ht,{children:[c.jsx(zt,{className:"fixed inset-0 z-50 bg-scrim data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0"}),c.jsxs(Kt,{"aria-describedby":void 0,className:`
30            fixed z-50 bg-bg dark:bg-bg-dark text-text dark:text-text-dark
31            top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2
32            w-[94vw] max-w-md overflow-hidden rounded-2xl font-inter
33            border border-border-light dark:border-border-dark shadow-xl
34            data-[state=open]:animate-in data-[state=closed]:animate-out
35            data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0
36          `,children:[c.jsx(Wt,{className:"sr-only",children:"Edit Lounge"}),c.jsx(hf,{loungeId:n,onClose:()=>t(!1)})]})]})})}function pf({tabs:n,activeKey:e,onSelect:t}){return c.jsx("div",{role:"tablist",className:"flex gap-4 sm:gap-6 border-b border-border-light/60 dark:border-border-dark/60 px-3 sm:px-4",children:n.map(i=>{const s=i.key===e;return c.jsx("button",{type:"button",role:"tab","aria-selected":s,onClick:()=>t(i.key),className:`-mb-px whitespace-nowrap border-b-2 pb-2 text-[15px] font-bold transition-colors ${s?"border-brand text-text dark:text-text-dark":"border-transparent text-text-secondary dark:text-text-secondary-dark hover:text-text dark:hover:text-text-dark"}`,children:i.label},i.key)})})}function ff({space:n,tabs:e,activeKey:t,onSelect:i}){const s=Jm(),r=p.useRef(null),[o,a]=p.useState(!1),d=Vr("/lounges");return p.useEffect(()=>{const l=r.current;if(!l||typeof IntersectionObserver>"u")return;const u=new IntersectionObserver(([h])=>a(!h.isIntersecting));return u.observe(l),()=>u.disconnect()},[]),c.jsxs(c.Fragment,{children:[c.jsx("div",{ref:r,"aria-hidden":"true"}),c.jsxs("div",{className:`sticky top-14 md:top-0 z-10 mt-3 bg-bg/90 dark:bg-bg-dark/90 backdrop-blur transition-transform duration-200 ease-out ${s?"max-md:-translate-y-[calc(100%+3.5rem)]":"translate-y-0"}`,children:[c.jsxs("div",{className:`flex items-center justify-between overflow-hidden px-3 transition-all duration-200 ${o?"visible h-14 opacity-100":"invisible h-0 o
36pacity-0"}`,children:[c.jsx("button",{type:"button","aria-label":"Back",onClick:d,className:$n,children:c.jsx(_n,{width:18,height:18})}),c.jsx(ss,{loungeUlid:n.ulid,displayName:n.displayName??n.name,isOwner:n.isOwner,visibility:n.visibility,membershipStatus:n.membershipStatus,isTrendingExcluded:n.isTrendingExcluded,triggerClassName:$n})]}),c.jsx(pf,{tabs:e,activeKey:t,onSelect:i})]})]})}function gf({space:n}){const e=n.visibility==="hidden",t=n.membershipStatus==="invited",i=n.membershipStatus==="requested",s=e&&!t&&!i;return c.jsx("div",{className:"px-4 py-16 text-center flex flex-col items-center gap-8 font-inter",children:c.jsxs("div",{className:"flex flex-col items-center gap-3",children:[c.jsx("span",{className:"flex h-11 w-11 items-center justify-center rounded-lg bg-brand-gradient",children:c.jsx(Br,{width:24,height:24,"aria-hidden":"true"})}),c.jsxs("div",{className:"flex flex-col items-center gap-1",children:[c.jsx("h2",{className:"text-[22px] font-bold leading-[1.2] capitalize text-text dark:text-text-dark",children:dm}),c.jsx("p",{className:"max-w-sm text-sm leading-5 text-label-secondary",children:s?lm:i?um:hm})]})]})})}function vf({space:n,onLeft:e}){const t=De(a=>a.isLoggedIn),i=wc(),[s,r]=p.useState(!1),o=p.useCallback(()=>{i.mutate(n.ulid,{onSuccess:()=>{r(!1),e()}})},[i,n.ulid,e]);return c.jsxs("div",{className:"px-4 py-6 space-y-6",children:[n.bannerUrl&&c.jsx("img",{src:_r(n.bannerUrl,n.ulid)??"",alt:"",className:"w-full h-36 rounded-xl object-cover"}),c.jsxs("div",{children:[c.jsx("h2",{className:"text-lg font-bold text-text dark:text-text-dark",children:n.displayName??n.name}),n.category&&c.jsx("span",{className:"text-xs text-text-secondary dark:text-text-secondary-dark",children:n.category})]}),n.description&&c.jsx("p",{className:"text-sm text-text-secondary dark:text-text-secondary-dark whitespace-pre-wrap",children:n.description}),c.jsxs("div",{className:"flex gap-6 text-sm",children:[c.jsxs(Pe,{to:`/lounges/${n.ulid}/members`,className:"p-0 text-left rounded hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand",children:[c.jsx("span",{className:"font-semibold text-text dark:text-text-dark",children:n.memberCount.toLocaleString()})," ",c.jsx("span",{className:"text-text-secondary dark:text-text-secondary-dark",children:"members"})]}),n.onlineCount>0&&c.jsxs("div",{children:[c.jsx("span",{className:"font-semibold text-success",children:n.onlineCount})," ",c.jsx("span",{className:"text-text-secondary dark:text-text-secondary-dark",children:"online"})]})]}),t&&n.isJoined&&!n.isOwner&&c.jsx("button",{type:"button",onClick:()=>r(!0),disabled:i.isPending,className:"px-4 py-2 text-sm font-semibold rounded-lg border border-error text-error hover:bg-error/10 transition-colors disabled:opacity-50",children:i.isPending?"Leaving...":"Leave Lounge"}),c.jsx(Ae,{open:s,onOpenChange:r,title:"Leave lounge?",description:`You'll no longer be a member of ${Sh(n)}.`,confirmLabel:"Leave",onConfirm:o,isPending:i.isPending})]})}function bd({icon:n,title:e,body:t,children:i}){return c.jsxs("div",{className:"flex flex-col items-center gap-8 px-4 py-16 text-center",children:[c.jsxs("div",{className:"flex flex-col items-center gap-3",children:[c.jsx("span",{className:"flex h-11 w-11 items-center justify-center rounded-lg bg-brand-gradient text-white",children:n}),c.jsxs("div",{className:"flex flex-col items-center gap-1",children:[c.jsx("h2",{className:"text-[22px] font-bold leading-[1.2] capitalize text-text dark:text-text-dark",children:e}),c.jsx("p",{className:"max-w-sm text-sm leading-5 text-label-secondary",children:t})]})]}),i]})}function Wa({space:n}){return n.isBanned?c.jsx("div",{className:"px-4 py-12 text-center text-sm text-text-secondary dark:text-text-secondary-dark",children:Tr}):c.jsx(bd,{icon:c.jsx(Br,{width:24,height:24,"aria-hidden":"true"}),title:"Join to View Content",body:"Join this lounge to see its posts and activity."})}const bf=n=>p.createElement("svg",{width:44,height:44,viewBox:"0 0 44 44",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n},p.createElement("rect",{width:44,height:44,rx:8,fill:"url(#paint0_linear_5078_130423)"}),p.createElement("path",{d:"M23.3447 13.1299C23.5907 12.5201 24.2849 12.2253 24.8945 12.4717C25.5017 12.7171 25.7962 13.4072 25.5537 14.0156L22.9746 20.4854C22.8827 20.7163 22.9957 20.9784 23.2266 21.0703C23.4574 21.1621 23.7186 21.0491 23.8105 20.8184L25.748 15.9502C25.9823 15.3615 26.6557 15.0809 27.2383 15.3301C27.7921 15.567 28.061 16.1977 27.8496 16.7617L26.0879 21.4619C26.0013 21.6946 26.1191 21.9531 26.3516 22.04C26.5843 22.1268 26.8437 22.0089 26.9307 21.7764L27.9863 18.9463C28.2331 18.2846 28.9657 17.9436 29.6309 18.1807C30.3098 18.4229 30.6594 19.1742 30.4072 19.8496L28.0664 26.1182C27.715 27.0595 27.4386 27.8001 27.1758 28.3857C26.908 28.9824 26.6347 29.4655 26.2695 29.876C25.2315 31.0426 23.7398 31.7207 22.168 31.749C21.6164 31.7589 21.0667 31.6548 20.4297 31.4727C19.8036 31.2937 19.0474 31.0255 18.084 30.6836L17.9736 30.6445C17.0246 30.3079 16.4374 30.0995 15.9268 29.7832C15.1483 29.3009 14.503 28.6354 14.0508 27.8457C13.7538 27.3271 13.5717 26.7394 13.2803 25.7969L11.6523 20.5664C11.4588 19.9442 11.6976 19.2686 12.2393 18.9062C12.9964 18.3999 14.0277 18.6962 14.4004 19.5273L15.4736 21.9229C15.5478 22.0883 15.7143 22.1928 15.8955 22.1885C16.0767 22.184 16.2377 22.0712 16.3037 21.9023L19.4727 13.7871C19.7192 13.1555 20.4324 12.8452 21.0625 13.0957C21.6916 13.3459 21.9978 14.0594 21.7451 14.6875L19.7998 19.5176C19.7073 19.748 19.8194 20.0098 20.0498 20.1025C20.2802 20.1952 20.5419 20.0838 20.6348 19.8535L23.3447 13.1299ZM31.0137 23.0518C31.5375 22.8768 32.1043 23.1598 32.2793 23.6836C32.9858 25.7986 31.9421 28.1662 29.8457 28.9385C29.3275 29.1293 28.7524 28.8639 28.5615 28.3457C28.3709 27.8276 28.6363 27.2524 29.1543 27.0615C30.1726 26.6864 30.7687 25.4731 30.3828 24.3174C30.2079 23.7937 30.4901 23.2269 31.0137 23.0518Z",fill:"white"}),p.createElement("defs",null,p.createElement("linearGradient",{id:"paint0_linear_5078_130423",x1:22,
36y1:0,x2:22,y2:44,gradientUnits:"userSpaceOnUse"},p.createElement("stop",{stopColor:"#F7134A"}),p.createElement("stop",{offset:1,stopColor:"#BA032F"}))));function kd(n){const e=wh(n),t=p.useMemo(()=>(e.data?.pages??[]).flatMap(d=>d.data),[e.data]),i=p.useMemo(()=>new Map(t.map(d=>[d.id,d.isPinned])),[t]),s=kp(t),r=p.useMemo(()=>s.map(Rh),[s]),o=Eh(r),a=p.useMemo(()=>o.map(d=>({...d,isPinned:i.get(d.id)??!1})),[o,i]);return{query:e,posts:a}}function xd({title:n,body:e,onCreatePost:t,icon:i=c.jsx(lp,{width:24,height:24,"aria-hidden":"true"})}){return c.jsx(bd,{icon:i,title:n,body:e,children:t&&c.jsx("button",{type:"button",onClick:t,className:"flex h-[52px] items-center justify-center rounded-lg bg-label-primary px-5 text-[17px] leading-[18px] tracking-[-0.23px] font-semibold text-white transition-opacity",children:"Create Post"})})}function yd({startedAt:n,className:e}){const{liveSinceLabel:t,elapsedLabel:i}=Ph(n);return!t||!i?null:c.jsxs("p",{className:`text-xs leading-4 text-text-secondary dark:text-text-secondary-dark${e?` ${e}`:""}`,children:["Live since ",t," · ",i," elapsed"]})}function Cd({name:n,status:e}){const t=Math.max(0,e.participantCount-e.speakerCount);return c.jsxs("div",{className:"rounded-2xl border border-border-light dark:border-border-dark bg-bg-elevated dark:bg-bg-elevated-dark p-4",children:[c.jsx(Ir,{}),c.jsx("p",{className:"mt-2 truncate font-bold text-text dark:text-text-dark",children:e.topic||n}),c.jsx(yd,{startedAt:e.startedAt,className:"mt-1"}),c.jsxs("div",{className:"mt-2 flex items-center gap-2 text-xs text-text-secondary dark:text-text-secondary-dark",children:[e.speakerAvatars.length>0&&c.jsx("span",{className:"flex -space-x-2",children:e.speakerAvatars.map(i=>c.jsx("img",{src:i,alt:"",className:"h-7 w-7 rounded-full object-cover ring-2 ring-bg dark:ring-bg-dark",loading:"lazy"},i))}),c.jsxs("span",{children:[Li(e.speakerCount)," ",e.speakerCount===1?"speaker":"speakers"," · ",Li(t)," listening"]})]})]})}const kf=3,xf=5;function Rs({children:n}){return c.jsx("h2",{className:"px-4 pb-2 pt-5 text-[18px] font-bold leading-[1.2] text-text dark:text-text-dark",children:n})}function yf({loungeId:n,canModerate:e,canPin:t,canPost:i,onCreatePost:s,onOpenPosts:r}){const{query:o,posts:a}=kd(n),d=p.useMemo(()=>Nh(a,kf),[a]),l=p.useMemo(()=>a.filter(k=>!k.isPinned).slice(0,xf),[a]),u=De(k=>k.user?.badges),h=Et("voice_rooms",u),m=$i(n),f=p.useMemo(()=>h?(m.data?.data??[]).filter(k=>k.type==="voice"):[],[m.data,h]),C=Rc(n,{enabled:h&&i&&f.length>0}),x=i?f.map(k=>({channel:k,status:C[k.ulid]})).filter(k=>k.status?.isLive):[],S=id({loungePin:{loungeId:n,canPin:t}}),v=sd();if(o.isLoading&&a.length===0)return c.jsx(Mr,{count:3});if(o.isError)return c.jsx("div",{className:"p-8 text-center text-text-secondary dark:text-text-secondary-dark",children:c.jsx("p",{children:"Couldn't load this lounge's posts. Try refreshing."})});if(a.length===0&&x.length===0)return c.jsx(xd,{title:e?"Welcome To Your New Lounge":"No Posts Yet",body:e?"Start building your community by creating a post, adding rooms, or inviting your first members.":"Be the first to share something with this lounge.",onCreatePost:i?s:void 0,icon:e?c.jsx(bf,{width:44,height:44,"aria-hidden":"true"}):void 0});const g=k=>c.jsx("li",{children:c.jsx(Zc,{post:k,variant:"lounge",onOpenActions:S.openPostActions,onOpenCommentCompose:()=>v.openForPost(k.id),onOpenCommentReply:v.openForReply,inlineReply:!0})},`${k.repostId??""}-${k.id}`);return c.jsxs(c.Fragment,{children:[d.length>0&&c.jsxs("section",{children:[c.jsx(Rs,{children:"Pinned"}),c.jsx("ul",{"aria-label":"Pinned posts",children:d.map(g)})]}),x.length>0&&c.jsxs("section",{children:[c.jsx(Rs,{children:"Happening Now"}),c.jsx("div",{className:"flex flex-col gap-3 px-4",children:x.map(({channel:k,status:T})=>c.jsx(Pe,{to:`/lounges/${n}/voice/${k.ulid}`,className:"block",children:c.jsx(Cd,{name:k.name,status:T})},k.ulid))})]}),l.length>0&&c.jsxs("section",{children:[c.jsxs("div",{className:"flex items-center justify-between pr-4",children:[c.jsx(Rs,{children:"Latest Posts"}),c.jsx("button",{type:"button",onClick:r,className:"text-sm font-medium text-brand hover:underline",children:"See all"})]}),c.jsx("ul",{"aria-label":"Latest posts",children:l.map(g)})]}
36),c.jsx(ed,{postActions:S,commentModal:v})]})}function Cf({loungeId:n,canPin:e,canPost:t,contentQuery:i="",onCreatePost:s}){const{query:r,posts:o}=kd(n),a=p.useMemo(()=>_h(o),[o]),d=i.trim().toLowerCase(),l=p.useMemo(()=>d?a.filter(f=>f.content.toLowerCase().includes(d)||f.author.username?.toLowerCase().includes(d)||f.author.displayName?.toLowerCase().includes(d)):a,[a,d]),u=id({loungePin:{loungeId:n,canPin:e}}),h=sd(),m=$c({fetchNextPage:r.fetchNextPage,hasNextPage:r.hasNextPage,isFetchingNextPage:r.isFetchingNextPage,rootMargin:"1200px"});return r.isLoading&&l.length===0?c.jsx(Mr,{}):r.isError?c.jsx("div",{className:"p-8 text-center text-text-secondary dark:text-text-secondary-dark",children:c.jsx("p",{children:"Couldn't load posts. Try refreshing."})}):d&&l.length===0&&a.length>0?c.jsx("div",{className:"p-8 text-center text-text-secondary dark:text-text-secondary-dark",children:c.jsx("p",{children:"No posts match your search."})}):l.length===0?c.jsx(xd,{title:"No Posts Yet",body:"Posts shared in this Lounge will appear here. Start the conversation with an update, announcement, question, or welcome message.",onCreatePost:t?s:void 0,icon:c.jsx($m,{width:44,height:44,"aria-hidden":"true"})}):c.jsxs(c.Fragment,{children:[c.jsx("ul",{"aria-label":"Lounge posts",children:l.map(f=>c.jsx("li",{children:c.jsx(Zc,{post:f,variant:"lounge",onOpenActions:u.openPostActions,onOpenCommentCompose:()=>h.openForPost(f.id),onOpenCommentReply:h.openForReply,inlineReply:!0})},`${f.repostId??""}-${f.id}`))}),c.jsx("div",{ref:m,className:"h-px","aria-hidden":"true"}),r.isFetchingNextPage&&c.jsx(xp,{inline:!0}),!r.hasNextPage&&c.jsx("div",{className:"py-8 text-center text-xs text-text-secondary dark:text-text-secondary-dark",children:"You're all caught up."}
36),c.jsx(ed,{postActions:u,commentModal:h})]})}function Tf({item:n,loungeId:e}){const t=Sc(),[i,s]=p.useState(!1),[r,o]=p.useState(!1),a=ld(n.contentType),d=n.channelMessageContext?.channelId??null,l=n.flagStatus==="kept",u=ud(n.contentType),h=p.useCallback((C,x,S)=>{t.mutate({loungeId:e,contentId:n.ulid,postFlagId:n.postFlagId,action:C,channelId:d,roomId:n.roomId??null},{onSuccess:()=>{z.success(x),S?.()},onError:()=>z.error("Couldn't apply moderation. Try again.")})},[t,e,n.ulid,n.postFlagId,n.roomId,d]),m=p.useCallback(()=>{h("dismiss-flag","Flag kept",()=>o(!1))},[h]),f=p.useCallback(()=>{h("hide",u.success,()=>s(!1))},[h,u.success]);return c.jsxs("div",{className:"mt-3 pt-3 border-t border-border-light/60 dark:border-border-dark/60",onClick:C=>C.stopPropagation(),children:[l?c.jsxs("p",{className:"flex items-center gap-1.5 text-sm font-semibold text-text-secondary dark:text-text-secondary-dark",children:[c.jsx(es,{size:16,className:"text-success","aria-hidden":"true"}),"Kept"]}):c.jsxs("div",{className:"flex flex-wrap gap-2",children:[a&&c.jsx(Oa,{label:"Remove",tone:"danger",onClick:()=>s(!0),disabled:t.isPending,loading:t.isPending&&t.variables?.action==="hide"}),c.jsx(Oa,{label:"Keep",onClick:()=>o(!0),disabled:t.isPending,loading:t.isPending&&t.variables?.action==="dismiss-flag"})]}),a&&c.jsx(Ae,{open:i,onOpenChange:s,title:u.title,description:u.description,confirmLabel:"Remove",destructive:!0,onConfirm:f,isPending:t.isPending&&t.variables?.action==="hide"}),c.jsx(Ae,{open:r,onOpenChange:o,title:"Keep content",description:"Leaves the content up. The report stays in the queue marked Kept.",confirmLabel:"Keep",onConfirm:m,isPending:t.isPending&&t.variables?.action==="dismiss-flag"})]})}function Sf(n){switch(n){case"channel_message":return"Message";case"lounge":case"user":return"Lounge report";default:return n}}function wf({item:n,loungeId:e}){const t=n.author,i=t?.displayName||n.username,s=t?.avatarUrl??"",r=t?.badges??[],o=n.channelMessageContext,a=o?.channelName??o?.channelId,d=n.violationType??n.channelMessageContext?.violationType??n.violations?.[0]?.name??null,l=n.reporterUsername??o?.reporterUsername??null;return c.jsxs("article",{className:"border-b border-border-light/60 dark:border-border-dark/60 px-4 py-3",children:[c.jsxs("div",{className:"flex items-start gap-3",children:[s?c.jsx("img",{src:s,alt:"",className:"w-10 h-10 rounded-full object-cover flex-shrink-0",loading:"lazy"}):c.jsx("div",{className:"w-10 h-10 rounded-full bg-bg-elevated dark:bg-bg-elevated-dark flex items-center justify-center text-text-secondary dark:text-text-secondary-dark font-semibold flex-shrink-0",children:i?.[0]?.toUpperCase()??"?"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("header",{className:"flex items-start gap-2 text-sm",children:[c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[c.jsx(Ye,{className:"font-semibold text-text dark:text-text-dark",children:i}),c.jsx(Zi,{badges:r,size:14}),c.jsx("span",{className:"text-text-secondary dark:text-text-secondary-dark",children:"·"}),c.jsx("time",{className:"text-text-secondary dark:text-text-secondary-dark text-xs",children:Qi(n.flaggedAt)})]}),c.jsxs(Ye,{as:"span",className:"block text-text-secondary dark:text-text-secondary-dark text-xs",children:["@",n.username]})]}),c.jsx("span",{className:"flex-shrink-0 text-[10px] font-medium uppercase tracking-wider px-2 py-0.5 rounded-full bg-bg-elevated dark:bg-bg-elevated-dark text-text-secondary dark:text-text-secondary-dark",children:Sf(n.contentType)})]}),a&&c.jsxs("p",{className:"mt-1 text-xs text-text-secondary dark:text-text-secondary-dark",children:["#",a]}),n.body?c.jsx("p",{className:"mt-2 text-sm text-text dark:text-text-dark whitespace-pre-wrap break-words",children:n.body}):n.contentType==="user"||n.contentType==="lounge"?c.jsx("p",{className:"mt-2 text-sm text-text-secondary dark:text-text-secondary-dark",children:"This lounge was reported."}):null,c.jsx(dd,{item:n}),(l||d)&&c.jsxs("p",{className:"mt-2 text-xs text-text-dim dark:text-text-dim-dark",children:[l&&c.jsxs(c.Fragment,{children:["Reported by ",c.jsxs("span",{children:["@",l]})]}),l&&d&&c.jsx("span",{className:"mx-1",children:"·"}),d&&c.jsx("span",{className:"text-error",children:mm(d)})]})]})]}),c.jsx(Tf,{item:n,loungeId:e})]})}function Td({loungeId:n,queueQuery:e}){const t=p.useMemo(()=>e.data?.pages.flatMap(s=>s.data)??[],[e.data]),i=$c({fetchNextPage:e.fetchNextPage,hasNextPage:e.hasNextPage,isFetchingNextPage:e.isFetchingNextPage,rootMargin:"1200px"});return e.isLoading&&t.length===0?c.jsx(Mr,{}):e.isError?c.jsx("div",{className:"p-8 text-center text-text-secondary dark:text-text-secondary-dark",children:c.jsx("p",{children:"Couldn't load reports. Try refreshing."})}):t.length===0?c.jsx("div",{className:"p-8 text-center text-text-secondary dark:text-text-secondary-dark",children:c.jsx("p",{children:"No open reports."})}):c.jsxs(c.Fragment,{children:[t.map(s=>c.jsx(wf,{item:s,loungeId:n},`${s.contentType}:${s.ulid}:${s.postFlagId}`)),c.jsx("div",{ref:i,className:"h-4","aria-hidden":"true"}),e.isFetchingNextPage&&c.jsx("div",{className:"flex justify-center py-4",children:c.jsx(je,{size:"sm",label:"Loading more reports"})})]})}function Rf({loungeId:n,canModerate:e}){const t=Nn(n,e);return c.jsx(Td,{loungeId:n,queueQuery:t})}function Ga({emoji:n,title:e,description:t,selected:i,onSelect:s}){return c.jsxs("button",{type:"button",onClick:s,"aria-pressed":i,className:`relative w-full rounded-2xl border p-4 text-left transition-colors ${i?"border-brand":"border-border-light dark:border-border-dark hover:border-text-secondary/40"}`,children:[c.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-lg bg-bg-elevated dark:bg-bg-elevated-dark text-lg","aria-hidden":"true",children:n}),c.jsx("span",{"aria-hidden":"true",className:`absolute right-4 top-4 flex h-6 w-6 items-center justify-center rounded-full ${i?"bg-brand text-white":"border border-border-light dark:border-border-dark"}`,children:i&&c.jsx(Qm,{size:14})}),c.jsx("span",{className:"mt-3 block text-lg font-bold text-text dark:text-text-dark",children:e}),c.jsx("span",{className:"mt-1 block text-sm leading-5 text-text-secondary dark:text-text-secondary-dark",children:t})]})}function Ef({spaceId:n,initialType:e,open:t,onOpenChange:i}
36){const[s,r]=p.useState("type"),[o,a]=p.useState(e),[d,l]=p.useState(""),[u,h]=p.useState(""),m=Ih(),f=lt(),C=De(w=>w.user?.badges),x=Et("voice_rooms",C),S=nd("lounge_audio_rooms"),v=x?o:"text",g=vd(d),k=()=>{if(!S.allowed){S.requestUpgrade();return}a("voice")},T=()=>{if(v==="voice"&&!S.allowed){S.requestUpgrade();return}r("details")},b=()=>{if(v==="voice"&&!S.allowed){S.requestUpgrade();return}if(g.length<Js){z.error("Room name must be at least 2 characters.");return}m.mutate({spaceId:n,input:{name:g,type:v,description:u.trim()}},{onSuccess:w=>{if(z.success("Room created"),i(!1),v==="voice"){const P=w,E=P?.data?.ulid??P?.ulid;E&&f(`/lounges/${n}/voice/${E}?goLive=1`)}},onError:w=>z.error(Je(w,"Couldn't create the room. Try again."))})};return c.jsx(qt,{open:t,onOpenChange:i,children:c.jsxs(Ht,{children:[c.jsx(zt,{className:"fixed inset-0 z-50 bg-scrim data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0"}),c.jsxs(Kt,{className:`
37            fixed z-50 bg-bg dark:bg-bg-dark text-text dark:text-text-dark
38            top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2
39            w-[90vw] max-w-md rounded-2xl p-5 font-inter
40            border border-border-light dark:border-border-dark shadow-xl
41            data-[state=open]:animate-in data-[state=closed]:animate-out
42            data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0
43          `,"aria-describedby":void 0,children:[c.jsx(Wt,{className:"pb-4 text-center text-lg font-bold",children:"Create Room"}),s==="type"?c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex flex-col gap-3",children:[c.jsx(Ga,{emoji:"✏️",title:"Chat Room",description:"Create dedicated spaces for ongoing conversations, updates, questions, and community discussions.",selected:v==="text",onSelect:()=>a("text")}),x&&c.jsx(Ga,{emoji:"🎙️",title:"Audio Room",description:"Start or join live voice conversations where people can listen, speak, and connect in real time.",selected:v==="voice",onSelect:k})]}),c.jsxs("div",{className:"mt-5 flex gap-3",children:[c.jsx("button",{type:"button",onClick:()=>i(!1),className:$s,children:"Cancel"}),c.jsx("button",{type:"button",onClick:T,className:Qs,children:"Continue"})]})]}):c.jsxs(c.Fragment,{children:[c.jsx(gd,{name:d,onNameChange:l,description:u,onDescriptionChange:h}),c.jsxs("div",{className:"mt-5 flex gap-3",children:[c.jsx("button",{type:"button",onClick:()=>r("type"),className:$s,children:"Cancel"}),c.jsxs("button",{type:"button",onClick:b,disabled:m.isPending||g.length<Js,className:Qs,children:[m.isPending&&c.jsx("span",{className:"inline-block h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent","aria-hidden":"true"}),"Create"]})]})]})]})]})})}function Pf({channel:n,onOpen:e}){const t=p.useCallback(i=>{i.preventDefault(),i.stopPropagation(),e(n,i.currentTarget)},[n,e]);return c.jsx("button",{type:"button",onClick:t,"aria-label":`Options for ${n.name}`,className:"flex h-7 w-7 flex-none items-center justify-center rounded-full text-text-secondary dark:text-text-secondary-dark transition-colors hover:bg-bg-elevated dark:hover:bg-bg-elevated-dark hover:text-text dark:hover:text-text-dark",children:c.jsx(di,{width:16,height:16})})}function Ja({children:n,onCreate:e,createLabel:t}){return c.jsxs("div",{className:"flex items-center justify-between px-4 pb-1 pt-4",children:[c.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wider text-text-secondary dark:text-text-secondary-dark",children:n}),e&&c.jsx("button",{type:"button","aria-label":t,onClick:e,className:"flex h-6 w-6 items-center justify-center rounded-full text-text-secondary dark:text-text-secondary-dark transition-colors hover:bg-bg-elevated dark:hover:bg-bg-elevated-dark hover:text-text dark:hover:text-text-dark",children:c.jsx(Jc,{size:18})})]})}function Nf({loungeId:n,channel:e,menu:t}){return c.jsxs("div",{className:"flex items-center gap-2 border-b border-border-light/60 dark:border-border-dark/60 px-4 transition-colors hover:bg-bg-elevated dark:hover:bg-bg-elevated-dark",children:[c.jsxs(Pe,{to:`/lounges/${n}/rooms/${e.ulid}`,className:"flex min-w-0 flex-1 items-center gap-2 py-3",children:[c.jsx("span",{className:"flex-none text-text-secondary dark:text-text-secondary-dark",children:"#"}),c.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-text dark:text-text-dark",children:e.name}),e.unreadCount>0&&c.jsx("span",{className:"flex h-[18px] min-w-[18px] flex-none items-center justify-center rounded-full bg-brand px-1 text-[10px] font-bold text-white",children:e.unreadCount>99?"99+":e.unreadCount})]}),t]})}function $a({kind:n,canCreate:e,onCreate:t}){const i=n==="chat",s=i?"Create a Chat Room":"Create an Audio Room",r=i?"Ongoing conversations, updates, questions, and community discussions.":"Start or join live voice conversations where people can listen, speak, and connect in real time.",o=i?Ym:ln;return e?c.jsxs("div",{className:"mx-4 mt-2 flex items-center gap-3 rounded-xl border border-border-light bg-bg p-4 dark:border-border-dark dark:bg-bg-dark",children:[c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("h4",{className:"text-base font-bold text-text dark:text-text-dark",children:s}),c.jsx("p",{className:"mt-1 text-sm leading-5 text-text-secondary dark:text-text-secondary-dark",children:r}),c.jsx("button",{type:"button",onClick:t,"aria-label":i?"Create a chat room":"Create an audio room",className:"mt-3 rounded-lg bg-label-primary px-4 py-2.5 text-sm font-semibold text-white transition-opacity hover:opacity-90",children:"Create Room"})]}),c.jsx("span",{className:"flex h-16 w-16 flex-none -rotate-3 items-center justify-center rounded-2xl border-2 border-brand bg-brand-pale text-brand shadow-sm dark:bg-brand-pale-dark",children:c.jsx(o,{size:29,"aria-hidden":"true"})})]}):c.jsxs("div",{className:"flex flex-col items-center px-4 py-7 text-text-secondary dark:text-text-secondary-dark",children:[c.jsx(o,{size:31,"aria-hidden":"true"}),c.jsxs("p",{className:"mt-2 text-sm",children:["No ",i?"chat":"audio"," rooms yet."]})]})}function _f({space:n,canCreate:e,canManageRooms:t,isMember:i}
43){const[s,r]=p.useState(null),[o,a]=p.useState(null),[d,l]=p.useState(!1),[u,h]=p.useState(null),m=p.useCallback((O,q)=>{a(O),h(q),l(!0)},[]),{roomOptions:f,roomDialogs:C}=Fr({spaceId:n.ulid,channel:o,canManage:t}),x=p.useCallback(O=>t?c.jsx(Pf,{channel:O,onOpen:m}):null,[t,m]),S=p.useCallback(()=>r("text"),[]),v=p.useCallback(()=>r("voice"),[]),g=p.useCallback(O=>{O||r(null)},[]),k=De(O=>O.user?.badges),T=Et("voice_rooms",k),b=$i(n.ulid),w=p.useMemo(()=>b.data?.data??[],[b.data]),P=p.useMemo(()=>T?w:w.filter(O=>O.type!=="voice"),[w,T]),E=p.useMemo(()=>P.filter(O=>O.type==="text"||O.type==="announcement"),[P]),_=p.useMemo(()=>T?P.filter(O=>O.type==="voice"):[],[P,T]),N=!!n.isJoined||!!n.isOwner,L=Rc(n.ulid,{enabled:T&&N&&_.length>0});return b.isLoading?c.jsx("div",{className:"flex justify-center py-12",children:c.jsx(je,{size:"lg",label:"Loading rooms"})}):i?c.jsxs("div",{className:"pb-6",children:[c.jsxs("section",{"aria-labelledby":"chat-rooms-heading",children:[c.jsx(Ja,{onCreate:e&&E.length>0?S:void 0,createLabel:"Create chat room",children:c.jsx("span",{id:"chat-rooms-heading",children:"Chat Rooms"})}),E.length>0?c.jsx("nav",{"aria-label":"Chat rooms",children:E.map(O=>c.jsx(Nf,{loungeId:n.ulid,channel:O,menu:x(O)},O.ulid))}):c.jsx($a,{kind:"chat",canCreate:e,onCreate:S})]}),T&&c.jsxs("section",{"aria-labelledby":"audio-rooms-heading",children:[c.jsx(Ja,{onCreate:e&&_.length>0?v:void 0,createLabel:"Create audio room",children:c.jsx("span",{id:"audio-rooms-heading",children:"Audio Rooms"})}),_.length>0?c.jsx("div",{className:"flex flex-col gap-3 px-4 pt-1",children:_.map(O=>{const q=L[O.ulid],J=`/lounges/${n.ulid}/voice/${O.ulid}`;if(q?.isLive){const se=c.jsx(Cd,{name:O.name,status:q});return c.jsxs("div",{className:"flex items-start gap-2",children:[N?c.jsx(Pe,{to:J,className:"block min-w-0 flex-1",children:se}):c.jsx("div",{className:"block min-w-0 flex-1",children:se}),x(O)]},O.ulid)}const D="flex min-w-0 flex-1 items-center gap-2 py-1.5 text-sm text-text-secondary dark:text-text-secondary-dark",K=c.jsxs(c.Fragment,{children:[c.jsx(ln,{size:16,"aria-hidden":"true"}),c.jsx("span",{className:"min-w-0 flex-1 truncate font-semibold text-text dark:text-text-dark",children:O.name})]});return c.jsxs("div",{className:`flex items-center gap-2 rounded-lg${N?" transition-colors hover:bg-bg-elevated dark:hover:bg-bg-elevated-dark":""}`,children:[N?c.jsx(Pe,{to:J,className:D,children:K}):c.jsx("div",{className:D,children:K}),x(O)]},O.ulid)})}):c.jsx($a,{kind:"audio",canCreate:e,onCreate:v})]}),s&&c.jsx(Ef,{spaceId:n.ulid,initialType:s,open:!0,onOpenChange:g}),c.jsx(Rr,{open:d,onOpenChange:l,options:f,triggerEl:u}),C]}):n.isBanned?c.jsx("div",{className:"px-4 py-12 text-center text-sm text-text-secondary dark:text-text-secondary-dark",children:Tr}):c.jsx("div",{children:P.length>0?c.jsx("ul",{className:"px-4 pt-4","aria-label":"Channels",children:P.map(O=>c.jsxs("li",{className:"border-b border-border-light/60 dark:border-border-dark/60 py-2.5 text-sm text-text-secondary dark:text-text-secondary-dark",children:["#",O.name]},O.ulid))}):c.jsx("p",{className:"px-4 py-12 text-center text-sm text-text-secondary dark:text-text-secondary-dark",children:"Join this lounge to access its rooms."})})}function If({space:n,activeKey:e,roles:t,isRestricted:i,isMember:s,contentQuery:r="",onCreatePost:o,onOpenPosts:a,onLeft:d}){if(i)return c.jsx(gf,{space:n});const l=n.isJoined||n.isOwner;switch(e){case"home":return s?c.jsx(yf,{loungeId:n.ulid,canModerate:t.canModerate,canPin:t.canPin,canPost:l,onCreatePost:o,onOpenPosts:a}):c.jsx(Wa,{space:n});case"posts":return s?c.jsx(Cf,{loungeId:n.ulid,canPin:t.canPin,canPost:l,contentQuery:r,onCreatePost:o}):c.jsx(Wa,{space:n});case"rooms":return c.jsx(_f,{space:n,canCreate:t.canCreateRoom,canManageRooms:t.canModerate,isMember:s});case"about":return c.jsx(vf,{space:n,onLeft:d});case"reports":return t.canModerate?c.jsx(Rf,{loungeId:n.ulid,canModerate:t.canModerate}):null}}function Mf(n){const[e,t]=Uc(),i=p.useMemo(()=>Mh({canModerate:n}),[n]),s=i[jh(e.get("tab")??void 0,i)].key,r=p.useCallback(o=>{t(a=>{const d=new URLSearchParams(a);return d.set("tab",o),d},{replace:!0})},[t]);return{tabs:i,activeKey:s,setTab:r}}function jf(){is("LoungeDetailRedesign");const{spaceId:n=""}=ci(),e=lt(),t=Sr(),i=Et("hidden_lounges"),s=oi(n),r=s.data?.data??null,o=td(),a=r?.myRole??null,d=!!r?.isOwner||a==="admin",u={isAdmin:d,canModerate:d||a==="moderator",canPin:d,canCreateRoom:d},h=r?vn(r.visibility):"public",m=r?.membershipStatus==="requested"||r?.membershipStatus==="invited",f=!!r&&!r.isJoined&&!r.isOwner&&!o&&(m||h==="private"||i&&h==="hidden"),C=!!r&&(r.isJoined||r.isOwner||o),{tabs:x,activeKey:S,setTab:v}=Mf(u.canModerate),[g,k]=p.useState(""),T=p.useCallback(ne=>{k(ne),ne&&v("posts")},[v]),b=p.useCallback(()=>
43{if(!r)return;const ne=r.displayName||r.name;e({pathname:"/compose",search:`?loungeId=${r.ulid}&loungeName=${encodeURIComponent(ne)}`},{state:{background:t}})},[e,r,t]),w=Vr("/lounges"),P=p.useCallback(()=>v("posts"),[v]),[E,_]=p.useState(!1),N=p.useCallback(()=>_(!0),[]),[L,O]=p.useState(!1),q=p.useCallback(()=>{f||O(!0)},[f]),J=p.useCallback(ne=>{ne||O(!1)},[]),[D,K]=p.useState(!1),se=p.useCallback(()=>{f||K(!0)},[f]),[re,F]=p.useState(!1),ie=p.useCallback(()=>F(!0),[]),$=p.useCallback(ne=>{if(ne==="about"){if(f){v(ne);return}K(!0);return}if(ne==="reports"){_(!0);return}v(ne)},[f,v]);return s.isLoading?c.jsx("div",{className:"flex items-center justify-center min-h-[60vh]",children:c.jsx(je,{size:"lg",label:"Loading lounge"})}):s.isError||!r?c.jsx(rs,{}):c.jsxs("div",{className:"flex mx-auto font-inter",children:[c.jsxs("div",{className:"flex-1 min-w-0 max-w-[600px] md:border-r border-border-light/60 dark:border-border-dark/60",children:[c.jsx(lf,{space:r,canModerate:u.canModerate,isAdmin:u.isAdmin,isMember:C,onOpenReports:N,onOpenMembers:q,onEdit:ie}),c.jsx(ff,{space:r,tabs:x,activeKey:S,onSelect:$}),c.jsx(If,{space:r,activeKey:S,roles:u,isRestricted:f,isMember:C,contentQuery:g,onCreatePost:b,onOpenPosts:P,onLeft:w})]}),c.jsx(Ur,{space:r,isAdmin:u.isAdmin,isRestricted:f,isMember:C,onOpenAbout:se,onOpenMembers:q,onOpenReports:N,contentQuery:g,onContentQueryChange:T}),D&&!f&&c.jsx(Or,{space:r,open:!0,onOpenChange:K}),re&&c.jsx(mf,{loungeId:r.ulid,open:!0,onOpenChange:F}),L&&!f&&c.jsx(Lr,{space:r,open:!0,onOpenChange:J}),c.jsx(Dr,{loungeId:r.ulid,enabled:u.canModerate,open:E,onOpenChange:_})]})}function Of(){is("LoungeReportsQueue");const{spaceId:n=""}=ci(),e=oi(n),t=e.data?.data??null,i=t?.myRole??null,s=!!t?.isOwner||i==="admin"||i==="moderator",r=Nn(n,s),o=p.useMemo(()=>`/lounges/${n}`,[n]);return e.isLoading?c.jsx("div",{className:"flex items-center justify-center min-h-[60vh]",children:c.jsx(je,{size:"lg"})}):e.isError||!t?c.jsx(rs,{}):e.isSuccess&&!s?c.jsx(ei,{to:o,replace:!0}):c.jsxs("div",{className:"flex flex-col h-[calc(100dvh-3.5rem)] md:h-dvh max-w-[600px] mx-auto font-inter",children:[c.jsxs("header",{className:"sticky top-0 z-10 flex items-center gap-2 px-2 py-3 bg-bg/90 dark:bg-bg-dark/90 backdrop-blur border-b border-border-light/60 dark:border-border-dark/60",children:[c.jsx(Pe,{to:o,"aria-label":"Back to lounge",className:"p-2 rounded-full hover:bg-bg-elevated dark:hover:bg-bg-elevated-dark",children:c.jsx(_n,{width:20,height:20})}),c.jsx("h1",{className:"text-xl font-bold text-text dark:text-text-dark",children:"Reports"})]}),c.jsx("div",{className:"flex-1 overflow-y-auto",children:c.jsx(Td,{loungeId:n,queueQuery:r})})]})}var Qa={};function Lf(n,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(i){if(i!=="default"&&!(i in n)){var s=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(n,i,s.get?s:{enumerable:!0,get:function(){return t[i]}})}})}),Object.freeze(n)}var Af=Object.defineProperty,Df=(n,e,t)=>e in n?Af(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Ya=(n,e,t)=>Df(n,typeof e!="symbol"?e+"":e,t);class Be{constructor(){Ya(this,"_locking"),Ya(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e;const t=new Promise(s=>e=()=>{this._locks-=1,s()}),i=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),i}}function xe(n,e){if(!n)throw new Error(e)}const Uf=34028234663852886e22,Ff=-34028234663852886e22,Vf=4294967295,Bf=2147483647,qf=-2147483648;function Ci(n){if(typeof n!="number")throw new Error("invalid int 32: "+typeof n);if(!Number.isInteger(n)||n>Bf||n<qf)throw new Error("invalid int 32: "+n)}function Ys(n){if(typeof n!="number")throw new Error("invalid uint 32: "+typeof n);if(!Number.isInteger(n)||n>Vf||n<0)throw new Error("invalid uint 32: "+n)}function Sd(n){if(typeof n!="number")throw new Error("invalid float 32: "+typeof n);if(Number.isFinite(n)&&(n>Uf||n<Ff))throw new Error("invalid float 32: "+n)}const wd=Symbol("@bufbuild/protobuf/enum-type");function Hf(n){const e=n[wd];return xe(e,"missing enum type on enum object"),e}function Rd(n,e,t,i){n[wd]=Ed(e,t.map(s=>({no:s.no,name:s.name,localName:n[s.no]})))}function Ed(n,e,t){const i=Object.create(null),s=Object.create(null),r=[];for(const o of e){const a=Pd(o);r.push(a),i[o.name]=a,s[o.no]=a}return{typeName:n,values:r,findName(o){return i[o]},findNumber(o){return s[o]}}}function zf(n,e,t){const i={};for(const s of e){const r=Pd(s);i[r.localName]=r.no,i[r.no]=r.localName}return Rd(i,n,e),i}function Pd(n){return"localName"in n?n:Object.assign(Object.assign({},n),{localName:n.name})}class qr{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const i=this.getType(),s=i.runtime.bin,r=s.makeReadOptions(t);return s.readMessage(this,r.readerFactory(e),e.byteLength,r),this}fromJson(e,t){const i=this.getType(),s=i.runtime.json,r=s.makeReadOptions(t);return s.readMessage(i,e,r,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(s){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(s instanceof Error?s.message:String(s)))}return this.fromJson(i,t)}toBinary(e){const t=this.getType(),i=t.runtime.bin,s=i.makeWriteOptions(e),r=s.writerFactory();return i.writeMessage(this,r,s),r.finish()}
vendor: 10,502 bytes, line 43
43toJson(e){const t=this.getType(),i=t.runtime.json,s=i.makeWriteOptions(e);return i.writeMessage(this,s)}toJsonString(e){var t;const i=this.toJson(e);return JSON.stringify(i,null,(t=e?.prettySpaces)!==null&&t!==void 0?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function Kf(n,e,t,i){var s;const r=(s=i?.localName)!==null&&s!==void 0?s:e.substring(e.lastIndexOf(".")+1),o={[r]:function(a){n.util.initFields(this),n.util.initPartial(a,this)}}[r];return Object.setPrototypeOf(o.prototype,new qr),Object.assign(o,{runtime:n,typeName:e,fields:n.util.newFieldList(t),fromBinary(a,d){return new o().fromBinary(a,d)},fromJson(a,d){return new o().fromJson(a,d)},fromJsonString(a,d){return new o().fromJsonString(a,d)},equals(a,d){return n.util.equals(o,a,d)}}),o}function Wf(){let n=0,e=0;for(let i=0;i<28;i+=7){let s=this.buf[this.pos++];if(n|=(s&127)<<i,(s&128)==0)return this.assertBounds(),[n,e]}let t=this.buf[this.pos++];if(n|=(t&15)<<28,e=(t&112)>>4,(t&128)==0)return this.assertBounds(),[n,e];for(let i=3;i<=31;i+=7){let s=this.buf[this.pos++];if(e|=(s&127)<<i,(s&128)==0)return this.assertBounds(),[n,e]}throw new Error("invalid varint")}function Es(n,e,t){for(let r=0;r<28;r=r+7){const o=n>>>r,a=!(!(o>>>7)&&e==0),d=(a?o|128:o)&255;if(t.push(d),!a)return}const i=n>>>28&15|(e&7)<<4,s=e>>3!=0;if(t.push((s?i|128:i)&255),!!s){for(let r=3;r<31;r=r+7){const o=e>>>r,a=!!(o>>>7),d=(a?o|128:o)&255;if(t.push(d),!a)return}t.push(e>>>31&1)}}const Ti=4294967296;function Za(n){const e=n[0]==="-";e&&(n=n.slice(1));const t=1e6;let i=0,s=0;function r(o,a){const d=Number(n.slice(o,a));s*=t,i=i*t+d,i>=Ti&&(s=s+(i/Ti|0),i=i%Ti)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),e?_d(i,s):Hr(i,s)}function Gf(n,e){let t=Hr(n,e);const i=t.hi&2147483648;i&&(t=_d(t.lo,t.hi));const s=Nd(t.lo,t.hi);return i?"-"+s:s}function Nd(n,e){if({lo:n,hi:e}=Jf(n,e),e<=2097151)return String(Ti*e+n);const t=n&16777215,i=(n>>>24|e<<8)&16777215,s=e>>16&65535;let r=t+i*6777216+s*6710656,o=i+s*8147497,a=s*2;const d=1e7;return r>=d&&(o+=Math.floor(r/d),r%=d),o>=d&&(a+=Math.floor(o/d),o%=d),a.toString()+Xa(o)+Xa(r)}function Jf(n,e){return{lo:n>>>0,hi:e>>>0}}function Hr(n,e){return{lo:n|0,hi:e|0}}function _d(n,e){return e=~e,n?n=~n+1:e+=1,Hr(n,e)}const Xa=n=>{const e=String(n);return"0000000".slice(e.length)+e};function eo(n,e){if(n>=0){for(;n>127;)e.push(n&127|128),n=n>>>7;e.push(n)}else{for(let t=0;t<9;t++)e.push(n&127|128),n=n>>7;e.push(1)}}function $f(){let n=this.buf[this.pos++],e=n&127;if((n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<7,(n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<14,(n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<21,(n&128)==0)return this.assertBounds(),e;n=this.buf[this.pos++],e|=(n&15)<<28;for(let t=5;(n&128)!==0&&t<10;t++)n=this.buf[this.pos++];if((n&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function Qf(){const n=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof n.getBigInt64=="function"&&typeof n.getBigUint64=="function"&&typeof n.setBigInt64=="function"&&typeof n.setBigUint64=="function"&&(typeof process!="object"||typeof Qa!="object"||Qa.BUF_BIGINT_DISABLE!=="1")){const s=BigInt("-9223372036854775808"),r=BigInt("9223372036854775807"),o=BigInt("0"),a=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(d){const l=typeof d=="bigint"?d:BigInt(d);if(l>r||l<s)throw new Error("int64 invalid: ".concat(d));return l},uParse(d){const l=typeof d=="bigint"?d:BigInt(d);if(l>a||l<o)throw new Error("uint64 invalid: ".concat(d));return l},enc(d){return n.setBigInt64(0,this.parse(d),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},uEnc(d){return n.setBigInt64(0,this.uParse(d),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},dec(d,l){return n.setInt32(0,d,!0),n.setInt32(4,l,!0),n.getBigInt64(0,!0)},uDec(d,l){return n.setInt32(0,d,!0),n.setInt32(4,l,!0),n.getBigUint64(0,!0)}}}const t=s=>xe(/^-?[0-9]+$/.test(s),"int64 invalid: ".concat(s)),i=s=>xe(/^[0-9]+$/.test(s),"uint64 invalid: ".concat(s));return{zero:"0",supported:!1,parse(s){return typeof s!="string"&&(s=s.toString()),t(s),s},uParse(s){return typeof s!="string"&&(s=s.toString()),i(s),s},enc(s){return typeof s!="string"&&(s=s.toString()),t(s),Za(s)},uEnc(s){return typeof s!="string"&&(s=s.toString()),i(s),Za(s)},dec(s,r){return Gf(s,r)},uDec(s,r){return Nd(s,r)}}}const ge=Qf();var M;(function(n){n[n.DOUBLE=1]="DOUBLE",n[n.FLOAT=2]="FLOAT",n[n.INT64=3]="INT64",n[n.UINT64=4]="UINT64",n[n.INT32=5]="INT32",n[n.FIXED64=6]="FIXED64",n[n.FIXED32=7]="FIXED32",n[n.BOOL=8]="BOOL",n[n.STRING=9]="STRING",n[n.BYTES=12]="BYTES",n[n.UINT32=13]="UINT32",n[n.SFIXED32=15]="SFIXED32",n[n.SFIXED64=16]="SFIXED64",n[n.SINT32=17]="SINT32",n[n.SINT64=18]="SINT64"})(M||(M={}));var Vt;(function(n){n[n.BIGINT=0]="BIGINT",n[n.STRING=1]="STRING"})(Vt||(Vt={}));function It(n,e,t){if(e===t)return!0;if(n==M.BYTES){if(!(e instanceof Uint8Array)||!(t instanceof Uint8Array)||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0}switch(n){case M.UINT64:case M.FIXED64:case M.INT64:case M.SFIXED64:case M.SINT64:return e==t}return!1}function wn(n,e){switch(n){case M.BOOL:return!1;case M.UINT64:case M.FIXED64:case M.INT64:case M.SFIXED64:case M.SINT64:return e==0?ge.zero:"0";case M.DOUBLE:case M.FLOAT:return 0;case M.BYTES:return new Uint8Array(0);case M.STRING:return"";default:return 0}}function Id(n,e){switch(n){case M.BOOL:return e===!1;case M.STRING:return e==="";case M.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}var Se;(function(n){n[n.Varint=0]="Varint",n[n.Bit64=1]="Bit64",n[n.LengthDelimited=2]="LengthDelimited",n[n.StartGroup=3]="StartGroup",n[n.EndGroup=4]="EndGroup",n[n.Bit32=5]="Bit32"})(Se||(Se={}));class Yf{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let s=0;s<this.chunks.length;s++)e+=this.chunks[s].length;let t=new Uint8Array(e),i=0;for(let s=0;s<this.chunks.length;s++)t.set(this.chunks[s],i),i+=this.chunks[s].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(Ys(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Ci(e),eo(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){Sd(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){Ys(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Ci(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Ci(e),e=(e<<1^e>>31)>>>0,eo(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),s=ge.enc(e);return i.setInt32(0,s.lo,!0),i.setInt32(4,s.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),s=ge.uEnc(e);return i.setInt32(0,s.lo,!0),i.setInt32(4,s.hi,!0),this.raw(t)}int64(e){let t=ge.enc(e);return Es(t.lo,t.hi,this.buf),this}sint64(e){let t=ge.enc(e),i=t.hi>>31,s=t.lo<<1^i,r=(t.hi<<1|t.lo>>>31)^i;return Es(s,r,this.buf),this}uint64(e){let t=ge.uEnc(e);return Es(t.lo,t.hi,this.buf),this}}class Zf{constructor(e,t){this.varint64=Wf,this.uint32=$f,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=e&7;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case Se.Varint:for(;this.buf[this.pos++]&128;);break;case Se.Bit64:this.pos+=4;case Se.Bit32:this.pos+=4;break;case Se.LengthDelimited:let s=this.uint32();this.pos+=s;break;case Se.StartGroup:for(;;){const[r,o]=this.tag();if(o===Se.EndGroup){if(t!==void 0&&r!==t)throw new Error("invalid end group tag");break}this.skip(o,r)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return ge.dec(...this.varint64())}uint64(){return ge.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(e&1);return e=(e>>>1|(t&1)<<31)^i,t=t>>>1^i,ge.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return ge.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return ge.dec(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 e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}}function Xf(n,e,t,i){let s;return{typeName:e,extendee:t,get field(){if(!s){const r=typeof i=="function"?i():i;r.name=e.split(".").pop(),r.jsonName="[".concat(e,"]"),s=n.util.newFieldList([r]).list()[0]}return s},runtime:n}}function Md(n){const e=n.field.localName,t=Object.create(null);return t[e]=eg(n),[t,()=>t[e]]}function eg(n){const e=n.field;if(e.repeated)return[];if(e.default!==void 0)return e.default;switch(e.kind){case"enum":return e.T.values[0].no;case"scalar":return wn(e.T,e.L);case"message":const t=e.T,i=new t;return t.fieldWrapper?t.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}function tg(n,e){if(!e.repeated&&(e.kind=="enum"||e.kind=="scalar")){for(let t=n.length-1;t>=0;--t)if(n[t].no==e.no)return[n[t]];return[]}return n.filter(t=>t.no===e.no)}let Tt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
43+/".split(""),os=[];for(let n=0;n<Tt.length;n++)os[Tt[n].charCodeAt(0)]=n;os[45]=Tt.indexOf("+");os[95]=Tt.indexOf("/");const jd={dec(n){let e=n.length*3/4;n[n.length-2]=="="?e-=2:n[n.length-1]=="="&&(e-=1);let t=new Uint8Array(e),i=0,s=0,r,o=0;for(let a=0;a<n.length;a++){if(r=os[n.charCodeAt(a)],r===void 0)switch(n[a]){case"=":s=0;case`
44`:case"\r":case"	":case" ":continue;default:throw Error("invalid base64 string.")}switch(s){case 0:o=r,s=1;break;case 1:t[i++]=o<<2|(r&48)>>4,o=r,s=2;break;case 2:t[i++]=(o&15)<<4|(r&60)>>2,o=r,s=3;break;case 3:t[i++]=(o&3)<<6|r,s=0;break}}if(s==1)throw Error("invalid base64 string.");return t.subarray(0,i)},enc(n){let e="",t=0,i,s=0;for(let r=0;r<n.length;r++)switch(i=n[r],t){case 0:e+=Tt[i>>2],s=(i&3)<<4,t=1;break;case 1:e+=Tt[s|i>>4],s=(i&15)<<2,t=2;break;case 2:e+=Tt[s|i>>6],e+=Tt[i&63],t=0;break}return t&&(e+=Tt[s],e+="=",t==1&&(e+="=")),e}};function ng(n,e,t){Ld(e,n);const i=e.runtime.bin.makeReadOptions(t),s=tg(n.getType().runtime.bin.listUnknownFields(n),e.field),[r,o]=Md(e);for(const a of s)e.runtime.bin.readField(r,i.readerFactory(a.data),e.field,a.wireType,i);return o()}function ig(n,e,t,i){Ld(e,n);const s=e.runtime.bin.makeReadOptions(i),r=e.runtime.bin.makeWriteOptions(i);if(Od(n,e)){const l=n.getType().runtime.bin.listUnknownFields(n).filter(u=>u.no!=e.field.no);n.getType().runtime.bin.discardUnknownFields(n);for(const u of l)n.getType().runtime.bin.onUnknownField(n,u.no,u.wireType,u.data)}const o=r.writerFactory();let a=e.field;!a.opt&&!a.repeated&&(a.kind=="enum"||a.kind=="scalar")&&(a=Object.assign(Object.assign({},e.field),{opt:!0})),e.runtime.bin.writeField(a,t,o,r);const d=s.readerFactory(o.finish());for(;d.pos<d.len;){const[l,u]=d.tag(),h=d.skip(u,l);n.getType().runtime.bin.onUnknownField(n,l,u,h)}}function Od(n,e){const t=n.getType();return e.extendee.typeName===t.typeName&&!!t.runtime.bin.listUnknownFields(n).find(i=>i.no==e.field.no)}function Ld(n,e){xe(n.extendee.typeName==e.getType().typeName,"extension ".concat(n.typeName," can only be applied to message ").concat(n.extendee.typeName))}function Ad(n,e){const t=n.localName;if(n.repeated)return e[t].length>0;if(n.oneof)return e[n.oneof.localName].case===t;switch(n.kind){case"enum":case"scalar":return n.opt||n.req?e[t]!==void 0:n.kind=="enum"?e[t]!==n.T.values[0].no:!Id(n.T,e[t]);case"message":return e[t]!==void 0;case"map":return Object.keys(e[t]).length>0}}function to(n,e){const t=n.localName,i=!n.opt&&!n.req;if(n.repeated)e[t]=[];else if(n.oneof)e[n.oneof.localName]={case:void 0};else switch(n.kind){case"map":e[t]={};break;case"enum":e[t]=i?n.T.values[0].no:void 0;break;case"scalar":e[t]=i?wn(n.T,n.L):void 0;break;case"message":e[t]=void 0;break}}function St(n,e){if(n===null||typeof n!="object"||!Object.getOwnPropertyNames(qr.prototype).every(i=>i in n&&typeof n[i]=="function"))return!1;const t=n.getType();return t===null||typeof t!="function"||!("typeName"in t)||typeof t.typeName!="string"?!1:e===void 0?!0:t.typeName==e.typeName}function Dd(n,e){return St(e)||!n.fieldWrapper?e:n.fieldWrapper.wrapField(e)}M.DOUBLE,M.FLOAT,M.INT64,M.UINT64,M.INT32,M.UINT32,M.BOOL,M.STRING,M.BYTES;const no={ignoreUnknownFields:!1},io={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function sg(n){return n?Object.assign(Object.assign({},no),n):no}function rg(n){return n?Object.assign(Object.assign({},io),n):io}const Ai=Symbol(),Si=Symbol();function ag(){return{makeReadOptions:sg,makeWriteOptions:rg,readMessage(n,e,t,i){if(e==null||Array.isArray(e)||typeof e!="object")throw new Error("cannot decode message ".concat(n.typeName," from JSON: ").concat(mt(e)));i=i??new n;const s=new Map,r=t.typeRegistry;for(const[o,a]of Object.entries(e)){const d=n.fields.findJsonName(o);if(d){if(d.oneof){if(a===null&&d.kind=="scalar")continue;const l=s.get(d.oneof);if(l!==void 0)throw new Error("cannot decode message ".concat(n.typeName,' from JSON: multiple keys for oneof "').concat(d.oneof.name,'" present: "').concat(l,'", "').concat(o,'"'));s.set(d.oneof,o)}so(i,a,d,t,n)}else{let l=!1;if(r?.findExtension&&o.startsWith("[")&&o.endsWith("]")){const u=r.findExtension(o.substring(1,o.length-1));if(u&&u.extendee.typeName==n.typeName){l=!0;const[h,m]=Md(u);so(h,a,u.field,t,u),ig(i,u,m(),t)}}if(!l&&!t.ignoreUnknownFields)throw new Error("cannot decode message ".concat(n.typeName,' from JSON: key "').concat(o,'" is unknown'))}}return i},writeMessage(n,e){const t=n.getType(),i={};let s;try{for(s of t.fields.byNumber()){if(!Ad(s,n)){if(s.req)throw"required field not set";if(!e.emitDefaultValues||!cg(s))continue}const o=s.oneof?n[s.oneof.localName].value:n[s.localName],a=ro(s,o,e);a!==void 0&&(i[e.useProtoFieldName?s.name:s.jsonName]=a)}const r=e.typeRegistry;if(r?.findExtensionFor)for(const o of t.runtime.bin.listUnknownFields(n)){const a=r.findExtensionFor(t.typeName,o.no);if(a&&Od(n,a)){const d=ng(n,a,e),l=ro(a.field,d,e);l!==void 0&&(i[a.field.jsonName]=l)}}}catch(r){const o=s?"cannot encode field ".concat(t.typeName,".").concat(s.name," to JSON"):"cannot encode message ".concat(t.typeName," to JSON"),a=r instanceof Error?r.message:String(r);throw new Error(o+(a.length>0?": ".concat(a):""))}return i}
vendor: 25,511 bytes, line 44
44,readScalar(n,e,t){return Qn(n,e,t??Vt.BIGINT,!0)},writeScalar(n,e,t){if(e!==void 0&&(t||Id(n,e)))return wi(n,e)},debug:mt}}function mt(n){if(n===null)return"null";switch(typeof n){case"object":return Array.isArray(n)?"array":"object";case"string":return n.length>100?"string":'"'.concat(n.split('"').join('\\"'),'"');default:return String(n)}}function so(n,e,t,i,s){let r=t.localName;if(t.repeated){if(xe(t.kind!="map"),e===null)return;if(!Array.isArray(e))throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(mt(e)));const o=n[r];for(const a of e){if(a===null)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(mt(a)));switch(t.kind){case"message":o.push(t.T.fromJson(a,i));break;case"enum":const d=Ps(t.T,a,i.ignoreUnknownFields,!0);d!==Si&&o.push(d);break;case"scalar":try{o.push(Qn(t.T,a,t.L,!0))}catch(l){let u="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(mt(a));throw l instanceof Error&&l.message.length>0&&(u+=": ".concat(l.message)),new Error(u)}break}}}else if(t.kind=="map"){if(e===null)return;if(typeof e!="object"||Array.isArray(e))throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(mt(e)));const o=n[r];for(const[a,d]of Object.entries(e)){if(d===null)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: map value null"));let l;try{l=og(t.K,a)}catch(u){let h="cannot decode map key for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(mt(e));throw u instanceof Error&&u.message.length>0&&(h+=": ".concat(u.message)),new Error(h)}switch(t.V.kind){case"message":o[l]=t.V.T.fromJson(d,i);break;case"enum":const u=Ps(t.V.T,d,i.ignoreUnknownFields,!0);u!==Si&&(o[l]=u);break;case"scalar":try{o[l]=Qn(t.V.T,d,Vt.BIGINT,!0)}catch(h){let m="cannot decode map value for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(mt(e));throw h instanceof Error&&h.message.length>0&&(m+=": ".concat(h.message)),new Error(m)}break}}}else switch(t.oneof&&(n=n[t.oneof.localName]={case:r},r="value"),t.kind){case"message":const o=t.T;if(e===null&&o.typeName!="google.protobuf.Value")return;let a=n[r];St(a)?a.fromJson(e,i):(n[r]=a=o.fromJson(e,i),o.fieldWrapper&&!t.oneof&&(n[r]=o.fieldWrapper.unwrapField(a)));break;case"enum":const d=Ps(t.T,e,i.ignoreUnknownFields,!1);switch(d){case Ai:to(t,n);break;case Si:break;default:n[r]=d;break}break;case"scalar":try{const l=Qn(t.T,e,t.L,!1);switch(l){case Ai:to(t,n);break;default:n[r]=l;break}}catch(l){let u="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(mt(e));throw l instanceof Error&&l.message.length>0&&(u+=": ".concat(l.message)),new Error(u)}break}}function og(n,e){if(n===M.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return Qn(n,e,Vt.BIGINT,!0).toString()}function Qn(n,e,t,i){if(e===null)return i?wn(n,t):Ai;switch(n){case M.DOUBLE:case M.FLOAT:if(e==="NaN")return Number.NaN;if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e===""||typeof e=="string"&&e.trim().length!==e.length||typeof e!="string"&&typeof e!="number")break;const s=Number(e);if(Number.isNaN(s)||!Number.isFinite(s))break;return n==M.FLOAT&&Sd(s),s;case M.INT32:case M.FIXED32:case M.SFIXED32:case M.SINT32:case M.UINT32:let r;if(typeof e=="number"?r=e:typeof e=="string"&&e.length>0&&e.trim().length===e.length&&(r=Number(e)),r===void 0)break;return n==M.UINT32||n==M.FIXED32?Ys(r):Ci(r),r;case M.INT64:case M.SFIXED64:case M.SINT64:if(typeof e!="number"&&typeof e!="string")break;const o=ge.parse(e);return t?o.toString():o;case M.FIXED64:case M.UINT64:if(typeof e!="number"&&typeof e!="string")break;const a=ge.uParse(e);return t?a.toString():a;case M.BOOL:if(typeof e!="boolean")break;return e;case M.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case M.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return jd.dec(e)}throw new Error}function Ps(n,e,t,i){if(e===null)return n.typeName=="google.protobuf.NullValue"?0:i?n.values[0].no:Ai;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":const s=n.findName(e);if(s!==void 0)return s.no;if(t)return Si;break}throw new Error("cannot decode enum ".concat(n.typeName," from JSON: ").concat(mt(e)))}function cg(n){return n.repeated||n.kind=="map"?!0:!(n.oneof||n.kind=="message"||n.opt||n.req)}function ro(n,e,t){if(n.kind=="map"){xe(typeof e=="object"&&e!=null);const i={},s=Object.entries(e);switch(n.V.kind){case"scalar":for(const[o,a]of s)i[o.toString()]=wi(n.V.T,a);break;case"message":for(const[o,a]of s)i[o.toString()]=a.toJson(t);break;case"enum":const r=n.V.T;for(const[o,a]of s)i[o.toString()]=Ns(r,a,t.enumAsInteger);break}return t.emitDefaultValues||s.length>0?i:void 0}if(n.repeated){xe(Array.isArray(e));const i=[];switch(n.kind){case"scalar":for(let s=0;s<e.length;s++)i.push(wi(n.T,e[s]));break;case"enum":for(let s=0;s<e.length;s++)i.push(Ns(n.T,e[s],t.enumAsInteger));break;case"message":for(let s=0;s<e.length;s++)i.push(e[s].toJson(t));break}return t.emitDefaultValues||i.length>0?i:void 0}switch(n.kind){case"scalar":return wi(n.T,e);case"enum":return Ns(n.T,e,t.enumAsInteger);case"message":return Dd(n.T,e).toJson(t)}}function Ns(n,e,t){var i;if(xe(typeof e=="number"),n.typeName=="google.protobuf.NullValue")return null;if(t)return e;const s=n.findNumber(e);return(i=s?.name)!==null&&i!==void 0?i:e}function wi(n,e){switch(n){case M.INT32:case M.SFIXED32:case M.SINT32:case M.FIXED32:case M.UINT32:return xe(typeof e=="number"),e;case M.FLOAT:case M.DOUBLE:return xe(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case M.STRING:return xe(typeof e=="string"),e;case M.BOOL:return xe(typeof e=="boolean"),e;case M.UINT64:case M.FIXED64:case M.INT64:case M.SFIXED64:case M.SINT64:return xe(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case M.BYTES:return xe(e instanceof Uint8Array),jd.enc(e)}}const hn=Symbol("@bufbuild/protobuf/unknown-fields"),ao={readUnknownFields:!0,readerFactory:n=>new Zf(n)},oo={writeUnknownFields:!0,writerFactory:()=>new Yf};function dg(n){return n?Object.assign(Object.assign({},ao),n):ao}function lg(n){return n?Object.assign(Object.assign({},oo),n):oo}function ug(){return{makeReadOptions:dg,makeWriteOptions:lg,listUnknownFields(n){var e;return(e=n[hn])!==null&&e!==void 0?e:[]},discardUnknownFields(n){delete n[hn]},writeUnknownFields(n,e){const i=n[hn];if(i)for(const s of i)e.tag(s.no,s.wireType).raw(s.data)},onUnknownField(n,e,t,i){const s=n;Array.isArray(s[hn])||(s[hn]=[]),s[hn].push({no:e,wireType:t,data:i})},readMessage(n,e,t,i,s){const r=n.getType(),o=s?e.len:e.pos+t;let a,d;for(;e.pos<o&&([a,d]=e.tag(),!(s===!0&&d==Se.EndGroup));){const l=r.fields.find(a);if(!l){const u=e.skip(d,a);i.readUnknownFields&&this.onUnknownField(n,a,d,u);continue}co(n,e,l,d,i)}if(s&&(d!=Se.EndGroup||a!==t))throw new Error("invalid end group tag")},readField:co,writeMessage(n,e,t){const i=n.getType();for(const s of i.fields.byNumber()){if(!Ad(s,n)){if(s.req)throw new Error("cannot encode field ".concat(i.typeName,".").concat(s.name," to binary: required field not set"));continue}const r=s.oneof?n[s.oneof.localName].value:n[s.localName];lo(s,r,e,t)}return t.writeUnknownFields&&this.writeUnknownFields(n,e),e},writeField(n,e,t,i){e!==void 0&&lo(n,e,t,i)}}}function co(n,e,t,i,s){let{repeated:r,localName:o}=t;switch(t.oneof&&(n=n[t.oneof.localName],n.case!=o&&delete n.value,n.case=o,o="value"),t.kind){case"scalar":case"enum":const a=t.kind=="enum"?M.INT32:t.T;let d=Di;if(t.kind=="scalar"&&t.L>0&&(d=mg),r){let m=n[o];if(i==Se.LengthDelimited&&a!=M.STRING&&a!=M.BYTES){let C=e.uint32()+e.pos;for(;e.pos<C;)m.push(d(e,a))}else m.push(d(e,a))}else n[o]=d(e,a);break;case"message":const l=t.T;r?n[o].push(Ri(e,new l,s,t)):St(n[o])?Ri(e,n[o],s,t):(n[o]=Ri(e,new l,s,t),l.fieldWrapper&&!t.oneof&&!t.repeated&&(n[o]=l.fieldWrapper.unwrapField(n[o])));break;case"map":let[u,h]=hg(t,e,s);n[o][u]=h;break}}function Ri(n,e,t,i){const s=e.getType().runtime.bin,r=i?.delimited;return s.readMessage(e,n,r?i.no:n.uint32(),t,r),e}function hg(n,e,t){const i=e.uint32(),s=e.pos+i;let r,o;for(;e.pos<s;){const[a]=e.tag();switch(a){case 1:r=Di(e,n.K);break;case 2:switch(n.V.kind){case"scalar":o=Di(e,n.V.T);break;case"enum":o=e.int32();break;case"message":o=Ri(e,new n.V.T,t,void 0);break}break}}if(r===void 0&&(r=wn(n.K,Vt.BIGINT)),typeof r!="string"&&typeof r!="number"&&(r=r.toString()),o===void 0)switch(n.V.kind){case"scalar":o=wn(n.V.T,Vt.BIGINT);break;case"enum":o=n.V.T.values[0].no;break;case"message":o=new n.V.T;break}return[r,o]}function mg(n,e){const t=Di(n,e);return typeof t=="bigint"?t.toString():t}function Di(n,e){switch(e){case M.STRING:return n.string();case M.BOOL:return n.bool();case M.DOUBLE:return n.double();case M.FLOAT:return n.float();case M.INT32:return n.int32();case M.INT64:return n.int64();case M.UINT64:return n.uint64();case M.FIXED64:return n.fixed64();case M.BYTES:return n.bytes();case M.FIXED32:return n.fixed32();case M.SFIXED32:return n.sfixed32();case M.SFIXED64:return n.sfixed64();case M.SINT64:return n.sint64();case M.UINT32:return n.uint32();case M.SINT32:return n.sint32()}}function lo(n,e,t,i){xe(e!==void 0);const s=n.repeated;switch(n.kind){case"scalar":case"enum":let r=n.kind=="enum"?M.INT32:n.T;if(s)if(xe(Array.isArray(e)),n.packed)fg(t,r,n.no,e);else for(const o of e)Yn(t,r,n.no,o);else Yn(t,r,n.no,e);break;case"message":if(s){xe(Array.isArray(e));for(const o of e)uo(t,i,n,o)}else uo(t,i,n,e);break;case"map":xe(typeof e=="object"&&e!=null);for(const[o,a]of Object.entries(e))pg(t,i,n,o,a);break}}function pg(n,e,t,i,s){n.tag(t.no,Se.LengthDelimited),n.fork();let r=i;switch(t.K){case M.INT32:case M.FIXED32:case M.UINT32:case M.SFIXED32:case M.SINT32:r=Number.parseInt(i);break;case M.BOOL:xe(i=="true"||i=="false"),r=i=="true";break}switch(Yn(n,t.K,1,r),t.V.kind){case"scalar":Yn(n,t.V.T,2,s);break;case"enum":Yn(n,M.INT32,2,s);break;case"message":xe(s!==void 0),n.tag(2,Se.LengthDelimited).bytes(s.toBinary(e));break}n.join()}function uo(n,e,t,i){const s=Dd(t.T,i);t.delimited?n.tag(t.no,Se.StartGroup).raw(s.toBinary(e)).tag(t.no,Se.EndGroup):n.tag(t.no,Se.LengthDelimited).bytes(s.toBinary(e))}function Yn(n,e,t,i){xe(i!==void 0);let[s,r]=Ud(e);n.tag(t,s)[r](i)}function fg(n,e,t,i){if(!i.length)return;n.tag(t,Se.LengthDelimited).fork();let[,s]=Ud(e);for(let r=0;r<i.length;r++)n[s](i[r]);n.join()}function Ud(n){let e=Se.Varint;switch(n){case M.BYTES:case M.STRING:e=Se.LengthDelimited;break;case M.DOUBLE:case M.FIXED64:case M.SFIXED64:e=Se.Bit64;break;case M.FIXED32:case M.SFIXED32:case M.FLOAT:e=Se.Bit32;break}const t=M[n].toLowerCase();return[e,t]}function gg(){return{setEnumType:Rd,initPartial(n,e){if(n===void 0)return;const t=e.getType();for(const i of t.fields.byMember()){const s=i.localName,r=e,o=n;if(o[s]!=null)switch(i.kind){case"oneof":const a=o[s].case;if(a===void 0)continue;const d=i.findField(a);let l=o[s].value;d&&d.kind=="message"&&!St(l,d.T)?l=new d.T(l):d&&d.kind==="scalar"&&d.T===M.BYTES&&(l=Fn(l)),r[s]={case:a,value:l};break;case"scalar":case"enum":let u=o[s];i.T===M.BYTES&&(u=i.repeated?u.map(Fn):Fn(u)),r[s]=u;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===M.BYTES)for(const[f,C]of Object.entries(o[s]))r[s][f]=Fn(C);else Object.assign(r[s],o[s]);break;case"message":const m=i.V.T;for(const f of Object.keys(o[s])){let C=o[s][f];m.fieldWrapper||(C=new m(C)),r[s][f]=C}break}break;case"message":const h=i.T;if(i.repeated)r[s]=o[s].map(m=>St(m,h)?m:new h(m));else{const m=o[s];h.fieldWrapper?h.typeName==="google.protobuf.BytesValue"?r[s]=Fn(m):r[s]=m:r[s]=St(m,h)?m:new h(m)}break}}},equals(n,e,t){return e===t?!0:!e||!t?!1:n.fields.byMember().every(i=>{const s=e[i.localName],r=t[i.localName];if(i.repeated){if(s.length!==r.length)return!1;switch(i.kind){case"message":return s.every((o,a)=>i.T.equals(o,r[a]));case"scalar":return s.every((o,a)=>It(i.T,o,r[a]));case"enum":return s.every((o,a)=>It(M.INT32,o,r[a]))}throw new Error("repeated cannot contain ".concat(i.kind))}switch(i.kind){case"message":let o=s,a=r;return i.T.fieldWrapper&&(o!==void 0&&!St(o)&&(o=i.T.fieldWrapper.wrapField(o)),a!==void 0&&!St(a)&&(a=i.T.fieldWrapper.wrapField(a))),i.T.equals(o,a);case"enum":return It(M.INT32,s,r);case"scalar":return It(i.T,s,r);case"oneof":if(s.case!==r.case)return!1;const d=i.findField(s.case);if(d===void 0)return!0;switch(d.kind){case"message":return d.T.equals(s.value,r.value);case"enum":return It(M.INT32,s.value,r.value);case"scalar":return It(d.T,s.value,r.value)}throw new Error("oneof cannot contain ".concat(d.kind));case"map":const l=Object.keys(s).concat(Object.keys(r));switch(i.V.kind){case"message":const u=i.V.T;return l.every(m=>u.equals(s[m],r[m]));case"enum":return l.every(m=>It(M.INT32,s[m],r[m]));case"scalar":const h=i.V.T;return l.every(m=>It(h,s[m],r[m]))}break}})},clone(n){const e=n.getType(),t=new e,i=t;for(const s of e.fields.byMember()){const r=n[s.localName];let o;if(s.repeated)o=r.map(bi);else if(s.kind=="map"){o=i[s.localName];for(const[a,d]of Object.entries(r))o[a]=bi(d)}else s.kind=="oneof"?o=s.findField(r.case)?{case:r.case,value:bi(r.value)}:{case:void 0}:o=bi(r);i[s.localName]=o}for(const s of e.runtime.bin.listUnknownFields(n))e.runtime.bin.onUnknownField(i,s.no,s.wireType,s.data);return t}}}function bi(n){if(n===void 0)return n;if(St(n))return n.clone();if(n instanceof Uint8Array){const e=new Uint8Array(n.byteLength);return e.set(n),e}return n}function Fn(n){return n instanceof Uint8Array?n:new Uint8Array(n)}function vg(n,e,t){return{syntax:n,json:ag(),bin:ug(),util:Object.assign(Object.assign({},gg()),{newFieldList:e,initFields:t}),makeMessageType(i,s,r){return Kf(this,i,s,r)},makeEnum:zf,makeEnumType:Ed,getEnumType:Hf,makeExtension(i,s,r){return Xf(this,i,s,r)}}}class bg{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const t={};for(const i of this.list())t[i.jsonName]=t[i.name]=i;this.jsonNames=t}return this.jsonNames[e]}find(e){if(!this.numbers){const t={};for(const i of this.list())t[i.no]=i;this.numbers=t}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((e,t)=>e.no-t.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const i of this.list())i.oneof?i.oneof!==t&&(t=i.oneof,e.push(t)):e.push(i)}return this.members}}function Fd(n,e){const t=Vd(n);return e?t:Sg(Tg(t))}function kg(n){return Fd(n,!1)}const xg=Vd;function Vd(n){let e=!1;const t=[];for(let i=0;i<n.length;i++){let s=n.charAt(i);switch(s){case"_":e=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":t.push(s),e=!1;break;default:e&&(e=!1,s=s.toUpperCase()),t.push(s);break}}return t.join("")}const yg=new Set(["constructor","toString","toJSON","valueOf"]),Cg=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Bd=n=>"".concat(n,"$"),Tg=n=>Cg.has(n)?Bd(n):n,Sg=n=>yg.has(n)?Bd(n):n;class wg{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=kg(e)}addField(e){xe(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let t=0;t<this.fields.length;t++)this._lookup[this.fields[t].localName]=this.fields[t]}return this._lookup[e]}}function Rg(n,e){var t,i,s,r,o,a;const d=[];let l;for(const u of typeof n=="function"?n():n){const h=u;if(h.localName=Fd(u.name,u.oneof!==void 0),h.jsonName=(t=u.jsonName)!==null&&t!==void 0?t:xg(u.name),h.repeated=(i=u.repeated)!==null&&i!==void 0?i:!1,u.kind=="scalar"&&(h.L=(s=u.L)!==null&&s!==void 0?s:Vt.BIGINT),h.delimited=(r=u.delimited)!==null&&r!==void 0?r:!1,h.req=(o=u.req)!==null&&o!==void 0?o:!1,h.opt=(a=u.opt)!==null&&a!==void 0?a:!1,u.packed===void 0&&(h.packed=u.kind=="enum"||u.kind=="scalar"&&u.T!=M.BYTES&&u.T!=M.STRING),u.oneof!==void 0){const m=typeof u.oneof=="string"?u.oneof:u.oneof.name;(!l||l.name!=m)&&(l=new wg(m)),h.oneof=l,l.addField(h)}d.push(h)}return d}const R=vg("proto3",n=>new bg(n,e=>Rg(e)),n=>{for(const e of n.getType().fields.byMember()){if(e.opt)continue;const t=e.localName,i=n;if(e.repeated){i[t]=[];continue}switch(e.kind){case"oneof":i[t]={case:void 0};break;case"enum":i[t]=0;break;case"map":i[t]={};break;case"scalar":i[t]=wn(e.T,e.L);break}}});class Ke extends qr{constructor(e){super(),this.seconds=ge.zero,this.nanos=0,R.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(R.json.debug(e)));const i=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const s=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(s))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(s<Date.parse("0001-01-01T00:00:00Z")||s>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=ge.parse(s/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){const t=Number(this.seconds)*1e3;if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){const s=(this.nanos+1e9).toString().substring(1);s.substring(3)==="000000"?i="."+s.substring(0,3)+"Z":s.substring(6)==="000"?i="."+s.substring(0,6)+"Z":i="."+s+"Z"}return new Date(t).toISOString().replace(".000Z",i)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return Ke.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new Ke({seconds:ge.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new Ke().fromBinary(e,t)}static fromJson(e,t){return new Ke().fromJson(e,t)}static fromJsonString(e,t){return new Ke().fromJsonString(e,t)}static equals(e,t){return R.util.equals(Ke,e,t)}}Ke.runtime=R;Ke.typeName="google.protobuf.Timestamp";Ke.fields=R.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const Eg=R.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Ke},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:Pg,repeated:!0},{no:5,name:"events",kind:"message",T:_g,repeated:!0}]),Pg=R.makeMessageType("livekit.TimeSeriesMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"samples",kind:"message",T:Ng,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),Ng=R.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Ke},{no:3,name:"value",kind:"scalar",T:2}]),_g=R.makeMessageType("livekit.EventMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"start_timestamp_ms",kind:"scalar",T:3},{no:5,name:"end_timestamp_ms",kind:"scalar",T:3,opt:!0},{no:6,name:"normalized_start_timestamp",kind:"message",T:Ke},{no:7,name:"normalized_end_timestamp",kind:"message",T:Ke,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),qd=R.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),at=R.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),Re=R.makeEnum("livekit.TrackSource",[{no:0,name:"UNKNOWN"},{no:1,name:"CAMERA"},{no:2,name:"MICROPHONE"},{no:3,name:"SCREEN_SHARE"},{no:4,name:"SCREEN_SHARE_AUDIO"}]),zr=R.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),Gn=R.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),ti=R.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),dt=R.makeEnum("livekit.DisconnectReason",[{no:0,name:"UNKNOWN_REASON"},{no:1,name:"CLIENT_INITIATED"},{no:2,name:"DUPLICATE_IDENTITY"},{no:3,name:"SERVER_SHUTDOWN"},{no:4,name:"PARTICIPANT_REMOVED"},{no:5,name:"ROOM_DELETED"},{no:6,name:"STATE_MISMATCH"},{no:7,name:"JOIN_FAILURE"},{no:8,name:"MIGRATION"},{no:9,name:"SIGNAL_CLOSE"},{no:10,name:"ROOM_CLOSED"},{no:11,name:"USER_UNAVAILABLE"},{no:12,name:"USER_REJECTED"},{no:13,name:"SIP_TRUNK_FAILURE"},{no:14,name:"CONNECTION_TIMEOUT"},{no:15,name:"MEDIA_FAILURE"}]),Xt=R.makeEnum("livekit.ReconnectReason",[{no:0,name:"RR_UNKNOWN"},{no:1,name:"RR_SIGNAL_DISCONNECTED"},{no:2,name:"RR_PUBLISHER_FAILED"},{no:3,name:"RR_SUBSCRIBER_FAILED"},{no:4,name:"RR_SWITCH_CANDIDATE"}]),Ig=R.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),_e=R.makeEnum("livekit.AudioTrackFeature",[{no:0,name:"TF_STEREO"},{no:1,name:"TF_NO_DTX"},{no:2,name:"TF_AUTO_GAIN_CONTROL"},{no:3,name:"TF_ECHO_CANCELLATION"},{no:4,name:"TF_NOISE_SUPPRESSION"},{no:5,name:"TF_ENHANCED_NOISE_CANCELLATION"},{no:6,name:"TF_PRECONNECT_BUFFER"}]),cs=R.makeMessageType("livekit.Room",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"empty_timeout",kind:"scalar",T:13},{no:14,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:5,name:"creation_time",kind:"scalar",T:3},{no:15,name:"creation_time_ms",kind:"scalar",T:3},{no:6,name:"turn_password",kind:"scalar",T:9},{no:7,name:"enabled_codecs",kind:"message",T:Ui,repeated:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"num_participants",kind:"scalar",T:13},{no:11,name:"num_publishers",kind:"scalar",T:13},{no:10,name:"active_recording",kind:"scalar",T:8},{no:13,name:"version",kind:"message",T:tl}]),Ui=R.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),Mg=R.makeMessageType("livekit.ParticipantPermission",()=>[{no:1,name:"can_subscribe",kind:"scalar",T:8},{no:2,name:"can_publish",kind:"scalar",T:8},{no:3,name:"can_publish_data",kind:"scalar",T:8},{no:9,name:"can_publish_sources",kind:"enum",T:R.getEnumType(Re),repeated:!0},{no:7,name:"hidden",kind:"scalar",T:8},{no:8,name:"recorder",kind:"scalar",T:8},{no:10,name:"can_update_metadata",kind:"scalar",T:8},{no:11,name:"agent",kind:"scalar",T:8},{no:12,name:"can_subscribe_metrics",kind:"scalar",T:8}]),on=R.makeMessageType("livekit.ParticipantInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:R.getEnumType(bn)},{no:4,name:"tracks",kind:"message",T:pn,repeated:!0},{no:5,name:"metadata",kind:"scalar",T:9},{no:6,name:"joined_at",kind:"scalar",T:3},{no:17,name:"joined_at_ms",kind:"scalar",T:3},{no:9,name:"name",kind:"scalar",T:9},{no:10,name:"version",kind:"scalar",T:13},{no:11,name:"permission",kind:"message",T:Mg},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:R.getEnumType(ni)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:R.getEnumType(dt)},{no:18,name:"kind_details",kind:"enum",T:R.getEnumType(jg),repeated:!0},{no:19,name:"data_tracks",kind:"message",T:Kr,repeated:!0}]),bn=R.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),ni=R.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"},{no:7,name:"CONNECTOR"},{no:8,name:"BRIDGE"}]),jg=R.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"},{no:2,name:"CONNECTOR_WHATSAPP"},{no:3,name:"CONNECTOR_TWILIO"},{no:4,name:"BRIDGE_RTSP"}]),we=R.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),Og=R.makeMessageType("livekit.SimulcastCodecInfo",()=>[{no:1,name:"mime_type",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:Dt,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:R.getEnumType(Hd)},{no:6,name:"sdp_cid",kind:"scalar",T:9}]),pn=R.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:R.getEnumType(at)}
vendor: 14,227 bytes, line 44
44,{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"muted",kind:"scalar",T:8},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"simulcast",kind:"scalar",T:8},{no:8,name:"disable_dtx",kind:"scalar",T:8},{no:9,name:"source",kind:"enum",T:R.getEnumType(Re)},{no:10,name:"layers",kind:"message",T:Dt,repeated:!0},{no:11,name:"mime_type",kind:"scalar",T:9},{no:12,name:"mid",kind:"scalar",T:9},{no:13,name:"codecs",kind:"message",T:Og,repeated:!0},{no:14,name:"stereo",kind:"scalar",T:8},{no:15,name:"disable_red",kind:"scalar",T:8},{no:16,name:"encryption",kind:"enum",T:R.getEnumType(we)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:tl},{no:19,name:"audio_features",kind:"enum",T:R.getEnumType(_e),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:R.getEnumType(qd)}]),Kr=R.makeMessageType("livekit.DataTrackInfo",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13},{no:2,name:"sid",kind:"scalar",T:9},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"encryption",kind:"enum",T:R.getEnumType(we)}]),Lg=R.makeMessageType("livekit.DataTrackSubscriptionOptions",()=>[{no:1,name:"target_fps",kind:"scalar",T:13,opt:!0}]),Dt=R.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:R.getEnumType(zr)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13},{no:6,name:"spatial_layer",kind:"scalar",T:5},{no:7,name:"rid",kind:"scalar",T:9},{no:8,name:"repair_ssrc",kind:"scalar",T:13}]),Hd=R.makeEnum("livekit.VideoLayer.Mode",[{no:0,name:"MODE_UNUSED"},{no:1,name:"ONE_SPATIAL_LAYER_PER_STREAM"},{no:2,name:"MULTIPLE_SPATIAL_LAYERS_PER_STREAM"},{no:3,name:"ONE_SPATIAL_LAYER_PER_STREAM_INCOMPLETE_RTCP_SR"}]),Ve=R.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:R.getEnumType(X)},{no:4,name:"participant_identity",kind:"scalar",T:9},{no:5,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:2,name:"user",kind:"message",T:Wr,oneof:"value"},{no:3,name:"speaker",kind:"message",T:Ag,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:Gd,oneof:"value"},{no:7,name:"transcription",kind:"message",T:Dg,oneof:"value"},{no:8,name:"metrics",kind:"message",T:Eg,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:Fi,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:Gr,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Jr,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:$r,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:Vi,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:Bi,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:qi,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:zd,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),X=R.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),zd=R.makeMessageType("livekit.EncryptedPacket",()=>[{no:1,name:"encryption_type",kind:"enum",T:R.getEnumType(we)},{no:2,name:"iv",kind:"scalar",T:12},{no:3,name:"key_index",kind:"scalar",T:13},{no:4,name:"encrypted_value",kind:"scalar",T:12}]),Kd=R.makeMessageType("livekit.EncryptedPacketPayload",()=>[{no:1,name:"user",kind:"message",T:Wr,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:Fi,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:Gr,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:Jr,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:$r,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:Vi,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:Bi,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:qi,oneof:"value"}]),Ag=R.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:Wd,repeated:!0}]),Wd=R.makeMessageType("livekit.SpeakerInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"level",kind:"scalar",T:2},{no:3,name:"active",kind:"scalar",T:8}]),Wr=R.makeMessageType("livekit.UserPacket",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:5,name:"participant_identity",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"destination_sids",kind:"scalar",T:9,repeated:!0},{no:6,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:4,name:"topic",kind:"scalar",T:9,opt:!0},{no:8,name:"id",kind:"scalar",T:9,opt:!0},{no:9,name:"start_time",kind:"scalar",T:4,opt:!0},{no:10,name:"end_time",kind:"scalar",T:4,opt:!0},{no:11,name:"nonce",kind:"scalar",T:12}]),Gd=R.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),Dg=R.makeMessageType("livekit.Transcription",()=>[{no:2,name:"transcribed_participant_identity",kind:"scalar",T:9},{no:3,name:"track_id",kind:"scalar",T:9},{no:4,name:"segments",kind:"message",T:Ug,repeated:!0}]),Ug=R.makeMessageType("livekit.TranscriptionSegment",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}]),Fi=R.makeMessageType("livekit.ChatMessage",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"edit_timestamp",kind:"scalar",T:3,opt:!0},{no:4,name:"message",kind:"scalar",T:9},{no:5,name:"deleted",kind:"scalar",T:8},{no:6,name:"generated",kind:"scalar",T:8}]),Gr=R.makeMessageType("livekit.RpcRequest",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"method",kind:"scalar",T:9},{no:3,name:"payload",kind:"scalar",T:9},{no:4,name:"response_timeout_ms",kind:"scalar",T:13},{no:5,name:"version",kind:"scalar",T:13}]),Jr=R.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),$r=R.makeMessageType("livekit.RpcResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:9,oneof:"value"},{no:3,name:"error",kind:"message",T:Jd,oneof:"value"}]),Jd=R.makeMessageType("livekit.RpcError",()=>[{no:1,name:"code",kind:"scalar",T:13},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"data",kind:"scalar",T:9}]),$d=R.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),Qd=R.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:R.getEnumType(Yd)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"region",kind:"scalar",T:9},{no:5,name:"node_id",kind:"scalar",T:9},{no:6,name:"debug_info",kind:"scalar",T:9},{no:7,name:"agent_protocol",kind:"scalar",T:5}]),Yd=R.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Zd=R.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:R.getEnumType(Xd)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"os",kind:"scalar",T:9},{no:5,name:"os_version",kind:"scalar",T:9},{no:6,name:"device_model",kind:"scalar",T:9},{no:7,name:"browser",kind:"scalar",T:9},{no:8,name:"browser_version",kind:"scalar",T:9},{no:9,name:"address",kind:"scalar",T:9},{no:10,name:"network",kind:"scalar",T:9},{no:11,name:"other_sdks",kind:"scalar",T:9}]),Xd=R.makeEnum("livekit.ClientInfo.SDK",[{no:0,name:"UNKNOWN"},{no:1,name:"JS"},{no:2,name:"SWIFT"},{no:3,name:"ANDROID"},{no:4,name:"FLUTTER"},{no:5,name:"GO"},{no:6,name:"UNITY"},{no:7,name:"REACT_NATIVE"},{no:8,name:"RUST"},{no:9,name:"PYTHON"},{no:10,name:"CPP"},{no:11,name:"UNITY_WEB"},{no:12,name:"NODE"},{no:13,name:"UNREAL"},{no:14,name:"ESP32"}]),el=R.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:ho},{no:2,name:"screen",kind:"message",T:ho},{no:3,name:"resume_connection",kind:"enum",T:R.getEnumType(ti)},{no:4,name:"disabled_codecs",kind:"message",T:Fg},{no:5,name:"force_relay",kind:"enum",T:R.getEnumType(ti)}]),ho=R.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:R.getEnumType(ti)}]),Fg=R.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:Ui,repeated:!0},{no:2,name:"publish",kind:"message",T:Ui,repeated:!0}]),tl=R.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),Zs=R.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),nl=R.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:R.getEnumType(Zs)},{no:2,name:"version",kind:"scalar",T:5},{no:3,name:"reply_to_stream_id",kind:"scalar",T:9},{no:4,name:"attached_stream_ids",kind:"scalar",T:9,repeated:!0},{no:5,name:"generated",kind:"scalar",T:8}],{localName:"DataStream_TextHeader"}),il=R.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),Vi=R.makeMessageType("livekit.DataStream.Header",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"topic",kind:"scalar",T:9},{no:4,name:"mime_type",kind:"scalar",T:9},{no:5,name:"total_length",kind:"scalar",T:4,opt:!0},{no:7,name:"encryption_type",kind:"enum",T:R.getEnumType(we)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:nl,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:il,oneof:"content_header"}],{localName:"DataStream_Header"}),Bi=R.makeMessageType("livekit.DataStream.Chunk",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"chunk_index",kind:"scalar",T:4},{no:3,name:"content",kind:"scalar",T:12},{no:4,name:"version",kind:"scalar",T:5},{no:5,name:"iv",kind:"scalar",T:12,opt:!0}],{localName:"DataStream_Chunk"}),qi=R.makeMessageType("livekit.DataStream.Trailer",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"reason",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}],{localName:"DataStream_Trailer"}),Vg=R.makeMessageType("livekit.SubscribedAudioCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}]),ot=R.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),Xs=R.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),Bg=R.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),qg=R.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:Bt,oneof:"message"},{no:2,name:"answer",kind:"message",T:Bt,oneof:"message"},{no:3,name:"trickle",kind:"message",T:ds,oneof:"message"},{no:4,name:"add_track",kind:"message",T:ii,oneof:"message"},{no:5,name:"mute",kind:"message",T:ls,oneof:"message"},{no:6,name:"subscription",kind:"message",T:us,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:ol,oneof:"message"},{no:8,name:"leave",kind:"message",T:hs,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:dl,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:hl,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:ea,oneof:"message"},{no:13,name:"simulate",kind:"message",T:ut,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:Zr,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:fl,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:Yr,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:cl,oneof:"message"},{no:19,name:"publish_data_track_request",kind:"message",T:sl,oneof:"message"},{no:20,name:"unpublish_data_track_request",kind:"message",T:al,oneof:"message"},{no:21,name:"update_data_subscription",kind:"message",T:Qg,oneof:"message"}]),mo=R.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:Wg,oneof:"message"},{no:2,name:"answer",kind:"message",T:Bt,oneof:"message"},{no:3,name:"offer",kind:"message",T:Bt,oneof:"message"},{no:4,name:"trickle",kind:"message",T:ds,oneof:"message"},{no:5,name:"update",kind:"message",T:$g,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Qr,oneof:"message"},{no:8,name:"leave",kind:"message",T:hs,oneof:"message"},{no:9,name:"mute",kind:"message",T:ls,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Zg,oneof:"message"},{no:11,name:"room_update",kind:"message",T:Xg,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:tv,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:iv,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:rv,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:ov,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Jg,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:Gg,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:dv,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:hv,oneof:"message"},{no:22,name:"request_response",kind:"message",T:mv,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:pv,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:cv,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:bv,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:av,oneof:"message"},{no:27,name:"publish_data_track_response",kind:"message",T:rl,oneof:"message"},{no:28,name:"unpublish_data_track_response",kind:"message",T:Hg,oneof:"message"},{no:29,name:"data_track_subscriber_handles",kind:"message",T:zg,oneof:"message"}]),er=R.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:Dt,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:R.getEnumType(Hd)}]),ii=R.makeMessageType("livekit.AddTrackRequest",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"type",kind:"enum",T:R.getEnumType(at)}
vendor: 8,885 bytes, line 44
44,{no:4,name:"width",kind:"scalar",T:13},{no:5,name:"height",kind:"scalar",T:13},{no:6,name:"muted",kind:"scalar",T:8},{no:7,name:"disable_dtx",kind:"scalar",T:8},{no:8,name:"source",kind:"enum",T:R.getEnumType(Re)},{no:9,name:"layers",kind:"message",T:Dt,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:er,repeated:!0},{no:11,name:"sid",kind:"scalar",T:9},{no:12,name:"stereo",kind:"scalar",T:8},{no:13,name:"disable_red",kind:"scalar",T:8},{no:14,name:"encryption",kind:"enum",T:R.getEnumType(we)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:R.getEnumType(qd)},{no:17,name:"audio_features",kind:"enum",T:R.getEnumType(_e),repeated:!0}]),sl=R.makeMessageType("livekit.PublishDataTrackRequest",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"encryption",kind:"enum",T:R.getEnumType(we)}]),rl=R.makeMessageType("livekit.PublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:Kr}]),al=R.makeMessageType("livekit.UnpublishDataTrackRequest",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13}]),Hg=R.makeMessageType("livekit.UnpublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:Kr}]),zg=R.makeMessageType("livekit.DataTrackSubscriberHandles",()=>[{no:1,name:"sub_handles",kind:"map",K:13,V:{kind:"message",T:Kg}}]),Kg=R.makeMessageType("livekit.DataTrackSubscriberHandles.PublishedDataTrack",()=>[{no:1,name:"publisher_identity",kind:"scalar",T:9},{no:2,name:"publisher_sid",kind:"scalar",T:9},{no:3,name:"track_sid",kind:"scalar",T:9}],{localName:"DataTrackSubscriberHandles_PublishedDataTrack"}),ds=R.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:R.getEnumType(ot)},{no:3,name:"final",kind:"scalar",T:8}]),ls=R.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),Wg=R.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:cs},{no:2,name:"participant",kind:"message",T:on},{no:3,name:"other_participants",kind:"message",T:on,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:ll,repeated:!0},{no:6,name:"subscriber_primary",kind:"scalar",T:8},{no:7,name:"alternative_url",kind:"scalar",T:9},{no:8,name:"client_configuration",kind:"message",T:el},{no:9,name:"server_region",kind:"scalar",T:9},{no:10,name:"ping_timeout",kind:"scalar",T:5},{no:11,name:"ping_interval",kind:"scalar",T:5},{no:12,name:"server_info",kind:"message",T:Qd},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:Ui,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),Gg=R.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:ll,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:el},{no:3,name:"server_info",kind:"message",T:Qd},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),Qr=R.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:pn}]),Jg=R.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),Bt=R.makeMessageType("livekit.SessionDescription",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"id",kind:"scalar",T:13},{no:4,name:"mid_to_track_id",kind:"map",K:9,V:{kind:"scalar",T:9}}]),$g=R.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:on,repeated:!0}]),us=R.makeMessageType("livekit.UpdateSubscription",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"participant_tracks",kind:"message",T:$d,repeated:!0}]),Qg=R.makeMessageType("livekit.UpdateDataSubscription",()=>[{no:1,name:"updates",kind:"message",T:Yg,repeated:!0}]),Yg=R.makeMessageType("livekit.UpdateDataSubscription.Update",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"options",kind:"message",T:Lg}],{localName:"UpdateDataSubscription_Update"}),ol=R.makeMessageType("livekit.UpdateTrackSettings",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:3,name:"disabled",kind:"scalar",T:8},{no:4,name:"quality",kind:"enum",T:R.getEnumType(zr)},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"fps",kind:"scalar",T:13},{no:8,name:"priority",kind:"scalar",T:13}]),Yr=R.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:R.getEnumType(_e),repeated:!0}]),cl=R.makeMessageType("livekit.UpdateLocalVideoTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13}]),hs=R.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:R.getEnumType(dt)},{no:3,name:"action",kind:"enum",T:R.getEnumType(kn)},{no:4,name:"regions",kind:"message",T:lv}]),kn=R.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),dl=R.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:Dt,repeated:!0}]),Zr=R.makeMessageType("livekit.UpdateParticipantMetadata",()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:4,name:"request_id",kind:"scalar",T:13}]),ll=R.makeMessageType("livekit.ICEServer",()=>[{no:1,name:"urls",kind:"scalar",T:9,repeated:!0},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"credential",kind:"scalar",T:9}]),Zg=R.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:Wd,repeated:!0}]),Xg=R.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:cs}]),ev=R.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:R.getEnumType(Gn)},{no:3,name:"score",kind:"scalar",T:2}]),tv=R.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:ev,repeated:!0}]),nv=R.makeMessageType("livekit.StreamStateInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:R.getEnumType(Xs)}]),iv=R.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:nv,repeated:!0}]),Xr=R.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:R.getEnumType(zr)},{no:2,name:"enabled",kind:"scalar",T:8}]),sv=R.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Xr,repeated:!0}]),rv=R.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Xr,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:sv,repeated:!0}]),av=R.makeMessageType("livekit.SubscribedAudioCodecUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:Vg,repeated:!0}]),ul=R.makeMessageType("livekit.TrackPermission",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"all_tracks",kind:"scalar",T:8},{no:3,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:4,name:"participant_identity",kind:"scalar",T:9}]),hl=R.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:ul,repeated:!0}]),ov=R.makeMessageType("livekit.SubscriptionPermissionUpdate",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"allowed",kind:"scalar",T:8}]),cv=R.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:cs},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:on},{no:4,name:"other_participants",kind:"message",T:on,repeated:!0}]),ea=R.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:Bt},{no:2,name:"subscription",kind:"message",T:us},{no:3,name:"publish_tracks",kind:"message",T:Qr,repeated:!0},{no:4,name:"data_channels",kind:"message",T:pl,repeated:!0},{no:5,name:"offer",kind:"message",T:Bt},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:ml,repeated:!0},{no:8,name:"publish_data_tracks",kind:"message",T:rl,repeated:!0}]),ml=R.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}
vendor: 10,741 bytes, line 44
44]),pl=R.makeMessageType("livekit.DataChannelInfo",()=>[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:13},{no:3,name:"target",kind:"enum",T:R.getEnumType(ot)}]),ut=R.makeMessageType("livekit.SimulateScenario",()=>[{no:1,name:"speaker_update",kind:"scalar",T:5,oneof:"scenario"},{no:2,name:"node_failure",kind:"scalar",T:8,oneof:"scenario"},{no:3,name:"migration",kind:"scalar",T:8,oneof:"scenario"},{no:4,name:"server_leave",kind:"scalar",T:8,oneof:"scenario"},{no:5,name:"switch_candidate_protocol",kind:"enum",T:R.getEnumType(Bg),oneof:"scenario"},{no:6,name:"subscriber_bandwidth",kind:"scalar",T:3,oneof:"scenario"},{no:7,name:"disconnect_signal_on_resume",kind:"scalar",T:8,oneof:"scenario"},{no:8,name:"disconnect_signal_on_resume_no_messages",kind:"scalar",T:8,oneof:"scenario"},{no:9,name:"leave_request_full_reconnect",kind:"scalar",T:8,oneof:"scenario"}]),fl=R.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),dv=R.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),lv=R.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:uv,repeated:!0}]),uv=R.makeMessageType("livekit.RegionInfo",()=>[{no:1,name:"region",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9},{no:3,name:"distance",kind:"scalar",T:3}]),hv=R.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:R.getEnumType(Ig)}]),mv=R.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:R.getEnumType(ta)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:ds,oneof:"request"},{no:5,name:"add_track",kind:"message",T:ii,oneof:"request"},{no:6,name:"mute",kind:"message",T:ls,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:Zr,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:Yr,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:cl,oneof:"request"},{no:10,name:"publish_data_track",kind:"message",T:sl,oneof:"request"},{no:11,name:"unpublish_data_track",kind:"message",T:al,oneof:"request"}]),ta=R.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"},{no:4,name:"QUEUED"},{no:5,name:"UNSUPPORTED_TYPE"},{no:6,name:"UNCLASSIFIED_ERROR"},{no:7,name:"INVALID_HANDLE"},{no:8,name:"INVALID_NAME"},{no:9,name:"DUPLICATE_HANDLE"},{no:10,name:"DUPLICATE_NAME"}]),pv=R.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),gl=R.makeMessageType("livekit.ConnectionSettings",()=>[{no:1,name:"auto_subscribe",kind:"scalar",T:8},{no:2,name:"adaptive_stream",kind:"scalar",T:8},{no:3,name:"subscriber_allow_pause",kind:"scalar",T:8,opt:!0},{no:4,name:"disable_ice_lite",kind:"scalar",T:8},{no:5,name:"auto_subscribe_data_track",kind:"scalar",T:8,opt:!0}]),fv=R.makeMessageType("livekit.JoinRequest",()=>[{no:1,name:"client_info",kind:"message",T:Zd},{no:2,name:"connection_settings",kind:"message",T:gl},{no:3,name:"metadata",kind:"scalar",T:9},{no:4,name:"participant_attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"add_track_requests",kind:"message",T:ii,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:Bt},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:R.getEnumType(Xt)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:ea}]),gv=R.makeMessageType("livekit.WrappedJoinRequest",()=>[{no:1,name:"compression",kind:"enum",T:R.getEnumType(vv)},{no:2,name:"join_request",kind:"scalar",T:12}]),vv=R.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),bv=R.makeMessageType("livekit.MediaSectionsRequirement",()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]);function kv(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var Ei={exports:{}},xv=Ei.exports,po;function yv(){return po||(po=1,(function(n){(function(e,t){n.exports?n.exports=t():e.log=t()})(xv,function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],r={},o=null;function a(x,S){var v=x[S];if(typeof v.bind=="function")return v.bind(x);try{return Function.prototype.bind.call(v,x)}catch{return function(){return Function.prototype.apply.apply(v,[x,arguments])}}}function d(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function l(x){return x==="debug"&&(x="log"),typeof console===t?!1:x==="trace"&&i?d:console[x]!==void 0?a(console,x):console.log!==void 0?a(console,"log"):e}function u(){for(var x=this.getLevel(),S=0;S<s.length;S++){var v=s[S];this[v]=S<x?e:this.methodFactory(v,x,this.name)}if(this.log=this.debug,typeof console===t&&x<this.levels.SILENT)return"No console available for logging"}function h(x){return function(){typeof console!==t&&(u.call(this),this[x].apply(this,arguments))}}function m(x,S,v){return l(x)||h.apply(this,arguments)}function f(x,S){var v=this,g,k,T,b="loglevel";typeof x=="string"?b+=":"+x:typeof x=="symbol"&&(b=void 0);function w(L){var O=(s[L]||"silent").toUpperCase();if(!(typeof window===t||!b)){try{window.localStorage[b]=O;return}catch{}try{window.document.cookie=encodeURIComponent(b)+"="+O+";"}catch{}}}function P(){var L;if(!(typeof window===t||!b)){try{L=window.localStorage[b]}catch{}if(typeof L===t)try{var O=window.document.cookie,q=encodeURIComponent(b),J=O.indexOf(q+"=");J!==-1&&(L=/^([^;]+)/.exec(O.slice(J+q.length+1))[1])}catch{}return v.levels[L]===void 0&&(L=void 0),L}}function E(){if(!(typeof window===t||!b)){try{window.localStorage.removeItem(b)}catch{}try{window.document.cookie=encodeURIComponent(b)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function _(L){var O=L;if(typeof O=="string"&&v.levels[O.toUpperCase()]!==void 0&&(O=v.levels[O.toUpperCase()]),typeof O=="number"&&O>=0&&O<=v.levels.SILENT)return O;throw new TypeError("log.setLevel() called with invalid level: "+L)}v.name=x,v.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},v.methodFactory=S||m,v.getLevel=function(){return T??k??g},v.setLevel=function(L,O){return T=_(L),O!==!1&&w(T),u.call(v)},v.setDefaultLevel=function(L){k=_(L),P()||v.setLevel(L,!1)},v.resetLevel=function(){T=null,E(),u.call(v)},v.enableAll=function(L){v.setLevel(v.levels.TRACE,L)},v.disableAll=function(L){v.setLevel(v.levels.SILENT,L)},v.rebuild=function(){if(o!==v&&(g=_(o.getLevel())),u.call(v),o===v)for(var L in r)r[L].rebuild()},g=_(o?o.getLevel():"WARN");var N=P();N!=null&&(T=_(N)),u.call(v)}o=new f,o.getLogger=function(S){if(typeof S!="symbol"&&typeof S!="string"||S==="")throw new TypeError("You must supply a name when creating a logger.");var v=r[S];return v||(v=r[S]=new f(S,o.methodFactory)),v};var C=typeof window!==t?window.log:void 0;return o.noConflict=function(){return typeof window!==t&&window.log===o&&(window.log=C),o},o.getLoggers=function(){return r},o.default=o,o})})(Ei)),Ei.exports}var ms=yv(),tr;(function(n){n[n.trace=0]="trace",n[n.debug=1]="debug",n[n.info=2]="info",n[n.warn=3]="warn",n[n.error=4]="error",n[n.silent=5]="silent"})(tr||(tr={}));var qe;(function(n){n.Default="livekit",n.Room="livekit-room",n.TokenSource="livekit-token-source",n.Participant="livekit-participant",n.Track="livekit-track",n.Publication="livekit-track-publication",n.Engine="livekit-engine",n.Signal="livekit-signal",n.PCManager="livekit-pc-manager",n.PCTransport="livekit-pc-transport",n.E2EE="lk-e2ee",n.DataTracks="livekit-data-tracks"})(qe||(qe={}));let Y=ms.getLogger("livekit");Object.values(qe).map(n=>ms.getLogger(n));Y.setDefaultLevel(tr.info);function Ze(n){const e=ms.getLogger(n);return e.setDefaultLevel(Y.getLevel()),e}const Cv=ms.getLogger("lk-e2ee"),Vn=7e3,Tv=[0,300,4*300,9*300,16*300,Vn,Vn,Vn,Vn,Vn];class Sv{constructor(e){this._retryDelays=e!==void 0?[...e]:Tv}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+Math.random()*1e3}}function wv(n,e){var t={};for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&e.indexOf(i)<0&&(t[i]=n[i]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,i=Object.getOwnPropertySymbols(n);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(n,i[s])&&(t[i[s]]=n[i[s]]);return t}function y(n,e,t,i){function s(r){return r instanceof t?r:new t(function(o){o(r)})}return new(t||(t=Promise))(function(r,o){function a(u){try{l(i.next(u))}catch(h){o(h)}}function d(u){try{l(i.throw(u))}catch(h){o(h)}}function l(u){u.done?r(u.value):s(u.value).then(a,d)}l((i=i.apply(n,e||[])).next())})}function fo(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],i=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&i>=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function wt(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof fo=="function"?fo(n):n[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(r){t[r]=n[r]&&function(o){return new Promise(function(a,d){o=n[r](o),s(a,d,o.done,o.value)})}}function s(r,o,a,d){Promise.resolve(d).then(function(l){r({value:l,done:a})},o)}}var ki={exports:{}},go;function Rv(){if(go)return ki.exports;go=1;var n=typeof Reflect=="object"?Reflect:null,e=n&&typeof n.apply=="function"?n.apply:function(b,w,P){return Function.prototype.apply.call(b,w,P)},t;n&&typeof n.ownKeys=="function"?t=n.ownKeys:Object.getOwnPropertySymbols?t=function(b){return Object.getOwnPropertyNames(b).concat(Object.getOwnPropertySymbols(b))}:t=function(b){return Object.getOwnPropertyNames(b)};function i(T){console&&console.warn&&console.warn(T)}var s=Number.isNaN||function(b){return b!==b};function r(){r.init.call(this)}ki.exports=r,ki.exports.once=v,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var o=10;function a(T){if(typeof T!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof T)}Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return o}
vendor: 4,188 bytes, line 44
44,set:function(T){if(typeof T!="number"||T<0||s(T))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+T+".");o=T}}),r.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},r.prototype.setMaxListeners=function(b){if(typeof b!="number"||b<0||s(b))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+b+".");return this._maxListeners=b,this};function d(T){return T._maxListeners===void 0?r.defaultMaxListeners:T._maxListeners}r.prototype.getMaxListeners=function(){return d(this)},r.prototype.emit=function(b){for(var w=[],P=1;P<arguments.length;P++)w.push(arguments[P]);var E=b==="error",_=this._events;if(_!==void 0)E=E&&_.error===void 0;else if(!E)return!1;if(E){var N;if(w.length>0&&(N=w[0]),N instanceof Error)throw N;var L=new Error("Unhandled error."+(N?" ("+N.message+")":""));throw L.context=N,L}var O=_[b];if(O===void 0)return!1;if(typeof O=="function")e(O,this,w);else for(var q=O.length,J=C(O,q),P=0;P<q;++P)e(J[P],this,w);return!0};function l(T,b,w,P){var E,_,N;if(a(w),_=T._events,_===void 0?(_=T._events=Object.create(null),T._eventsCount=0):(_.newListener!==void 0&&(T.emit("newListener",b,w.listener?w.listener:w),_=T._events),N=_[b]),N===void 0)N=_[b]=w,++T._eventsCount;else if(typeof N=="function"?N=_[b]=P?[w,N]:[N,w]:P?N.unshift(w):N.push(w),E=d(T),E>0&&N.length>E&&!N.warned){N.warned=!0;var L=new Error("Possible EventEmitter memory leak detected. "+N.length+" "+String(b)+" listeners added. Use emitter.setMaxListeners() to increase limit");L.name="MaxListenersExceededWarning",L.emitter=T,L.type=b,L.count=N.length,i(L)}return T}r.prototype.addListener=function(b,w){return l(this,b,w,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(b,w){return l(this,b,w,!0)};function u(){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 h(T,b,w){var P={fired:!1,wrapFn:void 0,target:T,type:b,listener:w},E=u.bind(P);return E.listener=w,P.wrapFn=E,E}r.prototype.once=function(b,w){return a(w),this.on(b,h(this,b,w)),this},r.prototype.prependOnceListener=function(b,w){return a(w),this.prependListener(b,h(this,b,w)),this},r.prototype.removeListener=function(b,w){var P,E,_,N,L;if(a(w),E=this._events,E===void 0)return this;if(P=E[b],P===void 0)return this;if(P===w||P.listener===w)--this._eventsCount===0?this._events=Object.create(null):(delete E[b],E.removeListener&&this.emit("removeListener",b,P.listener||w));else if(typeof P!="function"){for(_=-1,N=P.length-1;N>=0;N--)if(P[N]===w||P[N].listener===w){L=P[N].listener,_=N;break}if(_<0)return this;_===0?P.shift():x(P,_),P.length===1&&(E[b]=P[0]),E.removeListener!==void 0&&this.emit("removeListener",b,L||w)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(b){var w,P,E;if(P=this._events,P===void 0)return this;if(P.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):P[b]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete P[b]),this;if(arguments.length===0){var _=Object.keys(P),N;for(E=0;E<_.length;++E)N=_[E],N!=="removeListener"&&this.removeAllListeners(N);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(w=P[b],typeof w=="function")this.removeListener(b,w);else if(w!==void 0)for(E=w.length-1;E>=0;E--)this.removeListener(b,w[E]);return this};function m(T,b,w){var P=T._events;if(P===void 0)return[];var E=P[b];return E===void 0?[]:typeof E=="function"?w?[E.listener||E]:[E]:w?S(E):C(E,E.length)}r.prototype.listeners=function(b){return m(this,b,!0)},r.prototype.rawListeners=function(b){return m(this,b,!1)},r.listenerCount=function(T,b){return typeof T.listenerCount=="function"?T.listenerCount(b):f.call(T,b)},r.prototype.listenerCount=f;function f(T){var b=this._events;if(b!==void 0){var w=b[T];
vendor: 47,652 bytes, lines 44-78
44if(typeof w=="function")return 1;if(w!==void 0)return w.length}return 0}r.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function C(T,b){for(var w=new Array(b),P=0;P<b;++P)w[P]=T[P];return w}function x(T,b){for(;b+1<T.length;b++)T[b]=T[b+1];T.pop()}function S(T){for(var b=new Array(T.length),w=0;w<b.length;++w)b[w]=T[w].listener||T[w];return b}function v(T,b){return new Promise(function(w,P){function E(N){T.removeListener(b,_),P(N)}function _(){typeof T.removeListener=="function"&&T.removeListener("error",E),w([].slice.call(arguments))}k(T,b,_,{once:!0}),b!=="error"&&g(T,E,{once:!0})})}function g(T,b,w){typeof T.on=="function"&&k(T,"error",b,w)}function k(T,b,w,P){if(typeof T.on=="function")P.once?T.once(b,w):T.on(b,w);else if(typeof T.addEventListener=="function")T.addEventListener(b,function E(_){P.once&&T.removeEventListener(b,E),w(_)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof T)}return ki.exports}var bt=Rv();let vl=!0,bl=!0;function Jn(n,e,t){const i=n.match(e);return i&&i.length>=t&&parseFloat(i[t],10)}function un(n,e,t){if(!n.RTCPeerConnection)return;const i=n.RTCPeerConnection.prototype,s=i.addEventListener;i.addEventListener=function(o,a){if(o!==e)return s.apply(this,arguments);const d=l=>{const u=t(l);u&&(a.handleEvent?a.handleEvent(u):a(u))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(a,d),s.apply(this,[o,d])};const r=i.removeEventListener;i.removeEventListener=function(o,a){if(o!==e||!this._eventMap||!this._eventMap[e])return r.apply(this,arguments);if(!this._eventMap[e].has(a))return r.apply(this,arguments);const d=this._eventMap[e].get(a);return this._eventMap[e].delete(a),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,r.apply(this,[o,d])},Object.defineProperty(i,"on"+e,{get(){return this["_on"+e]},set(o){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),o&&this.addEventListener(e,this["_on"+e]=o)},enumerable:!0,configurable:!0})}function Ev(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(vl=n,n?"adapter.js logging disabled":"adapter.js logging enabled")}function Pv(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(bl=!n,"adapter.js deprecation warnings "+(n?"disabled":"enabled"))}function kl(){if(typeof window=="object"){if(vl)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function na(n,e){bl&&console.warn(n+" is deprecated, please use "+e+" instead.")}function Nv(n){const e={browser:null,version:null};if(typeof n>"u"||!n.navigator||!n.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:t}=n;if(t.userAgentData&&t.userAgentData.brands){const i=t.userAgentData.brands.find(s=>s.brand==="Chromium");if(i)return{browser:"chrome",version:parseInt(i.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=parseInt(Jn(t.userAgent,/Firefox\/(\d+)\./,1));else if(t.webkitGetUserMedia||n.isSecureContext===!1&&n.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(Jn(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(n.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=parseInt(Jn(t.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=n.RTCRtpTransceiver&&"currentDirection"in n.RTCRtpTransceiver.prototype,e._safariVersion=Jn(t.userAgent,/Version\/(\d+(\.?\d+))/,1);else return e.browser="Not a supported browser.",e;return e}function vo(n){return Object.prototype.toString.call(n)==="[object Object]"}function xl(n){return vo(n)?Object.keys(n).reduce(function(e,t){const i=vo(n[t]),s=i?xl(n[t]):n[t],r=i&&!Object.keys(s).length;return s===void 0||r?e:Object.assign(e,{[t]:s})},{}):n}function nr(n,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(i=>{i.endsWith("Id")?nr(n,n.get(e[i]),t):i.endsWith("Ids")&&e[i].forEach(s=>{nr(n,n.get(s),t)})}))}function bo(n,e,t){const i=t?"outbound-rtp":"inbound-rtp",s=new Map;if(e===null)return s;const r=[];return n.forEach(o=>{o.type==="track"&&o.trackIdentifier===e.id&&r.push(o)}),r.forEach(o=>{n.forEach(a=>{a.type===i&&a.trackId===o.id&&nr(n,a,s)})}),s}const ko=kl;function yl(n,e){const t=n&&n.navigator;if(!t.mediaDevices)return;const i=function(a){if(typeof a!="object"||a.mandatory||a.optional)return a;const d={};return Object.keys(a).forEach(l=>{if(l==="require"||l==="advanced"||l==="mediaSource")return;const u=typeof a[l]=="object"?a[l]:{ideal:a[l]};u.exact!==void 0&&typeof u.exact=="number"&&(u.min=u.max=u.exact);const h=function(m,f){return m?m+f.charAt(0).toUpperCase()+f.slice(1):f==="deviceId"?"sourceId":f};if(u.ideal!==void 0){d.optional=d.optional||[];let m={};typeof u.ideal=="number"?(m[h("min",l)]=u.ideal,d.optional.push(m),m={},m[h("max",l)]=u.ideal,d.optional.push(m)):(m[h("",l)]=u.ideal,d.optional.push(m))}u.exact!==void 0&&typeof u.exact!="number"?(d.mandatory=d.mandatory||{},d.mandatory[h("",l)]=u.exact):["min","max"].forEach(m=>{u[m]!==void 0&&(d.mandatory=d.mandatory||{},d.mandatory[h(m,l)]=u[m])})}),a.advanced&&(d.optional=(d.optional||[]).concat(a.advanced)),d},s=function(a,d){if(e.version>=61)return d(a);if(a=JSON.parse(JSON.stringify(a)),a&&typeof a.audio=="object"){const l=function(u,h,m){h in u&&!(m in u)&&(u[m]=u[h],delete u[h])};a=JSON.parse(JSON.stringify(a)),l(a.audio,"autoGainControl","googAutoGainControl"),l(a.audio,"noiseSuppression","googNoiseSuppression"),a.audio=i(a.audio)}if(a&&typeof a.video=="object"){let l=a.video.facingMode;l=l&&(typeof l=="object"?l:{ideal:l});const u=e.version<66;if(l&&(l.exact==="user"||l.exact==="environment"||l.ideal==="user"||l.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!u)){delete a.video.facingMode;let h;if(l.exact==="environment"||l.ideal==="environment"?h=["back","rear"]:(l.exact==="user"||l.ideal==="user")&&(h=["front"]),h)return t.mediaDevices.enumerateDevices().then(m=>{m=m.filter(C=>C.kind==="videoinput");let f=m.find(C=>h.some(x=>C.label.toLowerCase().includes(x)));return!f&&m.length&&h.includes("back")&&(f=m[m.length-1]),f&&(a.video.deviceId=l.exact?{exact:f.deviceId}:{ideal:f.deviceId}),a.video=i(a.video),ko("chrome: "+JSON.stringify(a)),d(a)})}a.video=i(a.video)}return ko("chrome: "+JSON.stringify(a)),d(a)},r=function(a){return e.version>=64?a:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[a.name]||a.name,message:a.message,constraint:a.constraint||a.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},o=function(a,d,l){s(a,u=>{t.webkitGetUserMedia(u,d,h=>{l&&l(r(h))})})};if(t.getUserMedia=o.bind(t),t.mediaDevices.getUserMedia){const a=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(d){return s(d,l=>a(l).then(u=>{if(l.audio&&!u.getAudioTracks().length||l.video&&!u.getVideoTracks().length)throw u.getTracks().forEach(h=>{h.stop()}),new DOMException("","NotFoundError");return u},u=>Promise.reject(r(u))))}}}function Cl(n){n.MediaStream=n.MediaStream||n.webkitMediaStream}function Tl(n){if(typeof n=="object"&&n.RTCPeerConnection&&!("ontrack"in n.RTCPeerConnection.prototype)){Object.defineProperty(n.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(t){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=t)},enumerable:!0,configurable:!0});const e=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=i=>{i.stream.addEventListener("addtrack",s=>{let r;n.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(a=>a.track&&a.track.id===s.track.id):r={track:s.track};const o=new Event("track");o.track=s.track,o.receiver=r,o.transceiver={receiver:r},o.streams=[i.stream],this.dispatchEvent(o)}),i.stream.getTracks().forEach(s=>{let r;n.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(a=>a.track&&a.track.id===s.id):r={track:s};const o=new Event("track");o.track=s,o.receiver=r,o.transceiver={receiver:r},o.streams=[i.stream],this.dispatchEvent(o)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else un(n,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function Sl(n){if(typeof n=="object"&&n.RTCPeerConnection&&!("getSenders"in n.RTCPeerConnection.prototype)&&"createDTMFSender"in n.RTCPeerConnection.prototype){const e=function(s,r){return{track:r,get dtmf(){return this._dtmf===void 0&&(r.kind==="audio"?this._dtmf=s.createDTMFSender(r):this._dtmf=null),this._dtmf},_pc:s}};if(!n.RTCPeerConnection.prototype.getSenders){n.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const s=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addTrack=function(a,d){let l=s.apply(this,arguments);return l||(l=e(this,a),this._senders.push(l)),l};const r=n.RTCPeerConnection.prototype.removeTrack;n.RTCPeerConnection.prototype.removeTrack=function(a){r.apply(this,arguments);const d=this._senders.indexOf(a);d!==-1&&this._senders.splice(d,1)}}const t=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(r){this._senders=this._senders||[],t.apply(this,[r]),r.getTracks().forEach(o=>{this._senders.push(e(this,o))})};const i=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(r){this._senders=this._senders||[],i.apply(this,[r]),r.getTracks().forEach(o=>{const a=this._senders.find(d=>d.track===o);a&&this._senders.splice(this._senders.indexOf(a),1)})}}else if(typeof n=="object"&&n.RTCPeerConnection&&"getSenders"in n.RTCPeerConnection.prototype&&"createDTMFSender"in n.RTCPeerConnection.prototype&&n.RTCRtpSender&&!("dtmf"in n.RTCRtpSender.prototype)){const e=n.RTCPeerConnection.prototype.getSenders;n.RTCPeerConnection.prototype.getSenders=function(){const i=e.apply(this,[]);return i.forEach(s=>s._pc=this),i},Object.defineProperty(n.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function wl(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender&&n.RTCRtpReceiver))return;if(!("getStats"in n.RTCRtpSender.prototype)){const t=n.RTCPeerConnection.prototype.getSenders;t&&(n.RTCPeerConnection.prototype.getSenders=function(){const r=t.apply(this,[]);return r.forEach(o=>o._pc=this),r});const i=n.RTCPeerConnection.prototype.addTrack;i&&(n.RTCPeerConnection.prototype.addTrack=function(){const r=i.apply(this,arguments);return r._pc=this,r}),n.RTCRtpSender.prototype.getStats=function(){const r=this;return this._pc.getStats().then(o=>bo(o,r.track,!0))}}if(!("getStats"in n.RTCRtpReceiver.prototype)){const t=n.RTCPeerConnection.prototype.getReceivers;t&&(n.RTCPeerConnection.prototype.getReceivers=function(){const s=t.apply(this,[]);return s.forEach(r=>r._pc=this),s}),un(n,"track",i=>(i.receiver._pc=i.srcElement,i)),n.RTCRtpReceiver.prototype.getStats=function(){const s=this;return this._pc.getStats().then(r=>bo(r,s.track,!1))}}if(!("getStats"in n.RTCRtpSender.prototype&&"getStats"in n.RTCRtpReceiver.prototype))return;const e=n.RTCPeerConnection.prototype.getStats;n.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof n.MediaStreamTrack){const i=arguments[0];let s,r,o;return this.getSenders().forEach(a=>{a.track===i&&(s?o=!0:s=a)}),this.getReceivers().forEach(a=>(a.track===i&&(r?o=!0:r=a),a.track===i)),o||s&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):s?s.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function Rl(n){n.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(o=>this._shimmedLocalStreams[o][0])};const e=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addTrack=function(o,a){if(!a)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const d=e.apply(this,arguments);return this._shimmedLocalStreams[a.id]?this._shimmedLocalStreams[a.id].indexOf(d)===-1&&this._shimmedLocalStreams[a.id].push(d):this._shimmedLocalStreams[a.id]=[a,d],d};const t=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(o){this._shimmedLocalStreams=this._shimmedLocalStreams||{},o.getTracks().forEach(l=>{if(this.getSenders().find(h=>h.track===l))throw new DOMException("Track already exists.","InvalidAccessError")});const a=this.getSenders();t.apply(this,arguments);const d=this.getSenders().filter(l=>a.indexOf(l)===-1);this._shimmedLocalStreams[o.id]=[o].concat(d)};const i=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[o.id],i.apply(this,arguments)};const s=n.RTCPeerConnection.prototype.removeTrack;n.RTCPeerConnection.prototype.removeTrack=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},o&&Object.keys(this._shimmedLocalStreams).forEach(a=>{const d=this._shimmedLocalStreams[a].indexOf(o);d!==-1&&this._shimmedLocalStreams[a].splice(d,1),this._shimmedLocalStreams[a].length===1&&delete this._shimmedLocalStreams[a]}),s.apply(this,arguments)}}function El(n,e){if(!n.RTCPeerConnection)return;if(n.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Rl(n);const t=n.RTCPeerConnection.prototype.getLocalStreams;n.RTCPeerConnection.prototype.getLocalStreams=function(){const u=t.apply(this);return this._reverseStreams=this._reverseStreams||{},u.map(h=>this._reverseStreams[h.id])};const i=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(u){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},u.getTracks().forEach(h=>{if(this.getSenders().find(f=>f.track===h))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[u.id]){const h=new n.MediaStream(u.getTracks());this._streams[u.id]=h,this._reverseStreams[h.id]=u,u=h}i.apply(this,[u])};const s=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(u){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[u.id]||u]),delete this._reverseStreams[this._streams[u.id]?this._streams[u.id].id:u.id],delete this._streams[u.id]},n.RTCPeerConnection.prototype.addTrack=function(u,h){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const m=[].slice.call(arguments,1);if(m.length!==1||!m[0].getTracks().find(x=>x===u))throw new DOMException("The adapter.js addTrack polyfill only supports a single  stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(x=>x.track===u))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const C=this._streams[h.id];if(C)C.addTrack(u),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const x=new n.MediaStream([u]);this._streams[h.id]=x,this._reverseStreams[x.id]=h,this.addStream(x)}return this.getSenders().find(x=>x.track===u)};function r(l,u){let h=u.sdp;return Object.keys(l._reverseStreams||[]).forEach(m=>{const f=l._reverseStreams[m],C=l._streams[f.id];h=h.replace(new RegExp(C.id,"g"),f.id)}),new RTCSessionDescription({type:u.type,sdp:h})}function o(l,u){let h=u.sdp;return Object.keys(l._reverseStreams||[]).forEach(m=>{const f=l._reverseStreams[m],C=l._streams[f.id];h=h.replace(new RegExp(f.id,"g"),C.id)}),new RTCSessionDescription({type:u.type,sdp:h})}["createOffer","createAnswer"].forEach(function(l){const u=n.RTCPeerConnection.prototype[l],h={[l](){const m=arguments;return arguments.length&&typeof arguments[0]=="function"?u.apply(this,[C=>{const x=r(this,C);m[0].apply(null,[x])},C=>{m[1]&&m[1].apply(null,C)},arguments[2]]):u.apply(this,arguments).then(C=>r(this,C))}};n.RTCPeerConnection.prototype[l]=h[l]});const a=n.RTCPeerConnection.prototype.setLocalDescription;n.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?a.apply(this,arguments):(arguments[0]=o(this,arguments[0]),a.apply(this,arguments))};const d=Object.getOwnPropertyDescriptor(n.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(n.RTCPeerConnection.prototype,"localDescription",{get(){const l=d.get.apply(this);return l.type===""?l:r(this,l)}}),n.RTCPeerConnection.prototype.removeTrack=function(u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!u._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(u._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let m;Object.keys(this._streams).forEach(f=>{this._streams[f].getTracks().find(x=>u.track===x)&&(m=this._streams[f])}),m&&(m.getTracks().length===1?this.removeStream(this._reverseStreams[m.id]):m.removeTrack(u.track),this.dispatchEvent(new Event("negotiationneeded")))}}function ir(n,e){!n.RTCPeerConnection&&n.webkitRTCPeerConnection&&(n.RTCPeerConnection=n.webkitRTCPeerConnection),n.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=n.RTCPeerConnection.prototype[t],s={[t](){return arguments[0]=new(t==="addIceCandidate"?n.RTCIceCandidate:n.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};n.RTCPeerConnection.prototype[t]=s[t]})}function Pl(n,e){un(n,"negotiationneeded",t=>{const i=t.target;if(!((e.version<72||i.getConfiguration&&i.getConfiguration().sdpSemantics==="plan-b")&&i.signalingState!=="stable"))return t})}var xo=Object.freeze({__proto__:null,fixNegotiationNeeded:Pl,shimAddTrackRemoveTrack:El,shimAddTrackRemoveTrackWithNative:Rl,shimGetSendersWithDtmf:Sl,shimGetUserMedia:yl,shimMediaStream:Cl,shimOnTrack:Tl,shimPeerConnection:ir,shimSenderReceiverGetStats:wl});function Nl(n,e){const t=n&&n.navigator,i=n&&n.MediaStreamTrack;if(t.getUserMedia=function(s,r,o){na("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(s).then(r,o)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const s=function(o,a,d){a in o&&!(d in o)&&(o[d]=o[a],delete o[a])},r=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(o){return typeof o=="object"&&typeof o.audio=="object"&&(o=JSON.parse(JSON.stringify(o)),s(o.audio,"autoGainControl","mozAutoGainControl"),s(o.audio,"noiseSuppression","mozNoiseSuppression")),r(o)},i&&i.prototype.getSettings){const o=i.prototype.getSettings;i.prototype.getSettings=function(){const a=o.apply(this,arguments);return s(a,"mozAutoGainControl","autoGainControl"),s(a,"mozNoiseSuppression","noiseSuppression"),a}}if(i&&i.prototype.applyConstraints){const o=i.prototype.applyConstraints;i.prototype.applyConstraints=function(a){return this.kind==="audio"&&typeof a=="object"&&(a=JSON.parse(JSON.stringify(a)),s(a,"autoGainControl","mozAutoGainControl"),s(a,"noiseSuppression","mozNoiseSuppression")),o.apply(this,[a])}}}}function _v(n,e){n.navigator.mediaDevices&&"getDisplayMedia"in n.navigator.mediaDevices||n.navigator.mediaDevices&&(n.navigator.mediaDevices.getDisplayMedia=function(i){if(!(i&&i.video)){const s=new DOMException("getDisplayMedia without video constraints is undefined");return s.name="NotFoundError",s.code=8,Promise.reject(s)}return i.video===!0?i.video={mediaSource:e}:i.video.mediaSource=e,n.navigator.mediaDevices.getUserMedia(i)})}function _l(n){typeof n=="object"&&n.RTCTrackEvent&&"receiver"in n.RTCTrackEvent.prototype&&!("transceiver"in n.RTCTrackEvent.prototype)&&Object.defineProperty(n.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function sr(n,e){if(typeof n!="object"||!(n.RTCPeerConnection||n.mozRTCPeerConnection))return;!n.RTCPeerConnection&&n.mozRTCPeerConnection&&(n.RTCPeerConnection=n.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(s){const r=n.RTCPeerConnection.prototype[s],o={[s](){return arguments[0]=new(s==="addIceCandidate"?n.RTCIceCandidate:n.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};n.RTCPeerConnection.prototype[s]=o[s]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=n.RTCPeerConnection.prototype.getStats;n.RTCPeerConnection.prototype.getStats=function(){const[r,o,a]=arguments;return i.apply(this,[r||null]).then(d=>{if(e.version<53&&!o)try{d.forEach(l=>{l.type=t[l.type]||l.type})}catch(l){if(l.name!=="TypeError")throw l;d.forEach((u,h)=>{d.set(h,Object.assign({},u,{type:t[u.type]||u.type}))})}return d}).then(o,a)}}function Il(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender)||n.RTCRtpSender&&"getStats"in n.RTCRtpSender.prototype)return;const e=n.RTCPeerConnection.prototype.getSenders;e&&(n.RTCPeerConnection.prototype.getSenders=function(){const s=e.apply(this,[]);return s.forEach(r=>r._pc=this),s});const t=n.RTCPeerConnection.prototype.addTrack;t&&(n.RTCPeerConnection.prototype.addTrack=function(){const s=t.apply(this,arguments);return s._pc=this,s}),n.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Ml(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender)||n.RTCRtpSender&&"getStats"in n.RTCRtpReceiver.prototype)return;const e=n.RTCPeerConnection.prototype.getReceivers;e&&(n.RTCPeerConnection.prototype.getReceivers=function(){const i=e.apply(this,[]);return i.forEach(s=>s._pc=this),i}),un(n,"track",t=>(t.receiver._pc=t.srcElement,t)),n.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function jl(n){!n.RTCPeerConnection||"removeStream"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.removeStream=function(t){na("removeStream","removeTrack"),this.getSenders().forEach(i=>{i.track&&t.getTracks().includes(i.track)&&this.removeTrack(i)})})}function Ol(n){n.DataChannel&&!n.RTCDataChannel&&(n.RTCDataChannel=n.DataChannel)}function Ll(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.addTransceiver;e&&(n.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let i=arguments[1]&&arguments[1].sendEncodings;i===void 0&&(i=[]),i=[...i];const s=i.length>0;s&&i.forEach(o=>{if("rid"in o&&!/^[a-z0-9]{0,16}$/i.test(o.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in o&&!(parseFloat(o.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in o&&!(parseFloat(o.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const r=e.apply(this,arguments);if(s){const{sender:o}=r,a=o.getParameters();(!("encodings"in a)||a.encodings.length===1&&Object.keys(a.encodings[0]).length===0)&&(a.encodings=i,o.sendEncodings=i,this.setParametersPromises.push(o.setParameters(a).then(()=>{delete o.sendEncodings}).catch(()=>{delete o.sendEncodings})))}return r})}function Al(n){if(!(typeof n=="object"&&n.RTCRtpSender))return;const e=n.RTCRtpSender.prototype.getParameters;e&&(n.RTCRtpSender.prototype.getParameters=function(){const i=e.apply(this,arguments);return"encodings"in i||(i.encodings=[].concat(this.sendEncodings||[{}])),i})}function Dl(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.createOffer;n.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function Ul(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.createAnswer;n.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}var yo=Object.freeze({__proto__:null,shimAddTransceiver:Ll,shimCreateAnswer:Ul,shimCreateOffer:Dl,shimGetDisplayMedia:_v,shimGetParameters:Al,shimGetUserMedia:Nl,shimOnTrack:_l,shimPeerConnection:sr,shimRTCDataChannel:Ol,shimReceiverGetStats:Ml,shimRemoveStream:jl,shimSenderGetStats:Il});function Fl(n){if(!(typeof n!="object"||!n.RTCPeerConnection)){if("getLocalStreams"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in n.RTCPeerConnection.prototype)){const e=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addStream=function(i){this._localStreams||(this._localStreams=[]),this._localStreams.includes(i)||this._localStreams.push(i),i.getAudioTracks().forEach(s=>e.call(this,s,i)),i.getVideoTracks().forEach(s=>e.call(this,s,i))},n.RTCPeerConnection.prototype.addTrack=function(i){for(var s=arguments.length,r=new Array(s>1?s-1:0),o=1;o<s;o++)r[o-1]=arguments[o];return r&&r.forEach(a=>{this._localStreams?this._localStreams.includes(a)||this._localStreams.push(a):this._localStreams=[a]}),e.apply(this,arguments)}}"removeStream"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const i=this._localStreams.indexOf(t);if(i===-1)return;this._localStreams.splice(i,1);const s=t.getTracks();this.getSenders().forEach(r=>{s.includes(r.track)&&this.removeTrack(r)})})}}function Vl(n){if(!(typeof n!="object"||!n.RTCPeerConnection)&&("getRemoteStreams"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in n.RTCPeerConnection.prototype))){Object.defineProperty(n.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=i=>{i.streams.forEach(s=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(s))return;this._remoteStreams.push(s);const r=new Event("addstream");r.stream=s,this.dispatchEvent(r)})})}});const e=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){const i=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(s){s.streams.forEach(r=>{if(i._remoteStreams||(i._remoteStreams=[]),i._remoteStreams.indexOf(r)>=0)return;i._remoteStreams.push(r);const o=new Event("addstream");o.stream=r,i.dispatchEvent(o)})}),e.apply(i,arguments)}}}function Bl(n){if(typeof n!="object"||!n.RTCPeerConnection)return;const e=n.RTCPeerConnection.prototype,t=e.createOffer,i=e.createAnswer,s=e.setLocalDescription,r=e.setRemoteDescription,o=e.addIceCandidate;e.createOffer=function(l,u){const h=arguments.length>=2?arguments[2]:arguments[0],m=t.apply(this,[h]);return u?(m.then(l,u),Promise.resolve()):m},e.createAnswer=function(l,u){const h=arguments.length>=2?arguments[2]:arguments[0],m=i.apply(this,[h]);return u?(m.then(l,u),Promise.resolve()):m};let a=function(d,l,u){const h=s.apply(this,[d]);return u?(h.then(l,u),Promise.resolve()):h};e.setLocalDescription=a,a=function(d,l,u){const h=r.apply(this,[d]);return u?(h.then(l,u),Promise.resolve()):h},e.setRemoteDescription=a,a=function(d,l,u){const h=o.apply(this,[d]);return u?(h.then(l,u),Promise.resolve()):h},e.addIceCandidate=a}function ql(n){const e=n&&n.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,i=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=s=>i(Hl(s))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=function(i,s,r){e.mediaDevices.getUserMedia(i).then(s,r)}.bind(e))}function Hl(n){return n&&n.video!==void 0?Object.assign({},n,{video:xl(n.video)}):n}function zl(n){if(!n.RTCPeerConnection)return;const e=n.RTCPeerConnection;n.RTCPeerConnection=function(i,s){if(i&&i.iceServers){const r=[];for(let o=0;o<i.iceServers.length;o++){let a=i.iceServers[o];a.urls===void 0&&a.url?(na("RTCIceServer.url","RTCIceServer.urls"),a=JSON.parse(JSON.stringify(a)),a.urls=a.url,delete a.url,r.push(a)):r.push(i.iceServers[o])}i.iceServers=r}return new e(i,s)},n.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(n.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function Kl(n){typeof n=="object"&&n.RTCTrackEvent&&"receiver"in n.RTCTrackEvent.prototype&&!("transceiver"in n.RTCTrackEvent.prototype)&&Object.defineProperty(n.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Wl(n){const e=n.RTCPeerConnection.prototype.createOffer;n.RTCPeerConnection.prototype.createOffer=function(i){if(i){typeof i.offerToReceiveAudio<"u"&&(i.offerToReceiveAudio=!!i.offerToReceiveAudio);const s=this.getTransceivers().find(o=>o.receiver.track.kind==="audio");i.offerToReceiveAudio===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):i.offerToReceiveAudio===!0&&!s&&this.addTransceiver("audio",{direction:"recvonly"}),typeof i.offerToReceiveVideo<"u"&&(i.offerToReceiveVideo=!!i.offerToReceiveVideo);const r=this.getTransceivers().find(o=>o.receiver.track.kind==="video");i.offerToReceiveVideo===!1&&r?r.direction==="sendrecv"?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":r.direction==="recvonly"&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):i.offerToReceiveVideo===!0&&!r&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function Gl(n){typeof n!="object"||n.AudioContext||(n.AudioContext=n.webkitAudioContext)}var Co=Object.freeze({__proto__:null,shimAudioContext:Gl,shimCallbacksAPI:Bl,shimConstraints:Hl,shimCreateOfferLegacy:Wl,shimGetUserMedia:ql,shimLocalStreamsAPI:Fl,shimRTCIceServerUrls:zl,shimRemoteStreamsAPI:Vl,shimTrackEventTransceiver:Kl}),_s={exports:{}},To;function Iv(){return To||(To=1,(function(n){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(`
45`).map(i=>i.trim())},e.splitSections=function(t){return t.split(`
46m=`).map((s,r)=>(r>0?"m="+s:s).trim()+`\r
47`)},e.getDescription=function(t){const i=e.splitSections(t);return i&&i[0]},e.getMediaSections=function(t){const i=e.splitSections(t);return i.shift(),i},e.matchPrefix=function(t,i){return e.splitLines(t).filter(s=>s.indexOf(i)===0)},e.parseCandidate=function(t){let i;t.indexOf("a=candidate:")===0?i=t.substring(12).split(" "):i=t.substring(10).split(" ");const s={foundation:i[0],component:{1:"rtp",2:"rtcp"}[i[1]]||i[1],protocol:i[2].toLowerCase(),priority:parseInt(i[3],10),ip:i[4],address:i[4],port:parseInt(i[5],10),type:i[7]};for(let r=8;r<i.length;r+=2)switch(i[r]){case"raddr":s.relatedAddress=i[r+1];break;case"rport":s.relatedPort=parseInt(i[r+1],10);break;case"tcptype":s.tcpType=i[r+1];break;case"ufrag":s.ufrag=i[r+1],s.usernameFragment=i[r+1];break;default:s[i[r]]===void 0&&(s[i[r]]=i[r+1]);break}return s},e.writeCandidate=function(t){const i=[];i.push(t.foundation);const s=t.component;s==="rtp"?i.push(1):s==="rtcp"?i.push(2):i.push(s),i.push(t.protocol.toUpperCase()),i.push(t.priority),i.push(t.address||t.ip),i.push(t.port);const r=t.type;return i.push("typ"),i.push(r),r!=="host"&&t.relatedAddress&&t.relatedPort&&(i.push("raddr"),i.push(t.relatedAddress),i.push("rport"),i.push(t.relatedPort)),t.tcpType&&t.protocol.toLowerCase()==="tcp"&&(i.push("tcptype"),i.push(t.tcpType)),(t.usernameFragment||t.ufrag)&&(i.push("ufrag"),i.push(t.usernameFragment||t.ufrag)),"candidate:"+i.join(" ")},e.parseIceOptions=function(t){return t.substring(14).split(" ")},e.parseRtpMap=function(t){let i=t.substring(9).split(" ");const s={payloadType:parseInt(i.shift(),10)};return i=i[0].split("/"),s.name=i[0],s.clockRate=parseInt(i[1],10),s.channels=i.length===3?parseInt(i[2],10):1,s.numChannels=s.channels,s},e.writeRtpMap=function(t){let i=t.payloadType;t.preferredPayloadType!==void 0&&(i=t.preferredPayloadType);const s=t.channels||t.numChannels||1;return"a=rtpmap:"+i+" "+t.name+"/"+t.clockRate+(s!==1?"/"+s:"")+`\r
48`},e.parseExtmap=function(t){const i=t.substring(9).split(" ");return{id:parseInt(i[0],10),direction:i[0].indexOf("/")>0?i[0].split("/")[1]:"sendrecv",uri:i[1],attributes:i.slice(2).join(" ")}},e.writeExtmap=function(t){return"a=extmap:"+(t.id||t.preferredId)+(t.direction&&t.direction!=="sendrecv"?"/"+t.direction:"")+" "+t.uri+(t.attributes?" "+t.attributes:"")+`\r
49`},e.parseFmtp=function(t){const i={};let s;const r=t.substring(t.indexOf(" ")+1).split(";");for(let o=0;o<r.length;o++)s=r[o].trim().split("="),i[s[0].trim()]=s[1];return i},e.writeFmtp=function(t){let i="",s=t.payloadType;if(t.preferredPayloadType!==void 0&&(s=t.preferredPayloadType),t.parameters&&Object.keys(t.parameters).length){const r=[];Object.keys(t.parameters).forEach(o=>{t.parameters[o]!==void 0?r.push(o+"="+t.parameters[o]):r.push(o)}),i+="a=fmtp:"+s+" "+r.join(";")+`\r
50`}return i},e.parseRtcpFb=function(t){const i=t.substring(t.indexOf(" ")+1).split(" ");return{type:i.shift(),parameter:i.join(" ")}},e.writeRtcpFb=function(t){let i="",s=t.payloadType;return t.preferredPayloadType!==void 0&&(s=t.preferredPayloadType),t.rtcpFeedback&&t.rtcpFeedback.length&&t.rtcpFeedback.forEach(r=>{i+="a=rtcp-fb:"+s+" "+r.type+(r.parameter&&r.parameter.length?" "+r.parameter:"")+`\r
51`}),i},e.parseSsrcMedia=function(t){const i=t.indexOf(" "),s={ssrc:parseInt(t.substring(7,i),10)},r=t.indexOf(":",i);return r>-1?(s.attribute=t.substring(i+1,r),s.value=t.substring(r+1)):s.attribute=t.substring(i+1),s},e.parseSsrcGroup=function(t){const i=t.substring(13).split(" ");return{semantics:i.shift(),ssrcs:i.map(s=>parseInt(s,10))}},e.getMid=function(t){const i=e.matchPrefix(t,"a=mid:")[0];if(i)return i.substring(6)},e.parseFingerprint=function(t){const i=t.substring(14).split(" ");return{algorithm:i[0].toLowerCase(),value:i[1].toUpperCase()}},e.getDtlsParameters=function(t,i){return{role:"auto",fingerprints:e.matchPrefix(t+i,"a=fingerprint:").map(e.parseFingerprint)}},e.writeDtlsParameters=function(t,i){let s="a=setup:"+i+`\r
52`;return t.fingerprints.forEach(r=>{s+="a=fingerprint:"+r.algorithm+" "+r.value+`\r
53`}),s},e.parseCryptoLine=function(t){const i=t.substring(9).split(" ");return{tag:parseInt(i[0],10),cryptoSuite:i[1],keyParams:i[2],sessionParams:i.slice(3)}},e.writeCryptoLine=function(t){return"a=crypto:"+t.tag+" "+t.cryptoSuite+" "+(typeof t.keyParams=="object"?e.writeCryptoKeyParams(t.keyParams):t.keyParams)+(t.sessionParams?" "+t.sessionParams.join(" "):"")+`\r
54`},e.parseCryptoKeyParams=function(t){if(t.indexOf("inline:")!==0)return null;const i=t.substring(7).split("|");return{keyMethod:"inline",keySalt:i[0],lifeTime:i[1],mkiValue:i[2]?i[2].split(":")[0]:void 0,mkiLength:i[2]?i[2].split(":")[1]:void 0}},e.writeCryptoKeyParams=function(t){return t.keyMethod+":"+t.keySalt+(t.lifeTime?"|"+t.lifeTime:"")+(t.mkiValue&&t.mkiLength?"|"+t.mkiValue+":"+t.mkiLength:"")},e.getCryptoParameters=function(t,i){return e.matchPrefix(t+i,"a=crypto:").map(e.parseCryptoLine)},e.getIceParameters=function(t,i){const s=e.matchPrefix(t+i,"a=ice-ufrag:")[0],r=e.matchPrefix(t+i,"a=ice-pwd:")[0];return s&&r?{usernameFragment:s.substring(12),password:r.substring(10)}:null},e.writeIceParameters=function(t){let i="a=ice-ufrag:"+t.usernameFragment+`\r
55a=ice-pwd:`+t.password+`\r
56`;return t.iceLite&&(i+=`a=ice-lite\r
57`),i},e.parseRtpParameters=function(t){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},r=e.splitLines(t)[0].split(" ");i.profile=r[2];for(let a=3;a<r.length;a++){const d=r[a],l=e.matchPrefix(t,"a=rtpmap:"+d+" ")[0];if(l){const u=e.parseRtpMap(l),h=e.matchPrefix(t,"a=fmtp:"+d+" ");switch(u.parameters=h.length?e.parseFmtp(h[0]):{},u.rtcpFeedback=e.matchPrefix(t,"a=rtcp-fb:"+d+" ").map(e.parseRtcpFb),i.codecs.push(u),u.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(u.name.toUpperCase());break}}}e.matchPrefix(t,"a=extmap:").forEach(a=>{i.headerExtensions.push(e.parseExtmap(a))});const o=e.matchPrefix(t,"a=rtcp-fb:* ").map(e.parseRtcpFb);return i.codecs.forEach(a=>{o.forEach(d=>{a.rtcpFeedback.find(u=>u.type===d.type&&u.parameter===d.parameter)||a.rtcpFeedback.push(d)})}),i},e.writeRtpDescription=function(t,i){let s="";s+="m="+t+" ",s+=i.codecs.length>0?"9":"0",s+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",s+=i.codecs.map(o=>o.preferredPayloadType!==void 0?o.preferredPayloadType:o.payloadType).join(" ")+`\r
58`,s+=`c=IN IP4 0.0.0.0\r
59`,s+=`a=rtcp:9 IN IP4 0.0.0.0\r
60`,i.codecs.forEach(o=>{s+=e.writeRtpMap(o),s+=e.writeFmtp(o),s+=e.writeRtcpFb(o)});let r=0;return i.codecs.forEach(o=>{o.maxptime>r&&(r=o.maxptime)}),r>0&&(s+="a=maxptime:"+r+`\r
61`),i.headerExtensions&&i.headerExtensions.forEach(o=>{s+=e.writeExtmap(o)}),s},e.parseRtpEncodingParameters=function(t){const i=[],s=e.parseRtpParameters(t),r=s.fecMechanisms.indexOf("RED")!==-1,o=s.fecMechanisms.indexOf("ULPFEC")!==-1,a=e.matchPrefix(t,"a=ssrc:").map(m=>e.parseSsrcMedia(m)).filter(m=>m.attribute==="cname"),d=a.length>0&&a[0].ssrc;let l;const u=e.matchPrefix(t,"a=ssrc-group:FID").map(m=>m.substring(17).split(" ").map(C=>parseInt(C,10)));u.length>0&&u[0].length>1&&u[0][0]===d&&(l=u[0][1]),s.codecs.forEach(m=>{if(m.name.toUpperCase()==="RTX"&&m.parameters.apt){let f={ssrc:d,codecPayloadType:parseInt(m.parameters.apt,10)};d&&l&&(f.rtx={ssrc:l}),i.push(f),r&&(f=JSON.parse(JSON.stringify(f)),f.fec={ssrc:d,mechanism:o?"red+ulpfec":"red"},i.push(f))}}),i.length===0&&d&&i.push({ssrc:d});let h=e.matchPrefix(t,"b=");return h.length&&(h[0].indexOf("b=TIAS:")===0?h=parseInt(h[0].substring(7),10):h[0].indexOf("b=AS:")===0?h=parseInt(h[0].substring(5),10)*1e3*.95-2e3*8:h=void 0,i.forEach(m=>{m.maxBitrate=h})),i},e.parseRtcpParameters=function(t){const i={},s=e.matchPrefix(t,"a=ssrc:").map(a=>e.parseSsrcMedia(a)).filter(a=>a.attribute==="cname")[0];s&&(i.cname=s.value,i.ssrc=s.ssrc);const r=e.matchPrefix(t,"a=rtcp-rsize");i.reducedSize=r.length>0,i.compound=r.length===0;const o=e.matchPrefix(t,"a=rtcp-mux");return i.mux=o.length>0,i},e.writeRtcpParameters=function(t){let i="";return t.reducedSize&&(i+=`a=rtcp-rsize\r
62`),t.mux&&(i+=`a=rtcp-mux\r
63`),t.ssrc!==void 0&&t.cname&&(i+="a=ssrc:"+t.ssrc+" cname:"+t.cname+`\r
64`),i},e.parseMsid=function(t){let i;const s=e.matchPrefix(t,"a=msid:");if(s.length===1)return i=s[0].substring(7).split(" "),{stream:i[0],track:i[1]};const r=e.matchPrefix(t,"a=ssrc:").map(o=>e.parseSsrcMedia(o)).filter(o=>o.attribute==="msid");if(r.length>0)return i=r[0].value.split(" "),{stream:i[0],track:i[1]}},e.parseSctpDescription=function(t){const i=e.parseMLine(t),s=e.matchPrefix(t,"a=max-message-size:");let r;s.length>0&&(r=parseInt(s[0].substring(19),10)),isNaN(r)&&(r=65536);const o=e.matchPrefix(t,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:i.fmt,maxMessageSize:r};const a=e.matchPrefix(t,"a=sctpmap:");if(a.length>0){const d=a[0].substring(10).split(" ");return{port:parseInt(d[0],10),protocol:d[1],maxMessageSize:r}}},e.writeSctpDescription=function(t,i){let s=[];return t.protocol!=="DTLS/SCTP"?s=["m="+t.kind+" 9 "+t.protocol+" "+i.protocol+`\r
65`,`c=IN IP4 0.0.0.0\r
66`,"a=sctp-port:"+i.port+`\r
67`]:s=["m="+t.kind+" 9 "+t.protocol+" "+i.port+`\r
68`,`c=IN IP4 0.0.0.0\r
69`,"a=sctpmap:"+i.port+" "+i.protocol+` 65535\r
70`],i.maxMessageSize!==void 0&&s.push("a=max-message-size:"+i.maxMessageSize+`\r
71`),s.join("")},e.generateSessionId=function(){return Math.random().toString().substr(2,22)},e.writeSessionBoilerplate=function(t,i,s){let r;const o=i!==void 0?i:2;return t?r=t:r=e.generateSessionId(),`v=0\r
72o=`+(s||"thisisadapterortc")+" "+r+" "+o+` IN IP4 127.0.0.1\r
73s=-\r
74t=0 0\r
75`},e.getDirection=function(t,i){const s=e.splitLines(t);for(let r=0;r<s.length;r++)switch(s[r]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return s[r].substring(2)}return i?e.getDirection(i):"sendrecv"},e.getKind=function(t){return e.splitLines(t)[0].split(" ")[0].substring(2)},e.isRejected=function(t){return t.split(" ",2)[1]==="0"},e.parseMLine=function(t){const s=e.splitLines(t)[0].substring(2).split(" ");return{kind:s[0],port:parseInt(s[1],10),protocol:s[2],fmt:s.slice(3).join(" ")}},e.parseOLine=function(t){const s=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:s[0],sessionId:s[1],sessionVersion:parseInt(s[2],10),netType:s[3],addressType:s[4],address:s[5]}},e.isValidSDP=function(t){if(typeof t!="string"||t.length===0)return!1;const i=e.splitLines(t);for(let s=0;s<i.length;s++)if(i[s].length<2||i[s].charAt(1)!=="=")return!1;return!0},n.exports=e})(_s)),_s.exports}var Jl=Iv(),xn=kv(Jl),Mv=Lf({__proto__:null,default:xn},[Jl]);function Pi(n){if(!n.RTCIceCandidate||n.RTCIceCandidate&&"foundation"in n.RTCIceCandidate.prototype)return;const e=n.RTCIceCandidate;n.RTCIceCandidate=function(i){if(typeof i=="object"&&i.candidate&&i.candidate.indexOf("a=")===0&&(i=JSON.parse(JSON.stringify(i)),i.candidate=i.candidate.substring(2)),i.candidate&&i.candidate.length){const s=new e(i),r=xn.parseCandidate(i.candidate);for(const o in r)o in s||Object.defineProperty(s,o,{value:r[o]});return s.toJSON=function(){return{candidate:s.candidate,sdpMid:s.sdpMid,sdpMLineIndex:s.sdpMLineIndex,usernameFragment:s.usernameFragment}},s}return new e(i)},n.RTCIceCandidate.prototype=e.prototype,un(n,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new n.RTCIceCandidate(t.candidate),writable:"false"}),t))}function rr(n){!n.RTCIceCandidate||n.RTCIceCandidate&&"relayProtocol"in n.RTCIceCandidate.prototype||un(n,"icecandidate",e=>{if(e.candidate){const t=xn.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function Ni(n,e){if(!n.RTCPeerConnection)return;"sctp"in n.RTCPeerConnection.prototype||Object.defineProperty(n.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const t=function(a){if(!a||!a.sdp)return!1;const d=xn.splitSections(a.sdp);return d.shift(),d.some(l=>{const u=xn.parseMLine(l);return u&&u.kind==="application"&&u.protocol.indexOf("SCTP")!==-1})},i=function(a){const d=a.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(d===null||d.length<2)return-1;const l=parseInt(d[1],10);return l!==l?-1:l},s=function(a){let d=65536;return e.browser==="firefox"&&(e.version<57?a===-1?d=16384:d=2147483637:e.version<60?d=e.version===57?65535:65536:d=2147483637),d},r=function(a,d){let l=65536;e.browser==="firefox"&&e.version===57&&(l=65535);const u=xn.matchPrefix(a.sdp,"a=max-message-size:");return u.length>0?l=parseInt(u[0].substring(19),10):e.browser==="firefox"&&d!==-1&&(l=2147483637),l},o=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76){const{sdpSemantics:d}=this.getConfiguration();d==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(t(arguments[0])){const d=i(arguments[0]),l=s(d),u=r(arguments[0],d);let h;l===0&&u===0?h=Number.POSITIVE_INFINITY:l===0||u===0?h=Math.max(l,u):h=Math.min(l,u);const m={};Object.defineProperty(m,"maxMessageSize",{get(){return h}}),this._sctp=m}return o.apply(this,arguments)}}function _i(n){if(!(n.RTCPeerConnection&&"createDataChannel"in n.RTCPeerConnection.prototype))return;function e(i,s){const r=i.send;i.send=function(){const a=arguments[0],d=a.length||a.size||a.byteLength;if(i.readyState==="open"&&s.sctp&&d>s.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+s.sctp.maxMessageSize+" bytes)");return r.apply(i,arguments)}}const t=n.RTCPeerConnection.prototype.createDataChannel;n.RTCPeerConnection.prototype.createDataChannel=function(){const s=t.apply(this,arguments);return e(s,this),s},un(n,"datachannel",i=>(e(i.channel,i.target),i))}function ar(n){if(!n.RTCPeerConnection||"connectionState"in n.RTCPeerConnection.prototype)return;const e=n.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(t){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),t&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=t)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(t=>{const i=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=s=>{const r=s.target;if(r._lastConnectionState!==r.connectionState){r._lastConnectionState=r.connectionState;const o=new Event("connectionstatechange",s);r.dispatchEvent(o)}return s},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function or(n,e){if(!n.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e._safariVersion>=13.1)return;const t=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(s){if(s&&s.sdp&&s.sdp.indexOf(`
76a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
77`).filter(o=>o.trim()!=="a=extmap-allow-mixed").join(`
78`);n.RTCSessionDescription&&s instanceof n.RTCSessionDescription?arguments[0]=new n.RTCSessionDescription({type:s.type,sdp:r}):s.sdp=r}return t.apply(this,arguments)}}function Ii(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const t=n.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(n.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.ver
78sion<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Mi(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const t=n.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(n.RTCPeerConnection.prototype.setLocalDescription=function(){let s=arguments[0]||{};if(typeof s!="object"||s.type&&s.sdp)return t.apply(this,arguments);if(s={type:s.type,sdp:s.sdp},!s.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":s.type="offer";break;default:s.type="answer";break}return s.sdp||s.type!=="offer"&&s.type!=="answer"?t.apply(this,[s]):(s.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(o=>t.apply(this,[o]))})}var jv=Object.freeze({__proto__:null,removeExtmapAllowMixed:or,shimAddIceCandidateNullOrEmpty:Ii,shimConnectionState:ar,shimMaxMessageSize:Ni,shimParameterlessSetLocalDescription:Mi,shimRTCIceCandidate:Pi,shimRTCIceCandidateRelayProtocol:rr,shimSendThrowTypeError:_i});function Ov(){let{window:n}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const t=kl,i=Nv(n),s={browserDetails:i,commonShim:jv,extractVersion:Jn,disableLog:Ev,disableWarnings:Pv,sdp:Mv};switch(i.browser){case"chrome":if(!xo||!ir||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),s;if(i.version===null)return t("Chrome shim can not determine version, not shimming."),s;t("adapter.js shimming chrome."),s.browserShim=xo,Ii(n,i),Mi(n),yl(n,i),Cl(n),ir(n,i),Tl(n),El(n,i),Sl(n),wl(n),Pl(n,i),Pi(n),rr(n),ar(n),Ni(n,i),_i(n),or(n,i);break;case"firefox":if(!yo||!sr||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),s;t("adapter.js shimming firefox."),s.browserShim=yo,Ii(n,i),Mi(n),Nl(n,i),sr(n,i),_l(n),jl(n),Il(n),Ml(n),Ol(n),Ll(n),Al(n),Dl(n),Ul(n),Pi(n),ar(n),Ni(n,i),_i(n);break;case"safari":if(!Co||!e.shimSafari)return t("Safari shim is not included in this adapter release."),s;t("adapter.js shimming safari."),s.browserShim=Co,Ii(n,i),Mi(n),zl(n),Wl(n),Bl(n),Fl(n),Vl(n),Kl(n),ql(n),Gl(n),Pi(n),rr(n),Ni(n,i),_i(n),or(n,i);break;default:t("Unsupported browser!");break}return s}Ov({window:typeof window>"u"?void 0:window});var cr,$l;class Le extends($l=Promise){constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}}cr=Le;Le.resolve=n=>Reflect.get($l,"resolve",cr).call(cr,n);const Lv=/version\/(\d+(\.?_?\d+)+)/i;let Is;function Ge(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const t=navigator.userAgent.toLowerCase();if(Is===void 0||e){const i=Av.find(s=>{let{test:r}=s;return r.test(t)});Is=i?.describe(t)}return Is}const Av=[{test:/firefox|iceweasel|fxios/i,describe(n){return{name:"Firefox",version:ji(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Ms(n)}}},{test:/chrom|crios|crmo/i,describe(n){return{name:"Chrome",version:ji(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Ms(n)}}},{test:/safari|applewebkit/i,describe(n){return{name:"Safari",version:ji(Lv,n),os:n.includes("mobile/")?"iOS":"macOS",osVersion:Ms(n)}}}];function ji(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const i=e.match(n);return i&&i.length>=t&&i[t]||""}function Ms(n){return n.includes("mac os")?ji(/\(.+?(\d+_\d+(:?_\d+)?)/,n,1).replace(/_/g,"."):void 0}var Dv="2.18.0";const Uv=Dv,Fv=16;class Gt extends Error{constructor(e,t,i){super(t||"an error has occurred"),this.name="LiveKitError",this.code=e,typeof i?.cause<"u"&&(this.cause=i?.cause)}}class ia extends Gt{}var pe;(function(n){n[n.NotAllowed=0]="NotAllowed",n[n.ServerUnreachable=1]="ServerUnreachable",n[n.InternalError=2]="InternalError",n[n.Cancelled=3]="Cancelled",n[n.LeaveRequest=4]="LeaveRequest",n[n.Timeout=5]="Timeout",n[n.WebSocket=6]="WebSocket",n[n.ServiceNotFound=7]="ServiceNotFound"})(pe||(pe={}));class G extends ia{constructor(e,t,i,s){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=s,this.reasonName=pe[t]}static notAllowed(e,t,i){return new G(e,pe.NotAllowed,t,i)}static timeout(e){return new G(e,pe.Timeout)}static leaveRequest(e,t){return new G(e,pe.LeaveRequest,void 0,t)}static internal(e,t){return new G(e,pe.InternalError,void 0,t)}static cancelled(e){return new G(e,pe.Cancelled)}static serverUnreachable(e,t){return new G(e,pe.ServerUnreachable,t)}static websocket(e,t,i){return new G(e,pe.WebSocket,t,i)}static serviceNotFound(e,t){return new G(e,pe.ServiceNotFound,void 0,t)}}class sa extends Gt{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}
78class Rt extends Gt{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class Vv extends Gt{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class Te extends Gt{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class tn extends Gt{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class So extends Gt{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class wo extends ia{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName=typeof t=="string"?t:ta[t]}}var Fe;(function(n){n[n.AlreadyOpened=0]="AlreadyOpened",n[n.AbnormalEnd=1]="AbnormalEnd",n[n.DecodeFailed=2]="DecodeFailed",n[n.LengthExceeded=3]="LengthExceeded",n[n.Incomplete=4]="Incomplete",n[n.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",n[n.EncryptionTypeMismatch=8]="EncryptionTypeMismatch"})(Fe||(Fe={}));class et extends ia{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=Fe[t]}}class mn extends Gt{constructor(e){super(18,e),this.name="SignalReconnectError"}}var Hi;(function(n){n.PermissionDenied="PermissionDenied",n.NotFound="NotFound",n.DeviceInUse="DeviceInUse",n.Other="Other"})(Hi||(Hi={}));(function(n){function e(t){if(t&&"name"in t)return t.name==="NotFoundError"||t.name==="DevicesNotFoundError"?n.NotFound:t.name==="NotAllowedError"||t.name==="PermissionDeniedError"?n.PermissionDenied:t.name==="NotReadableError"||t.name==="TrackStartError"?n.DeviceInUse:n.Other}n.getFailure=e})(Hi||(Hi={}));class Ee{}Ee.setTimeout=function(){return setTimeout(...arguments)};Ee.setInterval=function(){return setInterval(...arguments)};Ee.clearTimeout=function(){return clearTimeout(...arguments)};Ee.clearInterval=function(){return clearInterval(...arguments)};var j;(function(n){n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting",n.Reconnected="reconnected",n.Disconnected="disconnected",n.ConnectionStateChanged="connectionStateChanged",n.Moved="moved",n.MediaDevicesChanged="mediaDevicesChanged",n.ParticipantConnected="participantConnected",n.ParticipantDisconnected="participantDisconnected",n.TrackPublished="trackPublished",n.TrackSubscribed="trackSubscribed",n.TrackSubscriptionFailed="trackSubscriptionFailed",n.TrackUnpublished="trackUnpublished",n.TrackUnsubscribed="trackUnsubscribed",n.TrackMuted="trackMuted",n.TrackUnmuted="trackUnmuted",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalAudioSilenceDetected="localAudioSilenceDetected",n.ActiveSpeakersChanged="activeSpeakersChanged",n.ParticipantMetadataChanged="participantMetadataChanged",n.ParticipantNameChanged="participantNameChanged",n.ParticipantAttributesChanged="participantAttributesChanged",n.ParticipantActive="participantActive",n.RoomMetadataChanged="roomMetadataChanged",n.DataReceived="dataReceived",n.SipDTMFReceived="sipDTMFReceived",n.TranscriptionReceived="transcriptionReceived",n.ConnectionQualityChanged="connectionQualityChanged",n.TrackStreamStateChanged="trackStreamStateChanged",n.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",n.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",n.AudioPlaybackStatusChanged="audioPlaybackChanged",n.VideoPlaybackStatusChanged="videoPlaybackChanged",n.MediaDevicesError="mediaDevicesError",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.SignalConnected="signalConnected",n.RecordingStatusChanged="recordingStatusChanged",n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError",n.DCBufferStatusChanged="dcBufferStatusChanged",n.ActiveDeviceChanged="activeDeviceChanged",n.ChatMessage="chatMessage",n.LocalTrackSubscribed="localTrackSubscribed",n.MetricsReceived="metricsReceived"})(j||(j={}));var V;(function(n){n.TrackPublished="trackPublished",n.TrackSubscribed="trackSubscribed",n.TrackSubscriptionFailed="trackSubscriptionFailed",n.TrackUnpublished="trackUnpublished",n.TrackUnsubscribed="trackUnsubscribed",n.TrackMuted="trackMuted",n.TrackUnmuted="trackUnmuted",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalTrackCpuConstrained="localTrackCpuConstrained",n.LocalSenderCreated="localSenderCreated",
78n.ParticipantMetadataChanged="participantMetadataChanged",n.ParticipantNameChanged="participantNameChanged",n.DataReceived="dataReceived",n.SipDTMFReceived="sipDTMFReceived",n.TranscriptionReceived="transcriptionReceived",n.IsSpeakingChanged="isSpeakingChanged",n.ConnectionQualityChanged="connectionQualityChanged",n.TrackStreamStateChanged="trackStreamStateChanged",n.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",n.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",n.TrackCpuConstrained="trackCpuConstrained",n.MediaDevicesError="mediaDevicesError",n.AudioStreamAcquired="audioStreamAcquired",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.PCTrackAdded="pcTrackAdded",n.AttributesChanged="attributesChanged",n.LocalTrackSubscribed="localTrackSubscribed",n.ChatMessage="chatMessage",n.Active="active"})(V||(V={}));var U;(function(n){n.TransportsCreated="transportsCreated",n.Connected="connected",n.Disconnected="disconnected",n.Resuming="resuming",n.Resumed="resumed",n.Restarting="restarting",n.Restarted="restarted",n.SignalResumed="signalResumed",n.SignalRestarted="signalRestarted",n.Closing="closing",n.MediaTrackAdded="mediaTrackAdded",n.ActiveSpeakersUpdate="activeSpeakersUpdate",n.DataPacketReceived="dataPacketReceived",n.RTPVideoMapUpdate="rtpVideoMapUpdate",n.DCBufferStatusChanged="dcBufferStatusChanged",n.ParticipantUpdate="participantUpdate",n.RoomUpdate="roomUpdate",n.SpeakersChanged="speakersChanged",n.StreamStateChanged="streamStateChanged",n.ConnectionQualityUpdate="connectionQualityUpdate",n.SubscriptionError="subscriptionError",n.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",n.RemoteMute="remoteMute",n.SubscribedQualityUpdate="subscribedQualityUpdate",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalTrackSubscribed="localTrackSubscribed",n.Offline="offline",n.SignalRequestResponse="signalRequestResponse",n.SignalConnected="signalConnected",n.RoomMoved="roomMoved"})(U||(U={}));var A;(function(n){n.Message="message",n.Muted="muted",n.Unmuted="unmuted",n.Restarted="restarted",n.Ended="ended",n.Subscribed="subscribed",n.Unsubscribed="unsubscribed",n.CpuConstrained="cpuConstrained",n.UpdateSettings="updateSettings",n.UpdateSubscription="updateSubscription",n.AudioPlaybackStarted="audioPlaybackStarted",n.AudioPlaybackFailed="audioPlaybackFailed",n.AudioSilenceDetected="audioSilenceDetected",n.VisibilityChanged="visibilityChanged",n.VideoDimensionsChanged="videoDimensionsChanged",n.VideoPlaybackStarted="videoPlaybackStarted",n.VideoPlaybackFailed="videoPlaybackFailed",n.ElementAttached="elementAttached",n.ElementDetached="elementDetached",n.UpstreamPaused="upstreamPaused",n.UpstreamResumed="upstreamResumed",n.SubscriptionPermissionChanged="subscriptionPermissionChanged",n.SubscriptionStatusChanged="subscriptionStatusChanged",n.SubscriptionFailed="subscriptionFailed",n.TrackProcessorUpdate="trackProcessorUpdate",n.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",n.TranscriptionReceived="transcriptionReceived",n.TimeSyncUpdate="timeSyncUpdate",n.PreConnectBufferFlushed="preConnectBufferFlushed"})(A||(A={}));function Bv(n){return typeof n>"u"?n:typeof structuredClone=="function"?typeof n=="object"&&n!==null?structuredClone(Object.assign({},n)):structuredClone(n):JSON.parse(JSON.stringify(n))}class ue{constructor(e,t,i,s,r){if(typeof e=="object")this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(t!==void 0&&i!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:s,priority:r};else throw new TypeError("Unsupported options: provide at least width, height and maxBitrate")}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const qv=["vp8","h264"],Hv=["vp8","h264","vp9","av1","h265"];function zv(n){return!!qv.find(e=>e===n)}const Kv=zv;var Ro;(function(n){n[n.PREFER_REGRESSION=0]="PREFER_REGRESSION",n[n.SIMULCAST=1]="SIMULCAST",n[n.REGRESSION=2]="REGRESSION"})(Ro||(Ro={}));var zi;(function(n){n.telephone={maxBitrate:12e3}
vendor: 12,093 bytes, line 78
78,n.speech={maxBitrate:24e3},n.music={maxBitrate:48e3},n.musicStereo={maxBitrate:64e3},n.musicHighQuality={maxBitrate:96e3},n.musicHighQualityStereo={maxBitrate:128e3}})(zi||(zi={}));const si={h90:new ue(160,90,9e4,20),h180:new ue(320,180,16e4,20),h216:new ue(384,216,18e4,20),h360:new ue(640,360,45e4,20),h540:new ue(960,540,8e5,25),h720:new ue(1280,720,17e5,30),h1080:new ue(1920,1080,3e6,30),h1440:new ue(2560,1440,5e6,30),h2160:new ue(3840,2160,8e6,30)},dr={h120:new ue(160,120,7e4,20),h180:new ue(240,180,125e3,20),h240:new ue(320,240,14e4,20),h360:new ue(480,360,33e4,20),h480:new ue(640,480,5e5,20),h540:new ue(720,540,6e5,25),h720:new ue(960,720,13e5,30),h1080:new ue(1440,1080,23e5,30),h1440:new ue(1920,1440,38e5,30)},ra={h360fps3:new ue(640,360,2e5,3,"medium"),h360fps15:new ue(640,360,4e5,15,"medium"),h720fps5:new ue(1280,720,8e5,5,"medium"),h720fps15:new ue(1280,720,15e5,15,"medium"),h720fps30:new ue(1280,720,2e6,30,"medium"),h1080fps15:new ue(1920,1080,25e5,15,"medium"),h1080fps30:new ue(1920,1080,5e6,30,"medium"),original:new ue(0,0,7e6,30,"medium")};function Ql(n,e,t){var i,s,r,o;const{optionsWithoutProcessor:a,audioProcessor:d,videoProcessor:l}=Xl(n??{}),u=e?.processor,h=t?.processor,m=a??{};return m.audio===!0&&(m.audio={}),m.video===!0&&(m.video={}),m.audio&&(lr(m.audio,e),(i=(r=m.audio).deviceId)!==null&&i!==void 0||(r.deviceId={ideal:"default"}),(d||u)&&(m.audio.processor=d??u)),m.video&&(lr(m.video,t),(s=(o=m.video).deviceId)!==null&&s!==void 0||(o.deviceId={ideal:"default"}),(l||h)&&(m.video.processor=l??h)),m}function lr(n,e){return Object.keys(e).forEach(t=>{n[t]===void 0&&(n[t]=e[t])}),n}function aa(n){var e,t,i,s;const r={};if(n.video)if(typeof n.video=="object"){const o={},a=o,d=n.video;Object.keys(d).forEach(l=>{switch(l){case"resolution":lr(a,d.resolution);break;default:a[l]=d[l]}}),r.video=o,(e=(i=r.video).deviceId)!==null&&e!==void 0||(i.deviceId={ideal:"default"})}else r.video=n.video?{deviceId:{ideal:"default"}}:!1;else r.video=!1;return n.audio?typeof n.audio=="object"?(r.audio=n.audio,(t=(s=r.audio).deviceId)!==null&&t!==void 0||(s.deviceId={ideal:"default"})):r.audio={deviceId:{ideal:"default"}}:r.audio=!1,r}function Yl(n){return y(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return(function*(){const i=Zl();if(i){const s=i.createAnalyser();s.fftSize=2048;const r=s.frequencyBinCount,o=new Uint8Array(r);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(s),yield Me(t),s.getByteTimeDomainData(o);const d=o.some(l=>l!==128&&l!==0);return i.close(),!d}return!1})()})}function Zl(){var n;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const t=new e({latencyHint:"interactive"});if(t.state==="suspended"&&typeof window<"u"&&(!((n=window.document)===null||n===void 0)&&n.body)){const i=()=>y(this,void 0,void 0,function*(){var s;try{t.state==="suspended"&&(yield t.resume())}catch(r){console.warn("Error trying to auto-resume audio context",r)}finally{(s=window.document.body)===null||s===void 0||s.removeEventListener("click",i)}});t.addEventListener("statechange",()=>{var s;t.state==="closed"&&((s=window.document.body)===null||s===void 0||s.removeEventListener("click",i))}),window.document.body.addEventListener("click",i)}return t}}function Wv(n){return n==="audioinput"?I.Source.Microphone:n==="videoinput"?I.Source.Camera:I.Source.Unknown}function ur(n){return n===I.Source.Microphone?"audioinput":n===I.Source.Camera?"videoinput":void 0}function Gv(n){var e,t;let i=(e=n.video)!==null&&e!==void 0?e:!0;return n.resolution&&n.resolution.width>0&&n.resolution.height>0&&(i=typeof i=="boolean"?{}:i,dn()?i=Object.assign(Object.assign({},i),{width:{max:n.resolution.width},height:{max:n.resolution.height},frameRate:n.resolution.frameRate}):i=Object.assign(Object.assign({},i),{width:{ideal:n.resolution.width},height:{ideal:n.resolution.height},frameRate:n.resolution.frameRate})),{audio:(t=n.audio)!==null&&t!==void 0?t:!1,video:i,controller:n.controller,selfBrowserSurface:n.selfBrowserSurface,surfaceSwitching:n.surfaceSwitching,systemAudio:n.systemAudio,preferCurrentTab:n.preferCurrentTab}}function Zn(n){return n.split("/")[1].toLowerCase()}function Jv(n){const e=[];return n.forEach(t=>{t.track!==void 0&&e.push(new Qr({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function ee(n){return"mediaStreamTrack"in n?{trackID:n.sid,source:n.source,muted:n.isMuted,enabled:n.mediaStreamTrack.enabled,kind:n.kind,streamID:n.mediaStreamID,streamTrackID:n.mediaStreamTrack.id}:{trackID:n.trackSid,enabled:n.isEnabled,muted:n.isMuted,trackInfo:Object.assign({mimeType:n.mimeType,name:n.trackName,encrypted:n.isEncrypted,kind:n.kind,source:n.source},n.track?ee(n.track):{})}}function $v(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function Qv(n,e){var t;n===void 0&&(n={}),e===void 0&&(e={});const i=[...Object.keys(e),...Object.keys(n)],s={};for(const r of i)n[r]!==e[r]&&(s[r]=(t=e[r])!==null&&t!==void 0?t:"");return s}function Xl(n){const e=Object.assign({},n);let t,i;return typeof e.audio=="object"&&e.audio.processor&&(t=e.audio.processor,e.audio=Object.assign(Object.assign({},e.audio),{processor:void 0})),typeof e.video=="object"&&e.video.processor&&(i=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:t,videoProcessor:i,optionsWithoutProcessor:Bv(e)}}function Yv(n){switch(n){case Re.CAMERA:return I.Source.Camera;case Re.MICROPHONE:return I.Source.Microphone;case Re.SCREEN_SHARE:return I.Source.ScreenShare;case Re.SCREEN_SHARE_AUDIO:return I.Source.ScreenShareAudio;default:return I.Source.Unknown}}function Eo(n,e){return n.width*n.height<e.width*e.height}function Zv(n,e){var t;return(t=n.layers)===null||t===void 0?void 0:t.find(i=>i.quality===e)}const Xv=5e3,Bn=[];var Qe;(function(n){n[n.LOW=0]="LOW",n[n.MEDIUM=1]="MEDIUM",n[n.HIGH=2]="HIGH"})(Qe||(Qe={}));class I extends bt.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var s;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=I.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=Y,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),Xv):this.handleAppVisibilityChanged()},this.log=Ze((s=i.loggerName)!==null&&s!==void 0?s:qe.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=I.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),ee(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===I.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===I.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(Bn.forEach(r=>{r.parentElement===null&&!e&&(e=r)}),e&&Bn.splice(Bn.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),fn(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),s=i.some(r=>r.kind==="audio");return e.play().then(()=>{this.emit(s?A.AudioPlaybackStarted:A.VideoPlaybackStarted)}).catch(r=>{r.name==="NotAllowedError"?this.emit(s?A.AudioPlaybackFailed:A.VideoPlaybackFailed,r):r.name==="AbortError"?Y.debug("".concat(s?"audio":"video"," playback aborted, likely due to new play request")):Y.warn("could not playback ".concat(s?"audio":"video"),r),s&&e&&i.some(o=>o.kind==="video")&&r.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(A.ElementAttached,e),e}detach(e){try{if(e){yn(this.mediaStreamTrack,e);const i=this.attachedElements.indexOf(e);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(e),this.emit(A.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(i=>{yn(this.mediaStreamTrack,i),t.push(i),this.recycleElement(i),this.emit(A.ElementDetached,i)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=Ze(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Bn.forEach(i=>{i.parentElement||(t=!1)}),t&&Bn.push(e)}}handleAppVisibilityChanged(){return y(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===I.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){We()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){We()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function fn(n,e){let t;e.srcObject instanceof MediaStream?t=e.srcObject:t=new MediaStream;let i;n.kind==="audio"?i=t.getAudioTracks():i=t.getVideoTracks(),i.includes(n)||(i.forEach(s=>{t.removeTrack(s)}),t.addTrack(n)),(!dn()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(dn()||cn())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function yn(n,e){if(e.srcObject instanceof MediaStream){const t=e.srcObject;t.removeTrack(n),t.getTracks().length>0?e.srcObject=t:e.srcObject=null}}(function(n){let e;(function(l){l.Audio="audio",l.Video="video",l.Unknown="unknown"})(e=n.Kind||(n.Kind={}));let t;(function(l){l.Camera="camera",l.Microphone="microphone",l.ScreenShare="screen_share",l.ScreenShareAudio="screen_share_audio",l.Unknown="unknown"})(t=n.Source||(n.Source={}));let i;(function(l){l.Active="active",l.Paused="paused",l.Unknown="unknown"})(i=n.StreamState||(n.StreamState={}));function s(l){switch(l){case e.Audio:return at.AUDIO;case e.Video:return at.VIDEO;default:return at.DATA}}n.kindToProto=s;function r(l){switch(l){case at.AUDIO:return e.Audio;case at.VIDEO:return e.Video;default:return e.Unknown}}n.kindFromProto=r;function o(l){switch(l){case t.Camera:return Re.CAMERA;case t.Microphone:return Re.MICROPHONE;case t.ScreenShare:return Re.SCREEN_SHARE;case t.ScreenShareAudio:return Re.SCREEN_SHARE_AUDIO;default:return Re.UNKNOWN}}n.sourceToProto=o;function a(l){switch(l){case Re.CAMERA:return t.Camera;case Re.MICROPHONE:return t.Microphone;case Re.SCREEN_SHARE:return t.ScreenShare;case Re.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}n.sourceFromProto=a;function d(l){switch(l){case Xs.ACTIVE:return i.Active;case Xs.PAUSED:return i.Paused;default:return i.Unknown}}n.streamStateFromProto=d})(I||(I={}));const eb="|",Po="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function tb(n){const e=n.split(eb);return e.length>1?[e[0],n.substr(e[0].length+1)]:[n,""]}function Me(n){return new Le(e=>Ee.setTimeout(e,n))}function hr(){return"addTransceiver"in RTCPeerConnection.prototype}function mr(){return"addTrack"in RTCPeerConnection.prototype}function nb(){if(!("getCapabilities"in RTCRtpSender)||dn()||cn())return!1;const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType.toLowerCase()==="video/av1"){e=!0;break}}return e}function ib(){if(!("getCapabilities"in RTCRtpSender)||cn())return!1;
78if(dn()){const t=Ge();if(t?.version&&vt(t.version,"16")<0||t?.os==="iOS"&&t?.osVersion&&vt(t.osVersion,"16")<0)return!1}const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType.toLowerCase()==="video/vp9"){e=!0;break}}return e}function ct(n){return n==="av1"||n==="vp9"}function pr(n){return!document||ri()?!1:(n||(n=document.createElement("audio")),"setSinkId"in n)}function sb(){return typeof RTCPeerConnection>"u"?!1:hr()||mr()}function cn(){var n;return((n=Ge())===null||n===void 0?void 0:n.name)==="Firefox"}function No(){const n=Ge();return!!n&&n.name==="Chrome"&&n.os!=="iOS"}function dn(){var n;return((n=Ge())===null||n===void 0?void 0:n.name)==="Safari"}function ri(){const n=Ge();return n?.name==="Safari"||n?.os==="iOS"}function rb(){const n=Ge();return n?.name==="Safari"&&n.version.startsWith("17.")||n?.os==="iOS"&&!!n?.osVersion&&vt(n.osVersion,"17")>=0}function ab(n){return n||(n=Ge()),n?.name==="Safari"&&vt(n.version,"18.3")>0||n?.os==="iOS"&&!!n?.osVersion&&vt(n.osVersion,"18.3")>0}function eu(){var n,e;return We()?(e=(n=navigator.userAgentData)===null||n===void 0?void 0:n.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function ob(){const n=Ge(),e="17.2";if(n)return n.name!=="Safari"&&n.os!=="iOS"||n.os==="iOS"&&n.osVersion&&vt(n.osVersion,e)>=0?!0:n.name==="Safari"&&vt(n.version,e)>=0}function We(){return typeof document<"u"}function gt(){return navigator.product=="ReactNative"}function Rn(n){return n.hostname.endsWith(".livekit.cloud")||n.hostname.endsWith(".livekit.run")}function js(n){return Rn(n)?n.hostname.split(".")[0]:null}function tu(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function nu(){if(!gt())return;let n=tu();if(n)return n.platform}function _o(){if(We())return window.devicePixelRatio;if(gt()){let n=tu();if(n)return n.devicePixelRatio}return 1}function vt(n,e){const t=n.split("."),i=e.split("."),s=Math.min(t.length,i.length);for(let r=0;r<s;++r){const o=parseInt(t[r],10),a=parseInt(i[r],10);if(o>a)return 1;if(o<a)return-1;if(r===s-1&&o===a)return 0}return n===""&&e!==""?-1:e===""?1:t.length==i.length?0:t.length<i.length?-1:1}function cb(n){for(const e of n)e.target.handleResize(e)}function db(n){for(const e of n)e.target.handleVisibilityChanged(e)}let Os=null;const Io=()=>(Os||(Os=new ResizeObserver(cb)),Os);let Ls=null;const Mo=()=>(Ls||(Ls=new IntersectionObserver(db,{root:null,rootMargin:"0px"})),Ls);function lb(){var n;const e=new Zd({sdk:Xd.JS,protocol:Fv,version:Uv});return gt()&&(e.os=(n=nu())!==null&&n!==void 0?n:""),e}function jo(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const s=document.createElement("canvas");s.width=n,s.height=e;const r=s.getContext("2d");r?.fillRect(0,0,s.width,s.height),i&&r&&(r.beginPath(),r.arc(n/2,e/2,50,0,Math.PI*2,!0),r.closePath(),r.fillStyle="grey",r.fill());const o=s.captureStream(),[a]=o.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=t,a}let qn;function As(){if(!qn){const n=new AudioContext,e=n.createOscillator(),t=n.createGain();t.gain.setValueAtTime(0,0);const i=n.createMediaStreamDestination();if(e.connect(t),t.connect(i),e.start(),[qn]=i.stream.getAudioTracks(),!qn)throw Error("Could not get empty media stream audio track");qn.enabled=!1}return qn.clone()}class Lt{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((i,s)=>y(this,void 0,void 0,function*(){this.resolve=i,this.reject=s,e&&(yield e(i,s))})).finally(()=>{var i;this._isResolved=!0,(i=this.onFinally)===null||i===void 0||i.call(this)})}}function ub(n){return Hv.includes(n)}function nn(n){if(typeof n=="string"||typeof n=="number")return n;if(Array.isArray(n))return n[0];if(n.exact!==void 0)return Array.isArray(n.exact)?n.exact[0]:n.exact;if(n.ideal!==void 0)return Array.isArray(n.ideal)?n.ideal[0]:n.ideal;throw Error("could not unwrap constraint")}function hb(n){return n.startsWith("http")?n.replace(/^(http)/,"ws"):n}function ai(n){return n.startsWith("ws")?n.replace(/^(ws)/,"http"):n}function mb(n,e){return n.segments.map(t=>{let{id:i,text:s,language:r,startTime:o,endTime:a,final:d}=t;var l;const u=(l=e.get(i))!==null&&l!==void 0?l:Date.now(),h=Date.now();return d?e.delete(i):e.set(i,u),{id:i,text:s,startTime:Number.parseInt(o.toString()),endTime:Number.parseInt(a.toString()),final:d,language:r,firstReceivedTime:u,lastReceivedTime:h}})}function pb(n){const{id:e,timestamp:t,message:i,editTimestamp:s}=n;return{id:e,timestamp:Number.parseInt(t.toString()),editTimestamp:s?Number.parseInt(s.toString()):void 0,message:i}}function Oo(n){switch(n.reason){case pe.LeaveRequest:return n.context;case pe.Cancelled:return dt.CLIENT_INITIATED;case pe.NotAllowed:return dt.USER_REJECTED;case pe.ServerUnreachable:return dt.JOIN_FAILURE;default:return dt.UNKNOWN_REASON}}function Oi(n){return n!==void 0?Number(n):void 0}function en(n){return n!==void 0?BigInt(n):void 0}function Cn(n){return!!n&&!(n instanceof MediaStreamTrack)&&n.isLocal}function ft(n){return!!n&&n.kind==I.Kind.Audio}function Jt(n){return!!n&&n.kind==I.Kind.Video}function Mt(n){return Cn(n)&&Jt(n)}function yt(n){return Cn(n)&&ft(n)}function fr(n){return!!n&&!n.isLocal}function fb(n){return!!n&&!n.isLocal}function Ds(n){return fr(n)&&Jt(n)}function gb(n){return n.isLocal}function vb(n,e){const t=[];let i=new TextEncoder().encode(n);for(;i.length>e;){let s=e;for(;s>0;){const r=i[s];if(r!==void 0&&(r&192)!==128)break;s--}t.push(i.slice(0,s)),i=i.slice(s)}return i.length>0&&t.push(i),t}function bb(n){var e;const t=n.get("Cache-Control");if(t){const i=(e=t.match(/(?:^|[,\s])max-age=(\d+)/))===null||e===void 0?void 0:e[1];if(i)return parseInt(i,10)}}function kb(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;const i=xb(n,e);return t?i:oa(i,"v1")}function xb(n,e){const t=new URL(hb(n));return e.forEach((i,s)=>{t.searchParams.set(s,i)}),oa(t,"rtc")}function yb(n){const e=new URL(ai(n));return oa(e,"validate")}function iu(n){return n.endsWith("/")?n:"".concat(n,"/")}function oa(n,e){return n.pathname="".concat(iu(n.pathname)).concat(e),n}
78function Lo(n){if(typeof n=="string")return mo.fromJson(JSON.parse(n),{ignoreUnknownFields:!0});if(n instanceof ArrayBuffer)return mo.fromBinary(new Uint8Array(n));throw new Error("could not decode websocket message: ".concat(typeof n))}function Cb(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Unknown reason";if(!(n instanceof AbortSignal))return e;const t=n.reason;switch(typeof t){case"string":return t;case"object":return t instanceof Error?t.message:e;default:return"toString"in t?t.toString():e}}const Tb=10,Hn="lk_e2ee",Sb="LKFrameEncryptionKey",wb={sharedKey:!1,ratchetSalt:Sb,ratchetWindowSize:8,failureTolerance:Tb,keyringSize:16};var Ut;(function(n){n.SetKey="setKey",n.RatchetRequest="ratchetRequest",n.KeyRatcheted="keyRatcheted"})(Ut||(Ut={}));var Ao;(function(n){n.KeyRatcheted="keyRatcheted"})(Ao||(Ao={}));var At;(function(n){n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError"})(At||(At={}));var Do;(function(n){n.Error="cryptorError"})(Do||(Do={}));function Rb(){return Eb()||gr()}function gr(){return typeof window.RTCRtpScriptTransform<"u"}function Eb(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}function Pb(n){var e,t,i,s,r;if(((e=n.value)===null||e===void 0?void 0:e.case)!=="sipDtmf"&&((t=n.value)===null||t===void 0?void 0:t.case)!=="metrics"&&((i=n.value)===null||i===void 0?void 0:i.case)!=="speaker"&&((s=n.value)===null||s===void 0?void 0:s.case)!=="transcription"&&((r=n.value)===null||r===void 0?void 0:r.case)!=="encryptedPacket")return new Kd({value:n.value})}class py extends bt.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.latestManuallySetKeyIndex=0,this.onKeyRatcheted=(t,i,s)=>{Y.debug("key ratcheted event received",{ratchetResult:t,participantId:i,keyIndex:s})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},wb),e),this.on(Ut.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,i){const s={key:e,participantIdentity:t,keyIndex:i};if(!this.options.sharedKey&&!t)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(t??"shared","-").concat(i??0),s),i!==void 0&&(this.latestManuallySetKeyIndex=i),this.emit(Ut.SetKey,s,i!==void 0)}getKeys(){return Array.from(this.keyInfoMap.values())}getLatestManuallySetKeyIndex(){return this.latestManuallySetKeyIndex}getOptions(){return this.options}ratchetKey(e,t){this.emit(Ut.RatchetRequest,e,t)}}var Uo;(function(n){n[n.InvalidKey=0]="InvalidKey",n[n.MissingKey=1]="MissingKey",n[n.InternalError=2]="InternalError"})(Uo||(Uo={}));class Nb extends bt.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=i=>{var s,r;const{kind:o,data:a}=i.data;switch(o){case"error":if(Y.error(a.error.message),a.uuid){const u=this.decryptDataRequests.get(a.uuid);if(u?.reject){u.reject(a.error);break}const h=this.encryptDataRequests.get(a.uuid);if(h?.reject){h.reject(a.error);break}}this.emit(At.EncryptionError,a.error,a.participantIdentity);break;case"initAck":a.enabled&&this.keyProvider.getKeys().forEach(u=>{this.postKey(u,!1)});break;case"enable":if(a.enabled&&this.keyProvider.getKeys().forEach(u=>{this.postKey(u,!1)}),this.encryptionEnabled!==a.enabled&&a.participantIdentity===((s=this.room)===null||s===void 0?void 0:s.localParticipant.identity))this.emit(At.ParticipantEncryptionStatusChanged,a.enabled,this.room.localParticipant),this.encryptionEnabled=a.enabled;else if(a.participantIdentity){const u=(r=this.room)===null||r===void 0?void 0:r.getParticipantByIdentity(a.participantIdentity);if(!u)throw TypeError("couldn't set encryption status, participant not found".concat(a.participantIdentity));this.emit(At.ParticipantEncryptionStatusChanged,a.enabled,u)}break;case"ratchetKey":this.keyProvider.emit(Ut.KeyRatcheted,a.ratchetResult,a.participantIdentity,a.keyIndex);break;case"decryptDataResponse":const d=this.decryptDataRequests.get(a.uuid);d?.resolve&&d.resolve(a);break;case"encryptDataResponse":const l=this.encryptDataRequests.get(a.uuid);l?.resolve&&l.resolve(a);break}},this.onWorkerError=i=>{Y.error("e2ee worker encountered an error:",{error:i.error}
78),this.emit(At.EncryptionError,i.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!Rb())throw new sa("tried to setup end-to-end encryption on an unsupported browser");if(Y.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:Cv.getLevel()}};this.worker&&(Y.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){Y.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?Y.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(U.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(j.TrackPublished,(i,s)=>this.setParticipantCryptorEnabled(i.trackInfo.encryption!==we.NONE,s.identity)),e.on(j.ConnectionStateChanged,i=>
78{i===ce.Connected&&e.remoteParticipants.forEach(s=>{s.trackPublications.forEach(r=>{this.setParticipantCryptorEnabled(r.trackInfo.encryption!==we.NONE,s.identity)})})}).on(j.TrackUnsubscribed,(i,s,r)=>{var o;const a={kind:"removeTransform",data:{participantIdentity:r.identity,trackId:i.mediaStreamID}};(o=this.worker)===null||o===void 0||o.postMessage(a)}).on(j.TrackSubscribed,(i,s,r)=>{this.setupE2EEReceiver(i,r.identity,s.trackInfo)}).on(j.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");const i=t.getLatestManuallySetKeyIndex();t.getKeys().forEach(s=>{var r;this.postKey(s,i===((r=s.keyIndex)!==null&&r!==void 0?r:0))}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(V.LocalSenderCreated,(i,s)=>y(this,void 0,void 0,function*(){this.setupE2EESender(s,i)})),e.localParticipant.on(V.LocalTrackPublished,i=>{if(!Jt(i.track)||!ri())return;const s={kind:"updateCodec",data:{trackId:i.track.mediaStreamID,codec:Zn(i.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(s)}),t.on(Ut.SetKey,(i,s)=>this.postKey(i,s??!0)).on(Ut.RatchetRequest,(i,s)=>this.postRatchetRequest(i,s))}encryptData(e){return y(this,void 0,void 0,function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");const t=crypto.randomUUID(),i={kind:"encryptDataRequest",data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},s=new Lt;return s.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,s),this.worker.postMessage(i),s.promise})}handleEncryptedData(e,t,i,s){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");const r=crypto.randomUUID(),o={kind:"decryptDataRequest",data:{uuid:r,payload:e,iv:t,participantIdentity:i,keyIndex:s}},a=new Lt;return a.onFinally=()=>{this.decryptDataRequests.delete(r)},this.decryptDataRequests.set(r,a),this.worker.postMessage(o),a.promise}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(i)}postKey(e,t){let{key:i,participantIdentity:s,keyIndex:r}=e;var o;if(!this.worker)throw Error("could not set key, worker is missing");const a={kind:"setKey",data:{participantIdentity:s,isPublisher:s===((o=this.room)===null||o===void 0?void 0:o.localParticipant.identity),key:i,keyIndex:r,updateCurrentKeyIndex:t}};this.worker.postMessage(a)}postEnable(e,t){if(this.worker){const i={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(i)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((t=this.room)===null||t===void 0)&&t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,i){if(e.receiver){if(!i?.mimeType||i.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?Zn(i.mimeType):void 0)}}setupE2EESender(e,t){if(!Cn(e)||!t){t||Y.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,i,s){return y(this,void 0,void 0,function*(){if(this.worker){if(gr()&&!No()){const r={kind:"decode",participantIdentity:i,trackId:t,codec:s};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{if(Hn in e&&s){const d={kind:"updateCodec",data:{trackId:t,codec:s,participantIdentity:i}};this.worker.postMessage(d);return}let r=e.writableStream,o=e.readableStream;if(!r||!o){const d=e.createEncodedStreams();e.writableStream=d.writable,r=d.writable,e.readableStream=d.readable,o=d.readable}const a={kind:"decode",data:{readableStream:o,writableStream:r,trackId:t,codec:s,participantIdentity:i,isReuse:Hn in e}};
78this.worker.postMessage(a,[o,r])}e[Hn]=!0}})}handleSender(e,t,i){var s;if(!(Hn in e||!this.worker)){if(!(!((s=this.room)===null||s===void 0)&&s.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(gr()&&!No()){Y.info("initialize script transform");const r={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{Y.info("initialize encoded streams");const r=e.createEncodedStreams(),o={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(o,[r.readable,r.writable])}e[Hn]=!0}}}const _b=500,Ib=15e3;class Tn{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new Tn),this._instance}addFailedConnectionAttempt(e){var t;const i=new URL(e),s=js(i);if(!s)return;let r=(t=this.failedConnectionAttempts.get(s))!==null&&t!==void 0?t:0;this.failedConnectionAttempts.set(s,r+1),this.backOffPromises.set(s,Me(Math.min(_b*Math.pow(2,r),Ib)))}getBackOffPromise(e){const t=new URL(e),i=t&&js(t);return i&&this.backOffPromises.get(i)||Promise.resolve()}resetFailedConnectionAttempts(e){const t=new URL(e),i=t&&js(t);i&&(this.failedConnectionAttempts.set(i,0),this.backOffPromises.set(i,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}Tn._instance=null;const Us="default";class Ie{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new Ie),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return y(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var r;if(((r=Ie.userMediaPromiseMap)===null||r===void 0?void 0:r.size)>0){Y.debug("awaiting getUserMedia promise");try{t?yield Ie.userMediaPromiseMap.get(t):yield Promise.all(Ie.userMediaPromiseMap.values())}catch{Y.warn("error waiting for media permissons")}}let o=yield navigator.mediaDevices.enumerateDevices();if(s&&!(dn()&&i.hasDeviceInUse(t))&&(o.filter(d=>d.kind===t).length===0||o.some(d=>{const l=d.label==="",u=t?d.kind===t:!0;return l&&u}))){const d={video:t!=="audioinput"&&t!=="audiooutput",audio:t!=="videoinput"&&{deviceId:{ideal:"default"}}},l=yield navigator.mediaDevices.getUserMedia(d);o=yield navigator.mediaDevices.enumerateDevices(),l.getTracks().forEach(u=>{u.stop()})}return i._previousDevices=o,t&&(o=o.filter(a=>a.kind===t)),o})()})}normalizeDeviceId(e,t,i){return y(this,void 0,void 0,function*(){if(t!==Us)return t;const s=yield this.getDevices(e),r=s.find(a=>a.deviceId===Us);if(!r){Y.warn("could not reliably determine default device");return}const o=s.find(a=>a.deviceId!==Us&&a.groupId===(i??r.groupId));if(!o){Y.warn("could not reliably determine default device");return}return o?.deviceId})}hasDeviceInUse(e){return e?Ie.userMediaPromiseMap.has(e):Ie.userMediaPromiseMap.size>0}}Ie.mediaDeviceKinds=["audioinput","audiooutput","videoinput"];Ie.userMediaPromiseMap=new Map;var Xn;(function(n){n[n.WAITING=0]="WAITING",n[n.RUNNING=1]="RUNNING",n[n.COMPLETED=2]="COMPLETED"})(Xn||(Xn={}));class Mb{constructor(){this.pendingTasks=new Map,this.taskMutex=new Be,this.nextTaskIndex=0}run(e){return y(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Xn.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Xn.RUNNING,yield e()}finally{t.status=Xn.COMPLETED,this.pendingTasks.delete(t.id),i()}})}flush(){return y(this,void 0,void 0,function*(){return this.run(()=>y(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}class jb{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i,s;if(!((i=t.signal)===null||i===void 0)&&i.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;const r=new WebSocket(e,(s=t.protocols)!==null&&s!==void 0?s:[]);r.binaryType="arraybuffer",this.ws=r;const o=function(){let{closeCode:a,reason:d}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return r.close(a,d)};this.opened=new Le((a,d)=>{const l=()=>{d(G.websocket("Encountered websocket error during connection establishment"))};r.onopen=()=>{a({readable:new ReadableStream({start(u){r.onmessage=h=>{let{data:m}=h;return u.enqueue(m)},r.onerror=h=>u.error(h)},cancel:o}),writable:new WritableStream({write(u){r.send(u)},abort(){r.close()},close:o}),protocol:r.protocol,extensions:r.extensions}),r.removeEventListener("error",l)},r.addEventListener("error",l)}),this.closed=new Le((a,d)=>{const l=()=>y(this,void 0,void 0,function*(){const u=new Le(m=>{r.readyState!==WebSocket.CLOSED&&r.addEventListener("close",f=>{m(f)},{once:!0})}),h=yield Le.race([Me(250),u]);h?a(h):d(G.websocket("Encountered unspecified websocket error without a timely close event"))});r.onclose=u=>{let{code:h,reason:m}=u;a({closeCode:h,reason:m}),r.removeEventListener("error",l)},r.addEventListener("error",l)}),t.signal&&(t.signal.onabort=()=>r.close()),this.close=o}}const Ob=["syncState","trickle","offer","answer","simulate","leave"];
78function Lb(n){const e=Ob.indexOf(n.case)>=0;return Y.trace("request allowed to bypass queue:",{canPass:e,req:n}),e}var me;(function(n){n[n.CONNECTING=0]="CONNECTING",n[n.CONNECTED=1]="CONNECTED",n[n.RECONNECTING=2]="RECONNECTING",n[n.DISCONNECTING=3]="DISCONNECTING",n[n.DISCONNECTED=4]="DISCONNECTED"})(me||(me={}));const Ab=250;class ca{get currentState(){return this.state}get isDisconnected(){return this.state===me.DISCONNECTING||this.state===me.DISCONNECTED}get isEstablishingConnection(){return this.state===me.CONNECTING||this.state===me.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;this.rtt=0,this.state=me.DISCONNECTED,this.log=Y,this._requestId=0,this.useV0SignalPath=!1,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.log=Ze((i=t.loggerName)!==null&&i!==void 0?i:qe.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new Mb,this.queuedRequests=[],this.closingLock=new Be,this.connectionLock=new Be,this.state=me.DISCONNECTED}get logContext(){var e,t;return(t=(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this))!==null&&t!==void 0?t:{}}join(e,t,i,s){return y(this,arguments,void 0,function(r,o,a,d){var l=this;let u=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){return l.state=me.CONNECTING,l.options=a,yield l.connect(r,o,a,d,u)})()})}reconnect(e,t,i,s){return y(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);return}return this.state=me.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:s}),void 0,this.useV0SignalPath)})}connect(e,t,i,s){return y(this,arguments,void 0,function(r,o,a,d){var l=this;let u=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){const h=yield l.connectionLock.lock();l.connectOptions=a,l.useV0SignalPath=u;const m=lb(),f=u?Db(o,m,a):Ub(o,m,a),C=kb(r,f,u).toString(),x=yb(C).toString();return new Promise((S,v)=>y(l,void 0,void 0,function*(){var g,k;try{let T=!1;const b=N=>y(this,void 0,void 0,function*(){if(T)return;T=!0;const L=N instanceof Event?N.currentTarget:N,O=Cb(L,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(O)).catch(q=>{this.log.error(q),this.close()}):this.close(),w(),v(G.cancelled(O))});d?.addEventListener("abort",b);const w=()=>{clearTimeout(P),d?.removeEventListener("abort",b)},P=setTimeout(()=>{b(G.timeout("room connection has timed out (signal)"))},a.websocketTimeout),E=(N,L)=>{this.handleSignalConnected(N,P,L)},_=new URL(C);_.searchParams.has("access_token")&&_.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(_),Object.assign({reconnect:a.reconnect,reconnectReason:a.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new jb(C);try{this.ws.closed.then(K=>{var se;this.isEstablishingConnection&&v(G.internal("Websocket got closed during a (re)connection attempt: ".concat(K.reason))),K.closeCode!==1e3&&(this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:K.reason,code:K.closeCode,wasClean:K.closeCode===1e3,state:this.state})),this.state===me.CONNECTED&&this.handleOnClose((se=K.reason)!==null&&se!==void 0?se:"Unexpected WS error"))}).catch(K=>{this.isEstablishingConnection&&v(G.internal("Websocket error during a (re)connection attempt: ".concat(K)))});const N=yield this.ws.opened.catch(K=>y(this,void 0,void 0,function*(){if(this.state!==me.CONNECTED){this.state=me.DISCONNECTED,clearTimeout(P);const se=yield this.handleConnectionError(K,x);v(se);return}this.handleWSError(K),v(K)}));if(clearTimeout(P),!N)return;const L=N.readable.getReader();this.streamWriter=N.writable.getWriter();const O=yield L.read();if(L.releaseLock(),!O.value)throw G.internal("no message received as first message");const q=Lo(O.value),J=this.validateFirstMessage(q,(g=a.reconnect)!==null&&g!==void 0?g:!1);if(!J.isValid){v(J.error);return}((k=q.message)===null||k===void 0?void 0:k.case)==="join"&&(this.pingTimeoutDuration=q.message.value.pingTimeout,this.pingIntervalDuration=q.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})));const D=J.shouldProcessFirstMessage?q:void 0;E(N,D),S(J.response)}catch(N){v(N)}finally{w()}}finally{h()}}))})()})}startReadingLoop(e,t){return y(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield Me(this.signalLatency));const{done:i,value:s}=yield e.read();if(i)break;const r=Lo(s);this.handleSignalResponse(r)}})}close(){return y(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Close method called on signal client";return(function*(){if([me.DISCONNECTING||me.DISCONNECTED].includes(e.state)){e.log.debug("ignoring signal close as it's already in disconnecting state");return}const s=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=me.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:i});const r=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([r,Me(Ab)])}}catch(r){e.log.debug("websocket error while closing",Object.assign(Object.assign({},e.logContext),{error:r}))}finally{t&&(e.state=me.DISCONNECTED),s()}})()})}sendOffer(e,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:gn(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:gn(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new ds({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new ls({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return y(this,arguments,void 0,function(i,s){var r=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(function*(){const a=r.getNextRequestId();return yield r.sendRequest({case:"updateMetadata",value:new Zr({requestId:a,metadata:i,name:s,attributes:o})}),a})()})}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:"updateLayers",value:new dl({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new hl({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:ge.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new fl({timestamp:ge.parse(Date.now()),rtt:ge.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new Yr({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new hs({reason:dt.CLIENT_INITIATED,action:kn.DISCONNECT})})}sendRequest(e){return y(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return(function*(){if(!s&&!Lb(t)&&i.state===me.RECONNECTING){i.queuedRequests.push(()=>y(i,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(s||(yield i.requestQueue.flush()),i.signalLatency&&(yield Me(i.signalLatency)),i.isDisconnected){i.log.debug("skipping signal request (type: ".concat(t.case,") - SignalClient disconnected"));return}if(!i.streamWriter){i.log.error("cannot send signal request before connected, type: ".concat(t?.case),i.logContext);return}const o=new qg({message:t});try{i.useJSON?yield i.streamWriter.write(o.toJsonString()):yield i.streamWriter.write(o.toBinary())}catch(a){i.log.error("error sending signal message",Object.assign(Object.assign({}
78,i.logContext),{error:a}))}})()})}handleSignalResponse(e){var t,i;const s=e.message;if(s==null){this.log.debug("received unsupported message",this.logContext);return}let r=!1;if(s.case==="answer"){const o=Fo(s.value);this.onAnswer&&this.onAnswer(o,s.value.id,s.value.midToTrackId)}else if(s.case==="offer"){const o=Fo(s.value);this.onOffer&&this.onOffer(o,s.value.id,s.value.midToTrackId)}else if(s.case==="trickle"){const o=JSON.parse(s.value.candidateInit);this.onTrickle&&this.onTrickle(o,s.value.target)}else s.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((t=s.value.participants)!==null&&t!==void 0?t:[]):s.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(s.value):s.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((i=s.value.speakers)!==null&&i!==void 0?i:[]):s.case==="leave"?this.onLeave&&this.onLeave(s.value):s.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(s.value.sid,s.value.muted):s.case==="roomUpdate"?this.onRoomUpdate&&s.value.room&&this.onRoomUpdate(s.value.room):s.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(s.value):s.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(s.value):s.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(s.value):s.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(s.value):s.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(s.value):s.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(s.value):s.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(s.value):s.case==="pong"||(s.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(s.value.lastPingTimestamp.toString()),this.resetPingTimeout(),r=!0):s.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(s.value):s.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(s.value.trackSid):s.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(s.value.token),this.onRoomMoved&&this.onRoomMoved(s.value)):s.case==="mediaSectionsRequirement"?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(s.value):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:s.case})));r||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return y(this,void 0,void 0,function*(){if(this.state===me.DISCONNECTED)return;const t=this.onClose;yield this.close(void 0,e),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)})}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set",this.logContext);return}this.pingTimeout=Ee.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&Ee.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn("ping interval duration not set",this.logContext);return}this.log.debug("start ping interval",this.logContext),this.pingInterval=Ee.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&Ee.clearInterval(this.pingInterval)}handleSignalConnected(e,t,i){this.state=me.CONNECTED,clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),i)}validateFirstMessage(e,t){var i,s,r,o,a;return((i=e.message)===null||i===void 0?void 0:i.case)==="join"?{isValid:!0,response:e.message.value}:this.state===me.RECONNECTING&&((s=e.message)===null||s===void 0?void 0:s.case)!=="leave"?((r=e.message)===null||r===void 0?void 0:r.case)==="reconnect"?{isValid:!0,response:e.message.value}:(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&((o=e.message)===null||o===void 0?void 0:o.case)==="leave"?{isValid:!1,error:G.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:G.internal("Unexpected first message")}:{isValid:!1,error:G.internal("did not receive join response, got ".concat((a=e.message)===null||a===void 0?void 0:a.case," instead"))}}handleConnectionError(e,t){return y(this,void 0,void 0,function*(){try{const i=yield fetch(t);switch(i.status){case 404:return G.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const s=yield i.text();return G.notAllowed(s,i.status);default:break}return e instanceof G?e:G.internal("Encountered unknown websocket error during connection: ".concat(e),{status:i.status,statusText:i.statusText})}catch(i){return i instanceof G?i:G.serverUnreachable(i instanceof Error?i.message:"server was not reachable")}})}}function Fo(n){const e={type:"offer",sdp:n.sdp};switch(n.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=n.type;break}return e}function gn(n,e){return new Bt({sdp:n.sdp,type:n.type,id:e})}function Db(n,e,t){var i;const s=new URLSearchParams;return s.set("access_token",n),t.reconnect&&(s.set("reconnect","1"),t.sid&&s.set("sid",t.sid)),s.set("auto_subscribe",t.autoSubscribe?"1":"0"),s.set("sdk",gt()?"reactnative":"js"),s.set("version",e.version),s.set("protocol",e.protocol.toString()),e.deviceModel&&s.set("device_model",e.deviceModel),e.os&&s.set("os",e.os),e.osVersion&&s.set("os_version",e.osVersion),e.browser&&s.set("browser",e.browser),e.browserVersion&&s.set("browser_version",e.browserVersion),t.adaptiveStream&&s.set("adaptive_stream","1"),t.reconnectReason&&s.set("reconnect_reason",t.reconnectReason.toString()),!((i=navigator.connection)===null||i===void 0)&&i.type&&s.set("network",navigator.connection.type),s}function Ub(n,e,t){const i=new URLSearchParams;i.set("access_token",n);const s=new fv({clientInfo:e,connectionSettings:new gl({autoSubscribe:!!t.autoSubscribe,adaptiveStream:!!t.adaptiveStream}),reconnect:!!t.reconnect,participantSid:t.sid?t.sid:void 0});t.reconnectReason&&(s.reconnectReason=t.reconnectReason);const r=new gv({joinRequest:s.toBinary()});return i.set("join_request",btoa(new TextDecoder("utf-8").decode(r.toBinary()))),i}class Vo{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0;){const t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class Fb{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){const i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();const s=i+this.ttl;return this._map.set(e,{value:t,expiresAt:s}),this}get(e){const t=this._map.get(e);if(t){if(t.expiresAt<Date.now()){this._map.delete(e);return}return t.value}}has(e){const t=this._map.get(e);return t?t.expiresAt<Date.now()?(this._map.delete(e),!1):!0:!1}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){const e=Date.now();for(const[t,i]of this._map.entries())i.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e(i.value,t,this.asValueMap())}map(e){this.cleanup();const t=[],i=this.asValueMap();for(const[s,r]of i.entries())t.push(e(r,s,i));return t}asValueMap(){const e=new Map;for(const[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e.set(t,i.value);return e}}var st={},Fs={},Vs={exports:{}},Bo;function da(){if(Bo)return Vs.exports;Bo=1;var n=Vs.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(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.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(e){return e.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(e){return e.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S
78*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return e.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(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=e.raddr!=null?" raddr %s rport %d":"%v%v",t+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(t+=" generation %d"),t+=e["network-id"]!=null?" network-id %d":"%v",t+=e["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(e){var t="ssrc:%d";return e.attribute!=null&&(t+=" %s",e.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(e){return e.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(e){return e.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(e){return"imageattr:%s %s %s"+(e.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(e){return"simulcast:%s %s"+(e.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"}
vendor: 3,627 bytes, line 78
78,{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(e.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=e.id!=null?"id=%s %s":"%v%s",t+=e.mediaClockValue!=null?"=%s":"",t+=e.rateNumerator!=null?" rate=%s":"",t+=e.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"]}]};return Object.keys(n).forEach(function(e){var t=n[e];t.forEach(function(i){i.reg||(i.reg=/(.*)/),i.format||(i.format="%s")})}),Vs.exports}var qo;function Vb(){return qo||(qo=1,(function(n){var e=function(a){return String(Number(a))===a?Number(a):a},t=function(a,d,l,u){if(u&&!l)d[u]=e(a[1]);else for(var h=0;h<l.length;h+=1)a[h+1]!=null&&(d[l[h]]=e(a[h+1]))},i=function(a,d,l){var u=a.name&&a.names;a.push&&!d[a.push]?d[a.push]=[]:u&&!d[a.name]&&(d[a.name]={});var h=a.push?{}:u?d[a.name]:d;t(l.match(a.reg),h,a.names,a.name),a.push&&d[a.push].push(h)},s=da(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);n.parse=function(a){var d={},l=[],u=d;return a.split(/(\r\n|\r|\n)/).filter(r).forEach(function(h){var m=h[0],f=h.slice(2);m==="m"&&(l.push({rtp:[],fmtp:[]}),u=l[l.length-1]);for(var C=0;C<(s[m]||[]).length;C+=1){var x=s[m][C];if(x.reg.test(f))return i(x,u,f)}}),d.media=l,d};var o=function(a,d){var l=d.split(/=(.+)/,2);return l.length===2?a[l[0]]=e(l[1]):l.length===1&&d.length>1&&(a[l[0]]=void 0),a};n.parseParams=function(a){return a.split(/;\s?/).reduce(o,{})},n.parseFmtpConfig=n.parseParams,n.parsePayloads=function(a){return a.toString().split(" ").map(Number)},n.parseRemoteCandidates=function(a){for(var d=[],l=a.split(" ").map(e),u=0;u<l.length;u+=3)d.push({component:l[u],ip:l[u+1],port:l[u+2]});return d},n.parseImageAttributes=function(a){return a.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(o,{})})},n.parseSimulcastStreamList=function(a){return a.split(";").map(function(d){return d.split(",").map(function(l){var u,h=!1;return l[0]!=="~"?u=e(l):(u=e(l.substring(1,l.length)),h=!0),{scid:u,paused:h}})})}})(Fs)),Fs}var Bs,Ho;function Bb(){if(Ho)return Bs;Ho=1;var n=da(),e=/%[sdv%]/g,t=function(o){var a=1,d=arguments,l=d.length;return o.replace(e,function(u){if(a>=l)return u;var h=d[a];switch(a+=1,u){case"%%":return"%";case"%s":return String(h);case"%d":return Number(h);case"%v":return""}})},i=function(o,a,d){var l=a.format instanceof Function?a.format(a.push?d:d[a.name]):a.format,u=[o+"="+l];if(a.names)for(var h=0;h<a.names.length;h+=1){var m=a.names[h];a.name?u.push(d[a.name][m]):u.push(d[a.names[h]])}else u.push(d[a.name]);return t.apply(null,u)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r=["i","c","b","a"];return Bs=function(o,a){a=a||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(h){h.payloads==null&&(h.payloads="")});var d=a.outerOrder||s,l=a.innerOrder||r,u=[];return d.forEach(function(h){n[h].forEach(function(m){m.name in o&&o[m.name]!=null?u.push(i(h,m,o)):m.push in o&&o[m.push]!=null&&o[m.push].forEac
78h(function(f){u.push(i(h,m,f))})})}),o.media.forEach(function(h){u.push(i("m",n.m[0],h)),l.forEach(function(m){n[m].forEach(function(f){f.name in h&&h[f.name]!=null?u.push(i(m,f,h)):f.push in h&&h[f.push]!=null&&h[f.push].forEach(function(C){u.push(i(m,f,C))})})})}),u.join(`\r
79`)+`\r
80`},Bs}var zo;function qb(){if(zo)return st;zo=1;var n=Vb(),e=Bb(),t=da();return st.grammar=t,st.write=e,st.parse=n.parse,st.parseParams=n.parseParams,st.parseFmtpConfig=n.parseFmtpConfig,st.parsePayloads=n.parsePayloads,st.parseRemoteCandidates=n.parseRemoteCandidates,st.parseImageAttributes=n.parseImageAttributes,st.parseSimulcastStreamList=n.parseSimulcastStreamList,st}var jt=qb();function la(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:50,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var i,s;let r;const o=(i=t.isImmediate)!==null&&i!==void 0?i:!1,a=(s=t.callback)!==null&&s!==void 0?s:!1,d=t.maxWait;let l=Date.now(),u=[];function h(){if(d!==void 0){const f=Date.now()-l;if(f+e>=d)return d-f}return e}const m=function(){for(var f=arguments.length,C=new Array(f),x=0;x<f;x++)C[x]=arguments[x];const S=this;return new Promise((v,g)=>{const k=function(){if(r=void 0,l=Date.now(),!o){const b=n.apply(S,C);a&&a(b),u.forEach(w=>{let{resolve:P}=w;return P(b)}),u=[]}},T=o&&r===void 0;if(r!==void 0&&Ee.clearTimeout(r),r=Ee.setTimeout(k,h()),T){const b=n.apply(S,C);return a&&a(b),v(b)}u.push({resolve:v,reject:g})})};return m.cancel=function(f){r!==void 0&&Ee.clearTimeout(r),u.forEach(C=>{let{reject:x}=C;return x(f)}),u=[]},m}const Hb=.7,zb=20,sn={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class Ko extends bt.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;super(),this.log=Y,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=la(s=>y(this,void 0,void 0,function*(){this.emit(sn.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(s)s(r);else throw r}}),zb),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=Ze((i=t.loggerName)!==null&&i!==void 0?i:qe.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new Be}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var i;t.candidate&&((i=this.onIceCandidate)===null||i===void 0||i.call(this,t.candidate))},e.onicecandidateerror=t=>{var i;(i=this.onIceCandidateError)===null||i===void 0||i.call(this,t)},e.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,e.connectionState)},e.ondatachannel=t=>{var i;(i=this.onDataChannel)===null||i===void 0||i.call(this,t)},e.ontrack=t=>{var i;(i=this.onTrack)===null||i===void 0||i.call(this,t)},e}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return y(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return y(this,void 0,void 0,function*(){var i;if(e.type==="answer"&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let s;if(e.type==="offer"){let{stereoMids:r,nackMids:o}=Kb(e);this.remoteStereoMids=r,this.remoteNackMids=o}else if(e.type==="answer"){const r=jt.parse((i=e.sdp)!==null&&i!==void 0?i:"");
80r.media.forEach(o=>{const a=ua(o.mid);o.type==="audio"&&this.trackBitrates.some(d=>{if(!d.transceiver||a!=d.transceiver.mid)return!1;let l=0;if(o.rtp.some(h=>h.codec.toUpperCase()===d.codec.toUpperCase()?(l=h.payload,!0):!1),l===0)return!0;let u=!1;for(const h of o.fmtp)if(h.payload===l){h.config=h.config.split(";").filter(m=>!m.includes("maxaveragebitrate")).join(";"),d.maxbr>0&&(h.config+=";maxaveragebitrate=".concat(d.maxbr*1e3)),u=!0;break}return u||d.maxbr>0&&o.fmtp.push({payload:l,config:"maxaveragebitrate=".concat(d.maxbr*1e3)}),!0})}),s=jt.write(r)}return yield this.setMungedSDP(e,s,!0),this.pendingCandidates.forEach(r=>{this.pc.addIceCandidate(r)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(sn.NegotiationComplete),e.sdp&&jt.parse(e.sdp).media.forEach(o=>{o.type==="video"&&this.emit(sn.RTPVideoPayloadTypes,o.rtp)})),!0})}createAndSendOffer(e){return y(this,void 0,void 0,function*(){var t;const i=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e?.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const a=this._pc.remoteDescription;if(e?.iceRestart&&a)yield this._pc.setRemoteDescription(a);else{this.renegotiate=!0,this.log.debug("requesting renegotiation",Object.assign({},this.logContext));return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const s=this.latestOfferId+1;this.latestOfferId=s;const r=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:r.sdp},this.logContext));const o=jt.parse((t=r.sdp)!==null&&t!==void 0?t:"");if(o.media.forEach(a=>{Go(a),a.type==="audio"?Wo(a,["all"],[]):a.type==="video"&&this.trackBitrates.some(d=>{if(!a.msid||!d.cid||!a.msid.includes(d.cid))return!1;let l=0;if(a.rtp.some(h=>h.codec.toUpperCase()===d.codec.toUpperCase()?(l=h.payload,!0):!1),l===0||(ct(d.codec)&&!dn()&&this.ensureVideoDDExtensionForSVC(a,o),!ct(d.codec)))return!0;const u=Math.round(d.maxbr*Hb);for(const h of a.fmtp)if(h.payload===l){h.config.includes("x-google-start-bitrate")||(h.config+=";x-google-start-bitrate=".concat(u));break}return!0})}),this.latestOfferId>s){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:s}));return}yield this.setMungedSDP(r,jt.write(o)),this.onOffer(r,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return y(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),i=jt.parse((e=t.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(s=>{Go(s),s.type==="audio"&&Wo(s,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,jt.write(i)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new Te("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new Te("PC closed, cannot configure");return(t=this._pc)===null||t===void 0?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var t;return(t=this._pc)===null||t===void 0?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&t!==void 0?t:"closed"}getICEConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&t!==void 0?t:"closed"}getSignallingState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&t!==void 0?t:"closed"}getTransceivers(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[]}getSenders(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&t!==void 0?t:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return y(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const i=new Map,s=new Map;
80if((yield this._pc.getStats()).forEach(a=>{switch(a.type){case"transport":t=a.selectedCandidatePairId;break;case"candidate-pair":t===""&&a.selected&&(t=a.id),i.set(a.id,a);break;case"remote-candidate":s.set(a.id,"".concat(a.address,":").concat(a.port));break}}),t==="")return;const o=(e=i.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(o!==void 0)return s.get(o)})}setMungedSDP(e,t,i){return y(this,void 0,void 0,function*(){if(t){const s=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(r){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:r,sdp:t})),e.sdp=s}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(s){let r="unknown error";s instanceof Error?r=s.message:typeof s=="string"&&(r=s);const o={error:r,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(o.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:o})),new tn(r)}})}ensureVideoDDExtensionForSVC(e,t){var i,s;if(!((i=e.ext)===null||i===void 0?void 0:i.some(o=>o.uri===Po))){if(this.ddExtID===0){let o=0;t.media.forEach(a=>{var d;a.type==="video"&&((d=a.ext)===null||d===void 0||d.forEach(l=>{l.value>o&&(o=l.value)}))}),this.ddExtID=o+1}(s=e.ext)===null||s===void 0||s.push({value:this.ddExtID,uri:Po})}}}function Wo(n,e,t){const i=ua(n.mid);let s=0;n.rtp.some(r=>r.codec==="opus"?(s=r.payload,!0):!1),s>0&&(n.rtcpFb||(n.rtcpFb=[]),t.includes(i)&&!n.rtcpFb.some(r=>r.payload===s&&r.type==="nack")&&n.rtcpFb.push({payload:s,type:"nack"}),(e.includes(i)||e.length===1&&e[0]==="all")&&n.fmtp.some(r=>r.payload===s?(r.config.includes("stereo=1")||(r.config+=";stereo=1"),!0):!1))}function Kb(n){var e;const t=[],i=[],s=jt.parse((e=n.sdp)!==null&&e!==void 0?e:"");let r=0;return s.media.forEach(o=>{var a;const d=ua(o.mid);o.type==="audio"&&(o.rtp.some(l=>l.codec==="opus"?(r=l.payload,!0):!1),!((a=o.rtcpFb)===null||a===void 0)&&a.some(l=>l.payload===r&&l.type==="nack")&&i.push(d),o.fmtp.some(l=>l.payload===r?(l.config.includes("sprop-stereo=1")&&t.push(d),!0):!1))}),{stereoMids:t,nackMids:i}}function Go(n){if(n.connection){const e=n.connection.ip.indexOf(":")>=0;(n.connection.version===4&&e||n.connection.version===6&&!e)&&(n.connection.ip="0.0.0.0",n.connection.version=4)}}function ua(n){return typeof n=="number"?n.toFixed(0):n}const vr="vp8",Wb={audioPreset:zi.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:ra.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:vr,backupCodec:!0,preConnectBuffer:!1},su={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},ru={deviceId:{ideal:"default"},resolution:si.h720.resolution},Gb={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Sv,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},ha={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var be;(function(n){n[n.NEW=0]="NEW",n[n.CONNECTING=1]="CONNECTING",n[n.CONNECTED=2]="CONNECTED",n[n.FAILED=3]="FAILED",n[n.CLOSING=4]="CLOSING",n[n.CLOSED=5]="CLOSED"})(be||(be={}));class Jb{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t,i){var s;this.peerConnectionTimeout=ha.peerConnectionTimeout,this.log=Y,this.updateState=()=>{var r,o;const a=this.state,d=this.requiredTransports.map(l=>l.getConnectionState());d.every(l=>l==="connected")?this.state=be.CONNECTED:d.some(l=>l==="failed")?this.state=be.FAILED:d.some(l=>l==="connecting")?this.state=be.CONNECTING:d.every(l=>l==="closed")?this.state=be.CLOSED:d.some(l=>l==="closed")?this.state=be.CLOSING:d.every(l=>l==="new")&&(this.state=be.NEW),a!==this.state&&(this.log.debug("pc state change: from ".concat(be[a]," to ").concat(be[this.state]),this.logContext),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),(o=this.subscriber)===null||o===void 0?void 0:o.getConnectionState()))},this.log=Ze((s=i.loggerName)!==null&&s!==void 0?s:qe.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=t!=="subscriber-primary",this.isSubscriberConnectionRequired=t==="subscriber-primary",this.publisher=new Ko(e,i),this._mode=t,t!=="publisher-only"&&(this.subscriber=new Ko(e,i),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=r=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,r,ot.SUBSCRIBER)},this.subscriber.onDataChannel=r=>{var o;(o=this.onDataChannel)===null||o===void 0||o.call(this,r)},this.subscriber.onTrack=r=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,r)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=r=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,r,ot.PUBLISHER)},this.publisher.onTrack=r=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,r)},this.publisher.onOffer=(r,o)=>{var a;(a=this.onPublisherOffer)===null||a===void 0||a.call(this,r,o)},this.state=be.NEW,this.connectionLock=new Be,this.remoteOfferLock=new Be}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return y(this,void 0,void 0,function*(){var e;if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const t=this.publisher;for(const i of t.getSenders())try{t.canRemoveTrack()&&t.removeTrack(i)}catch(s){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:s}))}}yield Promise.all([this.publisher.close(),(e=this.subscriber)===null||e===void 0?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return y(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return y(this,void 0,void 0,function*(){var i;t===ot.PUBLISHER?yield this.publisher.addIceCandidate(e):yield(i=this.subscriber)===null||i===void 0?void 0:i.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return y(this,void 0,void 0,function*(){var i,s,r;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:(i=this.subscriber)===null||i===void 0?void 0:i.getSignallingState().toString()}));const o=yield this.remoteOfferLock.lock();try{return(yield(s=this.subscriber)===null||s===void 0?void 0:s.setRemoteDescription(e,t))?yield(r=this.subscriber)===null||r===void 0?void 0:r.createAndSetAnswer():void 0}finally{o()}})}updateConfiguration(e,t){var i;this.publisher.setConfiguration(e),(i=this.subscriber)===null||i===void 0||i.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return y(this,void 0,void 0,function*(){var i;const s=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((i=this.requiredTransports)===null||i===void 0?void 0:i.map(r=>
80this.ensureTransportConnected(r,e,t)))}finally{s()}})}negotiate(e){return y(this,void 0,void 0,function*(){return new Le((t,i)=>y(this,void 0,void 0,function*(){let s=setTimeout(()=>{i(new tn("negotiation timed out"))},this.peerConnectionTimeout);const r=()=>{clearTimeout(s),this.publisher.off(sn.NegotiationStarted,a),e.signal.removeEventListener("abort",o)},o=()=>{r(),i(new tn("negotiation aborted"))},a=()=>{e.signal.aborted||(clearTimeout(s),s=setTimeout(()=>{r(),i(new tn("negotiation timed out"))},this.peerConnectionTimeout))};e.signal.addEventListener("abort",o),this.publisher.on(sn.NegotiationStarted,a),this.publisher.once(sn.NegotiationComplete,()=>{r(),t()}),yield this.publisher.negotiate(d=>{r(),d instanceof Error?i(d):i(new Error(String(d)))})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){const i=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(s=>s.receiver===e);return i?.mid}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===ot.PUBLISHER?this.publisher.getConnectedAddress():e===ot.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return y(this,arguments,void 0,function(i,s){var r=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return(function*(){if(i.getConnectionState()!=="connected")return new Promise((d,l)=>y(r,void 0,void 0,function*(){const u=()=>{this.log.warn("abort transport connection",this.logContext),Ee.clearTimeout(h),l(G.cancelled("room connection has been cancelled"))};s?.signal.aborted&&u(),s?.signal.addEventListener("abort",u);const h=Ee.setTimeout(()=>{s?.signal.removeEventListener("abort",u),l(G.internal("could not establish pc connection"))},o);for(;this.state!==be.CONNECTED;)if(yield Me(50),s?.signal.aborted){l(G.cancelled("room connection has been cancelled"));return}Ee.clearTimeout(h),s?.signal.removeEventListener("abort",u),d()}))})()})}}const au=5e3,$b=3e4;class oe{static fetchRegionSettings(e,t,i){return y(this,void 0,void 0,function*(){const s=yield oe.fetchLock.lock();try{const r=yield fetch("".concat(Qb(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:i});if(r.ok){const o=bb(r.headers),a=o?o*1e3:au;return{regionSettings:yield r.json(),updatedAtInMs:Date.now(),maxAgeInMs:a}}else throw r.status===401?G.notAllowed("Could not fetch region settings: ".concat(r.statusText),r.status):G.internal("Could not fetch region settings: ".concat(r.statusText))}catch(r){throw r instanceof G?r:i?.aborted?G.cancelled("Region fetching was aborted"):G.serverUnreachable("Could not fetch region settings, ".concat(r instanceof Error?"".concat(r.name,": ").concat(r.message):r))}finally{s()}})}static scheduleRefetch(e,t,i){return y(this,void 0,void 0,function*(){const s=oe.settingsTimeouts.get(e.hostname);clearTimeout(s),oe.settingsTimeouts.set(e.hostname,setTimeout(()=>y(this,void 0,void 0,function*(){try{const r=yield oe.fetchRegionSettings(e,t);oe.updateCachedRegionSettings(e,t,r)}catch(r){if(r instanceof G&&r.reason===pe.NotAllowed){Y.debug("token is not valid, cancelling auto region refresh");return}Y.debug("auto refetching of region settings failed",{error:r}),oe.scheduleRefetch(e,t,i)}}),i))})}static updateCachedRegionSettings(e,t,i){oe.cache.set(e.hostname,i),oe.scheduleRefetch(e,t,i.maxAgeInMs)}static stopRefetch(e){const t=oe.settingsTimeouts.get(e);t&&(clearTimeout(t),oe.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=oe.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{const i=oe.connectionTrackers.get(e);i&&i.connectionCount===0&&(Y.debug("stopping region refetch after disconnect delay",{hostname:e}),oe.stopRefetch(e)),i&&(i.cleanupTimeout=void 0)},$b))}static cancelCleanup(e){const t=oe.connectionTrackers.get(e);t?.cleanupTimeout&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=oe.connectionTrackers.get(e);t||(t={connectionCount:0},oe.connectionTrackers.set(e,t)),t.connectionCount++,oe.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=oe.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),t.connectionCount===0&&oe.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return Rn(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return y(this,void 0,void 0,function*(){return oe.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return y(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");
80let t=oe.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),oe.updateCachedRegionSettings(this.serverUrl,this.token,t));const i=t.regionSettings.regions.filter(s=>!this.attemptedRegions.find(r=>r.url===s.url));if(i.length>0){const s=i[0];return this.attemptedRegions.push(s),Y.debug("next region: ".concat(s.region)),s.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){oe.updateCachedRegionSettings(this.serverUrl,this.token,e)}}oe.cache=new Map;oe.settingsTimeouts=new Map;oe.connectionTrackers=new Map;oe.fetchLock=new Be;function Qb(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}class ye extends Error{constructor(e,t,i){super(t),this.code=e,this.message=Jo(t,ye.MAX_MESSAGE_BYTES),this.data=i?Jo(i,ye.MAX_DATA_BYTES):void 0}static fromProto(e){return new ye(e.code,e.message,e.data)}toProto(){return new Jd({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new ye(ye.ErrorCode[e],ye.ErrorMessage[e],t)}}ye.MAX_MESSAGE_BYTES=256;ye.MAX_DATA_BYTES=15360;ye.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404};ye.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};const ou=15360;function ma(n){return new TextEncoder().encode(n).length}function Jo(n,e){if(ma(n)<=e)return n;let t=0,i=n.length;const s=new TextEncoder;for(;t<i;){const r=Math.floor((t+i+1)/2);s.encode(n.slice(0,r)).length<=e?t=r:i=r-1}return n.slice(0,t)}const pa=2e3;function ps(n,e){if(!e)return 0;let t,i;return"bytesReceived"in n?(t=n.bytesReceived,i=e.bytesReceived):"bytesSent"in n&&(t=n.bytesSent,i=e.bytesSent),t===void 0||i===void 0||n.timestamp===void 0||e.timestamp===void 0?0:(t-i)*8*1e3/(n.timestamp-e.timestamp)}const fa=typeof MediaRecorder<"u";class Yb{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const Zb=fa?MediaRecorder:Yb;class Xb extends Zb{constructor(e,t){if(!fa)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),t);let i,s;const r=()=>s===void 0,o=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",o),this.removeEventListener("error",a),s?.close(),s=void 0},a=d=>{s?.error(d),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",o),this.removeEventListener("error",a),s=void 0};this.byteStream=new ReadableStream({start:d=>{s=d,i=l=>y(this,void 0,void 0,function*(){let u;if(l.data.arrayBuffer){const h=yield l.data.arrayBuffer();u=new Uint8Array(h)}else if(l.data.byteArray)u=l.data.byteArray;else throw new Error("no data available!");r()||d.enqueue(u)}),this.addEventListener("dataavailable",i)},cancel:()=>{o()}}),this.addEventListener("stop",o),this.addEventListener("error",a)}}function ek(){return fa}const tk=1e3,nk=1e4;class cu extends I{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,i){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,r=arguments.length>4?arguments[4]:void 0;super(e,t,r),this.manuallyStopped=!1,this.pendingDeviceChange=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=la(()=>y(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>y(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>
80{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(A.Ended,this)},this.reacquireTrack=!1,this.providedByUser=s,this.muteLock=new Be,this.pauseUpstreamLock=new Be,this.trackChangeLock=new Be,this.trackChangeLock.lock().then(o=>y(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{o()}})),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==I.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return(t=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&t!==void 0?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t,i){return y(this,void 0,void 0,function*(){var s;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(o=>{yn(this._mediaStreamTrack,o)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let r;if(this.processor&&e){if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(fn(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),r=this.processor.processedTrack}this.sender&&((s=this.sender.transport)===null||s===void 0?void 0:s.state)!=="closed"&&(yield this.sender.replaceTrack(r??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=i?!0:!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(o=>{fn(r??e,o)}))})}waitForDimensions(){return y(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:tk;return(function*(){var i;if(e.kind===I.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=Ge())===null||i===void 0?void 0:i.os)==="iOS"&&(yield Me(10));const s=Date.now();for(;Date.now()-s<t;){const r=e.dimensions;if(r)return r;yield Me(50)}throw new Rt("unable to get track dimensions after timeout")})()})}setDeviceId(e){return y(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===nn(e)?!0:(this._constraints.deviceId=e,this.isMuted?(this.pendingDeviceChange=!0,!0):(yield this.restartTrack(),nn(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return y(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){if(e.source===I.Source.ScreenShare)return;const{deviceId:i,groupId:s}=e._mediaStreamTrack.getSettings(),r=e.kind===I.Kind.Audio?"audioinput":"videoinput";return t?Ie.getInstance().normalizeDeviceId(r,i,s):i})()})}mute(){return y(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return y(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return y(this,void 0,void 0,function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new Rt("unable to replace an unpublished track");let s,r;return typeof t=="boolean"?s=t:t!==void 0&&(s=t.userProvidedTrack,r=t.stopProcessor),this.providedByUser=s??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),r&&this.processor&&(yield this.internalStopProcessor()),this}finally{i()}})}restart(e,t){return y(this,void 0,void 0,function*(){this.manuallyStopped=!1;const i=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const{deviceId:s,facingMode:r}=e,o=wv(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const a={audio:!1,video:!1};this.kind===I.Kind.Video?a.video=s||r?{deviceId:s,facingMode:r}:!0:a.audio=s?Object.assign({deviceId:s}
80,o):!0,this.attachedElements.forEach(u=>{yn(this.mediaStreamTrack,u)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const l=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return this.kind===I.Kind.Video&&(yield l.applyConstraints(o)),l.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(l,!1,t),this._constraints=e,this.pendingDeviceChange=!1,this.emit(A.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{i()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?A.Muted:A.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return y(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),eu()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(e=this.processor)===null||e===void 0||e.destroy(),this.processor=void 0}pauseUpstream(){return y(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(A.UpstreamPaused,this);const i=Ge();if(i?.name==="Safari"&&vt(i.version,"12.0")<0)throw new sa("pauseUpstream is not supported on Safari < 12.");((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return y(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(A.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return y(this,void 0,void 0,function*(){var e;return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){return y(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var r;const o=yield i.trackChangeLock.lock();try{i.log.debug("setting up processor",i.logContext);const a=document.createElement(i.kind),d={kind:i.kind,track:i._mediaStreamTrack,element:a,audioContext:i.audioContext};if(yield t.init(d),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.internalStopProcessor()),i.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(fn(i._mediaStreamTrack,a),a.muted=!0,a.play().catch(l=>{l instanceof DOMException&&l.name==="AbortError"?(i.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},i.logContext),{error:l})),setTimeout(()=>{a.play().catch(u=>{i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{err:u}))})},100)):i.log.error("failed to play processor element",Object.assign(Object.assign({}
80,i.logContext),{error:l}))}),i.processor=t,i.processorElement=a,i.processor.processedTrack){for(const l of i.attachedElements)l!==i.processorElement&&s&&(yn(i._mediaStreamTrack,l),fn(i.processor.processedTrack,l));yield(r=i.sender)===null||r===void 0?void 0:r.replaceTrack(i.processor.processedTrack)}i.emit(A.TrackProcessorUpdate,i.processor)}finally{o()}})()})}getProcessor(){return this.processor}stopProcessor(){return y(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){const i=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{i()}})()})}internalStopProcessor(){return y(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var i,s;e.processor&&(e.log.debug("stopping processor",e.logContext),(i=e.processor.processedTrack)===null||i===void 0||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||((s=e.processorElement)===null||s===void 0||s.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(A.TrackProcessorUpdate))})()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!ek()){this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext);return}if(this.localTrackRecorder){this.log.warn("preconnect buffer already started");return}else{let t="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(t)||(t="video/mp4"),this.localTrackRecorder=new Xb(this,{mimeType:t})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},nk)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.mimeType}}class Ki extends cu{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(e,I.Kind.Audio,t,i,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>y(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let o;try{o=yield this.getSenderStats()}catch(a){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:a}));return}o&&this.prevStats&&(this._currentBitrate=ps(o,this.prevStats)),this.prevStats=o}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(A.AudioTrackFeatureUpdate,this,_e.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(A.AudioTrackFeatureUpdate,this,_e.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=s,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return y(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===I.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return y(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===I.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||this.pendingDeviceChange)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}restartTrack(e){return y(this,void 0,void 0,function*(){let t;if(e){const i=aa({audio:e});typeof i.audio!="boolean"&&(t=i.audio)}yield this.restart(t)})}restart(e,t){const i=Object.create(null,{restart:{get:()=>super.restart}});return y(this,void 0,void 0,function*(){const s=yield i.restart.call(this,e,t);return this.checkForSilence(),s})}
80startMonitor(){We()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},pa)))}setProcessor(e){return y(this,void 0,void 0,function*(){var t;const i=yield this.trackChangeLock.lock();try{if(!gt()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const s={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(s),this.processor=e,this.processor.processedTrack&&(yield(t=this.sender)===null||t===void 0?void 0:t.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(A.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return y(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let i;return t.forEach(s=>{s.type==="outbound-rtp"&&(i={type:"audio",streamId:s.id,packetsSent:s.packetsSent,packetsLost:s.packetsLost,bytesSent:s.bytesSent,timestamp:s.timestamp,roundTripTime:s.roundTripTime,jitter:s.jitter})}),i})}checkForSilence(){return y(this,void 0,void 0,function*(){const e=yield Yl(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(A.AudioSilenceDetected)),e})}}function ik(n,e,t){switch(n.kind){case"audio":return new Ki(n,e,!1,void 0,t);case"video":return new Wi(n,e,!1,t);default:throw new Rt("unsupported track type: ".concat(n.kind))}}const sk=Object.values(si),rk=Object.values(dr),ak=Object.values(ra),ok=[si.h180,si.h360],ck=[dr.h180,dr.h360],dk=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var i,s;return new ue(Math.floor(n.width/t.scaleResolutionDownBy),Math.floor(n.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(n.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((i=n.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((s=t.fps)!==null&&s!==void 0?s:30))))),t.fps,n.encoding.priority)}),br=["q","h","f"];function kr(n,e,t,i){var s,r;let o=i?.videoEncoding;n&&(o=i?.screenShareEncoding);const a=i?.simulcast,d=i?.scalabilityMode,l=i?.videoCodec;if(!o&&!a&&!d||!e||!t)return[{}];o||(o=uk(n,e,t,l),Y.debug("using video encoding",o));const u=o.maxFramerate,h=new ue(e,t,o.maxBitrate,o.maxFramerate,o.priority);if(d&&ct(l)){const C=new du(d),x=[];if(C.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(d));const S=Ge();if(ri()||gt()||S?.name==="Chrome"&&vt(S?.version,"113")<0){const v=C.suffix=="h"?2:3,g=ab(S);for(let k=0;k<C.spatial;k+=1)x.push({rid:br[2-k],maxBitrate:o.maxBitrate/Math.pow(v,k),maxFramerate:h.encoding.maxFramerate,scaleResolutionDownBy:g?Math.pow(2,k):void 0});x[0].scalabilityMode=d}else x.push({maxBitrate:o.maxBitrate,maxFramerate:h.encoding.maxFramerate,scalabilityMode:d});return h.encoding.priority&&(x[0].priority=h.encoding.priority,x[0].networkPriority=h.encoding.priority),Y.debug("using svc encoding",{encodings:x}),x}if(!a)return[o];let m=[];n?m=(s=Qo(i?.screenShareSimulcastLayers))!==null&&s!==void 0?s:$o(n,h):m=(r=Qo(i?.videoSimulcastLayers))!==null&&r!==void 0?r:$o(n,h);let f;if(m.length>0){const C=m[0];m.length>1&&([,f]=m);const x=Math.max(e,t);if(x>=960&&f)return qs(e,t,[C,f,h],u);if(x>=480)return qs(e,t,[C,h],u)}return qs(e,t,[h])}function lk(n,e,t){var i,s,r,o;
vendor: 11,580 bytes, line 80
80if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&Y.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const a=n.mediaStreamTrack.getSettings(),d=(i=a.width)!==null&&i!==void 0?i:(s=n.dimensions)===null||s===void 0?void 0:s.width,l=(r=a.height)!==null&&r!==void 0?r:(o=n.dimensions)===null||o===void 0?void 0:o.height;return n.source===I.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),kr(n.source===I.Source.ScreenShare,d,l,t)}function uk(n,e,t,i){const s=hk(n,e,t);let{encoding:r}=s[0];const o=Math.max(e,t);for(let a=0;a<s.length;a+=1){const d=s[a];if(r=d.encoding,d.width>=o)break}if(i)switch(i){case"av1":case"h265":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.7;break;case"vp9":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.85;break}return r}function hk(n,e,t){if(n)return ak;const i=e>t?e/t:t/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?sk:rk}function $o(n,e){if(n)return dk(e);const{width:t,height:i}=e,s=t>i?t/i:i/t;return Math.abs(s-16/9)<Math.abs(s-4/3)?ok:ck}function qs(n,e,t,i){const s=[];if(t.forEach((r,o)=>{if(o>=br.length)return;const a=Math.min(n,e),l={rid:br[o],scaleResolutionDownBy:Math.max(1,a/Math.min(r.width,r.height)),maxBitrate:r.encoding.maxBitrate},u=i&&r.encoding.maxFramerate?Math.min(i,r.encoding.maxFramerate):r.encoding.maxFramerate;u&&(l.maxFramerate=u);const h=cn()||o===0;r.encoding.priority&&h&&(l.priority=r.encoding.priority,l.networkPriority=r.encoding.priority),s.push(l)}),gt()&&nu()==="ios"){let r;s.forEach(a=>{r?a.maxFramerate&&a.maxFramerate>r&&(r=a.maxFramerate):r=a.maxFramerate});let o=!0;s.forEach(a=>{var d;a.maxFramerate!=r&&(o&&(o=!1,Y.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),Y.info('Setting framerate of encoding "'.concat((d=a.rid)!==null&&d!==void 0?d:"",'" to ').concat(r)),a.maxFramerate=r)})}return s}function Qo(n){if(n)return n.sort((e,t)=>{const{encoding:i}=e,{encoding:s}=t;return i.maxBitrate>s.maxBitrate?1:i.maxBitrate<s.maxBitrate?-1:i.maxBitrate===s.maxBitrate&&i.maxFramerate&&s.maxFramerate?i.maxFramerate>s.maxFramerate?1:-1:0})}class du{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function mk(n){return n.source===I.Source.ScreenShare||n.constraints.height&&nn(n.constraints.height)>=1080?"maintain-resolution":"balanced"}const pk=5e3;class Wi extends cu{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0;super(e,I.Kind.Video,t,i,s),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>y(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=yield this.getSenderStats()}catch(d){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:d}));return}const o=new Map(r.map(d=>[d.rid,d])),a=r.some(d=>d.qualityLimitationReason==="cpu");if(a!==this.isCpuConstrained&&(this.isCpuConstrained=a,this.isCpuConstrained&&this.emit(A.CpuConstrained)),this.prevStats){let d=0;o.forEach((l,u)=>{var h;const m=(h=this.prevStats)===null||h===void 0?void 0:h.get(u);d+=ps(l,m)}),this._currentBitrate=d}this.prevStats=o}),this.senderLock=new Be}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!We())return;const i=(t=this.sender)===null||t===void 0?void 0:t.getParameters();i&&(this.encodings=i.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},pa))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return y(this,void 0,void 0,function*(){var t,i,s,r,o;yield e.pauseUpstream.call(this);try{for(var a=!0,d=wt(this.simulcastCodecs.values()),l;l=yield d.next(),t=l.done,!t;a=!0)r=l.value,a=!1,yield(o=r.sender)===null||o===void 0?void 0:o.replaceTrack(null)}catch(u){i={error:u}}finally{try{!a&&!t&&(s=d.return)&&(yield s.call(d))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return y(this,void 0,void 0,function*(){var t,i,s,r,o;yield e.resumeUpstream.call(this);try{for(var a=!0,d=wt(this.simulcastCodecs.values()),l;l=yield d.next(),t=l.done,!t;a=!0){r=l.value,a=!1;const u=r;yield(o=u.sender)===null||o===void 0?void 0:o.replaceTrack(u.mediaStreamTrack)}}catch(u){i={error:u}}finally{try{!a&&!t&&(s=d.return)&&(yield s.call(d))}finally{if(i)throw i.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return y(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===I.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return y(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===I.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return y(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach(s=>{var r;if(s.type==="outbound-rtp"){const o={type:"video",streamId:s.id,frameHeight:s.frameHeight,frameWidth:s.frameWidth,framesPerSecond:s.framesPerSecond,framesSent:s.framesSent,firCount:s.firCount,pliCount:s.pliCount,nackCount:s.nackCount,packetsSent:s.packetsSent,bytesSent:s.bytesSent,qualityLimitationReason:s.qualityLimitationReason,qualityLimitationDurations:s.qualityLimitationDurations,qualityLimitationResolutionChanges:s.qualityLimitationResolutionChanges,rid:(r=s.rid)!==null&&r!==void 0?r:s.id,retransmittedPacketsSent:s.retransmittedPacketsSent,targetBitrate:s.targetBitrate,timestamp:s.timestamp},a=i.get(s.remoteId);a&&(o.jitter=a.jitter,o.packetsLost=a.packetsLost,o.roundTripTime=a.roundTripTime),t.push(o)}}),t.sort((s,r)=>{var o,a;return((o=r.frameWidth)!==null&&o!==void 0?o:0)-((a=s.frameWidth)!==null&&a!==void 0?a:0)}),t})}setPublishingQuality(e){const t=[];for(let i=Qe.LOW;i<=Qe.HIGH;i+=1)t.push(new Xr({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(ct(this.codec),t)}restartTrack(e){return y(this,void 0,void 0,function*(){var t,i,s,r,o;let a;if(e){const h=aa({video:e});typeof h.video!="boolean"&&(a=h.video)}yield this.restart(a),this.isCpuConstrained=!1;try{for(var d=!0,l=wt(this.simulcastCodecs.values()),u;u=yield l.next(),t=u.done,!t;d=!0){r=u.value,d=!1;const h=r;h.sender&&((o=h.sender.transport)===null||o===void 0?void 0:o.state)!=="closed"&&(h.mediaStreamTrack=this.mediaStreamTrack.clone(),yield h.sender.replaceTrack(h.mediaStreamTrack))}}catch(h){i={error:h}}finally{try{!d&&!t&&(s=l.return)&&(yield s.call(l))}finally{if(i)throw i.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return y(this,arguments,void 0,function(i){var s=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var o,a,d,l,u,h;if(yield t.setProcessor.call(s,i,r),!((u=s.processor)===null||u===void 0)&&u.processedTrack)try{for(var m=!0,f=wt(s.simulcastCodecs.values()),C;C=yield f.next(),o=C.done,!o;m=!0)l=C.value,m=!1,yield(h=l.sender)===null||h===void 0?void 0:h.replaceTrack(s.processor.processedTrack)}catch(x){a={error:x}}finally{try{!m&&!o&&(d=f.return)&&(yield d.call(f))}finally{if(a)throw a.error}}})()})}setDegradationPreference(e){return y(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},pk))}setPublishingCodecs(e){return y(this,void 0,void 0,function*(){var t,i,s,r,o,a,d;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(ct(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const l=[];try{for(t=!0,i=wt(e);s=yield i.next(),r=s.done,!r;t=!0){d=s.value,t=!1;const u=d;if(!this.codec||this.codec===u.codec)yield this.setPublishingLayers(ct(u.codec),u.qualities);else{const h=this.simulcastCodecs.get(u.codec);if(this.log.debug("try setPublishingCodec for ".concat(u.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:h})),!h||!h.sender){for(const m of u.qualities)if(m.enabled){l.push(u.codec);break}}else h.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(u.codec),this.logContext),yield Yo(h.sender,h.encodings,u.qualities,this.senderLock,ct(u.codec),this.log,this.logContext))}}}catch(u){o={error:u}}finally{try{!t&&!r&&(a=i.return)&&(yield a.call(i))}finally{if(o)throw o.error}}return l})}setPublishingLayers(e,t){return y(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:t}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),!(!this.sender||!this.encodings)&&(yield Yo(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return y(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");const e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const t=this.sender.getParameters();t.encodings=t.encodings.map((i,s)=>{var r;return Object.assign(Object.assign({},i),{active:s===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((r=this.mediaStreamTrack.getSettings().height)!==null&&r!==void 0?r:360)/360)),scalabilityMode:s===0&&
80ct(this.codec)?"L1T3":void 0,maxFramerate:s===0?15:0,maxBitrate:s===0?i.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:t.encodings})),this.encodings=t.encodings,yield this.sender.setParameters(t)}catch(t){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:t})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return y(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),eu()&&this.isInBackground&&this.source===I.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function Yo(n,e,t,i,s,r,o){return y(this,void 0,void 0,function*(){const a=yield i.lock();r.debug("setPublishingLayersForSender",Object.assign(Object.assign({},o),{sender:n,qualities:t,senderEncodings:e}));try{const d=n.getParameters(),{encodings:l}=d;if(!l)return;if(l.length!==e.length){r.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},o),{encodings:l,senderEncodings:e}));return}let u=!1;!1&&l[0].scalabilityMode||(s&&t.some(f=>f.enabled)&&t.forEach(f=>f.enabled=!0),l.forEach((m,f)=>{var C;let x=(C=m.rid)!==null&&C!==void 0?C:"";x===""&&(x="q");const S=lu(x),v=t.find(g=>g.quality===S);v&&m.active!==v.enabled&&(u=!0,m.active=v.enabled,r.debug("setting layer ".concat(v.quality," to ").concat(m.active?"enabled":"disabled"),o),cn()&&(v.enabled?(m.scaleResolutionDownBy=e[f].scaleResolutionDownBy,m.maxBitrate=e[f].maxBitrate,m.maxFrameRate=e[f].maxFrameRate):(m.scaleResolutionDownBy=4,m.maxBitrate=10,m.maxFrameRate=2)))})),u&&(d.encodings=l,r.debug("setting encodings",Object.assign(Object.assign({},o),{encodings:d.encodings})),yield n.setParameters(d))}finally{a()}})}function lu(n){switch(n){case"f":return Qe.HIGH;case"h":return Qe.MEDIUM;case"q":return Qe.LOW;default:return Qe.HIGH}}function Zo(n,e,t,i){if(!t)return[new Dt({quality:Qe.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(i){const s=t[0].scalabilityMode,r=new du(s),o=[],a=r.suffix=="h"?1.5:2,d=r.suffix=="h"?2:3;for(let l=0;l<r.spatial;l+=1)o.push(new Dt({quality:Math.min(Qe.HIGH,r.spatial-1)-l,width:Math.ceil(n/Math.pow(a,l)),height:Math.ceil(e/Math.pow(a,l)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(d,l)):0,ssrc:0}));return o}return t.map(s=>{var r,o,a;const d=(r=s.scaleResolutionDownBy)!==null&&r!==void 0?r:1;let l=lu((o=s.rid)!==null&&o!==void 0?o:"");return new Dt({quality:l,width:Math.ceil(n/d),height:Math.ceil(e/d),bitrate:(a=s.maxBitrate)!==null&&a!==void 0?a:0,ssrc:0})})}const Xo="_lossy",ec="_reliable",fk=2*1e3,Hs="leave-reconnect",gk=3e4,vk=8*1024,bk=256*1024;var Xe;(function(n){n[n.New=0]="New",n[n.Connected=1]="Connected",n[n.Disconnected=2]="Disconnected",n[n.Reconnecting=3]="Reconnecting",n[n.Closed=4]="Closed"})(Xe||(Xe={}));class kk extends bt.EventEmitter{get isClosed(){return this._isClosed}get isNewlyCreated(){return this._isNewlyCreated}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=ha.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Xe.New,this._isClosed=!0,this._isNewlyCreated=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=Y,this.reliableDataSequence=1,this.reliableMessageBuffer=new Vo,this.reliableReceivedState=new Fb(gk),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=i=>y(this,[i],void 0,function(s){var r=this;let{channel:o}=s;return(function*(){if(o){if(o.label===ec)r.reliableDCSub=o;else if(o.label===Xo)r.lossyDCSub=o;else return;r.log.debug("on data channel ".concat(o.id,", ").concat(o.label),r.logContext),o.onmessage=r.handleDataMessage}})()}),this.handleDataMessage=i=>y(this,void 0,void 0,function*(){var s,r,o,a,d;const l=yield this.dataProcessLock.lock();try{let u;if(i.data instanceof ArrayBuffer)u=i.data;else if(i.data instanceof Blob)u=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:i.data}));return}const h=Ve.fromBinary(new Uint8Array(u));if(h.sequence>0&&h.participantSid!==""){const m=this.reliableReceivedState.get(h.participantSid);if(m&&h.sequence<=m)return;this.reliableReceivedState.set(h.participantSid,h.sequence)}if(((s=h.value)===null||s===void 0?void 0:s.case)==="speaker")this.emit
80(U.ActiveSpeakersUpdate,h.value.value.speakers);else if(((r=h.value)===null||r===void 0?void 0:r.case)==="encryptedPacket"){if(!this.e2eeManager){this.log.error("Received encrypted packet but E2EE not set up",this.logContext);return}const m=yield(o=this.e2eeManager)===null||o===void 0?void 0:o.handleEncryptedData(h.value.value.encryptedValue,h.value.value.iv,h.participantIdentity,h.value.value.keyIndex),f=Kd.fromBinary(m.payload),C=new Ve({value:f.value,participantIdentity:h.participantIdentity,participantSid:h.participantSid});((a=C.value)===null||a===void 0?void 0:a.case)==="user"&&tc(C,C.value.value),this.emit(U.DataPacketReceived,C,h.value.value.encryptionType)}else((d=h.value)===null||d===void 0?void 0:d.case)==="user"&&tc(h,h.value.value),this.emit(U.DataPacketReceived,h,we.NONE)}finally{l()}}),this.handleDataError=i=>{const r=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(i instanceof ErrorEvent&&i.error){const{error:o}=i.error;this.log.error("DataChannel error on ".concat(r,": ").concat(i.message),Object.assign(Object.assign({},this.logContext),{error:o}))}else this.log.error("Unknown DataChannel error on ".concat(r),Object.assign(Object.assign({},this.logContext),{event:i}))},this.handleBufferedAmountLow=i=>{const r=i.currentTarget.maxRetransmits===0?X.LOSSY:X.RELIABLE;this.updateAndEmitDCBufferStatus(r)},this.handleDisconnect=(i,s)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const r=d=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(d,"ms. giving up"),this.logContext),this.emit(U.Disconnected),this.close()},o=Date.now()-this.reconnectStart;let a=this.getNextRetryDelay({elapsedMs:o,retryCount:this.reconnectAttempts});if(a===null){r(o);return}i===Hs&&(a=0),this.log.debug("reconnecting in ".concat(a,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Ee.setTimeout(()=>this.attemptReconnect(s).finally(()=>this.reconnectTimeout=void 0),a)},this.waitForRestarted=()=>new Promise((i,s)=>{this.pcState===Xe.Connected&&i();const r=()=>{this.off(U.Disconnected,o),i()},o=()=>{this.off(U.Restarted,r),s()};this.once(U.Restarted,r),this.once(U.Disconnected,o)}),this.updateAndEmitDCBufferStatus=i=>{if(i===X.RELIABLE){const r=this.dataChannelForKind(i);r&&this.reliableMessageBuffer.alignBufferedAmount(r.bufferedAmount)}const s=this.isBufferStatusLow(i);typeof s<"u"&&s!==this.dcBufferStatus.get(i)&&(this.dcBufferStatus.set(i,s),this.emit(U.DCBufferStatusChanged,s,i))},this.isBufferStatusLow=i=>{const s=this.dataChannelForKind(i);if(s)return s.bufferedAmount<=s.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>y(this,void 0,void 0,function*(){!this.url||!(yield fetch(ai(this.url),{method:"HEAD"}).then(s=>s.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===me.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===me.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(Xt.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>y(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(ai(this.url),{method:"HEAD"}),Me(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=Ze((t=e.loggerName)!==null&&t!==void 0?t:qe.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new ca(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new Be,this.dataProcessLock=new Be,this.dcBufferStatus=new Map([[X.LOSSY,!0],[X.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(U.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(U.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>
80this.emit(U.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(U.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(U.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(U.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(U.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(U.SignalRequestResponse,i)}get logContext(){var e,t,i,s,r,o;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(s=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.room)===null||s===void 0?void 0:s.sid,participant:(o=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.participant)===null||o===void 0?void 0:o.identity,participantID:this.participantSid}}join(e,t,i,s){return y(this,arguments,void 0,function(r,o,a,d){var l=this;let u=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){l._isNewlyCreated=!1,l.url=r,l.token=o,l.signalOpts=a,l.maxJoinAttempts=a.maxRetries;try{l.joinAttempts+=1,l.setupSignalClientCallbacks();const h=yield l.client.join(r,o,a,d,u);return l._isClosed=!1,l.latestJoinResponse=h,l.subscriberPrimary=h.subscriberPrimary,l.pcManager||(yield l.configure(h,!u)),(!l.subscriberPrimary||h.fastPublish)&&l.negotiate().catch(m=>{Y.error(m,l.logContext)}),l.registerOnLineListener(),l.clientConfiguration=h.clientConfiguration,l.emit(U.SignalConnected,h),h}catch(h){if(h instanceof G){if(h.reason===pe.ServerUnreachable){if(l.log.warn("Couldn't connect to server, attempt ".concat(l.joinAttempts," of ").concat(l.maxJoinAttempts),l.logContext),l.joinAttempts<l.maxJoinAttempts)return l.join(r,o,a,d,u)}else if(h.reason===pe.ServiceNotFound)return l.log.warn("Initial connection failed: ".concat(h.message," – Retrying")),l.join(r,o,a,d,!0)}throw h}})()})}close(){return y(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(U.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return y(this,void 0,void 0,function*(){var e;yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0;const t=i=>{i&&(i.close(),i.onbufferedamountlow=null,i.onclose=null,i.onclosing=null,i.onerror=null,i.onmessage=null,i.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new Vo,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyDataStatByterate=0,this.lossyDataStatCurrentBytes=0,this.lossyDataStatInterval&&(clearInterval(this.lossyDataStatInterval),this.lossyDataStatInterval=void 0),this.lossyDataDropCount=0}cleanupClient(){return y(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Rt("a track with the same ID has already been published");return new Promise((t,i)=>{const s=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(G.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:r=>{clearTimeout(s),t(r)},reject:()=>{clearTimeout(s),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return y(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e,t){return y(this,void 0,void 0,function*(){var i,s;if(this.pcManager&&this.pcManager.currentState!==be.NEW)return;this.participantSid=(i=e.participant)===null||i===void 0?void 0:i.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new Jb(r,t?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit
80(U.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(o,a)=>{this.client.sendIceCandidate(o,a)},this.pcManager.onPublisherOffer=(o,a)=>{this.client.sendOffer(o,a)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(o,a,d)=>y(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(o),this.logContext),["closed","disconnected","failed"].includes(a)&&(this.publisherConnectionPromise=void 0),o===be.CONNECTED){const h=this.pcState===Xe.New;this.pcState=Xe.Connected,h&&this.emit(U.Connected,e)}else o===be.FAILED&&(this.pcState===Xe.Connected||this.pcState===Xe.Reconnecting)&&(this.pcState=Xe.Disconnected,this.handleDisconnect("peerconnection failed",d==="failed"?Xt.RR_SUBSCRIBER_FAILED:Xt.RR_PUBLISHER_FAILED));const l=this.client.isDisconnected||this.client.currentState===me.RECONNECTING,u=[be.FAILED,be.CLOSING,be.CLOSED].includes(o);l&&u&&!this._isClosed&&this.emit(U.Offline)}),this.pcManager.onTrack=o=>{o.streams.length!==0&&this.emit(U.MediaTrackAdded,o.track,o.streams[0],o.receiver)},xk((s=e.serverInfo)===null||s===void 0?void 0:s.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,i)=>y(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:i})),this.midToTrackId=i,yield this.pcManager.setPublisherAnswer(e,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,i)=>y(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=i;const s=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);s&&this.client.sendAnswer(s,t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(t=e.track)===null||t===void 0?void 0:t.sid})),!this.pendingTrackResolvers[e.cid]){this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}const{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(U.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(U.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{var t;this.token=e,(t=this.regionUrlProvider)===null||t===void 0||t.updateToken(e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(U.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(U.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(U.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{var t,i;const s={direction:"recvonly"};for(let r=0;r<e.numAudios;r++)(t=this.pcManager)===null||t===void 0||t.addPublisherTransceiverOfKind("audio",s);for(let r=0;r<e.numVideos;r++)(i=this.pcManager)===null||i===void 0||i.addPublisherTransceiverOfKind("video",s);this.negotiate()},this.client.onClose=()=>{this.handleDisconnect("signal",Xt.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e?.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions({updatedAtInMs:Date.now(),maxAgeInMs:au,regionSettings:e.regions})),e.action){case kn.DISCONNECT:this.emit(U.Disconnected,e?.reason),this.close();break;case kn.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Hs);break;case kn.RESUME:this.handleDisconnect(Hs)}}}makeRTCConfiguration(e){var t;const i=Object.assign({},this.rtcConfig);if(!((t=this.signalOpts)===null||t===void 0)&&t.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const s=[];
vendor: 6,338 bytes, line 80
80e.iceServers.forEach(r=>{const o={urls:r.urls};r.username&&(o.username=r.username),r.credential&&(o.credential=r.credential),s.push(o)}),i.iceServers=s}return e.clientConfiguration&&e.clientConfiguration.forceRelay===ti.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(Xo,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(ec,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow,this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval(()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;const e=this.dataChannelForKind(X.LOSSY);if(e){const t=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,vk),bk)}},1e3))}createSender(e,t,i){return y(this,void 0,void 0,function*(){if(hr())return yield this.createTransceiverRTCRtpSender(e,t,i);if(mr())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new Te("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,i,s){return y(this,void 0,void 0,function*(){if(hr())return this.createSimulcastTransceiverSender(e,t,i,s);if(mr())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new Te("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,i){return y(this,void 0,void 0,function*(){if(!this.pcManager)throw new Te("publisher is closed");const s=[];e.mediaStream&&s.push(e.mediaStream),Jt(e)&&(e.codec=t.videoCodec);const r={direction:"sendonly",streams:s};return i&&(r.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender})}createSimulcastTransceiverSender(e,t,i,s){return y(this,void 0,void 0,function*(){if(!this.pcManager)throw new Te("publisher is closed");const r={direction:"sendonly"};s&&(r.sendEncodings=s);const o=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,o.sender),o.sender})}createRTCRtpSender(e){return y(this,void 0,void 0,function*(){if(!this.pcManager)throw new Te("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return y(this,void 0,void 0,function*(){var t,i,s;if(!this._isClosed){if(this.attemptingReconnect){Y.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===ti.DISABLED||((s=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&s!==void 0?s:be.NEW)===be.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(r){this.reconnectAttempts+=1;let o=!0;r instanceof Te?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:r})),o=!1):r instanceof mn||(this.fullReconnectOnNext=!0),o?this.handleDisconnect("reconnect",Xt.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(U.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(e){return y(this,void 0,void 0,function*(){var t,i,s;try{if(!this.url||!this.token)throw new Te("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(U.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let r;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new mn;r=yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)}catch(o){throw o instanceof G&&o.reason===pe.NotAllowed?new Te("could not reconnect, token might be expired"):new mn}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(U.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==me.CONNECTED)throw new mn("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(U.Restarted)}catch(r){const o=yield(i=this.regionUrlProvider)===null||i===void 0?void 0:i.getNextBestRegionUrl();if(o){yield this.restartConnection(o);return}else throw(s=this.regionUrlProvider)===null||s===void 0||s.resetAttempts(),r}})}resumeConnection(e){return y(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new Te("could not reconnect, url or token not saved");if(!this.pcManager)throw new Te("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(U.Resuming);let i;try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(s){let r="";throw s instanceof Error&&(r=s.message,this.log.error(s.message,Object.assign(Object.assign({},this.logContext),{error:s}))),s instanceof G&&s.reason===pe.NotAllowed?new Te("could not reconnect, token might be expired"):s instanceof G&&s.reason===pe.LeaveRequest?s:new mn(r)}
80if(this.emit(U.SignalResumed),i){const s=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(s),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==me.CONNECTED)throw new mn("Signal connection got severed during reconnect");this.client.setReconnected(),((t=this.reliableDC)===null||t===void 0?void 0:t.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),i?.lastMessageSeq&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(U.Resumed)})}waitForPCInitialConnection(e,t){return y(this,void 0,void 0,function*(){if(!this.pcManager)throw new Te("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return y(this,void 0,void 0,function*(){this.pcState=Xe.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Me(fk),!this.pcManager)throw new Te("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Xe.Connected}catch(e){throw this.pcState=Xe.Disconnected,G.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcResponse(e,t,i,s){return y(this,void 0,void 0,function*(){const r=new Ve({destinationIdentities:[e],kind:X.RELIABLE,value:{case:"rpcResponse",value:new $r({requestId:t,value:s?{case:"error",value:s.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(r,X.RELIABLE)})}publishRpcAck(e,t){return y(this,void 0,void 0,function*(){const i=new Ve({destinationIdentities:[e],kind:X.RELIABLE,value:{case:"rpcAck",value:new Jr({requestId:t})}});yield this.sendDataPacket(i,X.RELIABLE)})}sendDataPacket(e,t){return y(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const r=Pb(e);if(r){const o=yield this.e2eeManager.encryptData(r.toBinary());e.value={case:"encryptedPacket",value:new zd({encryptedValue:o.payload,iv:o.iv,keyIndex:o.keyIndex})}}}t===X.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=e.toBinary(),s=this.dataChannelForKind(t);if(s){if(t===X.RELIABLE)yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:i,sequence:e.sequence});else{if(!this.isBufferStatusLow(t)){this.lossyDataDropCount+=1,this.lossyDataDropCount%100===0&&this.log.warn("dropping lossy data channel messages, total dropped: ".concat(this.lossyDataDropCount),this.logContext);return}this.lossyDataStatCurrentBytes+=i.byteLength}if(this.attemptingReconnect)return;s.send(i)}this.updateAndEmitDCBufferStatus(t)})}resendReliableMessagesForResume(e){return y(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(X.RELIABLE);const t=this.dataChannelForKind(X.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(i=>{t.send(i.data)})),this.updateAndEmitDCBufferStatus(X.RELIABLE)})}waitForBufferStatusLow(e){return new Le((t,i)=>y(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const s=()=>i(new Te("engine closed"));for(this.once(U.Closing,s);!this.dcBufferStatus.get(e);)yield Me(10);this.off(U.Closing,s),t()}}))}ensureDataTransportConnected(e){return y(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return(function*(){var r;if(!i.pcManager)throw new Te("PC manager is closed");const o=s?i.pcManager.subscriber:i.pcManager.publisher,a=s?"Subscriber":"Publisher";if(!o)throw G.internal("".concat(a," connection not set"));let d=!1;!s&&!i.dataChannelForKind(t,s)&&(i.createDataChannels(),d=!0),!d&&!s&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(d=!0),d&&i.negotiate().catch(h=>{Y.error(h,i.logContext)});const l=i.dataChannelForKind(t,s);if(l?.readyState==="open")return;const u=new Date().getTime()+i.peerConnectionTimeout;for(;new Date().getTime()<u;){if(o.isICEConnected&&((r=i.dataChannelForKind(t,s))===null||r===void 0?void 0:r.readyState)==="open")return;yield Me(50)}throw G.internal("could not establish ".concat(a," connection, state: ").concat(o.getICEConnectionState()))})()})}ensurePublisherConnected(e){return y(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||![be.CONNECTING,be.CONNECTED].includes(this.pcManager.currentState)||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return y(this,void 0,void 0,function*(){return new Le((e,t)=>
80y(this,void 0,void 0,function*(){if(!this.pcManager){t(new tn("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const i=new AbortController,s=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t(new tn("cannot negotiate on closed engine")),this.on(U.Closing,s),this.on(U.Restarting,s),this.pcManager.publisher.once(sn.RTPVideoPayloadTypes,r=>{const o=new Map;r.forEach(a=>{const d=a.codec.toLowerCase();ub(d)&&o.set(a.payload,d)}),this.emit(U.RTPVideoMapUpdate,o)});try{yield this.pcManager.negotiate(i),e()}catch(r){if(i.signal.aborted){e();return}r instanceof tn&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Xt.RR_UNKNOWN),r instanceof Error?t(r):t(new Error(String(r)))}finally{this.off(U.Closing,s),this.off(U.Restarting,s)}}))})}dataChannelForKind(e,t){if(t){if(e===X.LOSSY)return this.lossyDCSub;if(e===X.RELIABLE)return this.reliableDCSub}else{if(e===X.LOSSY)return this.lossyDC;if(e===X.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,s,r,o;
80if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const a=this.pcManager.publisher.getLocalDescription(),d=this.pcManager.publisher.getRemoteDescription(),l=(i=this.pcManager.subscriber)===null||i===void 0?void 0:i.getRemoteDescription(),u=(s=this.pcManager.subscriber)===null||s===void 0?void 0:s.getLocalDescription(),h=(o=(r=this.signalOpts)===null||r===void 0?void 0:r.autoSubscribe)!==null&&o!==void 0?o:!0,m=new Array,f=new Array;e.forEach(C=>{C.isDesired!==h&&m.push(C.trackSid),C.isEnabled||f.push(C.trackSid)}),this.client.sendSyncState(new ea({answer:this.pcManager.mode==="publisher-only"?d?gn({sdp:d.sdp,type:d.type}):void 0:u?gn({sdp:u.sdp,type:u.type}):void 0,offer:this.pcManager.mode==="publisher-only"?a?gn({sdp:a.sdp,type:a.type}):void 0:l?gn({sdp:l.sdp,type:l.type}):void 0,subscription:new us({trackSids:m,subscribe:!h,participantTracks:[]}),publishTracks:Jv(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:f,datachannelReceiveStates:this.reliableReceivedState.map((C,x)=>new ml({publisherSid:x,lastSeq:C}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(i,s)=>{i?.id!==void 0&&i.id!==null&&e.push(new pl({label:i.label,id:i.id,target:s}))};return t(this.dataChannelForKind(X.LOSSY),ot.PUBLISHER),t(this.dataChannelForKind(X.RELIABLE),ot.PUBLISHER),t(this.dataChannelForKind(X.LOSSY,!0),ot.SUBSCRIBER),t(this.dataChannelForKind(X.RELIABLE,!0),ot.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Ee.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){We()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){We()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;const i=(t=this.pcManager)===null||t===void 0?void 0:t.getMidForReceiver(e);if(i){const s=Object.entries(this.midToTrackId).find(r=>{let[o]=r;return o===i});if(s)return s[1]}}}function xk(n){return n!==void 0&&n>13}function tc(n,e){const t=n.participantIdentity?n.participantIdentity:e.participantIdentity;n.participantIdentity=t,e.participantIdentity=t;const i=n.destinationIdentities.length!==0?n.destinationIdentities:e.destinationIdentities;n.destinationIdentities=i,e.destinationIdentities=i}class uu{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!(typeof this.totalByteSize!="number"||this.totalByteSize===0)){if(e&&this.bytesReceived<this.totalByteSize)throw new et("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),Fe.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new et("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),Fe.LengthExceeded)}}constructor(e,t,i){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class yk extends uu{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();e.closed.catch(()=>{});const t=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>y(this,void 0,void 0,function*(){try{const i=this.signal;if(i?.aborted)throw i.reason;const s=yield new Promise((r,o)=>{if(i){const a=()=>o(i.reason);i.addEventListener("abort",a,{once:!0}),e.read().then(r,o).finally(()=>{i.removeEventListener("abort",a)})}else e.read().then(r,o)});return s.done?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(s.value),{done:!1,value:s.value.content})}catch(i){throw t(),i}}),return(){return y(this,void 0,void 0,function*(){return t(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return y(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,s,r,o;let a=new Set;const d=t.signal?e.withAbortSignal(t.signal):e;try{for(var l=!0,u=wt(d),h;h=yield u.next(),i=h.done,!i;l=!0){o=h.value,l=!1;const m=o;a.add(m)}}catch(m){s={error:m}}finally{try{!l&&!i&&(r=u.return)&&(yield r.call(u))}finally{if(s)throw s.error}}return Array.from(a)})()})}}class Ck extends uu{constructor(e,t,i){super(e,t,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=Oi(e.chunkIndex),s=this.receivedChunks.get(i);if(s&&s.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,r)}[Symbol.asyncIterator](){const e=this.reader.getReader();e.closed.catch(()=>{});const t=new TextDecoder("utf-8",{fatal:!0}),i=this.signal,s=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>y(this,void 0,void 0,function*(){try{if(i?.aborted)throw i.reason;const r=yield new Promise((o,a)=>
80{if(i){const d=()=>a(i.reason);i.addEventListener("abort",d,{once:!0}),e.read().then(o,a).finally(()=>{i.removeEventListener("abort",d)})}else e.read().then(o,a)});if(r.done)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(r.value);let o;try{o=t.decode(r.value.content)}catch(a){throw new et("Cannot decode datastream chunk ".concat(r.value.chunkIndex," as text: ").concat(a),Fe.DecodeFailed)}return{done:!1,value:o}}}catch(r){throw s(),r}}),return(){return y(this,void 0,void 0,function*(){return s(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return y(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,s,r,o;let a="";const d=t.signal?e.withAbortSignal(t.signal):e;try{for(var l=!0,u=wt(d),h;h=yield u.next(),i=h.done,!i;l=!0)o=h.value,l=!1,a+=o}catch(m){s={error:m}}finally{try{!l&&!i&&(r=u.return)&&(yield r.call(u))}finally{if(s)throw s.error}}return a})()})}}class Tk{constructor(){this.log=Y,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new et('A text stream handler for topic "'.concat(e,'" has already been set.'),Fe.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new et('A byte stream handler for topic "'.concat(e,'" has already been set.'),Fe.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(e){const t=Array.from(this.textStreamControllers.entries()).filter(s=>s[1].sendingParticipantIdentity===e),i=Array.from(this.byteStreamControllers.entries()).filter(s=>s[1].sendingParticipantIdentity===e);if(t.length>0||i.length>0){const s=new et("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),Fe.AbnormalEnd);for(const[r,o]of i)o.controller.error(s),this.byteStreamControllers.delete(r);for(const[r,o]of t)o.controller.error(s),this.textStreamControllers.delete(r)}}handleDataStreamPacket(e,t){return y(this,void 0,void 0,function*(){switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case"streamChunk":return this.handleStreamChunk(e.value.value,t);case"streamTrailer":return this.handleStreamTrailer(e.value.value,t);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}})}handleStreamHeader(e,t,i){return y(this,void 0,void 0,function*(){var s;if(e.contentHeader.case==="byteHeader"){const r=this.byteStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let o;const a={id:e.streamId,name:(s=e.contentHeader.value.name)!==null&&s!==void 0?s:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Oi(e.timestamp),attributes:e.attributes,encryptionType:i},d=new ReadableStream({start:l=>{if(o=l,this.textStreamControllers.has(e.streamId))throw new et("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),Fe.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:a,controller:o,startTime:Date.now(),sendingParticipantIdentity:t})}});r(new yk(a,d,Oi(e.totalLength)),{identity:t})}else if(e.contentHeader.case==="textHeader"){const r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let o;const a={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:i,attachedStreamIds:e.contentHeader.value.attachedStreamIds},d=new ReadableStream({start:l=>{if(o=l,this.textStreamControllers.has(e.streamId))throw new et("A data stream read is already in progress for a stream with i
80d ".concat(e.streamId,"."),Fe.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:a,controller:o,startTime:Date.now(),sendingParticipantIdentity:t})}});r(new Ck(a,d,Oi(e.totalLength)),{identity:t})}})}handleStreamChunk(e,t){const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?(i.controller.error(new et("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),Fe.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&i.controller.enqueue(e));const s=this.textStreamControllers.get(e.streamId);s&&(s.info.encryptionType!==t?(s.controller.error(new et("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(s.info.encryptionType),Fe.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&s.controller.enqueue(e))}handleStreamTrailer(e,t){const i=this.textStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?i.controller.error(new et("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),Fe.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.textStreamControllers.delete(e.streamId)));const s=this.byteStreamControllers.get(e.streamId);s&&(s.info.encryptionType!==t?s.controller.error(new et("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(s.info.encryptionType),Fe.EncryptionTypeMismatch)):(s.info.attributes=Object.assign(Object.assign({},s.info.attributes),e.attributes),s.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class hu{constructor(e,t,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return y(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)===null||e===void 0||e.call(this)})}}class Sk extends hu{}class wk extends hu{}const nc=15e3;class Rk{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return y(this,void 0,void 0,function*(){var i;const s=crypto.randomUUID(),o=new TextEncoder().encode(e).byteLength,a=(i=t?.attachments)===null||i===void 0?void 0:i.map(()=>crypto.randomUUID()),d=new Array(a?a.length+1:1).fill(0),l=(h,m)=>{var f;d[m]=h;const C=d.reduce((x,S)=>x+S,0);(f=t?.onProgress)===null||f===void 0||f.call(t,C)},u=yield this.streamText({streamId:s,totalSize:o,destinationIdentities:t?.destinationIdentities,topic:t?.topic,attachedStreamIds:a,attributes:t?.attributes});return yield u.write(e),l(1,0),yield u.close(),t?.attachments&&a&&(yield Promise.all(t.attachments.map((h,m)=>y(this,void 0,void 0,function*(){return this._sendFile(a[m],h,{topic:t.topic,mimeType:h.type,onProgress:f=>{l(f,m+1)}})})))),u.info})}streamText(e){return y(this,void 0,void 0,function*(){var t,i,s;const r=(t=e?.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),o={id:r,mimeType:"text/plain",timestamp:Date.now(),topic:(i=e?.topic)!==null&&i!==void 0?i:"",size:e?.totalSize,attributes:e?.attributes,encryptionType:!((s=this.engine.e2eeManager)===null||s===void 0)&&s.isDataChannelEncryptionEnabled?we.GCM:we.NONE,attachedStreamIds:e?.attachedStreamIds},a=new Vi({streamId:r,mimeType:o.mimeType,topic:o.topic,timestamp:en(o.timestamp),totalLength:en(o.size),attributes:o.attributes,contentHeader:{case:"textHeader",value:new nl({version:e?.version,attachedStreamIds:o.attachedStreamIds,replyToStreamId:e?.replyToStreamId,operationType:e?.type==="update"?Zs.UPDATE:Zs.CREATE})}}),d=e?.destinationIdentities,l=new Ve({destinationIdentities:d,value:{case:"streamHeader",value:a}});yield this.engine.sendDataPacket(l,X.RELIABLE);let u=0;const h=this.engine,m=new WritableStream({write(x){return y(this,void 0,void 0,function*(){for(const S of vb(x,nc)){const v=new Bi({content:S,streamId:r,chunkIndex:en(u)}),g=new Ve({destinationIdentities:d,value:{case:"streamChunk",value:v}});yield h.sendDataPacket(g,X.RELIABLE),u+=1}})},close(){return y(this,void 0,void 0,function*(){const x=new qi({streamId:r}),S=new Ve({destinationIdentities:d,value:{case:"streamTrailer",value:x}});yield h.sendDataPacket(S,X.RELIABLE)})},abort(x){console.log("Sink error:",x)}});let f=()=>y(this,void 0,void 0,function*(){yield C.close()});h.once(U.Closing,f);const C=new Sk(m,o,()=>this.engine.off(U.Closing,f));return C})}sendFile(e,t){return y(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return y(this,void 0,void 0,function*(){var s;const r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(s=i?.mimeType)!==null&&s!==void 0?s:t.type,topic:i?.topic,destinationIdentities:i?.destinationIdentities}),o=t.stream().getReader();for(;;){const{done:a,value:d}=yield o.read();if(a)break;yield r.write(d)}return yield r.close(),r.info})}streamBytes(e){return y(this,void 0,void 0,function*(){var t,i,s,r,o;const a=(t=e?.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),d=e?.destinationIdentities,l={id:a,mimeType:(i=e?.mimeType)!==null&&i!==void 0?i:"application/octet-stream",topic:(s=e?.topic)!==null&&s!==void 0?s:"",timestamp:Date.now(),attributes:e?.attributes,size:e?.totalSize,name:(r=e?.name)!==null&&r!==void 0?r:"unknown",encryptionType:!((o=this.engine.e2eeManager)===null||o===void 0)&&o.isDataChannelEncryptionEnabled?we.GCM:we.NONE},u=new Vi({totalLength:en(l.size),mimeType:l.mimeType,streamId:a,topic:l.topic,timestamp:en(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new il({name:l.name})}}),h=new Ve({destinationIdentities:d,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(h,X.RELIABLE);let m=0;const f=new Be,C=this.engine,x=this.log,S=new WritableStream({write(g){return y(this,void 0,void 0,function*(){const k=yield f.lock();let T=0;try{for(;T<g.byteLength;
vendor: 13,018 bytes, line 80
80){const b=g.slice(T,T+nc),w=new Ve({destinationIdentities:d,value:{case:"streamChunk",value:new Bi({content:b,streamId:a,chunkIndex:en(m)})}});yield C.sendDataPacket(w,X.RELIABLE),m+=1,T+=b.byteLength}}finally{k()}})},close(){return y(this,void 0,void 0,function*(){const g=new qi({streamId:a}),k=new Ve({destinationIdentities:d,value:{case:"streamTrailer",value:g}});yield C.sendDataPacket(k,X.RELIABLE)})},abort(g){x.error("Sink error:",g)}});return new wk(S,l)})}}class mu extends I{constructor(e,t,i,s,r){super(e,i,r),this.sid=t,this.receiver=s}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?A.Muted:A.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(A.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return y(this,void 0,void 0,function*(){var e;return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),pa)),$v()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const i=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(i){const{timestamp:s,rtpTimestamp:r}=i;r&&this.rtpTimestamp!==r&&(this.emit(A.TimeSyncUpdate,{timestamp:s,rtpTimestamp:r}),this.rtpTimestamp=r)}};e()}}class Ek extends mu{constructor(e,t,i,s,r,o){super(e,t,I.Kind.Audio,i,o),this.monitorReceiver=()=>y(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=ps(a,this.prevStats)),this.prevStats=a}),this.audioContext=s,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):i.volume=e;gt()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(gt())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return y(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(pr(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&pr(e)&&e.setSinkId(this.sinkId).catch(i=>{this.log.error("Failed to set sink id on remote audio track",i,this.logContext)}),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(s=>{i.connect(s),i=s}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(A.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(s=>{this.emit(A.AudioPlaybackFailed,s)})}disconnectWebAudio(){var e,t;(e=this.gainNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return y(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(i=>{i.type==="inbound-rtp"&&(t={type:"audio",streamId:i.id,timestamp:i.timestamp,jitter:i.jitter,bytesReceived:i.bytesReceived,concealedSamples:i.concealedSamples,concealmentEvents:i.concealmentEvents,silentConcealedSamples:i.silentConcealedSamples,silentConcealmentEvents:i.silentConcealmentEvents,totalAudioEnergy:i.totalAudioEnergy,totalSamplesDuration:i.totalSamplesDuration})}),t})}}const zs=100;class Pk extends mu{constructor(e,t,i,s,r){super(e,t,I.Kind.Video,i,r),this.elementInfos=[],this.monitorReceiver=()=>y(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=ps(o,this.prevStats)),this.prevStats=o}),this.debouncedHandleResize=la(()=>{this.updateDimensions()},zs),this.adaptiveStreamSettings=s}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===I.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?yn(this._mediaStreamTrack,t):fn(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){const t=new Nk(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const t=this.elementInfos.filter(i=>i===e);for(const i of t)i.stopObserving();this.elementInfos=this.elementInfos.filter(i=>i!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const i of t)this.stopObservingElement(i);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return y(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",s=new Map;return e.forEach(r=>{r.type==="inbound-rtp"?(i=r.codecId,t={type:"video",streamId:r.id,framesDecoded:r.framesDecoded,framesDropped:r.framesDropped,framesReceived:r.framesReceived,packetsReceived:r.packetsReceived,packetsLost:r.packetsLost,frameWidth:r.frameWidth,frameHeight:r.frameHeight,pliCount:r.pliCount,firCount:r.firCount,nackCount:r.nackCount,jitter:r.jitter,timestamp:r.timestamp,bytesReceived:r.bytesReceived,decoderImplementation:r.decoderImplementation}):r.type==="codec"&&s.set(r.id,r)}),t&&i!==""&&s.get(i)&&(t.mimeType=s.get(i).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(i=>i.element===e);for(const i of t)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return y(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,i;const s=this.elementInfos.reduce((d,l)=>Math.max(d,l.visibilityChangedAt||0),0),r=!((i=(t=this.adaptiveStreamSettings)===null||t===void 0?void 0:t.pauseVideoInBackground)!==null&&i!==void 0)||i?this.isInBackground:!1,o=this.elementInfos.some(d=>d.pictureInPicture),a=this.elementInfos.some(d=>d.visible)&&!r||o;if(!(this.lastVisible===a&&!e)){if(!a&&Date.now()-s<zs){Ee.setTimeout(()=>{this.updateVisibility()},zs);return}this.lastVisible=a,this.emit(A.VisibilityChanged,a,this)}}updateDimensions(){var e,t;let i=0,s=0;const r=this.getPixelDensity();for(const o of this.elementInfos){const a=o.width()*r,d=o.height()*r;a+d>i+s&&(i=a,s=d)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===i&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===s||(this.lastDimensions={width:i,height:s},this.emit(A.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?_o():t||(_o()>2?2:1)}}class Nk{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=i=>{var s;const{target:r,isIntersecting:o}=i;r===this.element&&(this.isIntersecting=o,this.isPiP=zn(this.element),this.visibilityChangedAt=Date.now(),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this))},this.onEnterPiP=()=>{var i,s,r;(s=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||s===void 0||s.addEventListener("pagehide",this.onLeavePiP),this.isPiP=zn(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=zn(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=t??xr(e),this.isPiP=We()&&zn(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=xr(this.element),this.isPiP=zn(this.element),this.element.handleResize=()=>{var s;(s=this.handleResize)===null||s===void 0||s.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Mo().observe(this.element),Io().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(i=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,s,r;(e=Mo())===null||e===void 0||e.unobserve(this.element),(t=Io())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(i=window.documentPictureInPicture)===null||i===void 0||i.removeEventListener("enter",this.onEnterPiP),(r=(s=window.documentPictureInPicture)===null||s===void 0?void 0:s.window)===null||r===void 0||r.removeEventListener("pagehide",this.onLeavePiP)}}function zn(n){var e,t;return document.pictureInPictureElement===n?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?xr(n,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function xr(n,e){const t=e||window;let i=n.offsetTop,s=n.offsetLeft;const r=n.offsetWidth,o=n.offsetHeight,{hidden:a}=n,{display:d}=getComputedStyle(n);for(;n.offsetParent;)n=n.offsetParent,i+=n.offsetTop,s+=n.offsetLeft;return i<t.pageYOffset+t.innerHeight&&s<t.pageXOffset+t.innerWidth&&i+o>t.pageYOffset&&s+r>t.pageXOffset&&!a&&d!=="none"}class Ct extends bt.EventEmitter{constructor(e,t,i,s){var r;super(),this.metadataMuted=!1,this.encryption=we.NONE,this.log=Y,this.handleMuted=()=>{this.emit(A.Muted)},this.handleUnmuted=()=>{this.emit(A.Unmuted)},this.log=Ze((r=s?.loggerName)!==null&&r!==void 0?r:qe.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=I.Source.Unknown}setTrack(e){this.track&&(this.track.off(A.Muted,this.handleMuted),this.track.off(A.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(A.Muted,this.handleMuted),e.on(A.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),ee(this))}get isMuted(){return this.metadataMuted}
80get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==we.NONE}get audioTrack(){if(ft(this.track))return this.track}get videoTrack(){if(Jt(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=I.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===I.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(n){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(n.SubscriptionStatus||(n.SubscriptionStatus={})),(function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"})(n.PermissionStatus||(n.PermissionStatus={}))})(Ct||(Ct={}));class yr extends Ct{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,i,s){super(e,t.sid,t.name,s),this.track=void 0,this.handleTrackEnded=()=>{this.emit(A.Ended)},this.handleCpuConstrained=()=>{this.track&&Jt(this.track)&&this.emit(A.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(A.Ended,this.handleTrackEnded),this.track.off(A.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(A.Ended,this.handleTrackEnded),e.on(A.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return y(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return y(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return y(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return y(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(ft(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(_e.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(_e.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(_e.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(_e.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(_e.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(_e.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function fs(n,e){return y(this,void 0,void 0,function*(){n??(n={});let t=!1;const{audioProcessor:i,videoProcessor:s,optionsWithoutProcessor:r}=Xl(n);let o=r.audio,a=r.video;if(i&&typeof r.audio=="object"&&(r.audio.processor=i),s&&typeof r.video=="object"&&(r.video.processor=s),n.audio&&typeof r.audio=="object"&&typeof r.audio.deviceId=="string"){const h=r.audio.deviceId;r.audio.deviceId={exact:h},t=!0,o=Object.assign(Object.assign({},r.audio),{deviceId:{ideal:h}})}if(r.video&&typeof r.video=="object"&&typeof r.video.deviceId=="string"){const h=r.video.deviceId;r.video.deviceId={exact:h},t=!0,a=Object.assign(Object.assign({},r.video),{deviceId:{ideal:h}})}r.audio===!0?r.audio={deviceId:"default"}:typeof r.audio=="object"&&r.audio!==null&&(r.audio=Object.assign(Object.assign({},r.audio),{deviceId:r.audio.deviceId||"default"})),r.video===!0?r.video={deviceId:"default"}:typeof r.video=="object"&&!r.video.deviceId&&(r.video.deviceId="default");const d=Ql(r,su,ru),l=aa(d),u=navigator.mediaDevices.getUserMedia(l);r.audio&&(Ie.userMediaPromiseMap.set("audioinput",u),u.catch(()=>Ie.userMediaPromiseMap.delete("audioinput"))),r.video&&(Ie.userMediaPromiseMap.set("videoinput",u),u.catch(()=>Ie.userMediaPromiseMap.delete("videoinput")));try{const h=yield u;return yield Promise.all(h.getTracks().map(m=>y(this,void 0,void 0,function*(){const f=m.kind==="audio";let C=f?d.audio:d.video;(typeof C=="boolean"||!C)&&(C={});let x;const S=f?l.audio:l.video;typeof S!="boolean"&&(x=S);const v=m.getSettings().deviceId;x?.deviceId&&nn(x.deviceId)!==v?x.deviceId=v:x||(x={deviceId:v});const g=ik(m,x,e);return g.kind===I.Kind.Video?g.source=I.Source.Camera:g.kind===I.Kind.Audio&&(g.source=I.Source.Microphone),g.mediaStream=h,ft(g)&&i?yield g.setProcessor(i):Jt(g)&&s&&(yield g.setProcessor(s)),g})))}catch(h){if(!t)throw h;return fs(Object.assign(Object.assign({},n),{audio:o,video:a}),e)}})}function _k(n){return y(this,void 0,void 0,function*(){return(yield fs({audio:!1,video:!0}
80))[0]})}function Ik(n){return y(this,void 0,void 0,function*(){return(yield fs({audio:!0,video:!1}))[0]})}var Ot;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(Ot||(Ot={}));function Mk(n){switch(n){case Gn.EXCELLENT:return Ot.Excellent;case Gn.GOOD:return Ot.Good;case Gn.POOR:return Ot.Poor;case Gn.LOST:return Ot.Lost;default:return Ot.Unknown}}class pu extends bt.EventEmitter{get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return((e=this.permissions)===null||e===void 0?void 0:e.agent)||this.kind===ni.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===bn.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,s,r,o){let a=arguments.length>6&&arguments[6]!==void 0?arguments[6]:ni.STANDARD;var d;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Ot.Unknown,this.log=Y,this.log=Ze((d=o?.loggerName)!==null&&d!==void 0?d:qe.Participant),this.loggerOptions=o,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=s,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=a,this._attributes=r??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new Lt,this.once(V.Active,()=>{var e,t;(t=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||t===void 0||t.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(I.Source.Camera);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(I.Source.Microphone);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(I.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){var t;return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===bn.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==bn.ACTIVE&&this.emit(V.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(V.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(V.ParticipantNameChanged,e)}_setAttributes(e){const t=Qv(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(V.AttributesChanged,t)}setPermissions(e){var t,i,s,r,o,a;const d=this.permissions,l=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((i=this.permissions)===null||i===void 0?void 0:i.canSubscribe)||e.canPublishData!==((s=this.permissions)===null||s===void 0?void 0:s.canPublishData)||e.hidden!==((r=this.permissions)===null||r===void 0?void 0:r.hidden)||e.recorder!==((o=this.permissions)===null||o===void 0?void 0:o.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((u,h)=>{var m;return u!==((m=this.permissions)===null||m===void 0?void 0:m.canPublishSources[h])})||e.canSubscribeMetrics!==((a=this.permissions)===null||a===void 0?void 0:a.canSubscribeMetrics);
80return this.permissions=e,l&&this.emit(V.ParticipantPermissionsChanged,d),l}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(V.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=Mk(e),t!==this._connectionQuality&&this.emit(V.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&((t=(e=this.activeFuture).reject)===null||t===void 0||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>ft(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(A.Muted,()=>{this.emit(V.TrackMuted,e)}),e.on(A.Unmuted,()=>{this.emit(V.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case I.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case I.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function jk(n){var e,t,i;if(!n.participantSid&&!n.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new ul({participantIdentity:(e=n.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=n.participantSid)!==null&&t!==void 0?t:"",allTracks:(i=n.allowAll)!==null&&i!==void 0?i:!1,trackSids:n.allowedTrackSids||[]})}class Ok extends pu{constructor(e,t,i,s,r,o){super(e,t,void 0,void 0,void 0,{loggerName:s.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=we.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Lt)},this.handleReconnected=()=>{var a,d;(d=(a=this.reconnectFuture)===null||a===void 0?void 0:a.resolve)===null||d===void 0||d.call(a),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var a,d,l,u,h,m;this.reconnectFuture&&(this.reconnectFuture.promise.catch(f=>this.log.warn(f.message,this.logContext)),(d=(a=this.reconnectFuture)===null||a===void 0?void 0:a.reject)===null||d===void 0||d.call(a,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&((u=(l=this.signalConnectedFuture).reject)===null||u===void 0||u.call(l,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),(m=(h=this.activeAgentFuture)===null||h===void 0?void 0:h.reject)===null||m===void 0||m.call(h,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=a=>{var d,l;a.participant&&this.updateInfo(a.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new Lt),(l=(d=this.signalConnectedFuture).resolve)===null||l===void 0||l.call(d)},this.handleSignalRequestResponse=a=>{const{requestId:d,reason:l,message:u}=a,h=this.pendingSignalRequests.get(d);h&&(l!==ta.OK&&h.reject(new wo(u,l)),this.pendingSignalRequests.delete(d))},this.handleDataPacket=a=>{switch(a.value.case){case"rpcResponse":let d=a.value.value,l=null,u=null;d.value.case==="payload"?l=d.value.value:d.value.case==="error"&&(u=ye.fromProto(d.value.value)),this.handleIncomingRpcResponse(d.requestId,l,u);break;case"rpcAck":let h=a.value.value;this.handleIncomingRpcAck(h.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(a=>jk(a)))},this.onTrackUnmuted=a=>{this.onTrackMuted(a,a.isUpstreamPaused)},this.onTrackMuted=(a,d)=>
vendor: 5,717 bytes, line 80
80{if(d===void 0&&(d=!0),!a.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),ee(a)));return}this.engine.updateMuteStatus(a.sid,d)},this.onTrackUpstreamPaused=a=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),ee(a))),this.onTrackMuted(a,!0)},this.onTrackUpstreamResumed=a=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),ee(a))),this.onTrackMuted(a,a.isMuted)},this.onTrackFeatureUpdate=a=>{const d=this.audioTrackPublications.get(a.sid);if(!d){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(a.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(d.trackSid,d.getTrackFeatures())},this.onTrackCpuConstrained=(a,d)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),ee(d))),this.emit(V.LocalTrackCpuConstrained,a,d)},this.handleSubscribedQualityUpdate=a=>y(this,void 0,void 0,function*(){var d,l,u,h,m;if(!(!((m=this.roomOptions)===null||m===void 0)&&m.dynacast))return;const f=this.videoTrackPublications.get(a.trackSid);if(!f){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}if(!f.videoTrack)return;const C=yield f.videoTrack.setPublishingCodecs(a.subscribedCodecs);try{for(var x=!0,S=wt(C),v;v=yield S.next(),d=v.done,!d;x=!0){h=v.value,x=!1;const g=h;Kv(g)&&(this.log.debug("publish ".concat(g," for ").concat(f.videoTrack.sid),Object.assign(Object.assign({},this.logContext),ee(f))),yield this.publishAdditionalCodecForTrack(f.videoTrack,g,f.options))}}catch(g){l={error:g}}finally{try{!x&&!d&&(u=S.return)&&(yield u.call(S))}finally{if(l)throw l.error}}}),this.handleLocalTrackUnpublished=a=>{const d=this.trackPublications.get(a.trackSid);if(!d){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}this.unpublishTrack(d.track)},this.handleTrackEnded=a=>y(this,void 0,void 0,function*(){if(a.source===I.Source.ScreenShare||a.source===I.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),ee(a))),this.unpublishTrack(a);else if(a.isUserProvided)yield a.mute();else if(yt(a)||Mt(a))try{if(We())try{const d=yield navigator?.permissions.query({name:a.source===I.Source.Camera?"camera":"microphone"});if(d&&d.state==="denied")throw this.log.warn("user has revoked access to ".concat(a.source),Object.assign(Object.assign({},this.logContext),ee(a))),d.onchange=()=>{d.state!=="denied"&&(a.isMuted||a.restartTrack(),d.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}a.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),ee(a))),yt(a)?yield a.restartTrack({deviceId:"default"}):yield a.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),ee(a))),yield a.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=s,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=r,this.roomOutgoingDataStreamManager=o}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==we.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(U.RemoteMute,(i,s)=>{const r=this.trackPublications.get(i);!r||!r.track||(s?r.mute():r.unmute())}),!((t=this.signalConnectedFuture)===null||t===void 0)&&t.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(U.Connected,this.handleReconnected).on(U.SignalConnected,this.handleSignalConnected).on(U.SignalRestarted,this.handleReconnected).on(U.SignalResumed,this.handleReconnected).on(U.Restarting,this.handleReconnecting).on(U.Resuming,this.handleReconnecting).on(U.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(U.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(U.Closing,this.handleClosing).on(U.SignalRequestResponse,this.handleSignalRequestResponse).on(U.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return y(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return y(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return y(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return y(this,arguments,void 0,function(t){var i=this;let{metadata:s,name:r,attributes:o}=t;return(function*(){return new Le((a,d)=>y(i,void 0,void 0,function*(){var l,u;try{let h=!1;const m=yield this.engine.client.sendUpdateLocalMetadata((l=s??this.metadata)!==null&&l!==void 0?l:"",(u=r??this.name)!==null&&u!==void 0?u:"",o),f=performance.now();for(this.pendingSignalRequests.set(m,{resolve:a,reject:C=>{d(C),h=!0},values:{name:r,metadata:s,attributes:o}});performance.now()-f<5e3&&!h;){if((!r||this.name===r)&&(!s||this.metadata===s)&&(!o||Object.entries(o).every(C=>{let[x,S]=C;return this.attributes[x]===S||S===""&&!this.attributes[x]}))){this.pendingSignalRequests.delete(m),a();return}yield Me(50)}d(new wo("Request to update local metadata timed out","TimeoutError"))}
80catch(h){h instanceof Error?d(h):d(new Error(String(h)))}}))})()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(I.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(I.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(I.Source.ScreenShare,e,t,i)}setE2EEEnabled(e){return y(this,void 0,void 0,function*(){this.encryptionType=e?we.GCM:we.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,i,s){return y(this,void 0,void 0,function*(){var r,o;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let a=this.getTrackPublication(e);if(t)if(a)yield a.unmute();else{let d;if(this.pendingPublishing.has(e)){const l=yield this.waitForPendingPublicationOfSource(e);return l||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield l?.unmute(),l}this.pendingPublishing.add(e);try{switch(e){case I.Source.Camera:d=yield this.createTracks({video:(r=i)!==null&&r!==void 0?r:!0});break;case I.Source.Microphone:d=yield this.createTracks({audio:(o=i)!==null&&o!==void 0?o:!0});break;case I.Source.ScreenShare:d=yield this.createScreenTracks(Object.assign({},i));break;default:throw new Rt(e)}}catch(l){throw d?.forEach(u=>{u.stop()}),l instanceof Error&&this.emit(V.MediaDevicesError,l,ur(e)),this.pendingPublishing.delete(e),l}for(const l of d){const u=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===I.Source.Microphone&&ft(l)&&u.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),l.startPreConnectBuffer())}try{const l=[];for(const h of d)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),ee(h))),l.push(this.publishTrack(h,s));[a]=yield Promise.all(l)}catch(l){throw d?.forEach(u=>{u.stop()}),l}finally{this.pendingPublishing.delete(e)}}else if(!a?.track&&this.pendingPublishing.has(e)&&(a=yield this.waitForPendingPublicationOfSource(e),a||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),a&&a.track)if(e===I.Source.ScreenShare){a=yield this.unpublishTrack(a.track);const d=this.getTrackPublication(I.Source.ScreenShareAudio);d&&d.track&&this.unpublishTrack(d.track)}else yield a.mute();return a})}enableCameraAndMicrophone(){return y(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(I.Source.Camera)||this.pendingPublishing.has(I.Source.Microphone))){this.pendingPublishing.add(I.Source.Camera),this.pendingPublishing.add(I.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(t=>this.publishTrack(t)))}finally{this.pendingPublishing.delete(I.Source.Camera),this.pendingPublishing.delete(I.Source.Microphone)}}})}createTracks(e){return y(this,void 0,void 0,function*(){var t,i;e??(e={});const s=Ql(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(i=this.roomOptions)===null||i===void 0?void 0:i.videoCaptureDefaults);try{return(yield fs(s,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(a=>(ft(a)&&(this.microphoneError=void 0,a.setAudioContext(this.audioContext),a.source=I.Source.Microphone,this.emit(V.AudioStreamAcquired)),Jt(a)&&(this.cameraError=void 0,a.source=I.Source.Camera),a))}catch(r){throw r instanceof Error&&(e.audio&&(this.microphoneError=r),e.video&&(this.cameraError=r)),r}})}createScreenTracks(e){return y(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new sa("getDisplayMedia not supported");e.resolution===void 0&&!rb()&&(e.resolution=ra.h1080fps30.resolution);const t=Gv(e),i=yield navigator.mediaDevices.getDisplayMedia(t),s=i.getVideoTracks();if(s.length===0)throw new Rt("no video track found");const r=new Wi(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=I.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const o=[r];if(i.getAudioTracks().length>
800){this.emit(V.AudioStreamAcquired);const a=new Ki(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});a.source=I.Source.ScreenShareAudio,o.push(a)}return o})}publishTrack(e,t){return y(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return y(this,arguments,void 0,function(i,s){var r=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return(function*(){var a,d,l,u;yt(i)&&i.setAudioContext(r.audioContext),yield(a=r.reconnectFuture)===null||a===void 0?void 0:a.promise,r.republishPromise&&!o&&(yield r.republishPromise),Cn(i)&&r.pendingPublishPromises.has(i)&&(yield r.pendingPublishPromises.get(i));let h;if(i instanceof MediaStreamTrack)h=i.getConstraints();else{h=i.constraints;let v;switch(i.source){case I.Source.Microphone:v="audioinput";break;case I.Source.Camera:v="videoinput"}v&&r.activeDeviceMap.has(v)&&(h=Object.assign(Object.assign({},h),{deviceId:r.activeDeviceMap.get(v)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new Ki(i,h,!0,r.audioContext,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;case"video":i=new Wi(i,h,!0,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;default:throw new Rt("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});let m;if(r.trackPublications.forEach(v=>{v.track&&v.track===i&&(m=v)}),m)return r.log.warn("track has already been published, skipping",Object.assign(Object.assign({},r.logContext),ee(m))),m;const f=Object.assign(Object.assign({},r.roomOptions.publishDefaults),s),C="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,x=(d=f.forceStereo)!==null&&d!==void 0?d:C;x&&(f.dtx===void 0&&r.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},r.logContext),ee(i))),f.red===void 0&&r.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(l=f.dtx)!==null&&l!==void 0||(f.dtx=!1),(u=f.red)!==null&&u!==void 0||(f.red=!1)),!ob()&&r.roomOptions.e2ee&&(r.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},r.logContext)),f.simulcast=!1),f.source&&(i.source=f.source);const S=new Promise((v,g)=>y(r,void 0,void 0,function*(){try{if(this.engine.client.currentState!==me.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:ee(i)}));let k=!1;const T=setTimeout(()=>{k=!0,i.stop(),g(new So("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(T),k)return;const b=yield this.publish(i,f,x);v(b)}else try{const k=yield this.publish(i,f,x);v(k)}catch(k){g(k)}}catch(k){g(k)}}));r.pendingPublishPromises.set(i,S);try{return yield S}catch(v){throw v}finally{r.pendingPublishPromises.delete(i)}})()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Lt),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),ee(e))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return t&&(i.length===0||i.map(s=>Yv(s)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),ee(e))),!1)}publish(e,t,i){return y(this,void 0,void 0,function*(){var s,r,o,a,d,l,u,h,m,f;if(!this.hasPermissionsToPublish(e))throw new So("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(_=>Cn(e)&&_.source===e.source)&&e.source!==I.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),ee(e))),t.stopMicTrackOnMute&&ft(e)&&(e.stopOnMute=!0),e.source===I.Source.ScreenShare&&cn()&&(t.simulcast=!1),t.videoCodec==="av1"&&!nb()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!ib()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=vr),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(_=>t.videoCodec===Zn(_.mime))||(t.videoCodec=Zn(this.enabledPublishVideoCodecs[0].mime)));const x=t.videoCodec;e.on(A.Muted,this.onTrackMuted),e.on(A.Unmuted,this.onTrackUnmuted),e.on(A.Ended,this.handleTrackEnded),e.on(A.UpstreamPaused,this.onTrackUpstreamPaused),e.on(A.UpstreamResumed,this.onTrackUpstreamResumed),e.on(A.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const S=[],v=!(!((s=t.dtx)!==null&&s!==void 0)||s),g=e.getSourceTrackSettings();g.autoGainControl&&S.push(_e.TF_AUTO_GAIN_CONTROL),g.echoCancellation&&S.push(_e.TF_ECHO_CANCELLATION),g.noiseSuppression&&S.push(_e.TF_NOISE_SUPPRESSION),g.channelCount&&g.channelCount>1&&S.push(_e.TF_STEREO),v&&S.push(_e.TF_NO_DTX),yt(e)&&e.hasPreConnectBuffer&&S.push(_e.TF_PRECONNECT_BUFFER);const k=new ii({cid:e.mediaStreamTrack.id,name:t.name,type:I.kindToProto(e.kind),muted:e.isMuted,source:I.sourceToProto(e.source),disableDtx:v,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(!((r=t.red)!==null&&r!==void 0)||r),stream:t?.stream,backupCodecPolicy:t?.backupCodecPolicy,audioFeatures:S});let T;if(e.kind===I.Kind.Video){let _={width:0,height:0};try{_=yield e.waitForDimensions()}catch{const L=(a=(o=this.roomOptions.videoCaptureDefaults)===null||o===void 0?void 0:o.resolution)!==null&&a!==void 0?a:si.h720.resolution;_={width:L.width,height:L.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),ee(e)),{dims:_}))}k.width=_.width,k.height=_.height,Mt(e)&&(ct(x)&&(e.source===I.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),ee(e))))),t.scalabilityMode=(d=t.scalabilityMode)!==null&&d!==void 0?d:"L3T3_KEY"),k.simulcastCodecs=[new er({codec:x,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:vr}
80),t.backupCodec&&x!==t.backupCodec.codec&&k.encryption===we.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),k.simulcastCodecs.push(new er({codec:t.backupCodec.codec,cid:""})))),T=kr(e.source===I.Source.ScreenShare,k.width,k.height,t),k.layers=Zo(k.width,k.height,T,ct(t.videoCodec))}else e.kind===I.Kind.Audio&&(T=[{maxBitrate:(l=t.audioPreset)===null||l===void 0?void 0:l.maxBitrate,priority:(h=(u=t.audioPreset)===null||u===void 0?void 0:u.priority)!==null&&h!==void 0?h:"high",networkPriority:(f=(m=t.audioPreset)===null||m===void 0?void 0:m.priority)!==null&&f!==void 0?f:"high"}]);if(!this.engine||this.engine.isClosed)throw new Te("cannot publish track when not connected");const b=()=>y(this,void 0,void 0,function*(){var _,N,L;if(!this.engine.pcManager)throw new Te("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,T),this.emit(V.LocalSenderCreated,e.sender,e),Mt(e)&&((_=t.degradationPreference)!==null&&_!==void 0||(t.degradationPreference=mk(e)),e.setDegradationPreference(t.degradationPreference)),T)if(cn()&&e.kind===I.Kind.Audio){let O;for(const q of this.engine.pcManager.publisher.getTransceivers())if(q.sender===e.sender){O=q;break}O&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:O,codec:"opus",maxbr:!((N=T[0])===null||N===void 0)&&N.maxBitrate?T[0].maxBitrate/1e3:0})}else e.codec&&ct(e.codec)&&(!((L=T[0])===null||L===void 0)&&L.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:k.cid,codec:e.codec,maxbr:T[0].maxBitrate/1e3});yield this.engine.negotiate()});let w;const P=new Promise((_,N)=>y(this,void 0,void 0,function*(){var L;try{w=yield this.engine.addTrack(k),_(w)}catch(O){e.sender&&(!((L=this.engine.pcManager)===null||L===void 0)&&L.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(q=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),ee(e)),{error:q}))})),N(O)}}));if(this.enabledPublishVideoCodecs.length>0)w=(yield Promise.all([P,b()]))[0];else{w=yield P;let _;if(w.codecs.forEach(N=>{_===void 0&&(_=N.mimeType)}),_&&e.kind===I.Kind.Video){const N=Zn(_);N!==x&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),ee(e)),{codec:N})),t.videoCodec=N,T=kr(e.source===I.Source.ScreenShare,k.width,k.height,t))}yield b()}const E=new yr(e.kind,w,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(E.on(A.CpuConstrained,_=>this.onTrackCpuConstrained(_,E)),E.options=t,e.sid=w.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:T,trackInfo:w})),Mt(e)?e.startMonitor(this.engine.client):yt(e)&&e.startMonitor(),this.addTrackPublication(E),this.emit(V.LocalTrackPublished,E),yt(e)&&w.audioFeatures.includes(_e.TF_PRECONNECT_BUFFER)){const _=e.getPreConnectBuffer(),N=e.getPreConnectBufferMimeType();this.on(V.LocalTrackSubscribed,L=>
80{if(L.trackSid===w.sid){if(!e.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed",this.logContext);return}this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),ee(e))),e.stopPreConnectBuffer()}}),_&&new Promise((O,q)=>y(this,void 0,void 0,function*(){var J,D,K,se,re,F;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),ee(e)));const he=setTimeout(()=>{q(new Error("agent not active within 10 seconds"))},1e4),ke=yield this.waitUntilActiveAgentPresent();clearTimeout(he),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),ee(e)));const B=yield this.streamBytes({name:"preconnect-buffer",mimeType:N,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[ke.identity],attributes:{trackId:E.trackSid,sampleRate:String((re=g.sampleRate)!==null&&re!==void 0?re:"48000"),channels:String((F=g.channelCount)!==null&&F!==void 0?F:"1")}});try{for(var ie=!0,$=wt(_),ne;ne=yield $.next(),J=ne.done,!J;ie=!0){se=ne.value,ie=!1;const Q=se;yield B.write(Q)}}catch(Q){D={error:Q}}finally{try{!ie&&!J&&(K=$.return)&&(yield K.call($))}finally{if(D)throw D.error}}yield B.close(),O()}catch(he){q(he)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),ee(e)))}).catch(O=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),ee(e)),{error:O}))})}return E})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return y(this,void 0,void 0,function*(){var s;if(this.encryptionType!==we.NONE)return;let r;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(r=f)}),!r)throw new Rt("track is not published");if(!Mt(e))throw new Rt("track is not a video track");const o=Object.assign(Object.assign({},(s=this.roomOptions)===null||s===void 0?void 0:s.publishDefaults),i),a=lk(e,t,o);if(!a){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),ee(e)));return}const d=e.addSimulcastTrack(t,a);if(!d)return;const l=new ii({cid:d.mediaStreamTrack.id,type:I.kindToProto(e.kind),muted:e.isMuted,source:I.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:o.videoCodec,cid:d.mediaStreamTrack.id}]});if(l.layers=Zo(l.width,l.height,a),!this.engine||this.engine.isClosed)throw new Te("cannot publish track when not connected");const u=()=>y(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,d,o,a),yield this.engine.negotiate()}),m=(yield Promise.all([this.engine.addTrack(l),u()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:a,trackInfo:m}))})}unpublishTrack(e,t){return y(this,void 0,void 0,function*(){var i,s;if(Cn(e)){const l=this.pendingPublishPromises.get(e);l&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),ee(e))),yield l)}const r=this.getPublicationForTrack(e),o=r?ee(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),o)),!r||!r.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),o));return}e=r.track,e.off(A.Muted,this.onTrackMuted),e.off(A.Unmuted,this.onTrackUnmuted),e.off(A.Ended,this.handleTrackEnded),e.off(A.UpstreamPaused,this.onTrackUpstreamPaused),e.off(A.UpstreamResumed,this.onTrackUpstreamResumed),e.off(A.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(s=(i=this.roomOptions)===null||i===void 0?void 0:i.stopLocalTrackOnUnpublish)!==null&&s!==void 0?s:!0),t?e.stop():e.stopMonitor();let a=!1;const d=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<be.FAILED&&d)try{for(const l of this.engine.pcManager.publisher.getTransceivers())l.sender===d&&(l.direction="inactive",a=!0);if(this.engine.removeTrack(d)&&(a=!0),Mt(e)){for(const[,l]of e.simulcastCodecs)l.sender&&(this.engine.removeTrack(l.sender)&&(a=!0),l.sender=void 0);e.simulcastCodecs.clear()}}catch(l){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),o),{error:l}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case I.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case I.Kind.Video:this.videoTrackPublications.delete(r.trackSid);break}
80return this.emit(V.LocalTrackUnpublished,r),r.setTrack(void 0),a&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return y(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return y(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){i.republishPromise&&(yield i.republishPromise),i.republishPromise=new Le((r,o)=>y(i,void 0,void 0,function*(){try{const a=[];this.trackPublications.forEach(d=>{d.track&&(t&&(d.options=Object.assign(Object.assign({},d.options),t)),a.push(d))}),yield Promise.all(a.map(d=>y(this,void 0,void 0,function*(){const l=d.track;yield this.unpublishTrack(l,!1),s&&!l.isMuted&&l.source!==I.Source.ScreenShare&&l.source!==I.Source.ScreenShareAudio&&(yt(l)||Mt(l))&&!l.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:d.trackSid})),yield l.restartTrack()),yield this.publishOrRepublishTrack(l,d.options,!0)}))),r()}catch(a){a instanceof Error?o(a):o(new Error(String(a)))}finally{this.republishPromise=void 0}})),yield i.republishPromise})()})}publishData(e){return y(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return(function*(){const r=s.reliable?X.RELIABLE:X.LOSSY,o=s.destinationIdentities,a=s.topic;let d=new Wr({participantIdentity:i.identity,payload:t,destinationIdentities:o,topic:a});const l=new Ve({kind:r,value:{case:"user",value:d}});yield i.engine.sendDataPacket(l,r)})()})}publishDtmf(e,t){return y(this,void 0,void 0,function*(){const i=new Ve({kind:X.RELIABLE,value:{case:"sipDtmf",value:new Gd({code:e,digit:t})}});yield this.engine.sendDataPacket(i,X.RELIABLE)})}sendChatMessage(e,t){return y(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t?.attachments},s=new Ve({value:{case:"chatMessage",value:new Fi(Object.assign(Object.assign({},i),{timestamp:ge.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(s,X.RELIABLE),this.emit(V.ChatMessage,i),i})}editChatMessage(e,t){return y(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),s=new Ve({value:{case:"chatMessage",value:new Fi(Object.assign(Object.assign({},i),{timestamp:ge.parse(i.timestamp),editTimestamp:ge.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(s,X.RELIABLE),this.emit(V.ChatMessage,i),i})}sendText(e,t){return y(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return y(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return y(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return y(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){let{destinationIdentity:t,method:i,payload:s,responseTimeout:r=15e3}=e;const o=7e3,a=o+1e3;return new Le((d,l)=>y(this,void 0,void 0,function*(){var u,h,m,f;if(ma(s)>ou){l(ye.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((h=(u=this.engine.latestJoinResponse)===null||u===void 0?void 0:u.serverInfo)===null||h===void 0)&&h.version&&vt((f=(m=this.engine.latestJoinResponse)===null||m===void 0?void 0:m.serverInfo)===null||f===void 0?void 0:f.version,"1.8.0")<0){l(ye.builtIn("UNSUPPORTED_SERVER"));return}const C=Math.max(r,a),x=crypto.randomUUID();yield this.publishRpcRequest(t,x,i,s,C);const S=setTimeout(()=>{this.pendingAcks.delete(x),l(ye.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(x),clearTimeout(v)},o);this.pendingAcks.set(x,{resolve:()=>{clearTimeout(S)},participantIdentity:t});const v=setTimeout(()=>{this.pendingResponses.delete(x),l(ye.builtIn("RESPONSE_TIMEOUT"))},r);this.pendingResponses.set(x,{resolve:(g,k)=>{clearTimeout(v),this.pendingAcks.has(x)&&(this.log.warn("RPC response received before ack",x),this.pendingAcks.delete(x),clearTimeout(S)),k?l(k):d(g??"")},participantIdentity:t})}))}
80registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,i){const s=this.pendingResponses.get(e);s?(s.resolve(t,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,i,s,r){return y(this,void 0,void 0,function*(){const o=new Ve({destinationIdentities:[e],kind:X.RELIABLE,value:{case:"rpcRequest",value:new Gr({id:t,method:i,payload:s,responseTimeoutMs:r,version:1})}});yield this.engine.sendDataPacket(o,X.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:i,resolve:s}]of this.pendingResponses)i===e&&(s(null,ye.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(t=>{var i,s;const r=this.trackPublications.get(t.sid);if(r){const o=r.isMuted||((s=(i=r.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&s!==void 0?s:!1);o!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),ee(r)),{mutedOnServer:o})),this.engine.client.sendMuteTrack(t.sid,o))}}),!0):!1}setActiveAgent(e){var t,i,s,r;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(i=(t=this.activeAgentFuture)===null||t===void 0?void 0:t.resolve)===null||i===void 0||i.call(t,e):(r=(s=this.activeAgentFuture)===null||s===void 0?void 0:s.reject)===null||r===void 0||r.call(s,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Lt),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{const s=i.track;s&&(e instanceof MediaStreamTrack?(yt(s)||Mt(s))&&s.mediaStreamTrack===e&&(t=i):e===s&&(t=i))}),t}waitForPendingPublicationOfSource(e){return y(this,void 0,void 0,function*(){const i=Date.now();for(;Date.now()<i+1e4;){const s=Array.from(this.pendingPublishPromises.entries()).find(r=>{let[o]=r;return o.source===e});if(s)return s[1];yield Me(20)}})}}class Lk extends Ct{constructor(e,t,i,s){super(e,t.sid,t.name,s),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=r=>{this.setTrack(void 0),this.emit(A.Ended,r)},this.handleVisibilityChange=r=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(r),this.logContext),this.visible=r,this.emitTrackUpdate()},this.handleVideoDimensionsChange=r=>{this.log.debug("adaptivestream video dimensions ".concat(r.width,"x").concat(r.height),this.logContext),this.videoDimensionsAdaptiveStream=r,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const s=new us({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new $d({participantSid:"",trackSids:[this.trackSid]})]});this.emit(A.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?Ct.SubscriptionStatus.Unsubscribed:super.isSubscribed?Ct.SubscriptionStatus.Subscribed:Ct.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Ct.PermissionStatus.Allowed:Ct.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled!==void 0?!this.requestedDisabled:this.isAdaptiveStream?this.visible:!0}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.requestedDisabled===!e||(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.requestedMaxQuality===e||(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&(((t=this.requestedVideoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((i=this.requestedVideoDimensions)===null||i===void 0?void 0:i.height)===e.height||(Ds(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Ds(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:Qe.HIGH}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,s=this.track;s!==e&&(s&&(s.off(A.VideoDimensionsChanged,this.handleVideoDimensionsChange),s.off(A.VisibilityChanged,this.handleVisibilityChange),s.off(A.Ended,this.handleEnded),s.detach(),s.stopMonitor(),this.emit
80(A.Unsubscribed,s)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(A.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(A.VisibilityChanged,this.handleVisibilityChange),e.on(A.Ended,this.handleEnded),this.emit(A.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(A.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?A.Muted:A.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(A.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(A.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return Ds(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new ol({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===I.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)Eo(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){const i=Zv(this.trackInfo,this.requestedMaxQuality);i&&Eo(this.videoDimensionsAdaptiveStream,i)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream;t?(e.width=Math.ceil(t.width),e.height=Math.ceil(t.height)):this.requestedMaxQuality!==void 0?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:Qe.HIGH})),e.quality=Qe.HIGH)}this.emit(A.UpdateSettings,e)}}class Gi extends pu{static fromParticipantInfo(e,t,i){return new Gi(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{remoteParticipantID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,s,r,o,a){let d=arguments.length>7&&arguments[7]!==void 0?arguments[7]:ni.STANDARD;super(t,i||"",s,r,o,a,d),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(A.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),ee(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(A.UpdateSubscription,t=>{t.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(A.SubscriptionPermissionChanged,t=>{this.emit(V.TrackSubscriptionPermissionChanged,e,t)}),e.on(A.SubscriptionStatusChanged,t=>{this.emit(V.TrackSubscriptionStatusChanged,e,t)}),e.on(A.Subscribed,t=>{this.emit(V.TrackSubscribed,t,e)}),e.on(A.Unsubscribed,t=>{this.emit(V.TrackUnsubscribed,t,e)}),e.on(A.SubscriptionFailed,t=>{this.emit(V.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:I.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrackPublication(t);
vendor: 2,335 bytes, line 80
80i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:I.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,s,r,o){let a=this.getTrackPublicationBySid(t);if(a||t.startsWith("TR")||this.trackPublications.forEach(u=>{!a&&e.kind===u.kind.toString()&&(a=u)}),!a){if(o===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(V.TrackSubscriptionFailed,t);return}o===void 0&&(o=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,s,r,o-1)},150);return}if(e.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),ee(a))),this.emit(V.TrackSubscriptionFailed,t);return}const d=e.kind==="video";let l;return d?l=new Pk(e,t,s,r):l=new Ek(e,t,s,this.audioContext,this.audioOutput),l.source=a.source,l.isMuted=a.isMuted,l.setMediaStream(i),l.start(),a.setTrack(l),this.volumeMap.has(a.source)&&fr(l)&&ft(l)&&l.setVolume(this.volumeMap.get(a.source)),a}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,i=new Map;return e.tracks.forEach(s=>{var r,o;let a=this.getTrackPublicationBySid(s.sid);if(a)a.updateInfo(s);else{const d=I.kindFromProto(s.type);if(!d)return;a=new Lk(d,s,(r=this.signalClient.connectOptions)===null||r===void 0?void 0:r.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(o=this.loggerOptions)===null||o===void 0?void 0:o.loggerName}),a.updateInfo(s),i.set(s.sid,a);const l=Array.from(this.trackPublications.values()).find(u=>u.source===a?.source);l&&a.source!==I.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(a.source),Object.assign(Object.assign({},this.logContext),{oldTrack:ee(l),newTrack:ee(a)})),this.addTrackPublication(a)}t.set(s.sid,a)}),this.trackPublications.forEach(s=>{t.has(s.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),ee(s))),this.unpublishTrack(s.trackSid,!0))}
80),i.forEach(s=>{this.emit(V.TrackPublished,s)}),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const{track:s}=i;switch(s&&(s.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case I.Kind.Audio:this.audioTrackPublications.delete(e);break;case I.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(V.TrackUnpublished,i)}setAudioOutput(e){return y(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(i=>{var s;ft(i.track)&&fr(i.track)&&t.push(i.track.setSinkId((s=e.deviceId)!==null&&s!==void 0?s:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}var ce;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(ce||(ce={}));const Ak=4*1e3;class En extends bt.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(e){var t,i,s,r,o;if(super(),t=this,this.state=ce.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=Y,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(a,d,l)=>y(this,void 0,void 0,function*(){var u;if(!sb())throw gt()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const h=yield this.disconnectLock.lock();if(this.state===ce.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),h(),Promise.resolve();if(this.connectFuture)return h(),this.connectFuture.promise;this.setAndEmitConnectionState(ce.Connecting),((u=this.regionUrlProvider)===null||u===void 0?void 0:u.getServerUrl().toString())!==iu(a)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Rn(new URL(a))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new oe(a,d):this.regionUrlProvider.updateToken(d),this.regionUrlProvider.fetchRegionSettings().then(C=>{var x;(x=this.regionUrlProvider)===null||x===void 0||x.setServerReportedRegions(C)}).catch(C=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:C}))}));const m=(C,x,S)=>y(this,void 0,void 0,function*(){var v,g;this.abortController&&this.abortController.abort();const k=new AbortController;this.abortController=k,h?.();try{if(yield Tn.getInstance().getBackOffPromise(a),k.signal.aborted)throw G.cancelled("Connection attempt aborted");yield this.attemptConnection(S??a,d,l,k),this.abortController=void 0,C()}catch(T){if(this.regionUrlProvider&&T instanceof G&&T.reason!==pe.Cancelled&&T.reason!==pe.NotAllowed){let b=null;try{this.log.debug("Fetching next region"),b=yield this.regionUrlProvider.getNextBestRegionUrl((v=this.abortController)===null||v===void 0?void 0:v.signal)}catch(w){if(w instanceof G&&(w.status===401||w.reason===pe.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),x(w);return}}[pe.InternalError,pe.ServerUnreachable,pe.Timeout].includes(T.reason)&&(this.log.debug("Adding failed connection attempt to back off"),Tn.getInstance().addFailedConnectionAttempt(a)),b&&!(!((g=this.abortController)===null||g===void 0)&&g.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(T.message,". Retrying with another region: ").concat(b),this.logContext),this.recreateEngine(!0),yield m(C,x,b)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Oo(T)),x(T))}else{let b=dt.UNKNOWN_REASON;T instanceof G&&(b=Oo(T)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,b),x(T)}}}),f=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Lt((C,x)=>{m(C,x,f)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(a,d,l,u,h,m)=>y(this,void 0,void 0,function*(){var f,C,x;const S=yield l.join(a,d,{autoSubscribe:u.autoSubscribe,adaptiveStream:typeof h.adaptiveStream=="object"?!0:
80h.adaptiveStream,maxRetries:u.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:u.websocketTimeout},m.signal,!h.singlePeerConnection);let v=S.serverInfo;if(v||(v={version:S.serverVersion,region:S.serverRegion}),this.serverInfo=v,this.log.debug("connected to Livekit Server ".concat(Object.entries(v).map(g=>{let[k,T]=g;return"".concat(k,": ").concat(T)}).join(", ")),{room:(f=S.room)===null||f===void 0?void 0:f.name,roomSid:(C=S.room)===null||C===void 0?void 0:C.sid,identity:(x=S.participant)===null||x===void 0?void 0:x.identity}),!v.version)throw new Vv("unknown server version");return v.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),h.dynacast=!1),S}),this.applyJoinResponse=a=>{const d=a.participant;if(this.localParticipant.sid=d.sid,this.localParticipant.identity=d.identity,this.localParticipant.setEnabledPublishCodecs(a.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(a.sifTrailer)}catch(l){this.log.error(l instanceof Error?l.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:l}))}this.handleParticipantUpdates([d,...a.otherParticipants]),a.room&&this.handleRoomUpdate(a.room)},this.attemptConnection=(a,d,l,u)=>y(this,void 0,void 0,function*(){var h,m;this.state===ce.Reconnecting||this.isResuming||!((h=this.engine)===null||h===void 0)&&h.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine(!0)):this.maybeCreateEngine(),!((m=this.regionUrlProvider)===null||m===void 0)&&m.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},ha),l),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const f=yield this.connectSignal(a,d,this.engine,this.connOptions,this.options,u);this.applyJoinResponse(f),this.setupLocalParticipantEvents(),this.emit(j.SignalConnected)}catch(f){yield this.engine.close(),this.recreateEngine();const C=u.signal.aborted?G.cancelled("Signal connection aborted"):G.serverUnreachable("could not establish signal connection");throw f instanceof Error&&(C.message="".concat(C.message,": ").concat(f.message)),f instanceof G&&(C.reason=f.reason,C.status=f.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:f})),C}if(u.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),G.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,u)}catch(f){throw yield this.engine.close(),this.recreateEngine(),f}We()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),We()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(ce.Connected),this.emit(j.Connected),Tn.getInstance().resetFailedConnectionAttempts(a),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var a=arguments.length,d=new Array(a),l=0;l<a;l++)d[l]=arguments[l];return y(t,[...d],void 0,function(){var u=this;let h=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var m,f,C;const x=yield u.disconnectLock.lock();try{if(u.state===ce.Disconnected){u.log.debug("already disconnected",u.logContext);return}if(u.log.info("disconnect from room",Object.assign({},u.logContext)),u.state===ce.Connecting||u.state===ce.Reconnecting||u.isResuming){const S="Abort connection attempt due to user initiated disconnect";u.log.warn(S,u.logContext),(m=u.abortController)===null||m===void 0||m.abort(S),(C=(f=u.connectFuture)===null||f===void 0?void 0:f.reject)===null||C===void 0||C.call(f,G.cancelled("Client initiated disconnect")),u.connectFuture=void 0}u.engine&&(u.engine.client.isDisconnected||(yield u.engine.client.sendLeave()),yield u.engine.close()),u.handleDisconnect(h,dt.CLIENT_INITIATED),u.engine=void 0}finally{x()}})()})},this.onPageLeave=()=>y(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>y(this,void 0,void 0,function*(){const a=[],d=Ge();if(d&&d.os==="iOS"){const l="livekit-dummy-audio-el";let u=document.getElementById(l);if(!u){u=document.createElement("audio"),u.id=l,u.autoplay=!0,u.hidden=!0;const h=As();h.enabled=!0;const m=new MediaStream([h]);u.srcObject=m,document.addEventListener("visibilitychange",()=>{u&&(u.srcObject=document.hidden?null:m,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(u),this.once(j.Disconnected,()=>{u?.remove(),u=null})}a.push(u)}
vendor: 2,743 bytes, line 80
80this.remoteParticipants.forEach(l=>{l.audioTrackPublications.forEach(u=>{u.track&&u.track.attachedElements.forEach(h=>{a.push(h)})})});try{yield Promise.all([this.acquireAudioContext(),...a.map(l=>(l.muted=!1,l.play()))]),this.handleAudioPlaybackStarted()}catch(l){throw this.handleAudioPlaybackFailed(l),l}}),this.startVideo=()=>y(this,void 0,void 0,function*(){const a=[];for(const d of this.remoteParticipants.values())d.videoTrackPublications.forEach(l=>{var u;(u=l.track)===null||u===void 0||u.attachedElements.forEach(h=>{a.includes(h)||a.push(h)})});yield Promise.all(a.map(d=>d.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(d=>{d.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const a of this.remoteParticipants.values())this.handleParticipantDisconnected(a.identity,a);this.setAndEmitConnectionState(ce.Reconnecting)&&this.emit(j.Reconnecting)},this.handleSignalRestarted=a=>y(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(a.serverRegion),Object.assign(Object.assign({},this.logContext),{region:a.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(a);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(d){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:d}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:a.serverRegion}))}catch{return}this.setAndEmitConnectionState(ce.Connected),this.emit(j.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=a=>{a.forEach(d=>{var l;if(d.identity===this.localParticipant.identity){this.localParticipant.updateInfo(d);return}d.identity===""&&(d.identity=(l=this.sidToIdentity.get(d.sid))!==null&&l!==void 0?l:"");let u=this.remoteParticipants.get(d.identity);d.state===bn.DISCONNECTED?this.handleParticipantDisconnected(d.identity,u):u=this.getOrCreateParticipant(d.identity,d)})},this.handleActiveSpeakersUpdate=a=>{const d=[],l={};a.forEach(u=>{if(l[u.sid]=!0,u.sid===this.localParticipant.sid)this.localParticipant.audioLevel=u.level,this.localParticipant.setIsSpeaking(!0),d.push(this.localParticipant);else{const h=this.getRemoteParticipantBySid(u.sid);h&&(h.audioLevel=u.level,h.setIsSpeaking(!0),d.push(h))}}),l[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEac
80h(u=>{l[u.sid]||(u.audioLevel=0,u.setIsSpeaking(!1))}),this.activeSpeakers=d,this.emitWhenConnected(j.ActiveSpeakersChanged,d)},this.handleSpeakersChanged=a=>{const d=new Map;this.activeSpeakers.forEach(u=>{const h=this.remoteParticipants.get(u.identity);h&&h.sid!==u.sid||d.set(u.sid,u)}),a.forEach(u=>{let h=this.getRemoteParticipantBySid(u.sid);u.sid===this.localParticipant.sid&&(h=this.localParticipant),h&&(h.audioLevel=u.level,h.setIsSpeaking(u.active),u.active?d.set(u.sid,h):d.delete(u.sid))});const l=Array.from(d.values());l.sort((u,h)=>h.audioLevel-u.audioLevel),this.activeSpeakers=l,this.emitWhenConnected(j.ActiveSpeakersChanged,l)},this.handleStreamStateUpdate=a=>{a.streamStates.forEach(d=>{const l=this.getRemoteParticipantBySid(d.participantSid);if(!l)return;const u=l.getTrackPublicationBySid(d.trackSid);if(!u||!u.track)return;const h=I.streamStateFromProto(d.state);u.track.setStreamState(h),h!==u.track.streamState&&(l.emit(V.TrackStreamStateChanged,u,u.track.streamState),this.emitWhenConnected(j.TrackStreamStateChanged,u,u.track.streamState,l))})},this.handleSubscriptionPermissionUpdate=a=>{const d=this.getRemoteParticipantBySid(a.participantSid);if(!d)return;const l=d.getTrackPublicationBySid(a.trackSid);l&&l.setAllowed(a.allowed)},this.handleSubscriptionError=a=>{const d=Array.from(this.remoteParticipants.values()).find(u=>u.trackPublications.has(a.trackSid));if(!d)return;const l=d.getTrackPublicationBySid(a.trackSid);l&&l.setSubscriptionError(a.err)},this.handleDataPacket=(a,d)=>{const l=this.remoteParticipants.get(a.participantIdentity);if(a.value.case==="user")this.handleUserPacket(l,a.value.value,a.kind,d);else if(a.value.case==="transcription")this.handleTranscription(l,a.value.value);else if(a.value.case==="sipDtmf")this.handleSipDtmf(l,a.value.value);else if(a.value.case==="chatMessage")this.handleChatMessage(l,a.value.value);else if(a.value.case==="metrics")this.handleMetrics(a.value.value,l);else if(a.value.case==="streamHeader"||a.value.case==="streamChunk"||a.value.case==="streamTrailer")this.handleDataStream(a,d);else if(a.value.case==="rpcRequest"){const u=a.value.value;this.handleIncomingRpcRequest(a.participantIdentity,u.id,u.method,u.payload,u.responseTimeoutMs,u.version)}},this.handleUserPacket=(a,d,l,u)=>{this.emit(j.DataReceived,d.payload,a,l,d.topic,u),a?.emit(V.DataReceived,d.payload,l,u)},this.handleSipDtmf=(a,d)=>{this.emit(j.SipDTMFReceived,d,a),a?.emit(V.SipDTMFReceived,d)},this.handleTranscription=(a,d)=>{const l=d.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(d.transcribedParticipantIdentity),u=l?.trackPublications.get(d.trackId),h=mb(d,this.transcriptionReceivedTimes);u?.emit(A.TranscriptionReceived,h),l?.emit(V.TranscriptionReceived,h,u),this.emit(j.TranscriptionReceived,h,l,u)},this.handleChatMessage=(a,d)=>{const l=pb(d);this.emit(j.ChatMessage,l,a)},this.handleMetrics=(a,d)=>{this.emit(j.MetricsReceived,a,d)},this.handleDataStream=(a,d)=>{this.incomingDataStreamManager.handleDataStreamPacket(a,d)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(j.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=a=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:a})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(j.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(j.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(j.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>y(this,void 0,void 0,function*(){var a;((a=Ge())===null||a===void 0?void 0:a.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(j.MediaDevicesChanged)}),this.handleRoomUpdate=a=>{const d=this.roomInfo;this.roomInfo=a,d&&d.metadata!==a.metadata&&this.emitWhenConnected(j.RoomMetadataChanged,a.metadata),d?.activeRecording!==a.activeRecording&&this.emitWhenConnected(j.RecordingStatusChanged,a.activeRecording)},this.handleConnectionQualityUpdate=a=>
80{a.updates.forEach(d=>{if(d.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(d.quality);return}const l=this.getRemoteParticipantBySid(d.participantSid);l&&l.setConnectionQuality(d.quality)})},this.onLocalParticipantMetadataChanged=a=>{this.emit(j.ParticipantMetadataChanged,a,this.localParticipant)},this.onLocalParticipantNameChanged=a=>{this.emit(j.ParticipantNameChanged,a,this.localParticipant)},this.onLocalAttributesChanged=a=>{this.emit(j.ParticipantAttributesChanged,a,this.localParticipant)},this.onLocalTrackMuted=a=>{this.emit(j.TrackMuted,a,this.localParticipant)},this.onLocalTrackUnmuted=a=>{this.emit(j.TrackUnmuted,a,this.localParticipant)},this.onTrackProcessorUpdate=a=>{var d;(d=a?.onPublish)===null||d===void 0||d.call(a,this)},this.onLocalTrackPublished=a=>y(this,void 0,void 0,function*(){var d,l,u,h,m,f;(d=a.track)===null||d===void 0||d.on(A.TrackProcessorUpdate,this.onTrackProcessorUpdate),(l=a.track)===null||l===void 0||l.on(A.Restarted,this.onLocalTrackRestarted),(m=(h=(u=a.track)===null||u===void 0?void 0:u.getProcessor())===null||h===void 0?void 0:h.onPublish)===null||m===void 0||m.call(h,this),this.emit(j.LocalTrackPublished,a,this.localParticipant),yt(a.track)&&(yield a.track.checkForSilence())&&this.emit(j.LocalAudioSilenceDetected,a);const C=yield(f=a.track)===null||f===void 0?void 0:f.getDeviceId(!1),x=ur(a.source);x&&C&&C!==this.localParticipant.activeDeviceMap.get(x)&&(this.localParticipant.activeDeviceMap.set(x,C),this.emit(j.ActiveDeviceChanged,x,C))}),this.onLocalTrackUnpublished=a=>{var d,l;(d=a.track)===null||d===void 0||d.off(A.TrackProcessorUpdate,this.onTrackProcessorUpdate),(l=a.track)===null||l===void 0||l.off(A.Restarted,this.onLocalTrackRestarted),this.emit(j.LocalTrackUnpublished,a,this.localParticipant)},this.onLocalTrackRestarted=a=>y(this,void 0,void 0,function*(){const d=yield a.getDeviceId(!1),l=ur(a.source);l&&d&&d!==this.localParticipant.activeDeviceMap.get(l)&&(this.log.debug("local track restarted, setting ".concat(l," ").concat(d," active"),this.logContext),this.localParticipant.activeDeviceMap.set(l,d),this.emit(j.ActiveDeviceChanged,l,d))}),this.onLocalConnectionQualityChanged=a=>{this.emit(j.ConnectionQualityChanged,a,this.localParticipant)},this.onMediaDevicesError=(a,d)=>{this.emit(j.MediaDevicesError,a,d)},this.onLocalParticipantPermissionsChanged=a=>{this.emit(j.ParticipantPermissionsChanged,a,this.localParticipant)},this.onLocalChatMessageSent=a=>{this.emit(j.ChatMessage,a,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Gb),e),this.log=Ze((i=this.options.loggerName)!==null&&i!==void 0?i:qe.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},su),e?.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},ru),e?.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Wb),e?.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new Tk,this.outgoingDataStreamManager=new Rk(this.engine,this.log),this.disconnectLock=new Be,this.localParticipant=new Ok("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",nn(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",nn(this.options.audioCaptureDefaults.deviceId)),!((s=this.options.audioOutput)===null||s===void 0)&&s.deviceId&&this.switchActiveDevice("audiooutput",nn(this.options.audioOutput.deviceId)).catch(a=>this.log.warn("Could not set audio output: ".concat(a.message),this.logContext)),We()){const a=new AbortController;(o=(r=navigator.mediaDevices)===null||r===void 0?void 0:r.addEventListener)===null||o===void 0||o.call(r,"devicechange",this.handleDeviceChange,{signal:a.signal}),En.cleanupRegistry&&En.cleanupRegistry.register(this,()=>{a.abort()})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}
80registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return y(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity);else throw Error("e2ee not configured, please set e2ee settings within the room options")})}setupE2EE(){var e;const t=!!this.options.encryption,i=this.options.encryption||this.options.e2ee;i&&("e2eeManager"in i?(this.e2eeManager=i.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=t):this.e2eeManager=new Nb(i,t),this.e2eeManager.on(At.ParticipantEncryptionStatusChanged,(s,r)=>{gb(r)&&(this.isE2EEEnabled=s),this.emit(j.ParticipantEncryptionStatusChanged,s,r)}),this.e2eeManager.on(At.EncryptionError,(s,r)=>{const o=r?this.getParticipantByIdentity(r):void 0;this.emit(j.EncryptionError,s,o)}),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:this.localParticipant.identity,participantID:this.localParticipant.sid}}get isRecording(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&t!==void 0?t:!1}getSid(){return this.state===ce.Disconnected?Le.resolve(""):this.roomInfo&&this.roomInfo.sid!==""?Le.resolve(this.roomInfo.sid):new Le((e,t)=>{const i=s=>{s.sid!==""&&(this.engine.off(U.RoomUpdate,i),e(s.sid))};this.engine.on(U.RoomUpdate,i),this.once(j.Disconnected,()=>{this.engine.off(U.RoomUpdate,i),t(new Te("Room disconnected before room server id was available"))})})}get name(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&t!==void 0?t:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&t!==void 0?t:0}get numPublishers(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&t!==void 0?t:0}maybeCreateEngine(){this.engine&&(this.engine.isNewlyCreated||!this.engine.isClosed)||(this.engine=new kk(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(U.ParticipantUpdate,this.handleParticipantUpdates).on(U.RoomUpdate,this.handleRoomUpdate).on(U.SpeakersChanged,this.handleSpeakersChanged).on(U.StreamStateChanged,this.handleStreamStateUpdate).on(U.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(U.SubscriptionError,this.handleSubscriptionError).on(U.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(U.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(U.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(U.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(U.DataPacketReceived,this.handleDataPacket).on(U.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(ce.SignalReconnecting)&&this.emit(j.SignalReconnecting)}).on(U.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(ce.Connected)&&this.emit(j.Reconnected)}).on(U.SignalResumed,()=>{this.bufferedEvents=[],(this.state===ce.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(U.Restarting,this.handleRestarting).on(U.SignalRestarted,this.handleSignalRestarted).on(U.Offline,()=>{this.setAndEmitConnectionState(ce.Reconnecting)&&this.emit(j.Reconnecting)}).on(U.DCBufferStatusChanged,(e,t)=>{this.emit(j.DCBufferStatusChanged,e,t)}).on(U.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(i=>{let{trackSid:s}=i;return s===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(V.LocalTrackSubscribed,t),this.emitWhenConnected(j.LocalTrackSubscribed,t,this.localParticipant)}).on(U.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEac
80h((t,i)=>{this.handleParticipantDisconnected(i,t)}),this.emit(j.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return Ie.getInstance().getDevices(e,t)}prepareConnection(e,t){return y(this,void 0,void 0,function*(){if(this.state===ce.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Rn(new URL(e))&&t){this.regionUrlProvider=new oe(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===ce.Disconnected&&(this.regionUrl=i,yield fetch(ai(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(ai(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:i}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return y(this,void 0,void 0,function*(){let i=()=>y(this,void 0,void 0,function*(){}),s;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":s=new ut({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":s=new ut({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":s=new ut({scenario:{case:"serverLeave",value:!0}});break;case"migration":s=new ut({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":i=()=>y(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new ut({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>y(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new ut({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":s=new ut({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>y(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new hs({reason:dt.CLIENT_INITIATED,action:kn.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");s=new ut({scenario:{case:"subscriberBandwidth",value:en(t)}});break;case"leave-full-reconnect":s=new ut({scenario:{case:"leaveRequestFullReconnect",value:!0}})}s&&(yield this.engine.client.sendSimulateScenario(s),yield i())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return y(this,arguments,void 0,function(i,s){var r=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return(function*(){var a,d,l,u,h,m,f;let C=!0,x=!1;const S=o?{exact:s}:s;if(i==="audioinput"){x=r.localParticipant.audioTrackPublications.size===0;const v=(a=r.getActiveDevice(i))!==null&&a!==void 0?a:r.options.audioCaptureDefaults.deviceId;r.options.audioCaptureDefaults.deviceId=S;const g=Array.from(r.localParticipant.audioTrackPublications.values()).filter(T=>T.source===I.Source.Microphone);try{C=(yield Promise.all(g.map(T=>{var b;return(b=T.audioTrack)===null||b===void 0?void 0:b.setDeviceId(S)}))).every(T=>T===!0)}catch(T){throw r.options.audioCaptureDefaults.deviceId=v,T}const k=g.some(T=>{var b,w;return(w=(b=T.track)===null||b===void 0?void 0:b.isMuted)!==null&&w!==void 0?w:!1});C&&k&&(x=!0)}else if(i==="videoinput"){x=r.localParticipant.videoTrackPublications.size===0;const v=(d=r.getActiveDevice(i))!==null&&d!==void 0?d:r.options.videoCaptureDefaults.deviceId;r.options.videoCaptureDefaults.deviceId=S;const g=Array.from(r.localParticipant.videoTrackPublications.values()).filter(T=>T.source===I.Source.Camera);try{C=(yield Promise.all(g.map(T=>{var b;return(b=T.videoTrack)===null||b===void 0?void 0:b.setDeviceId(S)}))).every(T=>T===!0)}catch(T){throw r.options.videoCaptureDefaults.deviceId=v,T}const k=g.some(T=>{var b,w;return(w=(b=T.track)===null||b===void 0?void 0:b.isMuted)!==null&&w!==void 0?w:!1});C&&k&&(x=!0)}else if(i==="audiooutput"){if(x=!0,!pr()&&!r.options.webAudioMix||r.options.webAudioMix&&r.audioContext&&!("setSinkId"in r.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");r.options.webAudioMix&&(s=(l=yield Ie.getInstance().normalizeDeviceId("audiooutput",s))!==null&&l!==void 0?l:""),(u=(f=r.options).audioOutput)!==null&&u!==void 0||(f.audioOutput={});const v=(h=r.getActiveDevice(i))!==null&&h!==void 0?h:r.options.audioOutput.deviceId;r.options.audioOutput.deviceId=s;try{r.options.webAudioMix&&((m=r.audioContext)===null||m===void 0||m.setSinkId(s)),yield Promise.all(Array.from(r.remoteParticipants.values()).map(g=>g.setAudioOutput({deviceId:s})))}catch(g){throw r.options.audioOutput.deviceId=v,g}}return x&&(r.localParticipant.activeDeviceMap.set(i,s),r.emit(j.ActiveDeviceChanged,i,s)),C})()})}setupLocalParticipantEvents(){this.localParticipant.on(V.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(V.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(V.AttributesChanged,this.onLocalAttributesChanged).on(V.TrackMuted,this.onLocalTrackMuted).on(V.TrackUnmuted,this.onLocalTrackUnmuted).on(V.LocalTrackPublished,this.onLocalTrackPublished).on(V.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(V.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(V.MediaDevicesError,this.onMediaDevicesError).on(V.AudioStreamAcquired,this.startAudio).on(V.ChatMessage,this.onLocalChatMessageSent).on(V.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(e){const t=this.engine;e&&t&&!t.client.isDisconnected?t.client.sendLeave().finally(()=>t.close()):t?.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,i){if(this.state===ce.Connecting||this.state===ce.Reconnecting){const h=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(f=>f.id)}),this.onTrackAdded(e,t,i),m()},m=()=>{this.off(j.Reconnected,h),this.off(j.Connected,h),this.off(j.Disconnected,m)};this.once(j.Reconnected,h),this.once(j.Connected,h),this.once(j.Disconnected,m);return}if(this.state===ce.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if(e.readyState==="ended"){this.log.info("skipping incoming track as it already ended",this.logContext);return}const s=tb(t.id),r=s[0];let o=s[1],a=e.id;
80if(o&&o.startsWith("TR")&&(a=o),r===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const d=Array.from(this.remoteParticipants.values()).find(h=>h.sid===r);if(!d){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r),this.logContext);return}if(!a.startsWith("TR")){const h=this.engine.getTrackIdForReceiver(i);if(!h){this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(r),this.logContext);return}a=h}a.startsWith("TR")||this.log.warn("Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ".concat(r,", streamId: ").concat(o,", trackId: ").concat(a),Object.assign(Object.assign({},this.logContext),{remoteParticipantID:r,streamId:o,trackId:a}));let l;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?l=this.options.adaptiveStream:l={});const u=d.addSubscribedMediaTrack(e,a,t,i,l);u?.isEncrypted&&!this.e2eeManager&&this.emit(j.EncryptionError,new Error("Encrypted ".concat(u.source," track received from participant ").concat(d.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var i,s;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==ce.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();
vendor: 22,980 bytes, line 80
80try{this.remoteParticipants.forEach(r=>{r.trackPublications.forEach(o=>{r.unpublishTrack(o.trackSid)})}),this.localParticipant.trackPublications.forEach(r=>{var o,a,d;r.track&&this.localParticipant.unpublishTrack(r.track,e),e?((o=r.track)===null||o===void 0||o.detach(),(a=r.track)===null||a===void 0||a.stop()):(d=r.track)===null||d===void 0||d.stopMonitor()}),this.localParticipant.off(V.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(V.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(V.AttributesChanged,this.onLocalAttributesChanged).off(V.TrackMuted,this.onLocalTrackMuted).off(V.TrackUnmuted,this.onLocalTrackUnmuted).off(V.LocalTrackPublished,this.onLocalTrackPublished).off(V.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(V.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(V.MediaDevicesError,this.onMediaDevicesError).off(V.AudioStreamAcquired,this.startAudio).off(V.ChatMessage,this.onLocalChatMessageSent).off(V.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix=="boolean"&&(this.audioContext.close(),this.audioContext=void 0),We()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(s=(i=navigator.mediaDevices)===null||i===void 0?void 0:i.removeEventListener)===null||s===void 0||s.call(i,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(ce.Disconnected),this.emit(j.Disconnected,t)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),t.trackPublications.forEach(s=>{t.unpublishTrack(s.trackSid,!0)}),this.emit(j.ParticipantDisconnected,t),t.setDisconnected(),(i=this.localParticipant)===null||i===void 0||i.handleParticipantDisconnected(t.identity))}handleIncomingRpcRequest(e,t,i,s,r,o){return y(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),o!==1){yield this.engine.publishRpcResponse(e,t,null,ye.builtIn("UNSUPPORTED_VERSION"));return}const a=this.rpcHandlers.get(i);if(!a){yield this.engine.publishRpcResponse(e,t,null,ye.builtIn("UNSUPPORTED_METHOD"));return}let d=null,l=null;try{const u=yield a({requestId:t,callerIdentity:e,payload:s,responseTimeout:r});ma(u)>ou?(d=ye.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),this.log.warn("RPC Response payload too large for ".concat(i))):l=u}catch(u){u instanceof ye?d=u:(this.log.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),u),d=ye.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,l,d)})}selectDefaultDevices(){return y(this,void 0,void 0,function*(){var e,t,i;const s=Ie.getInstance().previousDevices,r=yield Ie.getInstance().getDevices(void 0,!1),o=Ge();if(o?.name==="Chrome"&&o.os!=="iOS")for(let d of r){const l=s.find(u=>u.deviceId===d.deviceId);l&&l.label!==""&&l.kind===d.kind&&l.label!==d.label&&this.getActiveDevice(d.kind)==="default"&&this.emit(j.ActiveDeviceChanged,d.kind,d.deviceId)}const a=["audiooutput","audioinput","videoinput"];for(let d of a){const l=Wv(d),u=this.localParticipant.getTrackPublication(l);if(u&&(!((e=u.track)===null||e===void 0)&&e.isUserProvided))continue;const h=r.filter(f=>f.kind===d),m=this.getActiveDevice(d);if(m===((t=s.filter(f=>f.kind===d)[0])===null||t===void 0?void 0:t.deviceId)&&h.length>0&&((i=h[0])===null||i===void 0?void 0:i.deviceId)!==m){yield this.switchActiveDevice(d,h[0].deviceId);continue}d==="audioinput"&&!ri()||d==="videoinput"||h.length>0&&!h.find(f=>f.deviceId===this.getActiveDevice(d))&&(d!=="audiooutput"||!ri())&&(yield this.switchActiveDevice(d,h[0].deviceId))}})}acquireAudioContext(){return y(this,void 0,void 0,function*(){var e,t;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=Zl())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(s=>s.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),Me(200)])}catch(s){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:s}))}const i=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(j.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let s;return t?s=Gi.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):s=new Gi(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&s.setAudioContext(this.audioContext),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&s.setAudioOutput(this.options.audioOutput).catch(r=>this.log.warn("Could not set audio output: ".concat(r.message),this.logContext)),s}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const s=this.remoteParticipants.get(e);return t&&s.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),s}const i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(j.ParticipantConnected,i),i.on(V.TrackPublished,s=>{this.emitWhenConnected(j.TrackPublished,s,i)}).on(V.TrackSubscribed,(s,r)=>{s.kind===I.Kind.Audio?(s.on(A.AudioPlaybackStarted,this.handleAudioPlaybackStarted),s.on(A.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):s.kind===I.Kind.Video&&(s.on(A.VideoPlaybackFailed,this.handleVideoPlaybackFailed),s.on(A.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(j.TrackSubscribed,s,r,i)}).on(V.TrackUnpublished,s=>{this.emit(j.TrackUnpublished,s,i)}).on(V.TrackUnsubscribed,(s,r)=>{this.emit(j.TrackUnsubscribed,s,r,i)}).on(V.TrackMuted,s=>{this.emitWhenConnected(j.TrackMuted,s,i)}).on(V.TrackUnmuted,s=>{this.emitWhenConnected(j.TrackUnmuted,s,i)}).on(V.ParticipantMetadataChanged,s=>{this.emitWhenConnected(j.ParticipantMetadataChanged,s,i)}).on(V.ParticipantNameChanged,s=>{this.emitWhenConnected(j.ParticipantNameChanged,s,i)}).on(V.AttributesChanged,s=>{this.emitWhenConnected(j.ParticipantAttributesChanged,s,i)}).on(V.ConnectionQualityChanged,s=>{this.emitWhenConnected(j.ConnectionQualityChanged,s,i)}).on(V.ParticipantPermissionsChanged,s=>{this.emitWhenConnected(j.ParticipantPermissionsChanged,s,i)}).on(V.TrackSubscriptionStatusChanged,(s,r)=>{this.emitWhenConnected(j.TrackSubscriptionStatusChanged,s,r,i)}).on(V.TrackSubscriptionFailed,(s,r)=>{this.emit(j.TrackSubscriptionFailed,s,i,r)}).on(V.TrackSubscriptionPermissionChanged,(s,r)=>{this.emitWhenConnected(j.TrackSubscriptionPermissionChanged,s,r,i)}).on(V.Active,()=>{this.emitWhenConnected(j.ParticipantActive,i),i.kind===ni.AGENT&&this.localParticipant.setActiveAgent(i)}),t&&i.updateInfo(t),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((i,s)=>(i.push(...s.getTrackPublications()),i),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&fb(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Ee.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnectedOrConnecting:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,dt.STATE_MISMATCH))):e=0},Ak)}clearConnectionReconcile(){this.connectionReconcileInterval&&Ee.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(j.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,i]=e;this.emit(t,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];if(this.state===ce.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===ce.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return y(this,void 0,void 0,function*(){var t,i,s,r;const o=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),a=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new cs({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:ge.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new on({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(j.SignalConnected),this.emit(j.Connected),this.setAndEmitConnectionState(ce.Connected),o.video){const d=new yr(I.Kind.Video,new pn({source:Re.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:at.AUDIO,name:"video-dummy"}),new Wi(o.useRealTracks&&(!((t=window.navigator.mediaDevices)===null||t===void 0)&&t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:jo(160*((i=a.aspectRatios[0])!==null&&i!==void 0?i:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(d),this.localParticipant.emit(V.LocalTrackPublished,d)}if(o.audio){const d=new yr(I.Kind.Audio,new pn({source:Re.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:at.AUDIO}),new Ki(o.useRealTracks&&(!((s=navigator.mediaDevices)===null||s===void 0)&&s.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:As(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(d),this.localParticipant.emit(V.LocalTrackPublished,d)}for(let d=0;d<a.count-1;d+=1){let l=new on({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(d),state:bn.ACTIVE,tracks:[],joinedAt:ge.parse(Date.now())});const u=this.getOrCreateParticipant(l.identity,l);if(a.video){const h=jo(160*((r=a.aspectRatios[d%a.aspectRatios.length])!==null&&r!==void 0?r:1),160,!1,!0),m=new pn({source:Re.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:at.AUDIO});u.addSubscribedMediaTrack(h,m.sid,new MediaStream([h]),new RTCRtpReceiver),l.tracks=[...l.tracks,m]}if(a.audio){const h=As(),m=new pn({source:Re.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:at.AUDIO});u.addSubscribedMediaTrack(h,m.sid,new MediaStream([h]),new RTCRtpReceiver),l.tracks=[...l.tracks,m]}u.updateInfo(l)}})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];if(e!==j.ActiveSpeakersChanged&&e!==j.TranscriptionReceived){const r=fu(i).filter(o=>o!==void 0);(e===j.TrackSubscribed||e===j.TrackUnsubscribed)&&this.log.trace("subscribe trace: ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r})),this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r}))}return super.emit(e,...i)}}En.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(n=>{n()});function fu(n){return n.map(e=>{if(e)return Array.isArray(e)?fu(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var ic;(function(n){n[n.Reserved=0]="Reserved",n[n.TooLarge=1]="TooLarge"})(ic||(ic={}));var sc;(function(n){n[n.TooShort=0]="TooShort",n[n.HeaderOverrun=1]="HeaderOverrun",n[n.MissingExtWords=2]="MissingExtWords",n[n.UnsupportedVersion=3]="UnsupportedVersion",n[n.InvalidHandle=4]="InvalidHandle",n[n.MalformedExt=5]="MalformedExt"})(sc||(sc={}));var rc;(function(n){n[n.TooSmallForHeader=0]="TooSmallForHeader",n[n.TooSmallForPayload=1]="TooSmallForPayload"})(rc||(rc={}));var Ji;(function(n){n[n.UserTimestamp=2]="UserTimestamp",n[n.E2ee=1]="E2ee"})(Ji||(Ji={}));Ji.UserTimestamp;Ji.E2ee;var ac;(function(n){n[n.Start=0]="Start",n[n.Inter=1]="Inter",n[n.Final=2]="Final",n[n.Single=3]="Single"})(ac||(ac={}));var oc;(function(n){n[n.MtuTooShort=0]="MtuTooShort"})(oc||(oc={}));Ze(qe.DataTracks);var cc;(function(n){n[n.Interrupted=0]="Interrupted",n[n.UnknownFrame=1]="UnknownFrame",n[n.BufferFull=2]="BufferFull",n[n.Incomplete=3]="Incomplete"})(cc||(cc={}));var dc;(function(n){n[n.Unpublished=0]="Unpublished",n[n.Timeout=1]="Timeout",n[n.Disconnected=2]="Disconnected",n[n.Cancelled=4]="Cancelled"})(dc||(dc={}));Ze(qe.DataTracks);Ze(qe.DataTracks);var lc;(function(n){n[n.NotAllowed=0]="NotAllowed",n[n.DuplicateName=1]="DuplicateName",n[n.Timeout=2]="Timeout",n[n.LimitReached=3]="LimitReached",n[n.Disconnected=4]="Disconnected",n[n.Cancelled=5]="Cancelled"})(lc||(lc={}));var uc;(function(n){n[n.TrackUnpublished=0]="TrackUnpublished",n[n.Dropped=1]="Dropped"})(uc||(uc={}));var hc;(function(n){n[n.Packetizer=0]="Packetizer",n[n.Encryption=1]="Encryption"})(hc||(hc={}));Ze(qe.DataTracks);var rt;(function(n){n[n.IDLE=0]="IDLE",n[n.RUNNING=1]="RUNNING",n[n.SKIPPED=2]="SKIPPED",n[n.SUCCESS=3]="SUCCESS",n[n.FAILED=4]="FAILED"})(rt||(rt={}));class $t extends bt.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=rt.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new En(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return y(this,void 0,void 0,function*(){if(this.status!==rt.IDLE)throw Error("check is running already");this.setStatus(rt.RUNNING);try{yield this.perform()}catch(t){t instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(t.message):this.appendError(t.message))}return yield this.disconnect(),yield new Promise(t=>setTimeout(t,500)),this.status!==rt.SKIPPED&&this.setStatus(this.isSuccess()?rt.SUCCESS:rt.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return y(this,void 0,void 0,function*(){return this.room.state===ce.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return y(this,void 0,void 0,function*(){this.room&&this.room.state!==ce.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(rt.SKIPPED)}switchProtocol(e){return y(this,void 0,void 0,function*(){let t=!1,i=!1;if(this.room.on(j.Reconnecting,()=>{t=!0}),this.room.once(j.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(r=>setTimeout(r,1e3)),!t)return;const s=Date.now()+1e4;for(;Date.now()<s;){if(i)return;yield Me(100)}throw new Error("Could not reconnect using ".concat(e," protocol after 10 seconds"))})}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return(e=this.room)===null||e===void 0?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class Dk extends $t{get description(){return"Cloud regions"}perform(){return y(this,void 0,void 0,function*(){const e=new oe(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],i=new Set;for(let r=0;r<3;r++){const o=yield e.getNextBestRegionUrl();if(!o)break;if(i.has(o))continue;i.add(o);const a=yield this.checkCloudRegion(o);this.appendMessage("".concat(a.region," RTT: ").concat(a.rtt,"ms, duration: ").concat(a.duration,"ms")),t.push(a)}t.sort((r,o)=>(r.duration-o.duration)*.5+(r.rtt-o.rtt)*.5);const s=t[0];this.bestStats=s,this.appendMessage("best Cloud region: ".concat(s.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return y(this,void 0,void 0,function*(){var t,i;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const s=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!s)throw new Error("Region not found");const r=yield this.room.localParticipant.streamText({topic:"test"}),o=1e3,d=1e6/o,l="A".repeat(o),u=Date.now();for(let C=0;C<d;C++)yield r.write(l);yield r.close();const h=Date.now(),m=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),f={region:s,rtt:1e4,duration:h-u};return m?.forEach(C=>{C.type==="candidate-pair"&&C.nominated&&(f.rtt=C.currentRoundTripTime*1e3)}),yield this.disconnect(),f})}}const Ks=1e4;class Uk extends $t{get description(){return"Connection via UDP vs TCP"}perform(){return y(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):this.appendMessage("best connection quality via udp");const i=this.bestStats;this.appendMessage("upstream bitrate: ".concat((i.bitrateTotal/i.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((i.rttTotal/i.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((i.jitterTotal/i.count*1e3).toFixed(2)," ms")),i.packetsLost>0&&this.appendWarning("packets lost: ".concat((i.packetsLost/i.packetsSent*100).toFixed(2),"%")),i.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((i.qualityLimitationDurations.bandwidth/(Ks/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(Ks/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return y(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const i=t.getContext("2d");if(!i)throw new Error("Could not get canvas context");let s=0;const r=()=>{s=(s+1)%360,i.fillStyle="hsl(".concat(s,", 100%, 50%)"),i.fillRect(0,0,t.width,t.height),requestAnimationFrame(r)};r();const a=t.captureStream(30).getVideoTracks()[0],l=(yield this.room.localParticipant.publishTrack(a,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,u={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},h=setInterval(()=>y(this,void 0,void 0,function*(){const m=yield l.getRTCStatsReport();m?.forEach(f=>{f.type==="outbound-rtp"?(u.packetsSent=f.packetsSent,u.qualityLimitationDurations=f.qualityLimitationDurations,u.bitrateTotal+=f.targetBitrate,u.count++):f.type==="remote-inbound-rtp"&&(u.packetsLost=f.packetsLost,u.rttTotal+=f.roundTripTime,u.jitterTotal+=f.jitter)})}),1e3);return yield new Promise(m=>setTimeout(m,Ks)),clearInterval(h),a.stop(),t.remove(),yield this.disconnect(),u})}}class Fk extends $t{get description(){return"Can publish audio"}perform(){return y(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield Ik();if(yield Yl(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,3e3));const r=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let o=0;if(r.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="audio"||!a.kind&&a.mediaType==="audio")&&(o=a.packetsSent)}),o===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(o," audio packets"))})}}class Vk extends $t{get description(){return"Can publish video"}perform(){return y(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield _k();yield this.checkForVideo(i.mediaStreamTrack),t.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,5e3));const s=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let r=0;if(s.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="video"||!o.kind&&o.mediaType==="video")&&(r+=o.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))})}checkForVideo(e){return y(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const i=document.createElement("video");i.srcObject=t,i.muted=!0,i.autoplay=!0,i.playsInline=!0,i.setAttribute("playsinline","true"),document.body.appendChild(i),yield new Promise(s=>{i.onplay=()=>{setTimeout(()=>{var r,o,a,d;const l=document.createElement("canvas"),u=e.getSettings(),h=(o=(r=u.width)!==null&&r!==void 0?r:i.videoWidth)!==null&&o!==void 0?o:1280,m=(d=(a=u.height)!==null&&a!==void 0?a:i.videoHeight)!==null&&d!==void 0?d:720;l.width=h,l.height=m;const f=l.getContext("2d");f.drawImage(i,0,0);const x=f.getImageData(0,0,l.width,l.height).data;let S=!0;for(let v=0;v<x.length;v+=4)if(x[v]!==0||x[v+1]!==0||x[v+2]!==0){S=!1;break}S?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),s()},1e3)},i.play()}),t.getTracks().forEach(s=>s.stop()),i.remove()})}}class Bk extends $t{get description(){return"Resuming connection after interruption"}perform(){return y(this,void 0,void 0,function*(){var e;const t=yield this.connect();let i=!1,s=!1,r;const o=new Promise(l=>{setTimeout(l,5e3),r=l}),a=()=>{i=!0};t.on(j.SignalReconnecting,a).on(j.Reconnecting,a).on(j.Reconnected,()=>{s=!0,r(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const d=t.engine.client.onClose;
80if(d&&d(""),yield o,i){if(!s||t.state!==ce.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}else throw new Error("Did not attempt to reconnect")})}}class qk extends $t{get description(){return"Can connect via TURN"}perform(){return y(this,void 0,void 0,function*(){var e,t,i;Rn(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(e=yield new oe(this.url,this.token).getNextBestRegionUrl())!==null&&e!==void 0?e:this.url);const s=new ca,r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0);let o=!1,a=!1,d=!1;for(let l of r.iceServers)for(let u of l.urls)u.startsWith("turn:")?(a=!0,d=!0):u.startsWith("turns:")&&(a=!0,d=!0,o=!0),u.startsWith("stun:")&&(d=!0);d?a&&!o&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield s.close(),!((i=(t=this.connectOptions)===null||t===void 0?void 0:t.rtcConfig)===null||i===void 0)&&i.iceServers||a?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(l=>setTimeout(l,0)))})}}class Hk extends $t{get description(){return"Establishing WebRTC connection"}perform(){return y(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(j.SignalConnected,()=>{var i;const s=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(r,o)=>{if(r.candidate){const a=new RTCIceCandidate(r);let d="".concat(a.protocol," ").concat(a.address,":").concat(a.port," ").concat(a.type);a.address&&(zk(a.address)?d+=" (private)":a.protocol==="tcp"&&a.tcpType==="passive"?(e=!0,d+=" (passive)"):a.protocol==="udp"&&(t=!0)),this.appendMessage(d)}s&&s(r,o)},!((i=this.room.engine.pcManager)===null||i===void 0)&&i.subscriber&&(this.room.engine.pcManager.subscriber.onIceCandidateError=r=>{r instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(r.errorCode," ").concat(r.errorText," ").concat(r.url))})});try{yield this.connect(),Y.info("now the room is connected")}catch(i){throw this.appendWarning("ports need to be open on firewall in order to connect."),i}e||this.appendWarning("Server is not configured for ICE/TCP"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function zk(n){const e=n.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}class Kk extends $t{get description(){return"Connecting to signal connection via WebSocket"}perform(){return y(this,void 0,void 0,function*(){var e,t,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let s=new ca,r;try{r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(o){if(Rn(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(o.message,". Retrying with region fallback"));const d=yield new oe(this.url,this.token).getNextBestRegionUrl();d&&(r=yield s.join(d,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0),this.appendMessage("Fallback to region worked. To avoid initial connections failing, ensure you're calling room.prepareConnection() ahead of time"))}}r?(this.appendMessage("Connected to server, version ".concat(r.serverVersion,".")),((e=r.serverInfo)===null||e===void 0?void 0:e.edition)===Yd.Cloud&&(!((t=r.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=r.serverInfo)===null||i===void 0?void 0:i.region))):this.appendError("Websocket connection could not be established"),yield s.close()})}}class fy extends bt.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=i}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:rt.IDLE,name:"",description:""}),e}
80updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==rt.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return y(this,void 0,void 0,function*(){const t=this.getNextCheckId(),i=new e(this.url,this.token,this.options),s=o=>{this.updateCheck(t,o)};i.on("update",s);const r=yield i.run();return i.off("update",s),r})}checkWebsocket(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(Kk)})}checkWebRTC(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(Hk)})}checkTURN(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(qk)})}checkReconnect(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(Bk)})}checkPublishAudio(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(Fk)})}checkPublishVideo(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(Vk)})}checkConnectionProtocol(){return y(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(Uk);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(Dk)})}}function te(n,e,t){return(e=Gk(e))in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function Wk(n,e){if(typeof n!="object"||!n)return n;var t=n[Symbol.toPrimitive];if(t!==void 0){var i=t.call(n,e);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function Gk(n){var e=Wk(n,"string");return typeof e=="symbol"?e:e+""}new TextEncoder;new TextDecoder;class He extends Error{constructor(e,t){var i;super(e,t),te(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,(i=Error.captureStackTrace)===null||i===void 0||i.call(Error,this,this.constructor)}}
80te(He,"code","ERR_JOSE_GENERIC");class Jk extends He{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:s,payload:t}}),te(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),te(this,"claim",void 0),te(this,"reason",void 0),te(this,"payload",void 0),this.claim=i,this.reason=s,this.payload=t}}te(Jk,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class $k extends He{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:s,payload:t}}),te(this,"code","ERR_JWT_EXPIRED"),te(this,"claim",void 0),te(this,"reason",void 0),te(this,"payload",void 0),this.claim=i,this.reason=s,this.payload=t}}te($k,"code","ERR_JWT_EXPIRED");class Qk extends He{constructor(){super(...arguments),te(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}te(Qk,"code","ERR_JOSE_ALG_NOT_ALLOWED");class Yk extends He{constructor(){super(...arguments),te(this,"code","ERR_JOSE_NOT_SUPPORTED")}}te(Yk,"code","ERR_JOSE_NOT_SUPPORTED");class Zk extends He{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"decryption operation failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),te(this,"code","ERR_JWE_DECRYPTION_FAILED")}}te(Zk,"code","ERR_JWE_DECRYPTION_FAILED");class Xk extends He{constructor(){super(...arguments),te(this,"code","ERR_JWE_INVALID")}}te(Xk,"code","ERR_JWE_INVALID");class ex extends He{constructor(){super(...arguments),te(this,"code","ERR_JWS_INVALID")}}te(ex,"code","ERR_JWS_INVALID");class tx extends He{constructor(){super(...arguments),te(this,"code","ERR_JWT_INVALID")}}te(tx,"code","ERR_JWT_INVALID");class nx extends He{constructor(){super(...arguments),te(this,"code","ERR_JWK_INVALID")}}te(nx,"code","ERR_JWK_INVALID");class ix extends He{constructor(){super(...arguments),te(this,"code","ERR_JWKS_INVALID")}}te(ix,"code","ERR_JWKS_INVALID");class sx extends He{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"no applicable key found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),te(this,"code","ERR_JWKS_NO_MATCHING_KEY")}}te(sx,"code","ERR_JWKS_NO_MATCHING_KEY");class rx extends He{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"multiple matching keys found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),te(this,Symbol.asyncIterator,void 0),te(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}}te(rx,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class ax extends He{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"request timed out",t=arguments.length>1?arguments[1]:void 0;super(e,t),te(this,"code","ERR_JWKS_TIMEOUT")}}te(ax,"code","ERR_JWKS_TIMEOUT");class ox extends He{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"signature verification failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),te(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}}te(ox,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");const mc=8e3,cx=["NotAllowed","ServerUnreachable","InternalError","Cancelled","LeaveRequest","Timeout","WebSocket","ServiceNotFound"];function dx(n){const e=n?.name;return e==="NotAllowedError"||e==="NotFoundError"}function lx(){const[n,e]=p.useState(!1),[t,i]=p.useState(!1),[s,r]=p.useState([]),[o,a]=p.useState(!1),[d,l]=p.useState(!1),u=p.useRef(!1),[h,m]=p.useState(!1),[f,C]=p.useState(!1),[x,S]=p.useState(null),v=p.useRef(null),g=p.useRef(null),k=p.useRef(!0),T=p.useRef(null),b=p.useRef(new Map),w=p.useCallback(F=>{if(!T.current){const $=document.createElement("div");$.style.display="none",$.setAttribute("aria-hidden","true"),$.setAttribute("data-livekit-audio",""),document.body.appendChild($),T.current=$}const ie=F.attach();T.current.appendChild(ie),F.sid&&b.current.set(F.sid,ie)},[]),P=p.useCallback(F=>{F.detach().forEach(ie=>ie.remove()),F.sid&&b.current.delete(F.sid)},[]),E=p.useCallback(()=>{b.current.forEach(F=>F.remove()),b.current.clear()},[]);p.useEffect(()=>(k.current=!0,()=>{if(k.current=!1,v.current){try{v.current.disconnect()}catch{}v.current=null}E(),T.current?.remove(),T.current=null,g.current&&(Un.leaveRoom(g.current).catch(()=>{}),g.current=null)}),[E]);const _=p.useCallback(()=>{const F=v.current;if(!F)return;const ie=[];if(F.localParticipant){const $=F.localParticipant;ie.push({identity:$.identity||"local",name:$.name||$.identity||"You",isMuted:!$.isMicrophoneEnabled,isSpeaking:$.isSpeaking||!1,isLocal:!0})}
80F.remoteParticipants.forEach($=>{ie.push({identity:$.identity,name:$.name||$.identity,isMuted:!$.isMicrophoneEnabled,isSpeaking:$.isSpeaking||!1,isLocal:!1})}),k.current&&r(ie)},[]),N=p.useCallback(()=>{const F=v.current?.localParticipant;F&&k.current&&a(!F.isMicrophoneEnabled)},[]),L=p.useRef(!1),O=p.useRef(0),q=p.useCallback(async()=>{O.current+=1,a(!0);try{const F=v.current?.localParticipant;F?.isMicrophoneEnabled&&await F.setMicrophoneEnabled(!1)}catch{}},[]),J=p.useCallback(async(F,ie)=>{const $=ie?.canPublish??!0;S(null),e(!0);const ne=!!v.current||!!g.current;if(v.current){try{v.current.disconnect()}catch{}v.current=null}if(E(),g.current){try{await Un.leaveRoom(g.current)}catch{}g.current=null}ne&&(i(!1),r([]),a(!1),l(!1),m(!1),u.current=!1);let he,ke;try{const{data:B}=await Un.joinRoom(F);he=B.token,ke=B.url,g.current=F}catch(B){throw $e("voice-server-join",{roomId:F},B),g.current=null,S("Could not join the room. Please try again."),i(!1),e(!1),r([]),a(!1),B}try{const B=new En({publishDefaults:{audioPreset:zi.speech}});if(v.current=B,B.on(j.ParticipantConnected,_),B.on(j.ParticipantDisconnected,_),B.on(j.ActiveSpeakersChanged,_),B.on(j.TrackMuted,_),B.on(j.TrackUnmuted,_),B.on(j.TrackMuted,N),B.on(j.TrackUnmuted,N),B.on(j.LocalTrackPublished,N),B.on(j.LocalTrackUnpublished,N),B.on(j.TrackSubscribed,(Q,fe)=>{if(Q.kind===I.Kind.Audio&&(w(Q),u.current))try{fe.setEnabled(!1)}catch{}}),B.on(j.TrackUnsubscribed,Q=>{Q.kind===I.Kind.Audio&&P(Q)}),B.on(j.AudioPlaybackStatusChanged,()=>{k.current&&C(!B.canPlaybackAudio)}),B.on(j.ParticipantPermissionsChanged,(Q,fe)=>{if(fe.identity!==B.localParticipant.identity)return;const Ue=!!B.localParticipant.permissions?.canPublish;k.current&&m(Ue),Ue||q()}),B.on(j.Disconnected,()=>{v.current=null,E(),k.current&&(i(!1),r([]))}),await B.connect(ke.replace(/^ws:/,"wss:"),he,{autoSubscribe:!0,peerConnectionTimeout:mc,websocketTimeout:mc}),$)try{await B.localParticipant.setMicrophoneEnabled(!0),a(!1)}catch(Q){$e("voice-mic-enable",{roomId:F},Q),a(!0),S(dx(Q)?"Microphone access was blocked — check your browser permissions.":"Couldn't start your microphone — you've joined muted.")}else a(!0);m(!!B.localParticipant.permissions?.canPublish),C(!B.canPlaybackAudio),_(),i(!0)}catch(B){const Q=B,fe=typeof Q.reason=="number"?cx[Q.reason]??`reason#${Q.reason}`:Q.reason;if($e("voice-livekit-connect",{roomId:F,canPublish:$,reason:fe,status:Q.status},B),v.current){try{v.current.disconnect()}catch{}v.current=null}throw E(),g.current&&(Un.leaveRoom(g.current).catch(()=>{}),g.current=null),S("Couldn't connect to the audio room. Please try again later."),i(!1),e(!1),r([]),a(!1),m(!1),B}finally{e(!1)}},[_,N,w,P,E,q]),D=p.useCallback(async()=>{if(v.current){try{await v.current.disconnect()}catch{}v.current=null}if(E(),g.current)try{await Un.leaveRoom(g.current)}catch{}g.current=null,u.current=!1,i(!1),r([]),a(!1),l(!1),m(!1),C(!1)},[E]),K=p.useCallback(async()=>{if(L.current)return;L.current=!0;const F=v.current?.localParticipant,$=!(F?!F.isMicrophoneEnabled:o);a($);const ne=O.current;try{if(F)if(await F.setMicrophoneEnabled(!$),!$&&O.current!==ne){try{await F.setMicrophoneEnabled(!1)}catch{}a(!0)}else a(!F.isMicrophoneEnabled)}catch{N()}finally{L.current=!1}},[o,N]),se=p.useCallback(()=>{const F=!u.current;u.current=F,l(F);const ie=v.current;
80ie&&ie.remoteParticipants.forEach($=>{$.trackPublications.forEach(ne=>{if(ne.kind===I.Kind.Audio)try{ne.setEnabled(!F)}catch{}})})},[]),re=p.useCallback(async()=>{const F=v.current;if(F)try{await F.startAudio(),k.current&&C(!F.canPlaybackAudio)}catch(ie){$e("voice-resume-audio",{roomId:g.current},ie)}},[]);return{connecting:n,connected:t,participants:s,isMuted:o,deafened:d,canPublishNow:h,audioBlocked:f,error:x,join:J,leave:D,toggleMute:K,muteMic:q,toggleDeafen:se,resumeAudio:re}}const ux="max-h-[min(360px,32dvh)]";function hx({participant:n,onAction:e,onProfile:t}){const i=as(n),s=fd(n),r=pd(n),o=n.name||n.username||"Member",a=t&&n.username?()=>t(n):void 0,d=n.username?Ft(n.username):null,l=c.jsx("div",{className:`rounded-full border-2 p-1 ${s}`,children:n.avatar?c.jsx("img",{src:n.avatar,alt:"",className:"h-[60px] w-[60px] rounded-full border-2 border-bg dark:border-bg-dark object-cover",loading:"lazy"}):c.jsx("div",{className:"flex h-[60px] w-[60px] items-center justify-center rounded-full border-2 border-bg dark:border-bg-dark bg-surface dark:bg-surface-dark text-lg font-bold text-text-dim dark:text-text-dim-dark",children:o.charAt(0).toUpperCase()})}),u=c.jsxs(c.Fragment,{children:[n.role==="listener"?c.jsx(Gc,{size:12,"aria-hidden":"true"}):i?c.jsx(Xc,{width:14,height:9}):n.isMuted?c.jsx(ns,{size:12,className:"text-error","aria-label":"Muted"}):c.jsx(ln,{size:12,"aria-hidden":"true"}),c.jsx("span",{children:r})]}),h=e?()=>e(n):void 0,m=h?f=>{tp(f.target)||(f.preventDefault(),f.stopPropagation(),h())}:void 0;return c.jsxs("div",{"data-participant-ulid":n.ulid,className:"flex min-w-0 flex-col items-center gap-1 py-1",onContextMenu:m,children:[a&&d?c.jsx(Pe,{to:d,...rn(),onClick:f=>an(f,a),"aria-label":`View profile for ${o}`,className:"rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-custom-blue",children:l}):l,c.jsxs("div",{className:"flex min-w-0 max-w-full items-center gap-1 px-1",children:[a&&d?c.jsx(Pe,{to:d,...rn(),onClick:f=>an(f,a),className:"min-w-0 max-w-full truncate text-sm font-medium text-text hover:underline focus-visible:outline-none focus-visible:underline dark:text-text-dark",children:o}):c.jsx("span",{className:"min-w-0 max-w-full truncate text-sm font-medium text-text dark:text-text-dark",children:o}),c.jsx(Zi,{badges:n.badges,size:12})]}),h?c.jsxs("button",{type:"button",onClick:h,"aria-label":`Manage ${o}`,className:"flex min-w-0 max-w-full items-center gap-1 rounded px-1 text-xs font-medium text-text-dim transition-colors hover:bg-nav-active/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-custom-blue dark:text-text-dim-dark dark:hover:bg-nav-active-dark/50",children:[u,c.jsx(ep,{size:12,className:"flex-none","aria-hidden":"true"})]}):c.jsx("div",{className:"flex items-center gap-1 text-xs font-medium text-text-dim dark:text-text-dim-dark",children:u})]})}function mx({roster:n,rosterLoading:e,onParticipantAction:t,onParticipantProfile:i,canManageParticipant:s,visibleListenerCount:r,onExpandListeners:o}){const a=p.useRef(null),d=p.useRef(null),[l,u]=p.useState(""),{speakers:h,listeners:m}=Ac(n),f=m.slice(0,r),C=Ra({visible:r,total:m.length});if(p.useLayoutEffect(()=>{const g=d.current;if(!g||(d.current=null,C>0))return;
80const k=a.current?.querySelector(`[data-participant-ulid="${CSS.escape(g)}"]`);if(!k)return;const T=k.querySelector("a[href], button")??k;T===k&&(k.tabIndex=-1),T.focus()},[r,C]),e&&n.length===0)return c.jsx("div",{className:"flex flex-none justify-center py-10",children:c.jsx(je,{size:"md",label:"Loading participants"})});if(n.length===0)return c.jsx("p",{className:"flex-none py-10 text-center text-sm text-text-dim dark:text-text-dim-dark",children:"No one is here yet"});const x=[{label:"Speakers",participants:h}],S=g=>c.jsx(hx,{participant:g,onProfile:i,onAction:t&&(s?.(g)??!0)?t:void 0},g.ulid),v=()=>{const g=m.length,k=Dc({visible:r,total:g});d.current=m[r]?.ulid??null,u(fm({added:k-r,remaining:Ra({visible:k,total:g})})),o(g)};return c.jsxs("div",{className:`min-h-0 flex-1 space-y-4 overflow-y-auto px-3 py-3 ${ux}`,children:[x.map(g=>g.participants.length>0&&c.jsxs("section",{"aria-label":g.label,children:[c.jsx("h3",{className:"mb-2 text-xs font-bold uppercase tracking-wide text-text-dim dark:text-text-dim-dark",children:g.label}),c.jsx("div",{className:"grid grid-cols-3 gap-x-2 gap-y-3",children:g.participants.map(S)})]},g.label)),m.length>0&&c.jsxs("section",{"aria-label":"Listeners",children:[c.jsxs("h3",{className:"mb-2 text-xs font-bold uppercase tracking-wide text-text-dim dark:text-text-dim-dark",children:["Listeners · ",m.length]}),c.jsx("div",{role:"status","aria-live":"polite",className:"sr-only",children:l}),c.jsxs("div",{ref:a,className:"grid grid-cols-3 gap-x-2 gap-y-3",children:[f.map(S),C>0&&c.jsxs("button",{type:"button",onClick:v,"aria-label":pm(C),className:"flex min-w-0 flex-col items-center gap-1 py-1 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-custom-blue",children:[c.jsxs("span",{className:"flex h-[68px] w-[68px] items-center justify-center rounded-full bg-surface text-sm font-bold text-text-secondary transition-colors hover:bg-nav-active/50 dark:bg-surface-dark dark:text-text-secondary-dark dark:hover:bg-nav-active-dark/50",children:["+",C]}),c.jsx("span",{className:"text-xs text-text-dim dark:text-text-dim-dark",children:"More"})]})]})]})]})}function px({description:n,liveStartedAt:e=null,isLive:t,joined:i,joinPending:s,roster:r,rosterLoading:o,onJoin:a,canGoLive:d=!1,onGoLive:l,controlBar:u,requestsQueue:h,onParticipantAction:m,onParticipantProfile:f,canManageParticipant:C,onRefresh:x,refreshPending:S=!1,roomId:v=""}){const[g,k]=p.useState(!1),[T,b]=p.useState(wa),[w,P]=p.useState(v);w!==v&&(P(v),b(wa),k(!1));const E=p.useCallback(N=>{b(L=>Dc({visible:L,total:N}))},[]),_=r.length>0;return c.jsxs("section",{className:"mx-4 mt-4 flex min-h-0 flex-col overflow-y-auto rounded-xl border border-nav-active dark:border-nav-active-dark bg-bg-elevated dark:bg-bg-elevated-dark shadow-[0_4px_12px_rgba(0,0,0,0.06)]",children:[n&&c.jsx("p",{className:"px-5 pt-5 pb-2 text-sm leading-[1.4] text-text dark:text-text-dark",children:n}),t?c.jsxs(c.Fragment,{children:[c.jsx(yd,{startedAt:e,className:"px-5 pt-4"}),i&&u,(_||x)&&c.jsxs("div",{className:`flex flex-none items-center gap-2 px-3 pt-2 ${_?"justify-between":"justify-end"}`,children:[_&&c.jsxs("button",{type:"button",onClick:()=>k(N=>!N),"aria-expanded":!g,className:"flex h-8 items-center gap-1.5 rounded-full px-2.5 text-xs font-semibold text-text-secondary transition-colors hover:bg-bg dark:text-text-secondary-dark dark:hover:bg-bg-dark",children:[c.jsx(Zm,{size:15,"aria-hidden":"true",className:`transition-transform ${g?"-rotate-90":""}`}),"Participants · ",r.length]}),x&&c.jsxs("button",{type:"button",onClick:x,disabled:S,"aria-label":"Refresh participants",className:"flex h-8 items-center gap-1.5 rounded-full px-2.5 text-xs font-semibold text-text-secondary transition-colors hover:bg-bg dark:text-text-secondary-dark dark:hover:bg-bg-dark disabled:opacity-50",children:[c.jsx(Xm,{size:15,"aria-hidden":"true",className:S?"animate-spin":void 0}),"Refresh"]})]}),(!g||!_)&&c.jsx(mx,{roster:r,rosterLoading:o,onParticipantAction:m,onParticipantProfile:f,canManageParticipant:C,visibleListenerCount:T,onExpandListeners:E}),h,!i&&c.jsx("div",{className:"border-t border-nav-active dark:border-nav-active-dark p-3",children:c.jsx("button",{type:"button",onClick:a,disabled:s,className:"w-full rounded-xl bg-text dark:bg-text-dark py-2.5 text-base font-semibold text-bg dark:text-bg-dark transition-opacity hover:opacity-90 disabled:opacity-50",children:s?"Joining…":"Join"})})]}):c.jsxs("div",{className:"flex flex-col items-center px-8 py-10 text-center",children:[c.jsx(ln,{size:40,className:"text-text-dim dark:text-text-dim-dark"}),c.jsx("p",{className:"mt-3 text-base font-bold text-text dark:text-text-dark",children:"Not Live Yet"}),d?c.jsxs(c.Fragment,{children:[c.jsx("p",{className:"mt-1.5 text-sm leading-5 text-text-secondary dark:text-text-secondary-dark",children:"Start the conversation by going live. Invite others in and give people a place to listen, talk, and connect in real time."}),c.jsx("button",{type:"button",onClick:l,disabled:s,className:"mt-5 w-full rounded-xl bg-text dark:bg-text-dark py-2.5 text-base font-semibold text-bg dark:text-bg-dark transition-opacity hover:opacity-90 disabled:opacity-50",children:s?"Connecting…":"Go Live"})]}):c.jsx("p",{className:"mt-1.5 text-sm leading-5 text-text-secondary dark:text-text-secondary-dark",children:"A host hasn't started this room yet. Hang tight — you'll be able to join once it goes live."})]})]})}const fx=n=>p.createElement("svg",{width:24,height:24,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n},p.createElement("path",{transform:"translate(3.25 1.25)",d:"M0.75 9C1.16421 9 1.5 9.33579 1.5 9.75C1.5 13.7541 4.74594 
8017 8.75 17C9.4026 17 10.0352 16.9136 10.6367 16.752C10.9497 16.6679 11.2891 16.77 11.4795 17.0322C11.7496 17.4044 11.617 17.9393 11.1875 18.1035C10.6775 18.2983 10.2041 18.409 9.5 18.4688V20H11.25C11.6642 20 12 20.3358 12 20.75C12 21.1642 11.6642 21.5 11.25 21.5H6.25C5.83579 21.5 5.5 21.1642 5.5 20.75C5.5 20.3358 5.83579 20 6.25 20H8V18.4688C3.5186 18.0883 0 14.3298 0 9.75C0 9.33579 0.335786 9 0.75 9ZM8.75 0C11.9256 0 14.5 2.57436 14.5 5.75V9.75C14.5 12.9256 11.9256 15.5 8.75 15.5C5.57436 15.5 3 12.9256 3 9.75V5.75C3 2.57436 5.57436 0 8.75 0ZM8.75 1.5C6.40279 1.5 4.5 3.40279 4.5 5.75V9.75C4.5 12.0972 6.40279 14 8.75 14C10.8412 14 12.5783 12.4894 12.9326 10.5H10.75C10.3358 10.5 10 10.1642 10 9.75C10 9.33579 10.3358 9 10.75 9H13V6.5H10.75C10.3358 6.5 10 6.16421 10 5.75C10 5.33579 10.3358 5 10.75 5H12.9326C12.5783 3.01061 10.8412 1.5 8.75 1.5Z",fill:"currentColor"}),p.createElement("path",{transform:"translate(16.25 13.25)",d:"M3.75 0C4.16421 0 4.5 0.335786 4.5 0.75V3H6.75C7.16421 3 7.5 3.33579 7.5 3.75C7.5 4.16421 7.16421 4.5 6.75 4.5H4.5V6.75C4.5 7.16421 4.16421 7.5 3.75 7.5C3.33579 7.5 3 7.16421 3 6.75V4.5H0.75C0.335786 4.5 1.28851e-07 4.16421 0 3.75C0 3.33579 0.335786 3 0.75 3H3V0.75C3 0.335786 3.33579 0 3.75 0Z",fill:"currentColor"})),gx=n=>p.createElement("svg",{width:24,height:24,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n},p.createElement("path",{transform:"translate(1.25 2.25)",d:"M9.75 11C10.7236 11 11.6571 11.1797 12.5176 11.5088C12.9045 11.6568 13.0982 12.0907 12.9502 12.4775C12.8022 12.8643 12.3692 13.0579 11.9824 12.9102C11.2902 12.6454 10.5378 12.5 9.75 12.5H7.75C4.55205 12.5 1.91546 14.9019 1.54492 18H10.25C10.6642 18 11 18.3358 11 18.75C11 19.1642 10.6642 19.5 10.25 19.5H0.75C0.335786 19.5 0 19.1642 0 18.75C0 14.4698 3.46979 11 7.75 11H9.75ZM17.25 11C17.6642 11 18 11.3358 18 11.75V14.5H20.75C21.1642 14.5 21.5 14.8358 21.5 15.25C21.5 15.6642 21.1642 16 20.75 16H18V18.75C18 19.1642 17.6642 19.5 17.25 19.5C16.8358 19.5 16.5 19.1642 16.5 18.75V16H13.75C13.3358 16 13 15.6642 13 15.25C13 14.8358 13.3358 14.5 13.75 14.5H16.5V11.75C16.5 11.3358 16.8358 11 17.25 11ZM8.75 0C11.3734 0 13.5 2.12665 13.5 4.75C13.5 7.37335 11.3734 9.5 8.75 9.5C6.12665 9.5 4 7.37335 4 4.75C4 2.12665 6.12665 0 8.75 0ZM8.75 1.5C6.95507 1.5 5.5 2.95507 5.5 4.75C5.5 6.54493 6.95507 8 8.75 8C10.5449 8 12 6.54493 12 4.75C12 2.95507 10.5449 1.5 8.75 1.5Z",fill:"currentColor"})),vx=n=>p.createElement("svg",{width:24,height:24,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n},p.createElement("path",{transform:"translate(1.25 2.25)",d:"M9.75 11C10.5182 11 11.2615 11.1122 11.9639 11.3213C12.3609 11.4394 12.5869 11.8569 12.4688 12.2539C12.3506 12.6508 11.9331 12.8769 11.5361 12.7588C10.9711 12.5906 10.3718 12.5 9.75 12.5H7.75C4.55205 12.5 1.91546 14.9019 1.54492 18H10.25C10.6642 18 11 18.3358 11 18.75C11 19.1642 10.6642 19.5 10.25 19.5H0.75C0.335786 19.5 0 19.1642 0 18.75C0 14.4698 3.46979 11 7.75 11H9.75ZM20.2197 12.2197C20.5126 11.9268 20.9874 11.9268 21.2803 12.2197C21.5732 12.5126 21.5732 12.9874 21.2803 13.2803L18.8105 15.75L21.2803 18.2197C21.5732 18.5126 21.5732 18.9874 21.2803 19.2803C20.9874 19.5732 20.5126 19.5732 20.2197 19.2803L17.75 16.8105L15.2803 19.2803C14.9874 19.5732 14.5126 19.5732 14.2197 19.2803C13.9268 18.9874 13.9268 18.5126 14.2197 18.2197L16.6895 15.75L14.2197 13.2803C13.9268 12.9874 13.9268 12.5126 14.2197 12.2197C14.5126 11.9268 14.9874 11.9268 15.2803 12.2197L17.75 14.6895L20.2197 12.2197ZM8.75 0C11.3734 0 13.5 2.12665 13.5 4.75C13.5 7.37335 11.3734 9.5 8.75 9.5C6.12665 9.5 4 7.37335 4 4.75C4 2.12665 6.12665 0 8.75 0ZM8.75 1.5C6.95507 1.5 5.5 2.95507 5.5 4.75C5.5 6.54493 6.95507 8 8.75 8C10.5449 8 12 6.54493 12 4.75C12 2.95507 10.5449 1.5 8.75 1.5Z",fill:"currentColor"}));function bx(n){return n==="host"?"Host":Yi(n)?"Speaker":"Listener"}function kx({roomId:n,roster:e,currentUserId:t,ownerId:i}){const s=Ec(),[r,o]=p.useState(null),a=s.isPending?s.variables?.userUlid:void 0,d=p.useMemo(()=>e.filter(h=>h.ulid!==t&&(!i||h.ulid!==i)),[e,t,i]),l=p.useCallback(h=>{!h&&!s.isPending&&o(null)},[s.isPending]),u=p.useCallback(()=>
80{if(!r)return;const h=r.name||r.username;s.mutate({roomId:n,userUlid:r.ulid},{onSuccess:()=>{z.success(`Removed ${h}`),o(null)},onError:m=>z.error(Je(m,"Couldn't remove. Try again."))})},[r,n,s]);return d.length===0?c.jsx("p",{className:"py-6 text-center text-sm text-text-secondary dark:text-text-secondary-dark",children:"There's no one else in this room to remove."}):c.jsxs(c.Fragment,{children:[c.jsx("ul",{children:d.map(h=>{const m=h.name||h.username;return c.jsxs("li",{className:"flex items-center gap-3 py-2",children:[h.avatar?c.jsx("img",{src:h.avatar,alt:"",className:"h-9 w-9 flex-none rounded-full object-cover"}):c.jsx("span",{className:"flex h-9 w-9 flex-none items-center justify-center rounded-full bg-bg-elevated dark:bg-bg-elevated-dark text-sm font-semibold text-text-secondary dark:text-text-secondary-dark",children:m.charAt(0).toUpperCase()}),c.jsxs("span",{className:"min-w-0 flex-1",children:[c.jsx(Ye,{className:"block truncate text-sm font-semibold text-text dark:text-text-dark",children:m}),c.jsx("span",{className:"block text-xs text-text-secondary dark:text-text-secondary-dark",children:bx(h.role)})]}),c.jsx("button",{type:"button",onClick:()=>o(h),disabled:a===h.ulid,className:"flex-none rounded-lg px-3 py-1.5 text-sm font-semibold text-error transition-colors hover:bg-error/10 disabled:opacity-50",children:a===h.ulid?"Removing…":"Remove"})]},h.ulid)})}),c.jsx(Ae,{open:!!r,onOpenChange:l,title:"Remove from room?",description:`${r?.name||r?.username||"This person"} will be removed from this room.`,confirmLabel:"Remove",onConfirm:u,isPending:s.isPending})]})}const xx="flex flex-1 basis-[calc(50%-0.25rem)] min-w-[7rem] flex-col items-center gap-2 rounded-lg border border-border-light dark:border-border-dark p-3 text-xs leading-[18px] text-text-secondary dark:text-text-secondary-dark transition-colors hover:bg-bg-elevated dark:hover:bg-bg-elevated-dark",pc="flex h-12 w-full items-center justify-center rounded-xl text-base font-semibold transition-colors";function yx({open:n,onOpenChange:e,target:t,permissions:i,onAddSpeaker:s,onInviteToJoin:r,onLeave:o,onEndRoom:a,endPending:d}){const[l,u]=p.useState("menu"),[h,m]=p.useState(!1),[f,C]=p.useState(!1),{canManage:x,canInvite:S,canEndRoom:v}=i,g=p.useCallback(_=>{_||u("menu"),e(_)},[e]),k=p.useCallback(_=>{g(!1),_()},[g]),T=Oh(t.localRole,t.joinedAsHost),b=p.useCallback(()=>{if(T){C(!0);return}g(!1),o()},[T,g,o]),w=p.useCallback(()=>{C(!1),g(!1),o()},[g,o]),P=p.useCallback(()=>{m(!1),g(!1),a()},[g,a]),E=l==="remove"?"Remove User":l==="invite"?"Invite to lounge":"Settings";return c.jsxs(c.Fragment,{children:[c.jsx(qt,{open:n,onOpenChange:g,children:c.jsxs(Ht,{children:[c.jsx(zt,{className:"fixed inset-0 z-50 bg-scrim data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0"}),c.jsxs(Kt,{"aria-describedby":void 0,className:`
81              fixed z-50 bg-bg dark:bg-bg-dark text-text dark:text-text-dark font-inter
82              inset-x-0 bottom-0 rounded-t-[38px]
83              data-[state=open]:animate-in data-[state=closed]:animate-out
84              data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom
85              sm:inset-x-auto sm:bottom-auto sm:top-1/2 sm:left-1/2
86              sm:-translate-x-1/2 sm:-translate-y-1/2
87              sm:w-[90vw] sm:max-w-sm sm:rounded-2xl
88              sm:data-[state=closed]:slide-out-to-bottom-0 sm:data-[state=open]:slide-in-from-bottom-0
89              sm:data-[state=closed]:fade-out-0 sm:data-[state=open]:fade-in-0
90              border-t sm:border border-border-light dark:border-border-dark shadow-xl
91            `,children:[c.jsxs("header",{className:"flex items-center gap-2 px-3 py-3",children:[l==="menu"?c.jsx(Nr,{"aria-label":"Close settings",className:"flex h-10 w-10 flex-none items-center justify-center rounded-full bg-bg-elevated dark:bg-bg-elevated-dark text-text dark:text-text-dark transition-colors hover:bg-border-light dark:hover:bg-border-dark",children:c.jsx(Hc,{})}):c.jsx("button",{type:"button",onClick:()=>u("menu"),"aria-label":"Back to settings",className:"flex h-10 w-10 flex-none items-center justify-center rounded-full bg-bg-elevated dark:bg-bg-elevated-dark text-text dark:text-text-dark transition-colors hover:bg-border-light dark:hover:bg-border-dark",children:c.jsx(_n,{width:18,height:18})}),c.jsx(Wt,{className:"min-w-0 flex-1 text-center text-[17px] font-semibold",children:E}),c.jsx("span",{className:"h-10 w-10 flex-none","aria-hidden":"true"})]}),c.jsxs("div",{className:"max-h-[60vh] overflow-y-auto customScroll border-t border-border-light/60 dark:border-border-dark/60 px-4 pb-6 pt-3",children:[l==="remove"&&c.jsxs(c.Fragment,{children:[c.jsx("p",{className:"pb-2 text-sm text-text-secondary dark:text-text-secondary-dark",children:"Removing someone disconnects them from this room. They can rejoin while it's still live."}),c.jsx(kx,{roomId:t.roomId,roster:t.roster,currentUserId:t.currentUserId,ownerId:t.ownerId})]}),l==="invite"&&c.jsxs(c.Fragment,{children:[c.jsx("p",{className:"pb-2 text-sm text-text-secondary dark:text-text-secondary-dark",children:"Invite someone to this lounge. This does not add them as a host or speaker in the live room."}),c.jsx(yp,{spaceId:t.spaceId})]}),l==="menu"&&c.jsxs("div",{className:"flex flex-col gap-4",children:[(x||S)&&c.jsxs("div",{className:"flex flex-wrap gap-2",children:[x&&c.jsxs(c.Fragment,{children:[c.jsx(xi,{Icon:Qc,label:"Invite to join",onClick:()=>k(r)}),c.jsx(xi,{Icon:fx,label:"Add Speaker",onClick:()=>k(s)}),c.jsx(xi,{Icon:vx,label:"Remove User",onClick:()=>u("remove")})]}),S&&c.jsx(xi,{Icon:gx,label:"Invite to lounge",onClick:()=>u("invite")})]}),c.jsx("button",{type:"button",onClick:b,className:`${pc} bg-bg-elevated dark:bg-bg-elevated-dark text-text dark:text-text-dark hover:bg-border-light dark:hover:bg-border-dark`,children:"Leave"}),v&&c.jsx("button",{type:"button",onClick:()=>m(!0),disabled:d,className:`${pc} border border-border-light dark:border-border-dark text-error hover:bg-error/10 disabled:opacity-50`,children:d?"Ending…":"End"})]})]})]})]})}
91),T&&c.jsx(Ae,{open:f,onOpenChange:C,title:T.title,description:T.message,confirmLabel:"Leave room",onConfirm:w}),c.jsx(Ae,{open:h,onOpenChange:m,title:"End room for everyone?",description:"All participants will be disconnected. This cannot be undone.",confirmLabel:"End room",onConfirm:P,isPending:d})]})}function xi({Icon:n,label:e,onClick:t}){return c.jsxs("button",{type:"button",onClick:t,className:xx,children:[c.jsx(n,{width:24,height:24,"aria-hidden":"true"}),c.jsx("span",{className:"text-center",children:e})]})}function Cx(n){n&&window.open(Ft(n),"_blank","noopener,noreferrer")}function gu({username:n,onOpenChange:e}){const t=p.useCallback(()=>{n&&(Cx(n),e(!1))},[e,n]);return c.jsx(Ae,{open:!!n,onOpenChange:e,title:"Open profile?",description:"Opening this profile in the current tab would disconnect you from the audio room. Open it in a new tab instead?",confirmLabel:"Open profile",cancelLabel:"Stay in room",destructive:!1,onConfirm:t})}function Tx({roomId:n,enabled:e,currentUserId:t,authorsByUlid:i}){const s=Lh(n,{enabled:e});Tp(t,n,e);const r=Ah(),o=Dh(),[a,d]=p.useState(""),[l,u]=p.useState(null),[h,m]=p.useState(null),f=p.useCallback(b=>{b&&m(b)},[]),C=p.useCallback((b,w)=>{an(b,()=>f(w))},[f]),x=p.useCallback(b=>{b||m(null)},[]),S=p.useMemo(()=>(s.data?.pages.flatMap(b=>b.data)??[]).slice().reverse(),[s.data]),v=p.useRef(null),g=p.useRef(0);p.useEffect(()=>{const b=v.current;if(!b||S.length===0)return;const w=g.current===0,P=b.scrollHeight-b.scrollTop-b.clientHeight;w?b.scrollTo({top:b.scrollHeight,behavior:"auto"}):P<200&&requestAnimationFrame(()=>{b.scrollTo({top:b.scrollHeight,behavior:"smooth"})}),g.current=S.length},[S]);const k=p.useCallback(b=>{b.preventDefault();const w=a.trim();!e||!w||r.isPending||(d(""),r.mutate({roomId:n,content:w}))},[e,a,n,r]),T=p.useCallback(async b=>{l&&await o.mutateAsync({roomId:n,messageUlid:l.ulid,violationType:b})},[l,n,o]);return c.jsxs("div",{className:"relative flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden",children:[c.jsxs("div",{ref:v,className:"flex-1 space-y-2.5 overflow-y-auto px-4 py-4",children:[s.hasNextPage&&c.jsx("div",{className:"flex justify-center py-2",children:c.jsx("button",{type:"button",onClick:()=>s.fetchNextPage(),disabled:s.isFetchingNextPage,className:"text-xs text-brand hover:underline disabled:opacity-50",children:s.isFetchingNextPage?"Loading...":"Load older messages"})}),S.length===0&&!s.isLoading&&c.jsx("p",{className:"py-8 text-center text-sm text-text-secondary dark:text-text-secondary-dark",children:"No messages yet. Say hello."}),S.map(b=>{const w=i.get(b.userUlid),P=w?.name||b.username||"Member",E=w?.username||b.username,_=w?.isHost??!1,N=!!t&&b.userUlid!==t;return c.jsxs("div",{className:"group flex items-start gap-2.5",children:[E?c.jsx(Pe,{to:Ft(E),...rn(),onClick:L=>C(L,E),"aria-label":`View profile for ${P}`,className:"h-7 w-7 flex-none rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand",children:w?.avatar?c.jsx("img",{src:w.avatar,alt:"",className:"h-full w-full rounded-full object-cover",loading:"lazy"}):c.jsx("span",{className:"flex h-full w-full items-center justify-center rounded-full bg-surface dark:bg-surface-dark text-xs font-bold text-text-dim dark:text-text-dim-dark",children:P.charAt(0).toUpperCase()})}):w?.avatar?c.jsx("img",{src:w.avatar,alt:"",className:"h-7 w-7 flex-none rounded-full object-cover",loading:"lazy"}):c.jsx("div",{className:"flex h-7 w-7 flex-none items-center justify-center rounded-full bg-surface dark:bg-surface-dark text-xs font-bold text-text-dim dark:text-text-dim-dark",children:P.charAt(0).toUpperCase()}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsxs("div",{className:"flex items-center gap-1.5 text-xs",children:[E?c.jsx(Pe,{to:Ft(E),...rn(),onClick:L=>C(L,E),className:`truncate font-semibold hover:underline focus-visible:outline-none focus-visible:underline ${_?"text-live-indicator":"text-text dark:text-text-dark"}`,children:P}):c.jsx("span",{className:`truncate font-semibold ${_?"text-live-indicator":"text-text dark:text-text-dark"}`,children:P}),_&&c.jsx("span",{className:"flex-none text-live-indicator",children:"(host)"}),c.jsx("span",{className:"flex-none text-text-dim dark:text-text-dim-dark",children:Qi(b.createdAt)})]}),!!b.content&&c.jsx("p",{className:"text-[13px] leading-4 tracking-[-0.08px] text-text dark:text-text-dark break-words",children:b.content})]}),N&&c.jsx("button",{type:"button",onClick:()=>u(b),"aria-label":`Report ${P}'s message`,className:"flex-none p-1 text-text-dim dark:text-text-dim-dark opacity-0 transition-opacity hover:text-text dark:hover:text-text-dark focus:opacity-100 group-hover:opacity-100",children:c.jsx(di,{width:14,height:14})})]},b.ulid)})]}),c.jsx(od,{value:a,onChange:d,onSubmit:k,sendDisabled:!e||!a.trim()||r.isPending,placeholder:"Message the room",layout:"docked"}),l&&c.jsx(Xi,{open:!0,onClose:()=>u(null),targetId:l.ulid,submitOverride:T,subjectLabel:"message",onReportSubmitted:()=>u(null)}),c.jsx(gu,{username:h,onOpenChange:x})]})}const yi="flex h-10 w-10 flex-none items-center justify-center rounded-full bg-bg dark:bg-surface-dark text-text dark:text-text-dark shadow-sm border border-nav-active dark:border-nav-active-dark transition-colors hover:bg-border-light dark:hover:bg-border-dark",fc="flex h-10 w-10 flex-none items-center justify-center rounded-full bg-error/10 text-error shadow-sm border border-error/30 transition-colors hover:bg-error/15";function Sx({canPublish:n,isMuted:e,onToggleMute:t,deafened:i,onToggleDeafen:s,audioBlocked:r,onResumeAudio:o,showRaiseHand:a,handRaised:d,handPending:l,onToggleHand:u,onShare:h}){return c.jsxs("div",{className:"px-3 pt-3",children:[r&&c.jsx("button",{type:"button",onClick:o,className:"mb-2 w-full rounded-xl bg-warning/15 px-3 py-2 text-sm font-medium text-warning transition-colors hover:bg-warning/25",children:"Audio is paused by your browser — click to enable"}),c.jsxs("div",{className:"flex items-center gap-2",children:[n&&c.jsx("button",{type:"button",onClick:t,"aria-label":e?"Unmute microphone":"Mute microphone","aria-pressed":e,className:e?fc:yi,children:e?c.jsx(ns,{size:20}):c.jsx(ln,{size:20})}),c.jsx("button",{type:"button",onClick:s,"aria-label":i?"Undeafen room audio":"Deafen room audio","aria-pressed":i,className:i?fc:yi,children:i?c.jsx(np,{size:20}):c.jsx(ip,{size:20})}),a&&c.jsxs("button",{type:"button",onClick:u,disabled:l,"aria-label":d?"Cancel request to speak":"Request to speak","aria-pressed":d,className:`${d?"flex h-10 flex-none items-center gap-1.5 rounded-full bg-brand/10 px-3 text-sm font-semibold text-brand shadow-sm border border-brand/30":`${yi} w-auto gap-1.5 px-3 text-sm font-semibold`} disabled:opacity-50`,children:[c.jsx(Yc,{size:18}),d?"Requested":"Request to speak"]}),c.jsx("button",{type:"button",onClick:h,"aria-label":"Share room",className:yi,children:c.jsx(Qc,{size:18})})]})]})}function gc(n){const e=n?.response?.data,t=e?.message??e?.error;return typeof t=="string"&&t?t:null}function wx({roomId:n,enabled:e,showEmptyState:t=!1}){const i=Pc(n,{enabled:e}),s=Nc(),r=_c(),[o,a]=p.useState(null),d=p.useCallback((h,m)=>{a(h),s.mutate({roomId:n,userUlid:h,role:"speaker"},{onSuccess:()=>z(`@${m} can speak now`),onError:f=>{$e("voice-approve-hand",{roomId:n,userUlid:h},f),z.error(gc(f)??`Couldn't approve @${m}. Try again.`)},onSettled:()=>a(null)})},[n,s]),l=p.useCallback((h,m)=>{a(h),r.mutate({roomId:n,userUlid:h},{onError:f=>{$e("voice-dismiss-hand",{roomId:n,userUlid:h},f),z.error(gc(f)??`Couldn't dismiss @${m}'s request.`)},onSettled:()=>a(null)})},[n,r]);if(!e)return null;const u=i.data?.data??[];return u.length===0?i.isLoading?null:t?c.jsx("p",{className:"py-10 text-center text-sm text-text-secondary dark:text-text-secondary-dark",children:"No requests to speak."}):null:c.jsxs("section",{className:"border-t border-nav-active dark:border-nav-active-dark px-3 py-2",children:[c.jsxs("h3",{className:"flex items-center gap-1.5 pb-1 text-xs font-semibold uppercase tracking-wider text-text-secondary dark:text-text-secondary-dark",children:[c.jsx(Yc,{size:14,"aria-hidden":"true"}),"Speak Requests",c.jsx("span",{className:"flex h-[18px] min-w-[18px] items-center justify-center rounded-full bg-brand px-1 text-[10px] font-bold text-white",children:u.length>99?"99+":u.length})]}),c.jsx("ul",{className:"max-h-40 overflow-y-auto",children:u.map(h=>{const m=o===h.userUlid;return c.jsxs("li",{className:"flex items-center gap-2 py-1.5",children:[c.jsxs("span",{className:"min-w-0 flex-1 text-sm",children:[c.jsxs("span",{className:"block truncate font-semibold text-text dark:text-text-dark",children:["@",h.username]}),c.jsx("span",{className:"mt-0.5 block text-xs font-medium text-text-secondary dark:text-text-secondary-dark",children:gm}),c.jsx("span",{className:"block text-xs text-text-dim dark:text-text-dim-dark",children:Qi(h.createdAt)})]}),c.jsx("button",{type:"button",onClick:()=>d(h.userUlid,h.username),disabled:m,className:"h-8 flex-none rounded-full bg-text dark:bg-text-dark px-3 text-xs font-semibold text-bg dark:text-bg-dark transition-opacity hover:opacity-90 disabled:opacity-50",children:"Approve"}),c.jsx("button",{type:"button",onClick:()=>l(h.userUlid,h.username),disabled:m,className:"h-8 flex-none rounded-full border border-border dark:border-border-dark px-3 text-xs font-semibold text-text-secondary dark:text-text-secondary-dark transition-colors hover:bg-bg dark:hover:bg-bg-dark disabled:opacity-50",children:"Dismiss"})]},h.userUlid)})})]})}function Rx({value:n,onChange:e}){return c.jsx("span",{className:"flex flex-none gap-1.5",children:["speaker","host"].map(t=>{const i=n===t;return c.jsx("button",{type:"button","aria-pressed":i,onClick:()=>e(i?null:t),className:`h-8 rounded-full px-3 text-xs font-semibold capitalize transition-colors ${i?"bg-text dark:bg-text-dark text-bg dark:text-bg-dark":"border border-border dark:border-border-dark text-text-secondary dark:text-text-secondary-dark hover:bg-bg-elevated dark:hover:bg-bg-elevated-dark"}`,children:t},t)})})}function Ex({spaceId:n,open:e,onOpenChange:t,mode:i="go-live",initialLineup:s=[],onConfirm:r,pen
91ding:o}){const a=De(k=>k.user?.id??null),[d,l]=p.useState(""),u=Tc(d.trim(),400),h=Lc(d),[m,f]=p.useState(()=>new Map(s.map(k=>[k.id,k]))),C=Pn(n,u||void 0,{enabled:e}),x=p.useMemo(()=>(C.data?.pages.flatMap(k=>k.data)??[]).filter(k=>k.ulid!==a),[C.data,a]),[S]=p.useState(()=>s.filter(k=>k.id!==a).map(k=>({ulid:k.id,username:k.username,name:k.name??"",avatar:k.avatar??""}))),v=p.useMemo(()=>{const k=new Set(x.map(P=>P.ulid)),T=S.filter(P=>!k.has(P.ulid)),b=u.toLowerCase();return[...b?T.filter(P=>P.username.toLowerCase().includes(b)||P.name.toLowerCase().includes(b)):T,...x]},[S,x,u]),g=(k,T)=>{f(b=>{const w=new Map(b);return T===null?w.delete(k.ulid):w.set(k.ulid,{id:k.ulid,username:k.username,name:k.name,avatar:k.avatar??void 0,role:T}),w})};return c.jsx(qt,{open:e,onOpenChange:t,children:c.jsxs(Ht,{children:[c.jsx(zt,{className:"fixed inset-0 z-50 bg-scrim data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0"}),c.jsxs(Kt,{className:`
92            fixed z-50 bg-bg dark:bg-bg-dark text-text dark:text-text-dark
93            top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2
94            flex max-h-[85vh] w-[90vw] max-w-md flex-col rounded-2xl font-inter
95            border border-border-light dark:border-border-dark shadow-xl
96            data-[state=open]:animate-in data-[state=closed]:animate-out
97            data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0
98          `,"aria-describedby":void 0,children:[c.jsx(Wt,{className:"flex-none pt-5 text-center text-lg font-bold",children:i==="edit"?"Edit Room":"Go Live"}),c.jsx("p",{className:"flex-none px-6 pt-1 text-center text-xs text-text-secondary dark:text-text-secondary-dark",children:"Add anyone in the lounge as a host or speaker — they can talk right away; everyone else listens."}),c.jsxs("div",{className:"flex-none px-4 pt-3",children:[c.jsxs("label",{className:"flex h-11 items-center gap-2 rounded-full border border-border-light dark:border-border-dark px-3",children:[c.jsx(ts,{size:18,className:"flex-none text-text-secondary dark:text-text-secondary-dark","aria-hidden":"true"}),c.jsx("input",{type:"search",value:d,onChange:k=>l(k.target.value),placeholder:"Search members","aria-label":"Search members",className:"min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-text-placeholder dark:placeholder:text-text-placeholder-dark"})]}),h&&c.jsx("p",{className:"mt-1.5 text-xs text-text-secondary dark:text-text-secondary-dark","data-testid":"lounge-members-search-byte-cap-hint",children:"Search limited to 200 bytes"})]}),c.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto px-4 pb-2",children:[C.isLoading?c.jsx("div",{className:"flex justify-center py-10",children:c.jsx(je,{size:"lg",label:"Loading members"})}):C.isError?c.jsx("p",{className:"py-10 text-center text-sm text-text-secondary dark:text-text-secondary-dark",children:"Couldn't load members. Try refreshing."}):v.length===0?c.jsx("p",{className:"py-10 text-center text-sm text-text-secondary dark:text-text-secondary-dark",children:u?"No members match your search.":"No other members yet."}):c.jsx("ul",{className:"pt-2",children:v.map(k=>c.jsxs("li",{className:"flex items-center gap-3 py-2.5",children:[k.avatar?c.jsx("img",{src:k.avatar,alt:"",className:"h-10 w-10 flex-none rounded-full object-cover",loading:"lazy"}):c.jsx("span",{className:"flex h-10 w-10 flex-none items-center justify-center rounded-full bg-bg-elevated dark:bg-bg-elevated-dark font-semibold text-text-secondary dark:text-text-secondary-dark",children:(k.name||k.username)?.[0]?.toUpperCase()??"?"}),c.jsxs("span",{className:"min-w-0 flex-1",children:[c.jsx(Ye,{className:"block truncate text-[15px] font-bold text-text dark:text-text-dark",children:k.name||k.username}),c.jsxs(Ye,{as:"span",className:"block truncate text-[13px] text-text-secondary dark:text-text-secondary-dark",children:["@",k.username]})]}),c.jsx(Rx,{value:m.get(k.ulid)?.role??null,onChange:T=>g(k,T)})]},k.ulid))}),C.hasNextPage&&c.jsx("button",{type:"button",onClick:()=>C.fetchNextPage(),disabled:C.isFetchingNextPage,className:"mt-3 block w-full rounded-xl border border-border-light dark:border-border-dark py-2 text-center text-sm font-semibold text-text dark:text-text-dark transition-colors hover:bg-bg-elevated dark:hover:bg-bg-elevated-dark disabled:opacity-50",children:C.isFetchingNextPage?"Loading…":"Load more"})]}),c.jsxs("div",{className:"flex flex-none gap-2 border-t border-border-light dark:border-border-dark p-4",children:[c.jsx(Nr,{asChild:!0,children:c.jsx("button",{type:"button",className:"h-11 flex-1 rounded-xl border border-border dark:border-border-dark text-base font-semibold text-text dark:text-text-dark transition-colors hover:bg-bg-elevated dark:hover:bg-bg-elevated-dark",children:"Cancel"})}),c.jsx("button",{type:"button",onClick:()=>r([...m.values()]),disabled:o,className:"h-11 flex-1 rounded-xl bg-text dark:bg-text-dark text-base font-semibold text-bg dark:text-bg-dark transition-opacity hover:opacity-90 disabled:opacity-50",children:o?i==="edit"?"Saving…":"Connecting…":i==="edit"?"Save":m.size>0?`Go Live (${m.size} selected)`:"Go Live"})]})]})]})})}function Kn(n,e){const t=n?.response?.data,i=t?.message??t?.error;return typeof i=="string"&&i?i:e}function vc(n,e){return{id:"promote-to-host",label:"Promote to Host",icon:c.jsx(ap,{size:20,"aria-hidden":"true"}),onPress:()=>e(n)}}function Px({roomId:n,canManage:e,currentUserId:t,ownerId:i}
98){const[s,r]=p.useState(null),[o,a]=p.useState(null),[d,l]=p.useState(null),u=Uh(),h=Nc(),m=Ec(),f=p.useCallback(b=>{!e||!t||b.ulid===t||i&&b.ulid===i||r(b)},[e,t,i]),C=p.useMemo(()=>{if(!s)return[];const b=s,w=b.name||b.username||"Member",P=[];return Yi(b.role)?(b.isMuted||P.push({id:"mute",label:"Mute",icon:c.jsx(ns,{size:20,"aria-hidden":"true"}),onPress:()=>u.mutate({roomId:n,userUlid:b.ulid,muted:!0},{onSuccess:()=>z.success(`Muted ${w}`),onError:E=>z.error(Kn(E,"Couldn't mute. Try again."))})}),b.role==="speaker"&&P.push(vc(b,l)),P.push({id:"move-to-listener",label:"Move to listener",icon:c.jsx(sp,{size:20,"aria-hidden":"true"}),onPress:()=>h.mutate({roomId:n,userUlid:b.ulid,role:"listener"},{onSuccess:()=>z.success(`${w} moved to listeners`),onError:E=>z.error(Kn(E,"Couldn't update. Try again."))})})):(P.push({id:"invite-to-speak",label:"Invite to speak",icon:c.jsx(ln,{size:20,"aria-hidden":"true"}),onPress:()=>h.mutate({roomId:n,userUlid:b.ulid,role:"speaker"},{onSuccess:()=>z.success(`${w} can now speak`),onError:E=>z.error(Kn(E,"Couldn't update. Try again."))})}),P.push(vc(b,l))),P.push({id:"remove",label:"Remove from room",icon:c.jsx(rp,{size:20,"aria-hidden":"true"}),destructive:!0,onPress:()=>a(b)}),P},[u,n,h,s]),x=p.useCallback(()=>{if(!o)return;const b=o,w=b.name||b.username||"Member";m.mutate({roomId:n,userUlid:b.ulid},{onSuccess:()=>{a(null),r(null),z.success(`Removed ${w}`)},onError:P=>z.error(Kn(P,"Couldn't remove. Try again."))})},[m,o,n]),S=p.useCallback(()=>{if(!d)return;const b=d,w=b.name||b.username||"Member";h.mutate({roomId:n,userUlid:b.ulid,role:"host"},{onSuccess:()=>{l(null),r(null),z.success(`${w} promoted to host`)},onError:P=>z.error(Kn(P,"Couldn't update. Try again."))})},[h,d,n]),v=p.useCallback(b=>{b||r(null)},[]),g=p.useCallback(b=>{b||a(null)},[]),k=p.useCallback(b=>{b||l(null)},[]),T=c.jsxs(c.Fragment,{children:[c.jsx(Kc,{open:!!s,onOpenChange:v,title:s?s.name||s.username||"Member":void 0,options:C}),c.jsx(Ae,{open:!!o,onOpenChange:g,title:"Remove from room?",description:`${o?.name||o?.username||"This member"} will be removed from this room.`,confirmLabel:"Remove",onConfirm:x,isPending:m.isPending}),c.jsx(Ae,{open:!!d,onOpenChange:k,title:"Promote to host?",description:`${d?.name||d?.username||"This member"} will be given full host permissions for this room.`,confirmLabel:"Promote",destructive:!1,onConfirm:S,isPending:h.isPending})]});return{openParticipantActions:f,participantActions:T}}const Nx=5;function _x({loungeId:n,roomId:e,enabled:t}){const i=Nn(n,t),s=p.useMemo(()=>(i.data?.pages.flatMap(u=>u.data)??[]).filter(u=>u.contentType==="voice_message"&&u.roomId===e),[i.data,e]),r=p.useMemo(()=>s.filter(u=>u.flagStatus!=="kept").length,[s]),o=p.useRef(0),{fetchNextPage:a,hasNextPage:d,isFetchingNextPage:l}=i;return p.useEffect(()=>{o.current=0},[t,n,e]),p.useEffect(()=>{t&&r===0&&d&&!l&&o.current<Nx&&(o.current+=1,a())},[t,a,d,l,r]),t?i.isLoading&&s.length===0?c.jsx("div",{className:"flex justify-center py-10",children:c.jsx(je,{size:"md",label:"Loading reported messages"})}):i.isError&&s.length===0?c.jsxs("div",{className:"py-10 text-center",children:[c.jsx("p",{className:"text-sm text-text-secondary dark:text-text-secondary-dark",children:"Couldn't load reports."}),c.jsx("button",{type:"button",onClick:()=>i.refetch(),className:"mt-2 text-sm text-brand",children:"Retry"})]}):s.length===0?l?c.jsx("div",{className:"flex justify-center py-10",children:c.jsx(je,{size:"md",label:"Checking older reports"})}):c.jsxs("div",{className:"py-10 text-center",children:[c.jsx("p",{className:"text-sm text-text-secondary dark:text-text-secondary-dark",children:"No reported messages in this room."}),d&&c.jsx("button",{type:"button",onClick:()=>a(),className:"mt-2 text-sm text-brand",children:"Check older reports"})]}):c.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto px-4 py-4",children:[c.jsx("ul",{className:"space-y-5",children:s.map(u=>c.jsx("li",{children:c.jsx(Ar,{loungeId:n,item:u})},`${u.postFlagId}-${u.ulid}`))}),d&&c.jsx("button",{type:"button",onClick:()=>a(),disabled:l,className:"mt-4 w-full rounded-xl border border-border-light dark:border-border-dark py-2 text-sm font-semibold disabled:opacity-50",children:l?"Loading…":"Load more"})]}):null}function Ix({currentUserId:n,isAdmin:e,joinedAsHost:t}){return!!n&&(e||t)}function Mx({roomId:n,requested:e,canOpen:t,onOpen:i}){const s=p.useRef(null);p.useEffect(()=>{!e||!t||s.current===n||(s.current=n,i())},[t,i,e,n])}const bc="Leave audio room? Navigating away will disconnect you from the room.";function jx(n){if(n.defaultPrevented||n.button!==0||n.metaKey||n.ctrlKey||n.shiftKey||n.altKey)return!1;const e=n.target,t=e instanceof Element?e:e instanceof Node?e.parentElement:null;if(!t)return!1;const i=t.closest("a[href]");if(!i||i.hasAttribute("download")||i.hasAttribute(op))return!1;const s=i.getAttribute("target");if(s&&s.toLowerCase()!=="_self")return!1;
98const r=new URL(i.href,window.location.href),o=new URL(window.location.href);return!(r.origin===o.origin&&r.pathname===o.pathname&&r.search===o.search)}function Ox(n){const e=p.useRef(!1),t=p.useRef(!1);p.useEffect(()=>{if(!n)return;const i=typeof window.history.state?.idx=="number"?window.history.state.idx:null,s=a=>{if(jx(a)){if(window.confirm(bc)){t.current=!0,window.setTimeout(()=>{t.current=!1},0);return}a.preventDefault(),a.stopImmediatePropagation()}},r=a=>{if(e.current){e.current=!1,a.stopImmediatePropagation();return}if(window.confirm(bc))return;a.stopImmediatePropagation(),e.current=!0;const d=typeof a.state?.idx=="number"?a.state.idx:null,l=i!==null&&d!==null&&d>i?-1:1;window.history.go(l)},o=a=>{t.current||(a.preventDefault(),a.returnValue="")};return document.addEventListener("click",s,!0),window.addEventListener("popstate",r,!0),window.addEventListener("beforeunload",o),()=>{document.removeEventListener("click",s,!0),window.removeEventListener("popstate",r,!0),window.removeEventListener("beforeunload",o),e.current=!1,t.current=!1}},[n])}const Ws="flex h-9 w-9 flex-none items-center justify-center rounded-full bg-bg-elevated dark:bg-bg-elevated-dark text-text dark:text-text-dark hover:bg-border-light dark:hover:bg-border-dark transition-colors";function Wn(n){const e=n?.response?.data,t=e?.message??e?.error;return typeof t=="string"&&t?t:null}function Lx(){is("LoungeVoiceRoom");const{spaceId:n="",channelId:e=""}=ci(),[t]=Uc(),i=`lounge-${n}-channel-${e}`,s=De(H=>H.user),r=s?.id??null,o=oi(n),a=o.data?.data??null,d=$i(n),l=(d.data?.data??[]).find(H=>H.ulid===e)??null,u=a?.myRole??null,h=!!a?.isOwner||u==="admin",m=h||u==="moderator",f=!!a?.isJoined||!!a?.isOwner,[C,x]=p.useState(!1),[S,v]=p.useState(!1),[g,k]=p.useState(!1),[T,b]=p.useState(null),w=p.useCallback(()=>x(!0),[]),P=p.useCallback(()=>v(!0),[]),E=p.useCallback(()=>k(!0),[]),_=p.useCallback(H=>{H||v(!1)},[]),N=p.useCallback(H=>{H.username&&b(H.username)},[]),L=p.useCallback(H=>{H&&b(H)},[]),O=p.useCallback(H=>{H||b(null)},[]),q=Er(H=>H.open),J=p.useCallback(()=>{l&&q({type:"space",spaceId:n,displayName:a?.displayName??a?.name??void 0,channelId:l.ulid,channelName:l.name,channelType:"voice"})},[l,q,a?.displayName,a?.name,n]),D=lx(),K=Cr(),{join:se,leave:re}=D,[F,ie]=p.useState(!1);Ox(F);const[$,ne]=p.useState("Live Chat"),[he,ke]=p.useState(!1),B=p.useRef(!1),[Q,fe]=p.useState(null),[Ue,ae]=p.useState([]),Z=p.useCallback(()=>{ae(Ts({channelLineup:l,excludeUlids:[r]})),fe("go-live")},[l,r]);Mx({roomId:i,requested:t.get("goLive")==="1",canOpen:!!a?.isJoined||!!a?.isOwner,onOpen:Z});const Pt=p.useRef(!1),kt=Fh(i,{refetchInterval:Pt.current?!1:Sa}),tt=kt.data?.data,Qt=F||vm(tt,kt.error),gs=tt?.startedAt??tt?.createdAt??null,In=Vh(),Yt=Bh(),Mn=qh(),jn=p.useRef(!1),nt=p.useCallback(H=>{ie(!1),ke(!1),fe(null),re(),H&&!jn.current&&(jn.current=!0,z(H))},[re]),li=p.useCallback(()=>{nt("This room has ended")},[nt]),{realtimeHealthy:W}=Cp(r,a?.ulid??null,i,!!a?.isJoined,F?li:void 0);p.useEffect(()=>{Pt.current=W},[W]);const ve=p.useRef(!1);p.useEffect(()=>{ve.current&&!D.connected&&F&&nt(),ve.current=D.connected},[D.connected,F,nt]);const Oe=Hh(i,{enabled:Qt,refetchInterval:W?!1:Sa}),it=p.useMemo(()=>Oe.data?.data??[],[Oe.data]),ze=p.useMemo(()=>{const H=new Map(D.participants.map(le=>[le.identity,le])),de=it.map(le=>{const Ne=H.get(le.ulid);return H.delete(le.ulid),Ne?{...le,isSpeaking:Ne.isSpeaking,isMuted:Ne.isMuted}:le});for(const le of H.values())le.isLocal||de.push({ulid:le.identity,username:le.identity,name:le.name||le.identity,avatar:"",isMuted:le.isMuted,isSpeaking:le.isSpeaking,role:"listener",joinedAt:"",badges:[]});return F&&s&&!de.some(le=>le.ulid===s.id)&&de.push({ulid:s.id,username:s.username,name:s.displayName||s.username,avatar:s.avatarUrl??"",isMuted:D.isMuted,isSpeaking:!1,role:he?"host":"listener",joinedAt:"",badges:[]}),bm(de)},[it,D.participants,D.isMuted,F,s,he]),ui=p.useRef(new Set),Nt=p.useMemo(()=>ze.filter(H=>H.ulid!==r&&!H.avatar).map(H=>H.ulid).sort().join(","),[r,ze]),{refetch:Ce}=Oe;p.useEffect(()=>{if(!Nt)return;const H=Nt.split(",").filter(de=>!ui.current.has(de));
98H.length!==0&&(H.forEach(de=>ui.current.add(de)),Ce())},[Nt,Ce]);const _t=p.useMemo(()=>ze.find(H=>H.ulid===r)?.role,[ze,r]),On=_t?Yi(_t):he,hi=On||F&&D.canPublishNow,Ln=_t==="host"||he&&!_t,vu=Ix({currentUserId:r,isAdmin:h,joinedAsHost:he}),vs=m||Ln,bs=["Live Chat",...Ln?["Requests"]:[],...m?["Moderation"]:[]],ks=bs.includes($)?$:"Live Chat",{openParticipantActions:bu,participantActions:ku}=Px({roomId:i,canManage:vs,currentUserId:r,ownerId:a?.ownerId??null}),xu=p.useMemo(()=>{const H=new Map;for(const de of ze)H.set(de.ulid,{username:de.username,name:de.name||de.username,avatar:de.avatar,isHost:de.role==="host"});return H},[ze]),mi=p.useCallback(async(H={})=>{const{hostUlids:de,speakerUlids:le,asHost:Ne=!1}=H;if(!B.current){B.current=!0;try{if(Ne)try{await In.mutateAsync({spaceId:n,channelId:e,hostUlids:de,speakerUlids:le})}catch(Dn){$e("voice-create-room",{spaceId:n,channelId:e},Dn),z.error(Wn(Dn)??"Couldn't start the room. Please try again."),fe(null);return}try{await se(i,{canPublish:Ne||On})}catch(Dn){!Ne&&km(Dn)?(K.resetQueries({queryKey:xt.voiceRoom(i)}),z("This room isn’t live yet. You’ll be able to join once a host goes live.")):z.error(Wn(Dn)??"Couldn't connect to the audio room. Please try again later."),fe(null);return}ie(!0),ke(Ne),fe(null),jn.current=!1}finally{B.current=!1}}},[n,e,i,On,In,se,K]),yu=p.useCallback(()=>{mi()},[mi]),Cu=p.useCallback(H=>{const de=!xm(H,Ue);mi({hostUlids:de?H.filter(le=>le.role==="host").map(le=>le.id):void 0,speakerUlids:de?H.filter(le=>le.role==="speaker").map(le=>le.id):void 0,asHost:!0})},[mi,Ue]),Tu=p.useCallback(()=>{ae(Ts({channelLineup:l,excludeUlids:[r]})),fe("go-live")},[l,r]),Su=p.useCallback(()=>{ae(Ts({roomLineup:tt?.lineup,channelLineup:l,participants:ze,excludeUlids:[r]})),fe("edit")},[l,r,ze,tt?.lineup]),wu=p.useCallback(H=>{const de=H.filter(Ne=>Ne.role==="host").map(Ne=>Ne.id),le=H.filter(Ne=>Ne.role==="speaker").map(Ne=>Ne.id);r&&Ln&&!de.includes(r)&&de.push(r),Yt.mutate({roomId:i,hostUlids:de,speakerUlids:le},{onSuccess:()=>{z.success("Room updated"),fe(null)},onError:Ne=>z.error(Wn(Ne)??"Couldn't update the room. Try again.")})},[r,Ln,i,Yt]),Ru=p.useCallback(()=>{nt()},[nt]),Eu=p.useCallback(()=>{Mn.mutate(i,{onSuccess:()=>nt("Room ended"),onError:H=>{$e("voice-end-room",{roomId:i},H),z.error(Wn(H)??"Couldn't end the room. Try again.")}})},[i,Mn,nt]),[Pu,ga]=p.useState(!1),{refetch:va}=kt,{refetch:ba}=d,Nu=p.useCallback(async()=>{ga(!0);try{await Promise.all([Ce(),va(),ba()])}finally{ga(!1)}},[ba,Ce,va]),[Zt,An]=p.useState(!1),xs=zh(),ys=_c(),ka=Pc(i,{enabled:!1});p.useEffect(()=>{if(!Zt||!r)return;const H=ka.data?.data;H&&!H.some(de=>de.userUlid===r)&&An(!1)},[ka.data,Zt,r]),p.useEffect(()=>{hi&&Zt&&(An(!1),z("You can speak now"))},[hi,Zt]),p.useEffect(()=>{F||An(!1)},[F]);const Cs=xs.isPending||ys.isPending,_u=p.useCallback(()=>{!r||Cs||(Zt?ys.mutate({roomId:i,userUlid:r},{onSuccess:()=>{An(!1),z("Request withdrawn")},onError:H=>{$e("voice-lower-hand",{roomId:i},H),z.error("Couldn't cancel your request. Try again.")}}):xs.mutate(i,{onSuccess:()=>{An(!0),z("Requested to speak")},onError:H=>{$e("voice-raise-hand",{roomId:i},H),z.error(Wn(H)??"Couldn't send your request. Try again.")}}))},[i,r,Cs,Zt,xs,ys]),pi=`/lounges/${n}?tab=rooms`,[Iu,xa]=p.useState(!1),ya=lt(),Mu=p.useCallback(()=>ya(pi,{replace:!0}),[ya,pi]),{roomOptions:ju,roomDialogs:Ou}=Fr({spaceId:n,channel:l,canManage:m,onDeleted:Mu}),Lu=Et("hidden_lounges")&&m&&(a?.visibility==="private"||a?.visibility==="hidden"),fi=In.isPending||D.connecting,Au=p.useCallback(H=>{!H&&!fi&&!Yt.isPending&&fe(null)},[fi,Yt.isPending]);if(o.isLoading||d.isLoading)return c.jsx("div",{className:"flex items-center justify-center min-h-[60vh]",children:c.jsx(je,{size:"lg",label:"Loading room"})});if(o.isError||!a)return c.jsx(rs,{});if(d.isError)return c.jsx("div",{className:"flex items-center justify-center min-h-[60vh]",children:c.jsx("p",{className:"text-sm text-text-secondary dark:text-text-secondary-dark",children:"Couldn't load this room. Try refreshing."})});if(o.isSuccess&&(!f||!l||l.type!=="voice"))return c.jsx(ei,{to:pi,replace:!0});const Du=f&&!!r&&h;return c.jsxs("div",{className:"flex mx-auto font-inter",children:[c.jsxs("div",{className:"flex h-[calc(100dvh-3.5rem)] md:h-dvh min-w-0 max-w-[600px] flex-1 flex-col md:border-r border-border-light/60 dark:border-border-dark/60",children:[c.jsxs("header",{className:"sticky top-0 z-10 flex items-center justify-between gap-2 border-b border-border-light/60 dark:border-border-dark/60 bg-bg/90 dark:bg-bg-dark/90 px-3 py-2 backdrop-blur",children:[c.jsx(Pe,{to:pi,"aria-label":"Back to rooms",className:Ws,children:c.jsx(_n,{width:18,height:18})}),c.jsxs("h1",{className:"flex min-w-0 items-center gap-2 text-[17px] font-bold text-text dark:text-text-dark",children:[Qt&&c.jsx(Ir,{}),c.jsx("span",{className:"truncate",children:l.name})]}),F?c.jsx("button",{type:"button",onClick:()=>xa(!0),"aria-label":"Room settings",className:Ws,children:c.jsx(di,{width:20,height:20})}):c.jsx(ss,{loungeUlid:a.ulid,displayName:a.displayName??a.name,channelId:l.ulid,channelName:l.name,channelType:"voice",isOwner:a.isOwner,visibility:a.visibility,membershipStatus:a.membershipStatus,isTrendingExcluded:a.isTrendingExcluded,triggerClassName:Ws,extraOptions:ju,triggerLabel:"Room options"})]}),c.jsx(px,{roomId:i,description:l.description??null,liveStartedAt:Qt?gs:null,isLive:Qt,joined:F,joinPending:fi,roster:ze,rosterLoading:Oe.isLoading,onJoin:yu,canGoLive:Du,onGoLive:Tu,controlBar:c.jsx(Sx,{canPublish:hi,isMuted:D.isMuted,onToggleMute:()=>void D.toggleMute(),deafened:D.deafened,onToggleDeafen:D.toggleDeafen,audioBlocked:D.audioBlocked,onResumeAudio:()=>void D.resumeAudio(),showRaiseHand:F&&!hi,handRaised:Zt,handPending:Cs,onToggleHand:_u,onShare:J}),onParticipantProfile:N,onParticipantAction:vs?bu:void 0,canManageParticipant:H=>H.ulid!==r&&H.ulid!==a.ownerId,onRefresh:()=>void Nu(),refreshPending:Pu}),F&&D.error&&c.jsx("p",{className:"mx-4 mt-2 rounded-lg bg-error/10 px-3 py-2 text-xs text-error",children:D.error}),F&&c.jsxs("div",{className:"mt-4 flex min-h-[min(240px,45dvh)] flex-1 flex-col border-t border-nav-active dark:border-nav-active-dark",children:[bs.length>1&&c.jsx("div",{role:"tablist","aria-label":"Voice room panels",className:"flex border-b border-nav-active dark:border-nav-active-dark",children:bs.map(H=>{const de=ks===H;return c.jsxs("button",{type:"button",role:"tab","aria-selected":de,onClick:()=>ne(H),className:`relative flex-1 px-2 py-3 text-sm font-semibold transition-colors ${de?"text-text dark:text-text-dark":"text-text-secondary dark:text-text-secondary-dark"}`,children:[H,de&&c.jsx("span",{className:"absolute inset-x-4 bottom-0 h-0.5 bg-brand"})]},H)})}),ks==="Live Chat"?c.jsx(Tx,{roomId:i,enabled:F&&f,currentUserId:r,authorsByUlid:xu}):ks==="Requests"?c.jsx(wx,{roomId:i,enabled:Ln,showEmptyState:!0}
98):c.jsx(_x,{loungeId:a.ulid,roomId:i,enabled:m})]})]}),c.jsx(Ur,{space:a,isAdmin:h,isRestricted:!1,isMember:f,onOpenAbout:w,onOpenMembers:P,onOpenReports:E,onSameTabProfile:F?L:void 0,voiceRoster:Qt?ze:void 0,onParticipantProfile:N}),c.jsx(gu,{username:T,onOpenChange:O}),Q&&c.jsx(Ex,{spaceId:n,open:!0,onOpenChange:Au,mode:Q,initialLineup:Ue,onConfirm:Q==="edit"?wu:Cu,pending:Q==="edit"?Yt.isPending:fi}),C&&c.jsx(Or,{space:a,open:!0,onOpenChange:x,onSameTabProfile:F?L:void 0}),S&&c.jsx(Lr,{space:a,open:!0,onOpenChange:_,onSameTabProfile:F?L:void 0}),c.jsx(Dr,{loungeId:a.ulid,enabled:m,open:g,onOpenChange:k}),F&&c.jsx(yx,{open:Iu,onOpenChange:xa,target:{spaceId:n,roomId:i,roster:ze,currentUserId:r,ownerId:a.ownerId??null,localRole:_t,joinedAsHost:he},permissions:{canManage:vs,canInvite:Lu,canEndRoom:vu},onAddSpeaker:Su,onInviteToJoin:J,onLeave:Ru,onEndRoom:Eu,endPending:Mn.isPending}),Ou,ku]})}function gy(){return c.jsx(cp,{hideRightSidebar:!0,children:c.jsx(jf,{})})}function vy(){return c.jsx(rf,{})}function by(){const n=De(s=>s.user?.badges),e=Et("voice_rooms",n),{isPending:t}=Kh(),{spaceId:i=""}=ci();return e?c.jsx(Lx,{}):t?c.jsx("div",{className:"flex items-center justify-center min-h-[60vh]",children:c.jsx(je,{size:"lg"})}):c.jsx(ei,{to:`/lounges/${i}`,replace:!0})}function ky(){return c.jsx(Of,{})}export{vy as LoungeChatRoomRoute,gy as LoungePageRoute,ky as LoungeReportsQueueRoute,by as LoungeVoiceRoomRoute};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.