Files
im_webapp/umd/index.prod.js
T
2023-05-10 16:36:33 -07:00

2 lines
665 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
(()=>{"use strict";var e,t,i,s,n={8962:(e,t,i)=>{i.d(t,{$_:()=>M,$h:()=>n,EI:()=>D,FX:()=>V,GQ:()=>k,H2:()=>T,Hm:()=>w,IX:()=>v,JG:()=>o,Mv:()=>r,NW:()=>q,RK:()=>p,Rc:()=>a,S8:()=>N,S9:()=>j,VL:()=>d,Zd:()=>R,Zf:()=>F,cG:()=>h,cl:()=>O,dm:()=>_,gD:()=>I,iC:()=>s,kd:()=>C,l8:()=>l,li:()=>B,ly:()=>P,mc:()=>c,nT:()=>x,o6:()=>f,pM:()=>u,rV:()=>A,rX:()=>L,sA:()=>y,uv:()=>b,vX:()=>U,wO:()=>S,xt:()=>m,yW:()=>E,yl:()=>g});const s="TinodeWeb/"+(i(3119).l||"0.21"),n="AQEAAAABAAD_rAp4DJh05a1HAwFT3A6K",a={hosted:"web.tinode.co",local:"localhost:6060"},r=a.hosted,o=!0,c=3e3,l=1500,d=2,h=96,u=16,p="JRWPS",m="N",g=640,f=13,v=384,b=4096,y=32,S=128,w=24,C=262144,k=1<<23,E=1024,T=64,P=96,M=36,R=48,_=4,N=60,D=360,I=20,A=80,O=30,U=84,x=48,L=2e3,F=6e5,B="mailto:support@tinode.co",q="https://tinode.co/privacy.html",j="https://tinode.co/terms.html",V=!1},8405:(e,t,i)=>{i.d(t,{DC:()=>p,EA:()=>c,Id:()=>l,JG:()=>g,Jr:()=>m,PD:()=>a,Y:()=>u,ay:()=>f,rS:()=>r,sT:()=>d,w8:()=>h});const s=["image/jpeg","image/gif","image/png","image/svg","image/svg+xml"],n=["jpg","gif","png","svg","svg"];function a(e){if(e&&"object"==typeof e){if(e.ref)return e.ref;if(e.data&&e.type){return"data:"+(e.type.startsWith("image/")?e.type:"image/"+e.type)+";base64,"+e.data}}return null}function r(e,t,i,s,n){if(t|=0,i|=0,s|=0,(e|=0)<=0||t<=0||i<=0||s<=0)return null;n&&(i=s=Math.min(i,s));const a=Math.min(Math.min(e,i)/e,Math.min(t,s)/t),r={dstWidth:e*a|0,dstHeight:t*a|0};return n?(r.dstWidth=r.dstHeight=Math.min(r.dstWidth,r.dstHeight),r.srcWidth=r.srcHeight=Math.min(e,t),r.xoffset=(e-r.srcWidth)/2|0,r.yoffset=(t-r.srcWidth)/2|0):(r.xoffset=r.yoffset=0,r.srcWidth=e,r.srcHeight=t),r}function o(e,t){const i=s.indexOf(t);if(i<0||!e)return e;const a=n[i],r=e.lastIndexOf(".");return r>=0&&(e=e.substring(0,r)),e+"."+a}function c(e,t,i,n,a){return new Promise(((c,l)=>{const d=new Image;d.crossOrigin="Anonymous",d.onerror=function(e){l(new Error("Image format unrecognized"))},d.onload=async function(){URL.revokeObjectURL(d.src);const h=r(d.width,d.height,t,i,a);if(!h)return void l(new Error("Invalid image"));let u=document.createElement("canvas");u.width=h.dstWidth,u.height=h.dstHeight;let p=u.getContext("2d");p.imageSmoothingEnabled=!0,p.drawImage(d,h.xoffset,h.yoffset,h.srcWidth,h.srcHeight,0,0,h.dstWidth,h.dstHeight);const m=s.includes(e.type)?e.type:"image/jpeg";let g=await new Promise((e=>u.toBlob(e,m)));if(g){for(;n>0&&g.length>n;)h.dstWidth=.70710678118*h.dstWidth|0,h.dstHeight=.70710678118*h.dstHeight|0,u.width=h.dstWidth,u.height=h.dstHeight,p=u.getContext("2d"),p.clearRect(0,0,u.width,u.height),p.drawImage(d,h.xoffset,h.yoffset,h.srcWidth,h.srcHeight,0,0,h.dstWidth,h.dstHeight),g=await new Promise((e=>u.toBlob(e,m)));u=null,c({mime:m,blob:g,width:h.dstWidth,height:h.dstHeight,name:o(e.name,m)})}else l(new Error("Unsupported image format"))},d.src=URL.createObjectURL(e)}))}function l(e,t,i,n,a,r,o){return new Promise(((c,l)=>{const d=new Image;d.crossOrigin="Anonymous",d.onerror=e=>{l(new Error("Image format unrecognized"))},d.onload=t=>{URL.revokeObjectURL(d.src);let h=document.createElement("canvas");h.width=a*o,h.height=r*o;let u=h.getContext("2d");u.imageSmoothingEnabled=!0,u.drawImage(d,i,n,a,r,0,0,h.width,h.height),e=s.includes(e)?e:"image/jpeg",h.toBlob((t=>{h=null,t?c({mime:e,blob:t,width:a,height:r}):l(new Error("Unsupported image format"))}),e)},d.src=t}))}function d(e){return new Promise(((t,i)=>{const s=new FileReader;s.onerror=e=>{i(s.error)},s.onload=i=>{t({mime:e.type,bits:s.result.split(",")[1],name:e.name})},s.readAsDataURL(e)}))}function h(e){return new Promise(((t,i)=>{const s=new FileReader;s.onerror=e=>{i(s.error)},s.onload=i=>{t({mime:e.type,bits:s.result.split(",")[1]})},s.readAsDataURL(e)}))}function u(e,t,i,s){const n=(e.clipboardData||e.originalEvent.clipboardData||{}).items;if(!n||!n.length)return!1;for(let e in n){const a=n[e];if("file"===a.kind){const e=a.getAsFile();if(!e){console.error("Failed to get file object from pasted file item",a.kind,a.type),s("Failed to get file object from pasted file item");continue}return e.type&&"image"==e.type.split("/")[0]?t(e):i(e),!0}}return!1}function p(e){if(e){e=e.replace(/-/g,"+").replace(/_/g,"/");try{e=btoa(atob(e))}catch(t){console.error("Failed to base64 re-encode string.",t),e=null}}return e}function m(e,t){if(!e)return null;try{const i=atob(e),s=i.length,n=new ArrayBuffer(s),a=new Uint8Array(n);for(let e=0;e<s;e++)a[e]=i.charCodeAt(e);return new Blob([n],{type:t})}catch(e){console.error("Failed to convert base64 to blob: ",e)}return null}function g(e){if(!Array.isArray(e))return null;try{let t="";return new Uint8Array(e).forEach((e=>t+=String.fromCharCode(e))),window.btoa(t)}catch(e){}return null}function f(e){const t=[];try{return[...window.atob(e)].forEach((e=>{t.push(e.charCodeAt(0))})),t}catch(e){}return null}},320:(e,t,i)=>{i.d(t,{Z:()=>s});class s{static setObject(e,t){localStorage.setItem(e,JSON.stringify(t))}static getObject(e){const t=localStorage.getItem(e);return t&&JSON.parse(t)}static updateObject(e,t){const i=this.getObject(e);this.setObject(e,Object.assign(i||{},t))}static removeItem(e){localStorage.removeItem(e)}}},5030:(e,t,i)=>{i.d(t,{Z:()=>s});class s{static parseUrlHash(e){const t=e.split("?",2),i={};let s=[];return t[0]&&(s=t[0].replace("#","").split("/")),t[1]&&t[1].split("&").forEach((e=>{const t=e.indexOf("=");t>0&&(i[e.slice(0,t)]=decodeURIComponent(e.slice(t+1)))})),{path:s,params:i}}static navigateTo(e){window.location.hash=e}static composeUrlHash(e,t){let i=e.join("/");const s=[];for(const e in t)t.hasOwnProperty(e)&&void 0!==t[e]&&s.push(e+"="+encodeURIComponent(t[e]));return s.length>0&&(i+="?"+s.join("&")),i}static addUrlParam(e,t,i){const n=s.parseUrlHash(e);return n.params[t]=i,s.composeUrlHash(n.path,n.params)}static removeUrlParam(e,t){const i=s.parseUrlHash(e);return delete i.params[t],s.composeUrlHash(i.path,i.params)}static setUrlSidePanel(e,t){const i=s.parseUrlHash(e);return i.path[0]=t,s.composeUrlHash(i.path,i.params)}static setUrlInfoPanel(e,t){const i=s.parseUrlHash(e);return t?i.params.info=t:delete i.params.info,s.composeUrlHash(i.path,i.params)}static setUrlTopic(e,t){const i=s.parseUrlHash(e);return i.path[1]=t,delete i.params.info,s.composeUrlHash(i.path,i.params)}}},3905:(e,t,i)=>{function s(e,t){t=t||window.navigator.userLanguage||window.navigator.language;const i=new Date;return e.getFullYear()==i.getFullYear()?e.getMonth()==i.getMonth()&&e.getDate()==i.getDate()?e.toLocaleTimeString(t,{hour12:!1,hour:"2-digit",minute:"2-digit"}):e.toLocaleDateString(t,{hour12:!1,month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):e.toLocaleDateString(t,{year:"numeric",month:"short",day:"numeric"})}function n(e,t){t=t||window.navigator.userLanguage||window.navigator.language;const i=new Date,s=Math.floor((e.getTime()-6e4*e.getTimezoneOffset())/864e5)-Math.floor((i.getTime()-6e4*i.getTimezoneOffset())/864e5);return Math.abs(s)<2?new Intl.RelativeTimeFormat(t,{numeric:"auto"}).format(s,"day"):new Intl.DateTimeFormat(t).format(e)}function a(e,t){if("number"!=typeof e)return"";let i=(0|Math.floor(e/60))%60,s=0|Math.floor(e/3600);(t||s>0)&&(i=i<10?`0${i}`:i);let n=(0|e)%60;return n=n<10?`0${n}`:n,0==s?`${i}:${n}`:`${s}:${i}:${n}`}function r(e){if(!e||0==e)return"0 Bytes";const t=["Bytes","KB","MB","GB","TB","PB"],i=Math.min(0|Math.floor(Math.log2(e)/10),t.length-1),s=e/Math.pow(1024,i),n=i>0?s<3?2:s<30?1:0:0;return s.toFixed(n)+" "+t[i]}function o(e,t){return"string"!=typeof e?e:e.length>t?e.slice(0,t/2-1)+"…"+e.slice(1-t/2):e}function c(e,t,i){return(t?"lt-":"dk-")+(i?"fg-":"bg-")+(s=e,Math.abs(function(e){let t=0;e=""+e;for(let i=0;i<e.length;i++)t=(t<<5)-t+e.charCodeAt(i),t&=t;return t}(s))%16);var s}function l(e){const t=e.toUpperCase().split("").map((e=>127397+e.charCodeAt()));return String.fromCodePoint(...t)}i.d(t,{Cj:()=>c,EZ:()=>n,FK:()=>r,TX:()=>o,Yu:()=>l,nH:()=>a,pz:()=>s})},3740:(e,t,i)=>{i.d(t,{Fv:()=>l,J_:()=>n,Nm:()=>c,Oi:()=>h,Th:()=>u,Xc:()=>o,es:()=>d,h6:()=>r,n$:()=>a});var s=i(2506);function n(e){const t=document.getElementById("shortcut-icon"),i=document.head||document.getElementsByTagName("head")[0],s=document.createElement("link");s.type="image/png",s.id="shortcut-icon",s.rel="shortcut icon",s.href="img/logo32x32"+(e>0?"a":"")+".png",t&&i.removeChild(t),i.appendChild(s),document.title=(e>0?"("+e+") ":"")+"Tinode"}function a(e,t,i,n){let a=null;if((e=e&&e.trim())&&(a={fn:e}),"string"==typeof(n=n&&n.trim())&&(a=a||{},a.note=n||s.Tinode.DEL_CHAR),t){a=a||{};let e=i;const n=/^data:(image\/[-a-z0-9+.]+)?(;base64)?,/i.exec(t);n?(e=n[1],a.photo={data:t.substring(t.indexOf(",")+1),ref:s.Tinode.DEL_CHAR}):a.photo={data:s.Tinode.DEL_CHAR,ref:t},a.photo.type=(e||"image/jpeg").substring("image/".length)}return a}function r(e,t){if(e===t)return!0;if(!Array.isArray(e)||!Array.isArray(t))return!1;if(e.length!=t.length)return!1;e.sort(),t.sort();for(let i=0,s=e.length;i<s;i++)if(e[i]!==t[i])return!1;return!0}function o(e){return e&&!/^\s*([a-z][a-z0-9+.-]*:|\/\/)/im.test(e)}function c(e,t){if("string"!=typeof e)return e;if(e=e.replace(/[^\x20-\x7E]/gim,"").trim(),!/^([a-z][a-z0-9+.-]*:|\/\/)/i.test(e))return e;if(/^blob:http/.test(e))return e;const i=Array.isArray(t)?t.join("|"):"http|https";return new RegExp("^(("+i+"):|//)","i").test(e)?e:null}function l(e,t){if(!e)return null;const i=c(e);if(i)return i;return new RegExp(`data:${t}/[a-z0-9.-]+;base64,`,"i").test(e.trim())?e:null}function d(e){switch(e){case s.Tinode.MESSAGE_STATUS_SENDING:return{name:"access_time"};case s.Tinode.MESSAGE_STATUS_FAILED:case s.Tinode.MESSAGE_STATUS_FATAL:return{name:"warning",color:"danger-color"};case s.Tinode.MESSAGE_STATUS_SENT:return{name:"done"};case s.Tinode.MESSAGE_STATUS_RECEIVED:return{name:"done_all"};case s.Tinode.MESSAGE_STATUS_READ:return{name:"done_all",color:"blue"}}return null}function h(e){let t=!1;return{promise:e instanceof Error?Promise.reject(e):new Promise(((i,s)=>{e.then((e=>t?s({isCanceled:!0}):i(e)),(e=>s(t?{isCanceled:!0}:e)))})),cancel(){t=!0}}}function u(e,t){return e&&e.substring(0,t)}},3119:(e,t,i)=>{i.d(t,{l:()=>s});const s="0.23.0-rc1"},4861:(e,t,i)=>{i.d(t,{Z:()=>h});var s=i(7363),n=i.n(s),a=i(916),r=i(3905),o=i(8405);const c="#666C",l=(0,a.defineMessages)({icon_title_play:{id:"icon_title_play",defaultMessage:[{type:0,value:"Play recording"}]}});class d extends n().PureComponent{constructor(e){super(e);let t=(0,o.ay)(this.props.preview);(!Array.isArray(t)||t.length<16)&&(t=null),this.state={canPlay:!1,playing:!1,currentTime:"0:00",duration:this.props.duration>0?(0,r.nH)(this.props.duration/1e3):"-:--",longMin:this.props.duration>=6e5,preview:t},this.initAudio=this.initAudio.bind(this),this.initCanvas=this.initCanvas.bind(this),this.resampleBars=this.resampleBars.bind(this),this.visualize=this.visualize.bind(this),this.handlePlay=this.handlePlay.bind(this),this.handleSeek=this.handleSeek.bind(this),this.handleError=this.handleError.bind(this),this.audioPlayer=null,this.viewBuffer=[],this.canvasRef=n().createRef()}componentDidMount(){this.props.src&&this.initAudio(),this.initCanvas()}componentWillUnmount(){this.audioPlayer&&(this.audioPlayer.onloadedmetadata=null,this.audioPlayer.ontimeupdate=null,this.audioPlayer.onended=null,this.audioPlayer.pause(),this.audioPlayer=null)}componentDidUpdate(e){if(this.props.src!=e.src&&this.initAudio(),this.props.preview!=e.preview){let e=(0,o.ay)(this.props.preview);(!Array.isArray(e)||e.length<16)&&(e=null),this.setState({preview:e},this.initCanvas)}}initAudio(){this.audioPlayer=new Audio(this.props.src),this.audioPlayer.onloadedmetadata=e=>this.setState({canPlay:!0}),this.audioPlayer.ontimeupdate=e=>this.setState({currentTime:(0,r.nH)(this.audioPlayer.currentTime,this.state.longMin)}),this.audioPlayer.onended=e=>{this.audioPlayer.currentTime=0,this.setState({playing:!1,currentTime:(0,r.nH)(0,this.state.longMin)})}}initCanvas(){this.canvasRef.current.width=2*this.canvasRef.current.offsetWidth,this.canvasRef.current.height=2*this.canvasRef.current.offsetHeight,this.canvasContext=this.canvasRef.current.getContext("2d"),this.canvasContext.lineCap="round",this.viewBuffer=this.resampleBars(this.state.preview),this.visualize()}visualize(){if(!this.canvasRef.current)return;const e=this.effectiveWidth,t=this.canvasRef.current.height;this.canvasContext.lineWidth=6;const i=s=>{if(this.canvasRef.current&&this.audioPlayer&&(this.canvasContext.clearRect(0,0,this.canvasRef.current.width,t),this.viewBuffer)){this.state.playing&&window.requestAnimationFrame(i);const s=this.props.duration?Math.max(0,Math.min(1e3*this.audioPlayer.currentTime/this.props.duration,1))*(e-12):-1;this.canvasContext.beginPath(),this.canvasContext.strokeStyle=c;for(let e=0;e<this.viewBuffer.length;e++){let i=1+10*e+3,n=Math.max(this.viewBuffer[e]*t*.9,1);const a=i<s?c:"#888A";this.canvasContext.strokeStyle!=a&&(this.canvasContext.stroke(),this.canvasContext.beginPath(),this.canvasContext.strokeStyle=a),this.canvasContext.moveTo(i,.5*(t-n)),this.canvasContext.lineTo(i,.5*(t+n))}this.canvasContext.stroke(),this.props.duration&&(this.canvasContext.beginPath(),this.canvasContext.arc(s+12,.5*t,12,0,2*Math.PI),this.canvasContext.fillStyle="#444E",this.canvasContext.fill())}};i()}resampleBars(e){const t=(this.canvasRef.current.width-4)/10|0;if(this.effectiveWidth=10*t+4,!Array.isArray(e)||0==e.length)return Array.apply(null,Array(t)).map((e=>.01));const i=e.length/t;let s=[],n=-1;for(let a=0;a<t;a++){let t=a*i|0,r=(a+1)*i|0;if(r==t)s[a]=e[t];else{let i=0;for(let s=t;s<r;s++)i+=e[s];s[a]=Math.max(0,i/(r-t))}n=Math.max(s[a],n)}return n>0?s.map((e=>e/n)):Array.apply(null,Array(t)).map((e=>.01))}handlePlay(e){e.preventDefault(),this.state.canPlay&&(this.state.playing?(this.audioPlayer.pause(),this.setState({playing:!1})):this.audioPlayer.readyState>=2&&(this.audioPlayer.play(),this.setState({playing:!0},this.visualize)))}handleError(e){console.error(e)}handleSeek(e){if(e.preventDefault(),e.target&&this.props.duration){const t=e.target.getBoundingClientRect(),i=(e.clientX-t.left)/this.effectiveWidth*2;this.audioPlayer.currentTime=this.props.duration*i/1e3,this.setState({currentTime:(0,r.nH)(this.audioPlayer.currentTime,this.state.longMin)}),this.state.playing||this.visualize()}}render(){const e="material-icons"+(this.props.short?"":" large")+(this.state.canPlay?"":" disabled"),t=n().createElement("a",{href:"#",onClick:this.handlePlay,title:this.props.intl.formatMessage(l.icon_title_play)},n().createElement("i",{className:e},this.state.playing?"pause_circle":this.state.canPlay?"play_circle":"not_interested"));return n().createElement("div",{className:"audio-player"},this.props.short?n().createElement(n().Fragment,null,n().createElement("canvas",{className:"playback",ref:this.canvasRef,onClick:this.handleSeek}),t):n().createElement(n().Fragment,null,t,n().createElement("div",null,n().createElement("canvas",{className:"playback",ref:this.canvasRef,onClick:this.handleSeek}),n().createElement("div",{className:"timer"},this.state.currentTime,"/",this.state.duration))))}}const h=(0,a.injectIntl)(d)},9875:(e,t,i)=>{i.d(t,{Z:()=>c});var s=i(7363),n=i.n(s),a=i(916);class r extends n().Component{constructor(e){super(e),this.state={panX:0,panY:0,originX:0,originY:0,zoom:1,minZoom:0,maxZoom:2.5},this.overlay=n().createRef(),this.cutout=n().createRef(),this.preview=n().createRef(),this.boundingBox=n().createRef(),this.imageWidth=0,this.imageHeight=0,this.mouseX=0,this.mouseY=0,this.prevDistance=0,this.cutoutRect={},this.bBoxRect={},this.originX=0,this.originY=0,this.initScaling=this.initScaling.bind(this),this.onZoom=this.onZoom.bind(this),this.handleZoom=this.handleZoom.bind(this),this.mouseDown=this.mouseDown.bind(this),this.mouseUp=this.mouseUp.bind(this),this.mouseMove=this.mouseMove.bind(this),this.mouseTouch=this.mouseTouch.bind(this),this.positionAll=this.positionAll.bind(this),this.translate=this.translate.bind(this)}componentDidMount(){this.overlay.current.addEventListener("mousedown",this.mouseDown,{passive:!0}),this.overlay.current.addEventListener("touchstart",this.mouseDown,{passive:!0}),this.bBoxRect=this.boundingBox.current.getBoundingClientRect(),this.originX=this.bBoxRect.width/2,this.originY=this.bBoxRect.height/2,this.cutoutRect=this.cutout.current.getBoundingClientRect()}componentWillUnmount(){this.overlay.current.removeEventListener("mousedown",this.mouseDown),this.overlay.current.removeEventListener("touchstart",this.mouseDown)}positionAll(e,t,i){this.setState({panX:e,panY:t,zoom:i,originX:this.originX-e,originY:this.originY-t});const s=(this.originX-e)*i-this.originX,n=(this.originY-t)*i-this.originY;this.props.onChange((s+this.cutoutRect.left-this.bBoxRect.left)/i,(n+this.cutoutRect.top-this.bBoxRect.top)/i,this.cutoutRect.width/i,this.cutoutRect.height/i,i)}static checkBound(e,t,i,s){let n=Math.min(0,i[0]-t[0]-s,t[1]-i[1]+s);return(0==n||Math.min(0,i[0]-t[0],t[1]-i[1])<n)&&(e+=s),e}initScaling(){const e=this.preview.current.getBoundingClientRect();this.imageWidth=e.width,this.imageHeight=e.height;const t=Math.max(this.cutoutRect.width/e.width,this.cutoutRect.height/e.height);this.setState({minZoom:t,maxZoom:Math.max(2.5,t+1)});const i=Math.max(this.bBoxRect.width/e.width,this.bBoxRect.height/e.height),s=this.cutoutRect.left-this.bBoxRect.left-(e.width-this.cutoutRect.width)/2,n=this.cutoutRect.top-this.bBoxRect.top-(e.height-this.cutoutRect.height)/2;this.positionAll(s,n,i)}onZoom(e){this.handleZoom(e.target.value)}handleZoom(e){let t=this.state.panX,i=this.state.panY;const s=this.originX-(this.originX-t)*e,n=s+this.imageWidth*e,a=this.cutoutRect.left-this.bBoxRect.left,r=a+this.cutoutRect.width;a<s?t-=s-a:r>n&&(t+=r-n);const o=this.originY-(this.originY-i)*e,c=o+this.imageHeight*e,l=this.cutoutRect.top-this.bBoxRect.top,d=l+this.cutoutRect.height;l<o?i-=o-l:d>c&&(i+=d-c),this.positionAll(t,i,e)}mouseDown(e){e.touches?(this.mouseX=e.touches[0].pageX,this.mouseY=e.touches[0].pageY):(this.mouseX=e.pageX,this.mouseY=e.pageY),window.addEventListener("mousemove",this.mouseMove,{passive:!1}),window.addEventListener("touchmove",this.mouseTouch,{passive:!1}),window.addEventListener("mouseup",this.mouseUp,{passive:!0}),window.addEventListener("touchend",this.mouseUp,{passive:!0}),document.body.style.userSelect="none"}translate(e,t){const i=e-this.mouseX,s=t-this.mouseY;this.mouseX=e,this.mouseY=t;const n=this.preview.current.getBoundingClientRect();let a=r.checkBound(this.state.panX,[n.left,n.right],[this.cutoutRect.left,this.cutoutRect.right],i),o=r.checkBound(this.state.panY,[n.top,n.bottom],[this.cutoutRect.top,this.cutoutRect.bottom],s);this.positionAll(a,o,this.state.zoom)}mouseMove(e){e.preventDefault(),this.translate(e.pageX,e.pageY)}mouseTouch(e){if(e.preventDefault(),1==e.touches.length)return void this.translate(e.touches[0].pageX,e.touches[0].pageY);const[t,i]=e.touches,s=Math.sqrt((t.pageX-i.pageX)*(t.pageX-i.pageX)+(t.pageY-i.pageY)*(t.pageY-i.pageY));this.prevDistance||(this.prevDistance=s/this.state.zoom);let n=s/this.prevDistance;this.handleZoom(Math.max(this.minZoom,Math.min(this.maxZoom,n)))}mouseUp(e){window.removeEventListener("mousemove",this.mouseMove),window.removeEventListener("touchmove",this.mouseTouch),window.removeEventListener("mouseup",this.mouseUp),window.removeEventListener("touchend",this.mouseUp),document.body.style.userSelect="",this.positionAll(this.state.panX,this.state.panY,this.state.zoom)}render(){const e=`translate3d(${this.state.panX}px, ${this.state.panY}px, 0) scale(${this.state.zoom})`,t=`${this.state.originX}px ${this.state.originY}px`,i={top:this.originY-this.state.originY*this.state.zoom+"px",left:this.originX-this.state.originX*this.state.zoom+"px",width:this.imageWidth*this.state.zoom+"px",height:this.imageHeight*this.state.zoom+"px"};return n().createElement("div",{className:"cropper"},n().createElement("div",{className:"bounding-box",ref:this.boundingBox},n().createElement("img",{src:this.props.source,className:"preview",alt:"",style:{transform:e,transformOrigin:t},ref:this.preview,onLoad:this.initScaling}),n().createElement("div",{className:"cutout circle",ref:this.cutout}),n().createElement("div",{className:"overlay",style:i,ref:this.overlay})),n().createElement("div",{className:"zoom-wrapper"},n().createElement("input",{type:"range",className:"zoomer",step:"0.001",min:this.state.minZoom,max:this.state.maxZoom,value:this.state.zoom,onChange:this.onZoom})))}}var o=i(8405);class c extends n().PureComponent{constructor(e){super(e),this.state={top:0,left:0,width:0,height:0,scale:1},this.handleSubmit=this.handleSubmit.bind(this),this.handleChange=this.handleChange.bind(this)}handleChange(e,t,i,s,n){this.setState({left:e,top:t,width:i,height:s,scale:n})}handleSubmit(){(0,o.Id)(this.props.mime,this.props.avatar,this.state.left,this.state.top,this.state.width,this.state.height,this.state.scale).then((e=>{this.props.onSubmit(e.mime,e.blob,e.width,e.height)})).catch((e=>{this.props.onError(e)}))}render(){return n().createElement("div",{className:"panel-form"},n().createElement("div",{className:"panel-form-row"},n().createElement(r,{source:this.props.avatar,onChange:this.handleChange})),n().createElement("div",{className:"dialog-buttons"},this.props.onCancel?n().createElement("button",{className:"secondary",onClick:this.props.onCancel},n().createElement(a.FormattedMessage,{id:"button_cancel",defaultMessage:[{type:0,value:"Cancel"}]})):null,n().createElement("button",{className:"primary",onClick:this.handleSubmit},n().createElement(a.FormattedMessage,{id:"button_ok",defaultMessage:[{type:0,value:"OK"}]}))))}}},7432:(e,t,i)=>{i.d(t,{Z:()=>l});var s=i(7363),n=i.n(s),a=i(1887),r=i(7646),o=i(3740),c=i(8962);class l extends n().Component{constructor(e){super(e),this.state={source:e.avatar},this.handleFileReceived=this.handleFileReceived.bind(this)}componentDidUpdate(e){this.props.avatar!=e.avatar&&this.setState({source:this.props.avatar})}handleFileReceived(e){const t=e.target.files[0];this.props.onImageUpdated(t.type,URL.createObjectURL(t),t.name),e.target.value=""}render(){const e="file-input-avatar-"+(""+Math.random()).substring(0,4),t="avatar-upload"+(this.props.readOnly?" read-only":"");return n().createElement("div",{className:t},this.props.readOnly||!this.state.source?null:n().createElement("a",{href:"#",className:"clear-avatar",onClick:e=>{e.preventDefault(),this.props.onImageUpdated()}},n().createElement("i",{className:"material-icons"},"clear")),this.state.source?n().createElement("img",{src:this.props.tinode.authorizeURL((0,o.Fv)(this.state.source,"image")),className:"preview"}):this.props.readOnly&&this.props.uid?n().createElement("div",{className:"avatar-box"},n().createElement(a.Z,{tinode:this.props.tinode,avatar:!0,topic:this.props.uid,title:this.props.title})):n().createElement("div",{className:"blank"},c.IX,"×",c.IX),this.props.readOnly?null:n().createElement("input",{type:"file",id:e,className:"inputfile hidden",accept:"image/*",onChange:this.handleFileReceived}),this.props.readOnly?null:n().createElement("label",{htmlFor:e,className:"round"},n().createElement("i",{className:"material-icons"},"file_upload")),n().createElement(r.Z,{show:this.props.uploading,large:!0,clear:!0,centered:!0}))}}},955:(e,t,i)=>{i.d(t,{Z:()=>l});var s=i(7363),n=i.n(s),a=i(916);const r={staff:"verified_user"},o=(0,a.defineMessages)({badge_verified:{id:"badge_verified",defaultMessage:[{type:0,value:"Verified/official"}]},badge_staff:{id:"badge_staff",defaultMessage:[{type:0,value:"Staff-managed"}]},badge_danger:{id:"badge_danger",defaultMessage:[{type:0,value:"Untrustworthy"}]}});class c extends n().PureComponent{render(){const{formatMessage:e}=this.props.intl;let t=null;return this.props.trustedBadges&&this.props.trustedBadges.length>0?(t=[],this.props.trustedBadges.forEach((i=>{const s=this.props.short?null:e(o["badge_"+i]),a="material-icons "+i+"-color";t.push(n().createElement("div",{className:"trusted-badge",key:i},n().createElement("i",{className:a},r[i]||i)," ",s))})),n().createElement(n().Fragment,null,t)):null}}const l=(0,a.injectIntl)(c)},2323:(e,t,i)=>{i.d(t,{Z:()=>a});var s=i(7363),n=i.n(s);class a extends n().PureComponent{constructor(e){super(e),this.handleChange=this.handleChange.bind(this)}handleChange(){this.props.onChange(this.props.name,!this.props.checked)}render(){let e,t=["material-icons"];Array.isArray(this.props.className)?t.push(...this.props.className):this.props.className&&t.push(this.props.className),this.props.onChange?this.props.checked?(t.push("blue","clickable"),e="check_box"):!1===this.props.checked?(t.push("blue","clickable"),e="check_box_outline_blank"):(t.push("lt-blue"),e="indeterminate_check_box"):e=this.props.checked?"check_box":"check_box_outline_blank";let i={className:t.join(" "),id:this.props.id};return this.props.onChange&&(i.onClick=this.handleChange),n().createElement("i",i,e)}}},1887:(e,t,i)=>{i.d(t,{Z:()=>c});var s=i(7363),n=i.n(s),a=i(2506),r=i(3905),o=i(3740);class c extends n().PureComponent{render(){let e;if(!0===this.props.avatar){const t=a.Tinode.isGroupTopicName(this.props.topic),i=(0,r.Cj)(this.props.topic,t);if(this.props.topic&&this.props.title&&this.props.title.trim()){const t=this.props.title.trim().charAt(0),s="lettertile "+i+(this.props.deleted?" disabled":"");e=n().createElement("div",{className:s},n().createElement("div",null,t))}else{const s="material-icons "+i+(this.props.deleted?" disabled":"");e=t?n().createElement("i",{className:s},"group"):n().createElement("i",{className:s},"person")}}else if(this.props.avatar){const t=this.props.tinode.authorizeURL((0,o.Fv)(this.props.avatar,"image")),i="avatar"+(this.props.deleted?" deleted":"");e=n().createElement("img",{className:i,alt:"avatar",src:t,onError:e=>{e.target.onerror=null,e.target.src="../img/broken_image.png"}})}else e=null;return e}}},7646:(e,t,i)=>{i.d(t,{Z:()=>a});var s=i(7363),n=i.n(s);class a extends n().PureComponent{render(){const e="load-spinner-box"+(this.props.large?" large":"")+(this.props.clear?" clear":"")+(this.props.centered?" centered":"");return this.props.show?n().createElement("div",{className:e},n().createElement("div",{className:"loader-spinner"})):null}}},195:(e,t,i)=>{i.d(t,{Z:()=>a});var s=i(7363),n=i.n(s);class a extends n().PureComponent{constructor(e){super(e),this.inputRef=n().createRef(),this.state={value:this.props.value||"",visible:!1},this.handleVisibility=this.handleVisibility.bind(this),this.handeTextChange=this.handeTextChange.bind(this),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleEditingFinished=this.handleEditingFinished.bind(this)}componentDidMount(){this.props.autoFocus&&this.inputRef.current.focus()}handeTextChange(e){this.setState({value:e.target.value}),this.props.onChange&&this.props.onChange(e)}handleVisibility(e){e.preventDefault(),this.setState({visible:!this.state.visible})}handleKeyDown(e){27==e.keyCode?(this.setState({value:this.props.value||"",visible:!1}),this.props.onFinished&&this.props.onFinished()):13==e.keyCode&&this.handleEditingFinished()}handleEditingFinished(e){if(e){let t=e.currentTarget;setTimeout((e=>{t.contains(document.activeElement)||this.props.onFinished&&this.props.onFinished(this.state.value)}),0)}else this.props.onFinished&&this.props.onFinished(this.state.value.trim())}render(){return n().createElement("div",{tabIndex:"-1",className:"group-focus",onBlur:this.handleEditingFinished},n().createElement("input",{className:"with-visibility",type:this.state.visible?"text":"password",value:this.state.value,placeholder:this.props.placeholder,required:this.props.required?"required":"",autoFocus:this.props.autoFocus?"autoFocus":"",autoComplete:this.props.autoComplete,onChange:this.handeTextChange,onKeyDown:this.handleKeyDown,ref:this.inputRef}),n().createElement("span",{onClick:this.handleVisibility},n().createElement("i",{className:"material-icons clickable light-gray"},this.state.visible?"visibility":"visibility_off")))}}},745:(e,t,i)=>{var s=i(1533);t.s=s.createRoot,s.hydrateRoot},7363:e=>{e.exports=React},1533:e=>{e.exports=ReactDOM},916:e=>{e.exports=ReactIntl},2506:e=>{e.exports=tinode}},a={};function r(e){var t=a[e];if(void 0!==t)return t.exports;var i=a[e]={exports:{}};return n[e].call(i.exports,i,i.exports,r),i.exports}r.m=n,r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,r.t=function(i,s){if(1&s&&(i=this(i)),8&s)return i;if("object"==typeof i&&i){if(4&s&&i.__esModule)return i;if(16&s&&"function"==typeof i.then)return i}var n=Object.create(null);r.r(n);var a={};e=e||[null,t({}),t([]),t(t)];for(var o=2&s&&i;"object"==typeof o&&!~e.indexOf(o);o=t(o))Object.getOwnPropertyNames(o).forEach((e=>a[e]=()=>i[e]));return a.default=()=>i,r.d(n,a),n},r.d=(e,t)=>{for(var i in t)r.o(t,i)&&!r.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},r.f={},r.e=e=>Promise.all(Object.keys(r.f).reduce(((t,i)=>(r.f[i](e,t),t)),[])),r.u=e=>e+".prod.js",r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i={},s="tinode-webapp:",r.l=(e,t,n,a)=>{if(i[e])i[e].push(t);else{var o,c;if(void 0!==n)for(var l=document.getElementsByTagName("script"),d=0;d<l.length;d++){var h=l[d];if(h.getAttribute("src")==e||h.getAttribute("data-webpack")==s+n){o=h;break}}o||(c=!0,(o=document.createElement("script")).charset="utf-8",o.timeout=120,r.nc&&o.setAttribute("nonce",r.nc),o.setAttribute("data-webpack",s+n),o.src=e),i[e]=[t];var u=(t,s)=>{o.onerror=o.onload=null,clearTimeout(p);var n=i[e];if(delete i[e],o.parentNode&&o.parentNode.removeChild(o),n&&n.forEach((e=>e(s))),t)return t(s)},p=setTimeout(u.bind(null,void 0,{type:"timeout",target:o}),12e4);o.onerror=u.bind(null,o.onerror),o.onload=u.bind(null,o.onload),c&&document.head.appendChild(o)}},r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.p="/umd/",(()=>{var e={826:0};r.f.j=(t,i)=>{var s=r.o(e,t)?e[t]:void 0;if(0!==s)if(s)i.push(s[2]);else{var n=new Promise(((i,n)=>s=e[t]=[i,n]));i.push(s[2]=n);var a=r.p+r.u(t),o=new Error;r.l(a,(i=>{if(r.o(e,t)&&(0!==(s=e[t])&&(e[t]=void 0),s)){var n=i&&("load"===i.type?"missing":i.type),a=i&&i.target&&i.target.src;o.message="Loading chunk "+t+" failed.\n("+n+": "+a+")",o.name="ChunkLoadError",o.type=n,o.request=a,s[1](o)}}),"chunk-"+t,t)}};var t=(t,i)=>{var s,n,[a,o,c]=i,l=0;if(a.some((t=>0!==e[t]))){for(s in o)r.o(o,s)&&(r.m[s]=o[s]);if(c)c(r)}for(t&&t(i);l<a.length;l++)n=a[l],r.o(e,n)&&e[n]&&e[n][0](),e[n]=0},i=globalThis.webpackChunktinode_webapp=globalThis.webpackChunktinode_webapp||[];i.forEach(t.bind(null,0)),i.push=t.bind(null,i.push.bind(i))})(),(()=>{var e=r(7363),t=r.n(e),i=r(745),s=r(916);const n=function(e){const t=[];let i=0;for(let s=0;s<e.length;s++){let n=e.charCodeAt(s);n<128?t[i++]=n:n<2048?(t[i++]=n>>6|192,t[i++]=63&n|128):55296==(64512&n)&&s+1<e.length&&56320==(64512&e.charCodeAt(s+1))?(n=65536+((1023&n)<<10)+(1023&e.charCodeAt(++s)),t[i++]=n>>18|240,t[i++]=n>>12&63|128,t[i++]=n>>6&63|128,t[i++]=63&n|128):(t[i++]=n>>12|224,t[i++]=n>>6&63|128,t[i++]=63&n|128)}return t},a={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();const i=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,s=[];for(let t=0;t<e.length;t+=3){const n=e[t],a=t+1<e.length,r=a?e[t+1]:0,o=t+2<e.length,c=o?e[t+2]:0,l=n>>2,d=(3&n)<<4|r>>4;let h=(15&r)<<2|c>>6,u=63&c;o||(u=64,a||(h=64)),s.push(i[l],i[d],i[h],i[u])}return s.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(n(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let i=0,s=0;for(;i<e.length;){const n=e[i++];if(n<128)t[s++]=String.fromCharCode(n);else if(n>191&&n<224){const a=e[i++];t[s++]=String.fromCharCode((31&n)<<6|63&a)}else if(n>239&&n<365){const a=((7&n)<<18|(63&e[i++])<<12|(63&e[i++])<<6|63&e[i++])-65536;t[s++]=String.fromCharCode(55296+(a>>10)),t[s++]=String.fromCharCode(56320+(1023&a))}else{const a=e[i++],r=e[i++];t[s++]=String.fromCharCode((15&n)<<12|(63&a)<<6|63&r)}}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();const i=t?this.charToByteMapWebSafe_:this.charToByteMap_,s=[];for(let t=0;t<e.length;){const n=i[e.charAt(t++)],a=t<e.length?i[e.charAt(t)]:0;++t;const r=t<e.length?i[e.charAt(t)]:64;++t;const c=t<e.length?i[e.charAt(t)]:64;if(++t,null==n||null==a||null==r||null==c)throw new o;const l=n<<2|a>>4;if(s.push(l),64!==r){const e=a<<4&240|r>>2;if(s.push(e),64!==c){const e=r<<6&192|c;s.push(e)}}}return s},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class o extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const c=function(e){return function(e){const t=n(e);return a.encodeByteArray(t,!0)}(e).replace(/\./g,"")},l=function(e){try{return a.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};const d=()=>function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==r.g)return r.g;throw new Error("Unable to locate global object.")}().__FIREBASE_DEFAULTS__,h=()=>{try{return d()||(()=>{if("undefined"==typeof process||void 0===process.env)return;const e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0})()||(()=>{if("undefined"==typeof document)return;let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}const t=e&&l(e[1]);return t&&JSON.parse(t)})()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},u=()=>{var e;return null===(e=h())||void 0===e?void 0:e.config};class p{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}wrapCallback(e){return(t,i)=>{t?this.reject(t):this.resolve(i),"function"==typeof e&&(this.promise.catch((()=>{})),1===e.length?e(t):e(t,i))}}}function m(){try{return"object"==typeof indexedDB}catch(e){return!1}}function g(){return new Promise(((e,t)=>{try{let i=!0;const s="validate-browser-context-for-indexeddb-analytics-module",n=self.indexedDB.open(s);n.onsuccess=()=>{n.result.close(),i||self.indexedDB.deleteDatabase(s),e(!0)},n.onupgradeneeded=()=>{i=!1},n.onerror=()=>{var e;t((null===(e=n.error)||void 0===e?void 0:e.message)||"")}}catch(e){t(e)}}))}class f extends Error{constructor(e,t,i){super(t),this.code=e,this.customData=i,this.name="FirebaseError",Object.setPrototypeOf(this,f.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,v.prototype.create)}}class v{constructor(e,t,i){this.service=e,this.serviceName=t,this.errors=i}create(e,...t){const i=t[0]||{},s=`${this.service}/${e}`,n=this.errors[e],a=n?function(e,t){return e.replace(b,((e,i)=>{const s=t[i];return null!=s?String(s):`<${i}?>`}))}(n,i):"Error",r=`${this.serviceName}: ${a} (${s}).`;return new f(s,r,i)}}const b=/\{\$([^}]+)}/g;function y(e,t){if(e===t)return!0;const i=Object.keys(e),s=Object.keys(t);for(const n of i){if(!s.includes(n))return!1;const i=e[n],a=t[n];if(S(i)&&S(a)){if(!y(i,a))return!1}else if(i!==a)return!1}for(const e of s)if(!i.includes(e))return!1;return!0}function S(e){return null!==e&&"object"==typeof e}function w(e){return e&&e._delegate?e._delegate:e}class C{constructor(e,t,i){this.name=e,this.instanceFactory=t,this.type=i,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}const k="[DEFAULT]";class E{constructor(e,t){this.name=e,this.container=t,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(e){const t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){const e=new p;if(this.instancesDeferred.set(t,e),this.isInitialized(t)||this.shouldAutoInitialize())try{const i=this.getOrInitializeService({instanceIdentifier:t});i&&e.resolve(i)}catch(e){}}return this.instancesDeferred.get(t).promise}getImmediate(e){var t;const i=this.normalizeInstanceIdentifier(null==e?void 0:e.identifier),s=null!==(t=null==e?void 0:e.optional)&&void 0!==t&&t;if(!this.isInitialized(i)&&!this.shouldAutoInitialize()){if(s)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:i})}catch(e){if(s)return null;throw e}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,this.shouldAutoInitialize()){if(function(e){return"EAGER"===e.instantiationMode}(e))try{this.getOrInitializeService({instanceIdentifier:k})}catch(e){}for(const[e,t]of this.instancesDeferred.entries()){const i=this.normalizeInstanceIdentifier(e);try{const e=this.getOrInitializeService({instanceIdentifier:i});t.resolve(e)}catch(e){}}}}clearInstance(e=k){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){const e=Array.from(this.instances.values());await Promise.all([...e.filter((e=>"INTERNAL"in e)).map((e=>e.INTERNAL.delete())),...e.filter((e=>"_delete"in e)).map((e=>e._delete()))])}isComponentSet(){return null!=this.component}isInitialized(e=k){return this.instances.has(e)}getOptions(e=k){return this.instancesOptions.get(e)||{}}initialize(e={}){const{options:t={}}=e,i=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(i))throw Error(`${this.name}(${i}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);const s=this.getOrInitializeService({instanceIdentifier:i,options:t});for(const[e,t]of this.instancesDeferred.entries()){i===this.normalizeInstanceIdentifier(e)&&t.resolve(s)}return s}onInit(e,t){var i;const s=this.normalizeInstanceIdentifier(t),n=null!==(i=this.onInitCallbacks.get(s))&&void 0!==i?i:new Set;n.add(e),this.onInitCallbacks.set(s,n);const a=this.instances.get(s);return a&&e(a,s),()=>{n.delete(e)}}invokeOnInitCallbacks(e,t){const i=this.onInitCallbacks.get(t);if(i)for(const s of i)try{s(e,t)}catch(e){}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let i=this.instances.get(e);if(!i&&this.component&&(i=this.component.instanceFactory(this.container,{instanceIdentifier:(s=e,s===k?void 0:s),options:t}),this.instances.set(e,i),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(i,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,i)}catch(e){}var s;return i||null}normalizeInstanceIdentifier(e=k){return this.component?this.component.multipleInstances?e:k:e}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class T{constructor(e){this.name=e,this.providers=new Map}addComponent(e){const t=this.getProvider(e.name);if(t.isComponentSet())throw new Error(`Component ${e.name} has already been registered with ${this.name}`);t.setComponent(e)}addOrOverwriteComponent(e){this.getProvider(e.name).isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){if(this.providers.has(e))return this.providers.get(e);const t=new E(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}}const P=[];var M;!function(e){e[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT"}(M||(M={}));const R={debug:M.DEBUG,verbose:M.VERBOSE,info:M.INFO,warn:M.WARN,error:M.ERROR,silent:M.SILENT},_=M.INFO,N={[M.DEBUG]:"log",[M.VERBOSE]:"log",[M.INFO]:"info",[M.WARN]:"warn",[M.ERROR]:"error"},D=(e,t,...i)=>{if(t<e.logLevel)return;const s=(new Date).toISOString(),n=N[t];if(!n)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[n](`[${s}] ${e.name}:`,...i)};const I=(e,t)=>t.some((t=>e instanceof t));let A,O;const U=new WeakMap,x=new WeakMap,L=new WeakMap,F=new WeakMap,B=new WeakMap;let q={get(e,t,i){if(e instanceof IDBTransaction){if("done"===t)return x.get(e);if("objectStoreNames"===t)return e.objectStoreNames||L.get(e);if("store"===t)return i.objectStoreNames[1]?void 0:i.objectStore(i.objectStoreNames[0])}return $(e[t])},set:(e,t,i)=>(e[t]=i,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function j(e){return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(O||(O=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(W(this),t),$(U.get(this))}:function(...t){return $(e.apply(W(this),t))}:function(t,...i){const s=e.call(W(this),t,...i);return L.set(s,t.sort?t.sort():[t]),$(s)}}function V(e){return"function"==typeof e?j(e):(e instanceof IDBTransaction&&function(e){if(x.has(e))return;const t=new Promise(((t,i)=>{const s=()=>{e.removeEventListener("complete",n),e.removeEventListener("error",a),e.removeEventListener("abort",a)},n=()=>{t(),s()},a=()=>{i(e.error||new DOMException("AbortError","AbortError")),s()};e.addEventListener("complete",n),e.addEventListener("error",a),e.addEventListener("abort",a)}));x.set(e,t)}(e),I(e,A||(A=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,q):e)}function $(e){if(e instanceof IDBRequest)return function(e){const t=new Promise(((t,i)=>{const s=()=>{e.removeEventListener("success",n),e.removeEventListener("error",a)},n=()=>{t($(e.result)),s()},a=()=>{i(e.error),s()};e.addEventListener("success",n),e.addEventListener("error",a)}));return t.then((t=>{t instanceof IDBCursor&&U.set(t,e)})).catch((()=>{})),B.set(t,e),t}(e);if(F.has(e))return F.get(e);const t=V(e);return t!==e&&(F.set(e,t),B.set(t,e)),t}const W=e=>B.get(e);function J(e,t,{blocked:i,upgrade:s,blocking:n,terminated:a}={}){const r=indexedDB.open(e,t),o=$(r);return s&&r.addEventListener("upgradeneeded",(e=>{s($(r.result),e.oldVersion,e.newVersion,$(r.transaction))})),i&&r.addEventListener("blocked",(()=>i())),o.then((e=>{a&&e.addEventListener("close",(()=>a())),n&&e.addEventListener("versionchange",(()=>n()))})).catch((()=>{})),o}function H(e,{blocked:t}={}){const i=indexedDB.deleteDatabase(e);return t&&i.addEventListener("blocked",(()=>t())),$(i).then((()=>{}))}const G=["get","getKey","getAll","getAllKeys","count"],z=["put","add","delete","clear"],Z=new Map;function K(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(Z.get(t))return Z.get(t);const i=t.replace(/FromIndex$/,""),s=t!==i,n=z.includes(i);if(!(i in(s?IDBIndex:IDBObjectStore).prototype)||!n&&!G.includes(i))return;const a=async function(e,...t){const a=this.transaction(e,n?"readwrite":"readonly");let r=a.store;return s&&(r=r.index(t.shift())),(await Promise.all([r[i](...t),n&&a.done]))[0]};return Z.set(t,a),a}q=(e=>({...e,get:(t,i,s)=>K(t,i)||e.get(t,i,s),has:(t,i)=>!!K(t,i)||e.has(t,i)}))(q);class Q{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map((e=>{if(function(e){const t=e.getComponent();return"VERSION"===(null==t?void 0:t.type)}(e)){const t=e.getImmediate();return`${t.library}/${t.version}`}return null})).filter((e=>e)).join(" ")}}const X="@firebase/app",Y="0.9.5",ee=new class{constructor(e){this.name=e,this._logLevel=_,this._logHandler=D,this._userLogHandler=null,P.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in M))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?R[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,M.DEBUG,...e),this._logHandler(this,M.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,M.VERBOSE,...e),this._logHandler(this,M.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,M.INFO,...e),this._logHandler(this,M.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,M.WARN,...e),this._logHandler(this,M.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,M.ERROR,...e),this._logHandler(this,M.ERROR,...e)}}("@firebase/app"),te="[DEFAULT]",ie={[X]:"fire-core","@firebase/app-compat":"fire-core-compat","@firebase/analytics":"fire-analytics","@firebase/analytics-compat":"fire-analytics-compat","@firebase/app-check":"fire-app-check","@firebase/app-check-compat":"fire-app-check-compat","@firebase/auth":"fire-auth","@firebase/auth-compat":"fire-auth-compat","@firebase/database":"fire-rtdb","@firebase/database-compat":"fire-rtdb-compat","@firebase/functions":"fire-fn","@firebase/functions-compat":"fire-fn-compat","@firebase/installations":"fire-iid","@firebase/installations-compat":"fire-iid-compat","@firebase/messaging":"fire-fcm","@firebase/messaging-compat":"fire-fcm-compat","@firebase/performance":"fire-perf","@firebase/performance-compat":"fire-perf-compat","@firebase/remote-config":"fire-rc","@firebase/remote-config-compat":"fire-rc-compat","@firebase/storage":"fire-gcs","@firebase/storage-compat":"fire-gcs-compat","@firebase/firestore":"fire-fst","@firebase/firestore-compat":"fire-fst-compat","fire-js":"fire-js",firebase:"fire-js-all"},se=new Map,ne=new Map;function ae(e,t){try{e.container.addComponent(t)}catch(i){ee.debug(`Component ${t.name} failed to register with FirebaseApp ${e.name}`,i)}}function re(e){const t=e.name;if(ne.has(t))return ee.debug(`There were multiple attempts to register component ${t}.`),!1;ne.set(t,e);for(const t of se.values())ae(t,e);return!0}function oe(e,t){const i=e.container.getProvider("heartbeat").getImmediate({optional:!0});return i&&i.triggerHeartbeat(),e.container.getProvider(t)}const ce=new v("app","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call Firebase App.initializeApp()","bad-app-name":"Illegal App name: '{$appName}","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","no-options":"Need to provide options, when not being deployed to hosting via source.","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance.","invalid-log-argument":"First argument to `onLog` must be null or a function.","idb-open":"Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.","idb-get":"Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.","idb-set":"Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.","idb-delete":"Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}."});class le{constructor(e,t,i){this._isDeleted=!1,this._options=Object.assign({},e),this._config=Object.assign({},t),this._name=t.name,this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled,this._container=i,this.container.addComponent(new C("app",(()=>this),"PUBLIC"))}get automaticDataCollectionEnabled(){return this.checkDestroyed(),this._automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this.checkDestroyed(),this._automaticDataCollectionEnabled=e}get name(){return this.checkDestroyed(),this._name}get options(){return this.checkDestroyed(),this._options}get config(){return this.checkDestroyed(),this._config}get container(){return this._container}get isDeleted(){return this._isDeleted}set isDeleted(e){this._isDeleted=e}checkDestroyed(){if(this.isDeleted)throw ce.create("app-deleted",{appName:this._name})}}function de(e,t={}){let i=e;if("object"!=typeof t){t={name:t}}const s=Object.assign({name:te,automaticDataCollectionEnabled:!1},t),n=s.name;if("string"!=typeof n||!n)throw ce.create("bad-app-name",{appName:String(n)});if(i||(i=u()),!i)throw ce.create("no-options");const a=se.get(n);if(a){if(y(i,a.options)&&y(s,a.config))return a;throw ce.create("duplicate-app",{appName:n})}const r=new T(n);for(const e of ne.values())r.addComponent(e);const o=new le(i,s,r);return se.set(n,o),o}function he(e,t,i){var s;let n=null!==(s=ie[e])&&void 0!==s?s:e;i&&(n+=`-${i}`);const a=n.match(/\s|\//),r=t.match(/\s|\//);if(a||r){const e=[`Unable to register library "${n}" with version "${t}":`];return a&&e.push(`library name "${n}" contains illegal characters (whitespace or "/")`),a&&r&&e.push("and"),r&&e.push(`version name "${t}" contains illegal characters (whitespace or "/")`),void ee.warn(e.join(" "))}re(new C(`${n}-version`,(()=>({library:n,version:t})),"VERSION"))}const ue="firebase-heartbeat-database",pe=1,me="firebase-heartbeat-store";let ge=null;function fe(){return ge||(ge=J(ue,pe,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(me)}}).catch((e=>{throw ce.create("idb-open",{originalErrorMessage:e.message})}))),ge}async function ve(e,t){try{const i=(await fe()).transaction(me,"readwrite"),s=i.objectStore(me);return await s.put(t,be(e)),i.done}catch(e){if(e instanceof f)ee.warn(e.message);else{const t=ce.create("idb-set",{originalErrorMessage:null==e?void 0:e.message});ee.warn(t.message)}}}function be(e){return`${e.name}!${e.options.appId}`}const ye=1024;class Se{constructor(e){this.container=e,this._heartbeatsCache=null;const t=this.container.getProvider("app").getImmediate();this._storage=new Ce(t),this._heartbeatsCachePromise=this._storage.read().then((e=>(this._heartbeatsCache=e,e)))}async triggerHeartbeat(){const e=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),t=we();if(null===this._heartbeatsCache&&(this._heartbeatsCache=await this._heartbeatsCachePromise),this._heartbeatsCache.lastSentHeartbeatDate!==t&&!this._heartbeatsCache.heartbeats.some((e=>e.date===t)))return this._heartbeatsCache.heartbeats.push({date:t,agent:e}),this._heartbeatsCache.heartbeats=this._heartbeatsCache.heartbeats.filter((e=>{const t=new Date(e.date).valueOf();return Date.now()-t<=2592e6})),this._storage.overwrite(this._heartbeatsCache)}async getHeartbeatsHeader(){if(null===this._heartbeatsCache&&await this._heartbeatsCachePromise,null===this._heartbeatsCache||0===this._heartbeatsCache.heartbeats.length)return"";const e=we(),{heartbeatsToSend:t,unsentEntries:i}=function(e,t=ye){const i=[];let s=e.slice();for(const n of e){const e=i.find((e=>e.agent===n.agent));if(e){if(e.dates.push(n.date),ke(i)>t){e.dates.pop();break}}else if(i.push({agent:n.agent,dates:[n.date]}),ke(i)>t){i.pop();break}s=s.slice(1)}return{heartbeatsToSend:i,unsentEntries:s}}(this._heartbeatsCache.heartbeats),s=c(JSON.stringify({version:2,heartbeats:t}));return this._heartbeatsCache.lastSentHeartbeatDate=e,i.length>0?(this._heartbeatsCache.heartbeats=i,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),s}}function we(){return(new Date).toISOString().substring(0,10)}class Ce{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!m()&&g().then((()=>!0)).catch((()=>!1))}async read(){if(await this._canUseIndexedDBPromise){return await async function(e){try{return(await fe()).transaction(me).objectStore(me).get(be(e))}catch(e){if(e instanceof f)ee.warn(e.message);else{const t=ce.create("idb-get",{originalErrorMessage:null==e?void 0:e.message});ee.warn(t.message)}}}(this.app)||{heartbeats:[]}}return{heartbeats:[]}}async overwrite(e){var t;if(await this._canUseIndexedDBPromise){const i=await this.read();return ve(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:i.lastSentHeartbeatDate,heartbeats:e.heartbeats})}}async add(e){var t;if(await this._canUseIndexedDBPromise){const i=await this.read();return ve(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:i.lastSentHeartbeatDate,heartbeats:[...i.heartbeats,...e.heartbeats]})}}}function ke(e){return c(JSON.stringify({version:2,heartbeats:e})).length}var Ee;Ee="",re(new C("platform-logger",(e=>new Q(e)),"PRIVATE")),re(new C("heartbeat",(e=>new Se(e)),"PRIVATE")),he(X,Y,Ee),he(X,Y,"esm2017"),he("fire-js","");he("firebase","9.18.0","app");const Te="@firebase/installations",Pe="0.6.4",Me=1e4,Re=`w:${Pe}`,_e="FIS_v2",Ne="https://firebaseinstallations.googleapis.com/v1",De=36e5,Ie=new v("installations","Installations",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"not-registered":"Firebase Installation is not registered.","installation-not-found":"Firebase Installation not found.","request-failed":'{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',"app-offline":"Could not process request. Application offline.","delete-pending-registration":"Can't delete installation while there is a pending registration request."});function Ae(e){return e instanceof f&&e.code.includes("request-failed")}function Oe({projectId:e}){return`${Ne}/projects/${e}/installations`}function Ue(e){return{token:e.token,requestStatus:2,expiresIn:(t=e.expiresIn,Number(t.replace("s","000"))),creationTime:Date.now()};var t}async function xe(e,t){const i=(await t.json()).error;return Ie.create("request-failed",{requestName:e,serverCode:i.code,serverMessage:i.message,serverStatus:i.status})}function Le({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function Fe(e,{refreshToken:t}){const i=Le(e);return i.append("Authorization",function(e){return`${_e} ${e}`}(t)),i}async function Be(e){const t=await e();return t.status>=500&&t.status<600?e():t}function qe(e){return new Promise((t=>{setTimeout(t,e)}))}const je=/^[cdef][\w-]{21}$/,Ve="";function $e(){try{const e=new Uint8Array(17);(self.crypto||self.msCrypto).getRandomValues(e),e[0]=112+e[0]%16;const t=function(e){const t=(i=e,btoa(String.fromCharCode(...i)).replace(/\+/g,"-").replace(/\//g,"_"));var i;return t.substr(0,22)}(e);return je.test(t)?t:Ve}catch(e){return Ve}}function We(e){return`${e.appName}!${e.appId}`}const Je=new Map;function He(e,t){const i=We(e);Ge(i,t),function(e,t){const i=Ze();i&&i.postMessage({key:e,fid:t});Ke()}(i,t)}function Ge(e,t){const i=Je.get(e);if(i)for(const e of i)e(t)}let ze=null;function Ze(){return!ze&&"BroadcastChannel"in self&&(ze=new BroadcastChannel("[Firebase] FID Change"),ze.onmessage=e=>{Ge(e.data.key,e.data.fid)}),ze}function Ke(){0===Je.size&&ze&&(ze.close(),ze=null)}const Qe="firebase-installations-database",Xe=1,Ye="firebase-installations-store";let et=null;function tt(){return et||(et=J(Qe,Xe,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(Ye)}})),et}async function it(e,t){const i=We(e),s=(await tt()).transaction(Ye,"readwrite"),n=s.objectStore(Ye),a=await n.get(i);return await n.put(t,i),await s.done,a&&a.fid===t.fid||He(e,t.fid),t}async function st(e){const t=We(e),i=(await tt()).transaction(Ye,"readwrite");await i.objectStore(Ye).delete(t),await i.done}async function nt(e,t){const i=We(e),s=(await tt()).transaction(Ye,"readwrite"),n=s.objectStore(Ye),a=await n.get(i),r=t(a);return void 0===r?await n.delete(i):await n.put(r,i),await s.done,!r||a&&a.fid===r.fid||He(e,r.fid),r}async function at(e){let t;const i=await nt(e.appConfig,(i=>{const s=function(e){const t=e||{fid:$e(),registrationStatus:0};return ct(t)}(i),n=function(e,t){if(0===t.registrationStatus){if(!navigator.onLine){return{installationEntry:t,registrationPromise:Promise.reject(Ie.create("app-offline"))}}const i={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},s=async function(e,t){try{const i=await async function({appConfig:e,heartbeatServiceProvider:t},{fid:i}){const s=Oe(e),n=Le(e),a=t.getImmediate({optional:!0});if(a){const e=await a.getHeartbeatsHeader();e&&n.append("x-firebase-client",e)}const r={fid:i,authVersion:_e,appId:e.appId,sdkVersion:Re},o={method:"POST",headers:n,body:JSON.stringify(r)},c=await Be((()=>fetch(s,o)));if(c.ok){const e=await c.json();return{fid:e.fid||i,registrationStatus:2,refreshToken:e.refreshToken,authToken:Ue(e.authToken)}}throw await xe("Create Installation",c)}(e,t);return it(e.appConfig,i)}catch(i){throw Ae(i)&&409===i.customData.serverCode?await st(e.appConfig):await it(e.appConfig,{fid:t.fid,registrationStatus:0}),i}}(e,i);return{installationEntry:i,registrationPromise:s}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:rt(e)}:{installationEntry:t}}(e,s);return t=n.registrationPromise,n.installationEntry}));return i.fid===Ve?{installationEntry:await t}:{installationEntry:i,registrationPromise:t}}async function rt(e){let t=await ot(e.appConfig);for(;1===t.registrationStatus;)await qe(100),t=await ot(e.appConfig);if(0===t.registrationStatus){const{installationEntry:t,registrationPromise:i}=await at(e);return i||t}return t}function ot(e){return nt(e,(e=>{if(!e)throw Ie.create("installation-not-found");return ct(e)}))}function ct(e){return 1===(t=e).registrationStatus&&t.registrationTime+Me<Date.now()?{fid:e.fid,registrationStatus:0}:e;var t}async function lt({appConfig:e,heartbeatServiceProvider:t},i){const s=function(e,{fid:t}){return`${Oe(e)}/${t}/authTokens:generate`}(e,i),n=Fe(e,i),a=t.getImmediate({optional:!0});if(a){const e=await a.getHeartbeatsHeader();e&&n.append("x-firebase-client",e)}const r={installation:{sdkVersion:Re,appId:e.appId}},o={method:"POST",headers:n,body:JSON.stringify(r)},c=await Be((()=>fetch(s,o)));if(c.ok){return Ue(await c.json())}throw await xe("Generate Auth Token",c)}async function dt(e,t=!1){let i;const s=await nt(e.appConfig,(s=>{if(!ut(s))throw Ie.create("not-registered");const n=s.authToken;if(!t&&function(e){return 2===e.requestStatus&&!function(e){const t=Date.now();return t<e.creationTime||e.creationTime+e.expiresIn<t+De}(e)}(n))return s;if(1===n.requestStatus)return i=async function(e,t){let i=await ht(e.appConfig);for(;1===i.authToken.requestStatus;)await qe(100),i=await ht(e.appConfig);const s=i.authToken;return 0===s.requestStatus?dt(e,t):s}(e,t),s;{if(!navigator.onLine)throw Ie.create("app-offline");const t=function(e){const t={requestStatus:1,requestTime:Date.now()};return Object.assign(Object.assign({},e),{authToken:t})}(s);return i=async function(e,t){try{const i=await lt(e,t),s=Object.assign(Object.assign({},t),{authToken:i});return await it(e.appConfig,s),i}catch(i){if(!Ae(i)||401!==i.customData.serverCode&&404!==i.customData.serverCode){const i=Object.assign(Object.assign({},t),{authToken:{requestStatus:0}});await it(e.appConfig,i)}else await st(e.appConfig);throw i}}(e,t),t}}));return i?await i:s.authToken}function ht(e){return nt(e,(e=>{if(!ut(e))throw Ie.create("not-registered");const t=e.authToken;return 1===(i=t).requestStatus&&i.requestTime+Me<Date.now()?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e;var i}))}function ut(e){return void 0!==e&&2===e.registrationStatus}async function pt(e,t=!1){const i=e;await async function(e){const{registrationPromise:t}=await at(e);t&&await t}(i);return(await dt(i,t)).token}function mt(e){return Ie.create("missing-app-config-values",{valueName:e})}const gt="installations",ft="installations-internal",vt=e=>{const t=oe(e.getProvider("app").getImmediate(),gt).getImmediate();return{getId:()=>async function(e){const t=e,{installationEntry:i,registrationPromise:s}=await at(t);return s?s.catch(console.error):dt(t).catch(console.error),i.fid}(t),getToken:e=>pt(t,e)}};re(new C(gt,(e=>{const t=e.getProvider("app").getImmediate(),i=function(e){if(!e||!e.options)throw mt("App Configuration");if(!e.name)throw mt("App Name");const t=["projectId","apiKey","appId"];for(const i of t)if(!e.options[i])throw mt(i);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t);return{app:t,appConfig:i,heartbeatServiceProvider:oe(t,"heartbeat"),_delete:()=>Promise.resolve()}}),"PUBLIC")),re(new C(ft,vt,"PRIVATE")),he(Te,Pe),he(Te,Pe,"esm2017");const bt="/firebase-messaging-sw.js",yt="/firebase-cloud-messaging-push-scope",St="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4",wt="https://fcmregistrations.googleapis.com/v1",Ct="google.c.a.c_id",kt="google.c.a.c_l",Et="google.c.a.ts",Tt="google.c.a.e";var Pt,Mt;function Rt(e){const t=new Uint8Array(e);return btoa(String.fromCharCode(...t)).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function _t(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/"),i=atob(t),s=new Uint8Array(i.length);for(let e=0;e<i.length;++e)s[e]=i.charCodeAt(e);return s}!function(e){e[e.DATA_MESSAGE=1]="DATA_MESSAGE",e[e.DISPLAY_NOTIFICATION=3]="DISPLAY_NOTIFICATION"}(Pt||(Pt={})),function(e){e.PUSH_RECEIVED="push-received",e.NOTIFICATION_CLICKED="notification-clicked"}(Mt||(Mt={}));const Nt="fcm_token_details_db",Dt=5,It="fcm_token_object_Store";const At="firebase-messaging-database",Ot=1,Ut="firebase-messaging-store";let xt=null;function Lt(){return xt||(xt=J(At,Ot,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(Ut)}})),xt}async function Ft(e){const t=qt(e),i=await Lt(),s=await i.transaction(Ut).objectStore(Ut).get(t);if(s)return s;{const t=await async function(e){if("databases"in indexedDB){const e=(await indexedDB.databases()).map((e=>e.name));if(!e.includes(Nt))return null}let t=null;return(await J(Nt,Dt,{upgrade:async(i,s,n,a)=>{var r;if(s<2)return;if(!i.objectStoreNames.contains(It))return;const o=a.objectStore(It),c=await o.index("fcmSenderId").get(e);if(await o.clear(),c)if(2===s){const e=c;if(!e.auth||!e.p256dh||!e.endpoint)return;t={token:e.fcmToken,createTime:null!==(r=e.createTime)&&void 0!==r?r:Date.now(),subscriptionOptions:{auth:e.auth,p256dh:e.p256dh,endpoint:e.endpoint,swScope:e.swScope,vapidKey:"string"==typeof e.vapidKey?e.vapidKey:Rt(e.vapidKey)}}}else if(3===s){const e=c;t={token:e.fcmToken,createTime:e.createTime,subscriptionOptions:{auth:Rt(e.auth),p256dh:Rt(e.p256dh),endpoint:e.endpoint,swScope:e.swScope,vapidKey:Rt(e.vapidKey)}}}else if(4===s){const e=c;t={token:e.fcmToken,createTime:e.createTime,subscriptionOptions:{auth:Rt(e.auth),p256dh:Rt(e.p256dh),endpoint:e.endpoint,swScope:e.swScope,vapidKey:Rt(e.vapidKey)}}}}})).close(),await H(Nt),await H("fcm_vapid_details_db"),await H("undefined"),function(e){if(!e||!e.subscriptionOptions)return!1;const{subscriptionOptions:t}=e;return"number"==typeof e.createTime&&e.createTime>0&&"string"==typeof e.token&&e.token.length>0&&"string"==typeof t.auth&&t.auth.length>0&&"string"==typeof t.p256dh&&t.p256dh.length>0&&"string"==typeof t.endpoint&&t.endpoint.length>0&&"string"==typeof t.swScope&&t.swScope.length>0&&"string"==typeof t.vapidKey&&t.vapidKey.length>0}(t)?t:null}(e.appConfig.senderId);if(t)return await Bt(e,t),t}}async function Bt(e,t){const i=qt(e),s=(await Lt()).transaction(Ut,"readwrite");return await s.objectStore(Ut).put(t,i),await s.done,t}function qt({appConfig:e}){return e.appId}const jt=new v("messaging","Messaging",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"only-available-in-window":"This method is available in a Window context.","only-available-in-sw":"This method is available in a service worker context.","permission-default":"The notification permission was not granted and dismissed instead.","permission-blocked":"The notification permission was not granted and blocked instead.","unsupported-browser":"This browser doesn't support the API's required to use the Firebase SDK.","indexed-db-unsupported":"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)","failed-service-worker-registration":"We are unable to register the default service worker. {$browserErrorMessage}","token-subscribe-failed":"A problem occurred while subscribing the user to FCM: {$errorInfo}","token-subscribe-no-token":"FCM returned no token when subscribing the user to push.","token-unsubscribe-failed":"A problem occurred while unsubscribing the user from FCM: {$errorInfo}","token-update-failed":"A problem occurred while updating the user from FCM: {$errorInfo}","token-update-no-token":"FCM returned no token when updating the user to push.","use-sw-after-get-token":"The useServiceWorker() method may only be called once and must be called before calling getToken() to ensure your service worker is used.","invalid-sw-registration":"The input to useServiceWorker() must be a ServiceWorkerRegistration.","invalid-bg-handler":"The input to setBackgroundMessageHandler() must be a function.","invalid-vapid-key":"The public VAPID key must be a string.","use-vapid-key-after-get-token":"The usePublicVapidKey() method may only be called once and must be called before calling getToken() to ensure your VAPID key is used."});async function Vt(e,t){const i={method:"DELETE",headers:await Wt(e)};try{const s=await fetch(`${$t(e.appConfig)}/${t}`,i),n=await s.json();if(n.error){const e=n.error.message;throw jt.create("token-unsubscribe-failed",{errorInfo:e})}}catch(e){throw jt.create("token-unsubscribe-failed",{errorInfo:null==e?void 0:e.toString()})}}function $t({projectId:e}){return`${wt}/projects/${e}/registrations`}async function Wt({appConfig:e,installations:t}){const i=await t.getToken();return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e.apiKey,"x-goog-firebase-installations-auth":`FIS ${i}`})}function Jt({p256dh:e,auth:t,endpoint:i,vapidKey:s}){const n={web:{endpoint:i,auth:t,p256dh:e}};return s!==St&&(n.web.applicationPubKey=s),n}const Ht=6048e5;async function Gt(e){const t=await async function(e,t){const i=await e.pushManager.getSubscription();if(i)return i;return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:_t(t)})}(e.swRegistration,e.vapidKey),i={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:t.endpoint,auth:Rt(t.getKey("auth")),p256dh:Rt(t.getKey("p256dh"))},s=await Ft(e.firebaseDependencies);if(s){if(function(e,t){const i=t.vapidKey===e.vapidKey,s=t.endpoint===e.endpoint,n=t.auth===e.auth,a=t.p256dh===e.p256dh;return i&&s&&n&&a}(s.subscriptionOptions,i))return Date.now()>=s.createTime+Ht?async function(e,t){try{const i=await async function(e,t){const i=await Wt(e),s=Jt(t.subscriptionOptions),n={method:"PATCH",headers:i,body:JSON.stringify(s)};let a;try{const i=await fetch(`${$t(e.appConfig)}/${t.token}`,n);a=await i.json()}catch(e){throw jt.create("token-update-failed",{errorInfo:null==e?void 0:e.toString()})}if(a.error){const e=a.error.message;throw jt.create("token-update-failed",{errorInfo:e})}if(!a.token)throw jt.create("token-update-no-token");return a.token}(e.firebaseDependencies,t),s=Object.assign(Object.assign({},t),{token:i,createTime:Date.now()});return await Bt(e.firebaseDependencies,s),i}catch(t){throw await zt(e),t}}(e,{token:s.token,createTime:Date.now(),subscriptionOptions:i}):s.token;try{await Vt(e.firebaseDependencies,s.token)}catch(e){console.warn(e)}return Zt(e.firebaseDependencies,i)}return Zt(e.firebaseDependencies,i)}async function zt(e){const t=await Ft(e.firebaseDependencies);t&&(await Vt(e.firebaseDependencies,t.token),await async function(e){const t=qt(e),i=(await Lt()).transaction(Ut,"readwrite");await i.objectStore(Ut).delete(t),await i.done}(e.firebaseDependencies));const i=await e.swRegistration.pushManager.getSubscription();return!i||i.unsubscribe()}async function Zt(e,t){const i=await async function(e,t){const i=await Wt(e),s=Jt(t),n={method:"POST",headers:i,body:JSON.stringify(s)};let a;try{const t=await fetch($t(e.appConfig),n);a=await t.json()}catch(e){throw jt.create("token-subscribe-failed",{errorInfo:null==e?void 0:e.toString()})}if(a.error){const e=a.error.message;throw jt.create("token-subscribe-failed",{errorInfo:e})}if(!a.token)throw jt.create("token-subscribe-no-token");return a.token}(e,t),s={token:i,createTime:Date.now(),subscriptionOptions:t};return await Bt(e,s),s.token}function Kt(e){const t={from:e.from,collapseKey:e.collapse_key,messageId:e.fcmMessageId};return function(e,t){if(!t.notification)return;e.notification={};const i=t.notification.title;i&&(e.notification.title=i);const s=t.notification.body;s&&(e.notification.body=s);const n=t.notification.image;n&&(e.notification.image=n);const a=t.notification.icon;a&&(e.notification.icon=a)}(t,e),function(e,t){if(!t.data)return;e.data=t.data}(t,e),function(e,t){var i,s,n,a,r;if(!t.fcmOptions&&!(null===(i=t.notification)||void 0===i?void 0:i.click_action))return;e.fcmOptions={};const o=null!==(n=null===(s=t.fcmOptions)||void 0===s?void 0:s.link)&&void 0!==n?n:null===(a=t.notification)||void 0===a?void 0:a.click_action;o&&(e.fcmOptions.link=o);const c=null===(r=t.fcmOptions)||void 0===r?void 0:r.analytics_label;c&&(e.fcmOptions.analyticsLabel=c)}(t,e),t}function Qt(e,t){const i=[];for(let s=0;s<e.length;s++)i.push(e.charAt(s)),s<t.length&&i.push(t.charAt(s));return i.join("")}function Xt(e){return jt.create("missing-app-config-values",{valueName:e})}Qt("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),Qt("AzSCbw63g1R0nCw85jG8","Iaya3yLKwmgvh7cF0q4");class Yt{constructor(e,t,i){this.deliveryMetricsExportedToBigQueryEnabled=!1,this.onBackgroundMessageHandler=null,this.onMessageHandler=null,this.logEvents=[],this.isLogServiceStarted=!1;const s=function(e){if(!e||!e.options)throw Xt("App Configuration Object");if(!e.name)throw Xt("App Name");const t=["projectId","apiKey","appId","messagingSenderId"],{options:i}=e;for(const e of t)if(!i[e])throw Xt(e);return{appName:e.name,projectId:i.projectId,apiKey:i.apiKey,appId:i.appId,senderId:i.messagingSenderId}}(e);this.firebaseDependencies={app:e,appConfig:s,installations:t,analyticsProvider:i}}_delete(){return Promise.resolve()}}async function ei(e){try{e.swRegistration=await navigator.serviceWorker.register(bt,{scope:yt}),e.swRegistration.update().catch((()=>{}))}catch(e){throw jt.create("failed-service-worker-registration",{browserErrorMessage:null==e?void 0:e.message})}}async function ti(e,t){if(!navigator)throw jt.create("only-available-in-window");if("default"===Notification.permission&&await Notification.requestPermission(),"granted"!==Notification.permission)throw jt.create("permission-blocked");return await async function(e,t){t?e.vapidKey=t:e.vapidKey||(e.vapidKey=St)}(e,null==t?void 0:t.vapidKey),await async function(e,t){if(t||e.swRegistration||await ei(e),t||!e.swRegistration){if(!(t instanceof ServiceWorkerRegistration))throw jt.create("invalid-sw-registration");e.swRegistration=t}}(e,null==t?void 0:t.serviceWorkerRegistration),Gt(e)}async function ii(e,t,i){const s=function(e){switch(e){case Mt.NOTIFICATION_CLICKED:return"notification_open";case Mt.PUSH_RECEIVED:return"notification_foreground";default:throw new Error}}(t);(await e.firebaseDependencies.analyticsProvider.get()).logEvent(s,{message_id:i[Ct],message_name:i[kt],message_time:i[Et],message_device_time:Math.floor(Date.now()/1e3)})}async function si(e,t){const i=t.data;if(!i.isFirebaseMessaging)return;e.onMessageHandler&&i.messageType===Mt.PUSH_RECEIVED&&("function"==typeof e.onMessageHandler?e.onMessageHandler(Kt(i)):e.onMessageHandler.next(Kt(i)));const s=i.data;var n;"object"==typeof(n=s)&&n&&Ct in n&&"1"===s[Tt]&&await ii(e,i.messageType,s)}const ni="@firebase/messaging",ai="0.12.4",ri=e=>{const t=e.getProvider("messaging").getImmediate();return{getToken:e=>ti(t,e)}};async function oi(){try{await g()}catch(e){return!1}return"undefined"!=typeof window&&m()&&!("undefined"==typeof navigator||!navigator.cookieEnabled)&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window&&"fetch"in window&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey")}function ci(e=function(e=te){const t=se.get(e);if(!t&&e===te)return de();if(!t)throw ce.create("no-app",{appName:e});return t}()){return oi().then((e=>{if(!e)throw jt.create("unsupported-browser")}),(e=>{throw jt.create("indexed-db-unsupported")})),oe(w(e),"messaging").getImmediate()}async function li(e,t){return ti(e=w(e),t)}function di(e){return async function(e){if(!navigator)throw jt.create("only-available-in-window");return e.swRegistration||await ei(e),zt(e)}(e=w(e))}function hi(e,t){return function(e,t){if(!navigator)throw jt.create("only-available-in-window");return e.onMessageHandler=t,()=>{e.onMessageHandler=null}}(e=w(e),t)}re(new C("messaging",(e=>{const t=new Yt(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return navigator.serviceWorker.addEventListener("message",(e=>si(t,e))),t}),"PUBLIC")),re(new C("messaging-internal",ri,"PRIVATE")),he(ni,ai),he(ni,ai,"esm2017");var ui=r(2506);class pi extends t().PureComponent{render(){return t().createElement("div",{className:"alert-container"},t().createElement("div",{className:"alert"},t().createElement("div",{className:"title"},this.props.title),t().createElement("div",{className:"content"},this.props.content),t().createElement("div",{className:"dialog-buttons"},this.props.onReject?t().createElement("button",{className:"outline",onClick:this.props.onReject},this.props.reject||t().createElement(s.FormattedMessage,{id:"button_cancel",defaultMessage:[{type:0,value:"Cancel"}]})):null,this.props.onConfirm?t().createElement("button",{className:"primary",onClick:this.props.onConfirm},this.props.confirm||t().createElement(s.FormattedMessage,{id:"button_ok",defaultMessage:[{type:0,value:"OK"}]})):null)))}}var mi=r(8962);const gi=(0,s.defineMessages)({info:{id:"menu_item_info",defaultMessage:[{type:0,value:"Info"}]},clear_messages:{id:"menu_item_clear_messages",defaultMessage:[{type:0,value:"Clear messages"}]},clear_for_all:{id:"menu_item_clear_messages_for_all",defaultMessage:[{type:0,value:"Clear for All"}]},delete:{id:"menu_item_delete",defaultMessage:[{type:0,value:"Delete"}]},delete_for_all:{id:"menu_item_delete_for_all",defaultMessage:[{type:0,value:"Delete for All"}]},send_retry:{id:"menu_item_send_retry",defaultMessage:[{type:0,value:"Retry"}]},mute:{id:"menu_item_mute",defaultMessage:[{type:0,value:"Mute"}]},unmute:{id:"menu_item_unmute",defaultMessage:[{type:0,value:"Unmute"}]},reply:{id:"menu_item_reply",defaultMessage:[{type:0,value:"Reply"}]},forward:{id:"menu_item_forward",defaultMessage:[{type:0,value:"Forward"}]},edit:{id:"menu_item_edit",defaultMessage:[{type:0,value:"Edit"}]},topic_delete:{id:"menu_item_delete_topic",defaultMessage:[{type:0,value:"Delete"}]},topic_delete_warning:{id:"topic_delete_warning",defaultMessage:[{type:0,value:"Are you sure you want to delete this conversation? It cannot be undone."}]},delete_messages_warning:{id:"delete_messages_warning",defaultMessage:[{type:0,value:"Are you sure you want to delete all messages for everyone? It cannot be undone."}]},unblock:{id:"menu_item_unblock",defaultMessage:[{type:0,value:"Unblock"}]},block:{id:"menu_item_block",defaultMessage:[{type:0,value:"Block"}]},topic_block_warning:{id:"topic_block_warning",defaultMessage:[{type:0,value:"Are you sure you want to block this conversation?"}]},member_delete:{id:"menu_item_member_delete",defaultMessage:[{type:0,value:"Remove"}]},archive:{id:"menu_item_archive_topic",defaultMessage:[{type:0,value:"Archive"}]},unarchive:{id:"menu_item_restore_topic",defaultMessage:[{type:0,value:"Restore"}]},edit_permissions:{id:"menu_item_edit_permissions",defaultMessage:[{type:0,value:"Edit permissions"}]},clear_messages_warning:{id:"clear_messages_warning",defaultMessage:[{type:0,value:"Are you sure you want to clear all messages? It cannot be undone."}]},pin_message:{id:"pin_message",defaultMessage:[{type:0,value:"Pin"}]},unpin_message:{id:"unpin_message",defaultMessage:[{type:0,value:"Unpin"}]}});class fi extends t().Component{constructor(e){super(e),this.selfRef=t().createRef();const{formatMessage:i}=e.intl;this.handlePageClick=this.handlePageClick.bind(this),this.handleEscapeKey=this.handleEscapeKey.bind(this),this.handleClick=this.handleClick.bind(this),this.MenuItems={topic_info:{id:"topic_info",title:i(gi.info),handler:null},messages_clear:{id:"messages_clear",title:i(gi.clear_messages),handler:(t,s)=>e.onShowAlert(i(gi.clear_messages),i(gi.clear_messages_warning),(e=>{this.deleteMessages(!0,!1,t,s)}),null,!0,null)},messages_clear_hard:{id:"messages_clear_hard",title:i(gi.clear_for_all),handler:(t,s)=>e.onShowAlert(i(gi.clear_for_all),i(gi.delete_messages_warning),(e=>this.deleteMessages(!0,!0,t,s)),null,!0,null)},message_delete:{id:"message_delete",title:i(gi.delete),handler:(e,t)=>this.deleteMessages(!1,!1,e,t)},message_delete_hard:{id:"message_delete_hard",title:i(gi.delete_for_all),handler:(e,t)=>this.deleteMessages(!1,!0,e,t)},menu_item_send_retry:{id:"menu_item_send_retry",title:i(gi.send_retry),handler:(e,t)=>this.retryMessage(e,t)},menu_item_reply:{id:"menu_item_reply",title:i(gi.reply),handler:(e,t)=>this.replyToMessage(e,t)},menu_item_forward:{id:"menu_item_forward",title:i(gi.forward),handler:e=>{}},menu_item_edit:{id:"menu_item_edit",title:i(gi.edit),handler:(e,t)=>this.editMessage(e,t)},menu_item_pin:{id:"menu_item_pin",title:i(gi.pin_message),handler:(e,t)=>this.pinMessage(!0,e,t)},menu_item_unpin:{id:"menu_item_unpin",title:i(gi.unpin_message),handler:(e,t)=>this.pinMessage(!1,e,t)},topic_unmute:{id:"topic_unmute",title:i(gi.unmute),handler:this.topicPermissionSetter.bind(this,"+P")},topic_mute:{id:"topic_mute",title:i(gi.mute),handler:this.topicPermissionSetter.bind(this,"-P")},topic_unblock:{id:"topic_unblock",title:i(gi.unblock),handler:this.topicPermissionSetter.bind(this,"+JP")},topic_block:{id:"topic_block",title:i(gi.block),handler:(t,s)=>e.onShowAlert(i(gi.block),i(gi.topic_block_warning),(e=>this.topicPermissionSetter("-JP",t,s).then((e=>(this.props.onTopicRemoved(t.topicName),e)))),null,!0,null)},topic_delete:{id:"topic_delete",title:i(gi.topic_delete),handler:(t,s)=>e.onShowAlert(i(gi.topic_delete),i(gi.topic_delete_warning),(e=>{const i=this.props.tinode.getTopic(t.topicName);if(i)return i.delTopic(!0).catch((e=>{s&&s(e.message,"err")}));console.warn("Topic not found: ",t.topicName)}),null,!0,null)},topic_archive:{id:"topic_archive",title:i(gi.archive),handler:(e,t)=>{const i=this.props.tinode.getTopic(e.topicName);if(i)return i.archive(!0).catch((e=>{t&&t(e.message,"err")}));console.warn("Topic not found: ",e.topicName)}},topic_restore:{id:"topic_restore",title:i(gi.unarchive),handler:(e,t)=>{const i=this.props.tinode.getTopic(e.topicName);if(i)return i.archive(!1).catch((e=>{t&&t(e.message,"err")}));console.warn("Topic not found: ",e.topicName)}},permissions:{id:"permissions",title:i(gi.edit_permissions),handler:null},member_delete:{id:"member_delete",title:i(gi.member_delete),handler:(e,t)=>{const i=this.props.tinode.getTopic(e.topicName);if(i&&e.user)return i.delSubscription(e.user).catch((e=>{t&&t(e.message,"err")}));console.warn("Topic or user not found: '"+e.topicName+"', '"+e.user+"'")}},member_mute:{id:"member_mute",title:i(gi.mute),handler:this.topicPermissionSetter.bind(this,"-P")},member_unmute:{id:"member_unmute",title:i(gi.unmute),handler:this.topicPermissionSetter.bind(this,"+P")},member_block:{id:"member_block",title:i(gi.block),handler:this.topicPermissionSetter.bind(this,"-JP")},member_unblock:{id:"member_unblock",title:i(gi.unblock),handler:this.topicPermissionSetter.bind(this,"+JP")}}}componentDidMount(){document.addEventListener("mousedown",this.handlePageClick,!1),document.addEventListener("keyup",this.handleEscapeKey,!1)}componentWillUnmount(){document.removeEventListener("mousedown",this.handlePageClick,!1),document.removeEventListener("keyup",this.handleEscapeKey,!1)}handlePageClick(e){this.selfRef.current.contains(e.target)||(e.preventDefault(),e.stopPropagation(),this.props.hide())}handleEscapeKey(e){27===e.keyCode&&this.props.hide()}handleClick(e){e.preventDefault(),e.stopPropagation(),this.props.hide();let t=this.props.items[e.currentTarget.dataset.id];"string"==typeof t&&(t=this.MenuItems[t]),t?this.props.onAction(t.id,t.handler(this.props.params,this.props.onError),this.props.params):console.error("Invalid menu item ID",e.currentTarget.dataset.id)}deleteMessages(e,t,i,s){const n=this.props.tinode.getTopic(i.topicName);if(!n)return void console.warn("Topic not found: ",i.topicName);if(!e&&n.cancelSend(i.seq))return;return(e?n.delMessagesAll(t):i.replace>0?n.delMessagesEdits(i.replace,t):n.delMessagesList([i.seq],t)).catch((e=>{s&&s(e.message,"err")}))}retryMessage(e,t){const i=this.props.tinode.getTopic(e.topicName);if(!i||!i.flushMessage(e.seq))return;const s=i.createMessage(e.content,!1);return i.publishDraft(s).catch((e=>{t&&t(e.message,"err")}))}pinMessage(e,t,i){const s=this.props.tinode.getTopic(t.topicName);s&&s.pinMessage(t.seq,e).catch((e=>i?i(e.message,"err"):null))}topicPermissionSetter(e,t,i){const s=this.props.tinode.getTopic(t.topicName);if(!s)return void console.warn("Topic not found",t.topicName);let n=s.updateMode(t.user,e);return i&&(n=n.catch((e=>i(e.message,"err")))),n}replyToMessage(e,t){e.pickReply(e.seq,e.content,e.userFrom,e.userName,t)}editMessage(e,t){e.editMessage(e.replace||e.seq,e.content,t)}render(){const e=[];let i=0;this.props.items.forEach((s=>{if("string"==typeof s&&(s=this.MenuItems[s]),s&&s.title){const n=s.disabled?"disabled":void 0;e.push("-"==s.title?t().createElement("li",{className:"separator",key:i}):t().createElement("li",{className:n,onClick:this.handleClick,"data-id":i,key:i},s.title))}i++}));const s=12*mi.o6,n=mi.o6*(.7+2.5*e.length),a={left:(this.props.bounds.right-this.props.clickAt.x<s?this.props.clickAt.x-this.props.bounds.left-s:this.props.clickAt.x-this.props.bounds.left)+"px",top:(this.props.bounds.bottom-this.props.clickAt.y<n?this.props.clickAt.y-this.props.bounds.top-n:this.props.clickAt.y-this.props.bounds.top)+"px"};return t().createElement("ul",{className:"menu",style:a,ref:this.selfRef},e)}}const vi=(0,s.injectIntl)(fi),bi={muted:"notifications_off",banned:"block",staff:"verified_user"};class yi extends t().PureComponent{render(){let e=null;return this.props.badges&&this.props.badges.length>0?(e=[],this.props.badges.forEach((i=>{const s=i.color?" "+i.color:"";i.icon?e.push(t().createElement("i",{className:"material-icons as-badge"+s,key:i.key||i.icon},bi[i.icon]||i.icon)):e.push(t().createElement("span",{className:"badge"+s,key:i.key||i.name},i.name))})),t().createElement(t().Fragment,null,e)):null}}var Si=r(1887);class wi extends t().PureComponent{render(){return this.props.count>0?t().createElement("span",{className:"unread"},this.props.count>9?"9+":this.props.count):null}}var Ci=r(4861),ki=r(3905);class Ei extends t().PureComponent{render(){const e=this.props.vc?"video_call":"call",i=["busy","declined","disconnected","missed"].includes(this.props.callState),n="material-icons medium "+(i?"red":"green"),a=this.props.incoming?i?"call_missed":"call_received":i?"call_missed_outgoing":"call_made",r=this.props.vc?t().createElement(s.FormattedMessage,{id:"calls_conference",defaultMessage:[{type:0,value:"Conference call"}]}):this.props.incoming?t().createElement(s.FormattedMessage,{id:"calls_incoming",defaultMessage:[{type:0,value:"Incoming call"}]}):t().createElement(s.FormattedMessage,{id:"calls_outgoing",defaultMessage:[{type:0,value:"Outgoing call"}]});let o;if(i)switch(this.props.callState){case"busy":o=t().createElement(s.FormattedMessage,{id:"call_busy",defaultMessage:[{type:0,value:"busy"}]});break;case"declined":o=t().createElement(s.FormattedMessage,{id:"call_declined",defaultMessage:[{type:0,value:"declined"}]});break;case"missed":o=this.props.incoming?t().createElement(s.FormattedMessage,{id:"call_missed",defaultMessage:[{type:0,value:"missed"}]}):t().createElement(s.FormattedMessage,{id:"call_cancelled",defaultMessage:[{type:0,value:"cancelled"}]});break;default:o=t().createElement(s.FormattedMessage,{id:"call_disconnected",defaultMessage:[{type:0,value:"disconnected"}]})}else o=t().createElement("span",null,(0,ki.nH)(this.props.duration/1e3));const c=this.props.vc&&"started"==this.props.callState;return t().createElement("div",{className:"call-message"},t().createElement("div",null,t().createElement("i",{className:"material-icons big gray"},e)),t().createElement("div",{className:"flex-column narrow"},t().createElement("div",null,r),t().createElement("div",{className:"duration"},t().createElement("i",{className:n},a)," ",o),c?t().createElement("a",{onClick:this.props.onCallJoin},"Join"):null))}}class Ti extends t().PureComponent{render(){const e=["busy","declined","disconnected","missed"].includes(this.props.callState),i=this.props.incoming?e?"call_missed":"call_received":e?"call_missed_outgoing":"call_made";let n;if(e)switch(this.props.callState){case"busy":n=t().createElement(s.FormattedMessage,{id:"call_busy",defaultMessage:[{type:0,value:"busy"}]});break;case"declined":n=t().createElement(s.FormattedMessage,{id:"call_declined",defaultMessage:[{type:0,value:"declined"}]});break;case"missed":n=this.props.incoming?t().createElement(s.FormattedMessage,{id:"call_missed",defaultMessage:[{type:0,value:"missed"}]}):t().createElement(s.FormattedMessage,{id:"call_cancelled",defaultMessage:[{type:0,value:"cancelled"}]});break;default:n=t().createElement(s.FormattedMessage,{id:"call_disconnected",defaultMessage:[{type:0,value:"disconnected"}]})}else n=["accepted","started"].includes(this.props.callState)&&!this.props.duration?t().createElement(s.FormattedMessage,{id:"call_in_progress",defaultMessage:[{type:0,value:"in progress"}]}):t().createElement("span",null,(0,ki.nH)(this.props.duration/1e3));return t().createElement(t().Fragment,null,t().createElement("div",{className:"composed-material"},t().createElement("i",{className:"material-icons"},"call"),t().createElement("i",{className:"material-icons second"},i))," ",n)}}class Pi extends t().PureComponent{constructor(e){super(e),this.videoRef=t().createRef(),this.handleClick=this.handleClick.bind(this)}handleClick(e){this.props.onClick&&this.props.onClick(e)}render(){const e=(0,ki.nH)(this.props["data-duration"]/1e3),i="inline-video"+(this.props.onClick?" image-clickable":"");return t().createElement("div",{className:i},t().createElement("img",this.props),t().createElement("div",{className:"play-control"},this.props.onClick?t().createElement("i",{className:"material-icons white bigger"},"play_arrow"):t().createElement("img",{src:"img/broken_video.png",style:{filter:"invert(100%)"},width:"36",height:"36"})),e?t().createElement("div",{className:"duration"},e):null)}}class Mi extends t().PureComponent{constructor(e){super(e),this.state={src:this.props.isvideo?"img/blankvid.png":"img/blankimg.png",style:Object.assign({padding:"4px"},this.props.style),className:this.props.className,alt:this.props.alt,onClick:this.props.onClick}}componentDidMount(){this.props.whenDone.promise.then((e=>this.setState({src:e.src,style:{...this.state.style,padding:0}}))).catch((e=>this.setState({src:this.props.isvideo?"img/broken_video.png":"img/broken_image.png"})))}componentWillUnmount(){this.props.whenDone.cancel()}componentDidUpdate(e){e.whenDone!=this.props.whenDone&&(this.setState({src:this.props.isvideo?"img/blankvid.png":"img/blankimg.png",style:{...this.state.style,padding:"4px"}}),this.props.whenDone.promise.then((e=>this.setState({src:e.src,style:{...this.state.style,padding:0}}))).catch((e=>this.setState({src:this.props.isvideo?"img/broken_video.png":"img/broken_image.png"}))))}render(){return t().createElement("img",this.state)}}class Ri extends t().PureComponent{render(){return t().createElement("div",{className:"uploader"},t().createElement("div",null,t().createElement("span",{style:{width:100*this.props.progress+"%"}})),this.props.progress<.999?t().createElement("a",{href:"#",onClick:e=>{e.preventDefault(),this.props.onCancel()}},t().createElement("i",{className:"material-icons"},"close")," ",t().createElement(s.FormattedMessage,{id:"action_cancel",defaultMessage:[{type:0,value:"cancel"}]})):t().createElement(s.FormattedMessage,{id:"upload_finishing",defaultMessage:[{type:0,value:"finishing..."}]}))}}class _i extends t().PureComponent{constructor(e){super(e)}render(){return t().createElement("div",{className:"inline-image"},t().createElement("img",this.props),t().createElement("div",{className:"rounded-container"},t().createElement(Ri,{progress:this.props.progress,onCancel:this.props.onCancelUpload})))}}var Ni=r(8405),Di=r(3740);const Ii=(0,s.defineMessages)({drafty_form:{id:"drafty_form",defaultMessage:[{type:0,value:"Form:"}]},drafty_attachment:{id:"drafty_attachment",defaultMessage:[{type:0,value:"Attachment"}]},drafty_image:{id:"drafty_image",defaultMessage:[{type:0,value:"Picture"}]},drafty_video:{id:"drafty_video",defaultMessage:[{type:0,value:"Video recording"}]},drafty_unknown:{id:"drafty_unknown",defaultMessage:[{type:0,value:"Unsupported"}]}});function Ai(e,i,s,n,a){if(a.includes("QQ"))return Bi.call(this,e,i,s,n);if(!e)return s;let r=ui.Drafty.tagName(e),o=ui.Drafty.attrValue(e,i)||{};switch(o.key=n,e){case"AU":o.src&&(o.src=this.authorizeURL((0,Di.Fv)(o.src,"audio")),o.duration=i.duration>0?0|i.duration:void 0,o.preview=i.preview,o.loading="lazy"),r=Ci.Z,s=null;break;case"BR":s=null;break;case"EX":case"RW":break;case"HL":o.className="highlight";break;case"HD":r=null,s=null;break;case"IM":r=Oi.call(this,r,i,o),s=null;break;case"BN":o.onClick=this.onFormButtonClick;let e=t().Children.map(s,(e=>"string"==typeof e?e:void 0));e&&0!=e.length||(e=[o.name]),o["data-title"]=e.join("");break;case"MN":o.className="mention",i&&(o.className+=" "+(0,ki.Cj)(i.val,!1,!0));break;case"FM":o.className="bot-form";break;case"QQ":o.className="reply-quote",o.onClick=this.onQuoteClick;break;case"VC":r=Ei,s=null,i&&(o.callState=i.state,o.incoming=i.incoming,o.duration=i.duration,o.vc=i.vc,o.onCallJoin=this.onCallJoin);break;case"VD":r=Ui.call(this,r,i,o),s=null;break;default:if(!r){r=t().Fragment,o={key:n};let e=s;Array.isArray(s)&&s.join("").trim()||(e=[t().createElement("span",{key:"x1",className:"gray"},this.formatMessage(Ii.drafty_unknown))]),s=[t().createElement("i",{key:"x0",className:"material-icons gray"},"extension")," "].concat(e)}}return r?t().createElement(r,o,s):s}function Oi(e,t,i){if(!t)return i.src="img/broken_image.png",i.style={width:mi.$_+"px",height:mi.$_+"px"},e;i.className="inline-image";const s=(0,Ni.rS)(t.width,t.height,this.viewportWidth>0?Math.min(this.viewportWidth-6.5*mi.o6,34.5*mi.o6):34.5*mi.o6,24*mi.o6,!1)||{dstWidth:mi.sA,dstHeight:mi.sA};return i.style={width:s.dstWidth+"px",height:s.dstHeight+"px",minWidth:s.dstWidth+"px",minHeight:s.dstHeight+"px"},ui.Drafty.isProcessing(t)?e=_i:(i.src=this.authorizeURL((0,Di.Fv)(i.src,"image")),i.alt=t.name,i.src?(Math.max(t.width||0,t.height||0)>mi.$_&&(i.onClick=this.onImagePreview,i.className+=" image-clickable"),i.loading="lazy"):i.src=null),e}function Ui(e,t,i){if(!t)return i.src="img/broken_video.png",i.style={width:mi.$_+"px",height:mi.$_+"px"},e;i.className="inline-image";const s=(0,Ni.rS)(t.width,t.height,this.viewportWidth>0?Math.min(this.viewportWidth-6.5*mi.o6,34.5*mi.o6):34.5*mi.o6,24*mi.o6,!1)||{dstWidth:mi.wO,dstHeight:mi.wO};return i.style={width:s.dstWidth+"px",height:s.dstHeight+"px",minWidth:s.dstWidth+"px",minHeight:s.dstHeight+"px"},ui.Drafty.isProcessing(t)?e=_i:(i.src=this.authorizeURL((0,Di.Fv)(i.src,"image")),i.alt=t.name,(t.ref||t.val)&&(i.onClick=this.onVideoPreview,i.loading="lazy"),e=Pi),e}function xi(e,i,s,n){if(!e)return s;let a=ui.Drafty.tagName(e);const r={key:n};switch(e){case"AU":a=t().Fragment,s=[t().createElement("i",{key:"au",className:"material-icons"},"mic")," ",(0,ki.nH)(i.duration/1e3)];break;case"BR":a=t().Fragment,s=[" "];break;case"HL":r.className="highlight preview";break;case"LN":case"MN":a="span";break;case"IM":a=t().Fragment,s=[t().createElement("i",{key:"im",className:"material-icons"},"photo")," ",this.formatMessage(Ii.drafty_image)];break;case"BN":a="span",r.className="flat-button faux";break;case"FM":a=t().Fragment,s=[t().createElement("i",{key:"fm",className:"material-icons"},"dashboard"),this.formatMessage(Ii.drafty_form)].concat(" ",s||[]);break;case"RW":a=t().Fragment;break;case"EX":if(i){if("application/json"==i.mime)return null;delete i.val,delete i.ref}a=t().Fragment,s=[t().createElement("i",{key:"ex",className:"material-icons"},"attachment")," ",this.formatMessage(Ii.drafty_attachment)];break;case"VC":a=Ti,i&&(r.callState=i.state,r.incoming=i.incoming,r.duration=i.duration),s=null;break;case"QQ":case"HD":a=null,s=null;break;case"VD":a=t().Fragment,s=[t().createElement("i",{key:"im",className:"material-icons"},"play_circle_outline")," ",this.formatMessage(Ii.drafty_video)];break;default:a||(a=t().Fragment,s=[t().createElement("i",{key:"x0",className:"material-icons gray"},"extension")," ",this.formatMessage(Ii.drafty_unknown)])}return a?t().createElement(a,r,s):s}function Li(e,t){return e.style={width:mi.$_+"px",height:mi.$_+"px",maxWidth:mi.$_+"px",maxHeight:mi.$_+"px"},e.className="inline-image",e.alt=this.formatMessage(Ii.drafty_image),e.src=t&&e.src||"img/broken_image.png",e.title=e.alt,e}function Fi(e,t){const i=(0,Ni.rS)(t.width,t.height,mi.Zd,mi.$_);return e.style={width:i.width+"px",height:i.height+"px",maxWidth:mi.Zd+"px",maxHeight:mi.$_+"px"},e.className="inline-image",e.alt=this.formatMessage(Ii.drafty_video),e.title=e.alt,e.src=t&&e.src||"img/broken_video.png",e}function Bi(e,i,s,n){if(["BR","EX","IM","MN","VD"].includes(e)){let a=ui.Drafty.tagName(e),r=ui.Drafty.attrValue(e,i)||{};switch(r.key=n,e){case"BR":s=null;break;case"IM":r=Li.call(this,r,i),s=[t().createElement("img",r,null)," ",r.alt],a=t().Fragment,r={key:n};break;case"VD":r=Fi.call(this,r,i),s=[t().createElement("img",r,null)," ",r.alt],a=t().Fragment,r={key:n};break;case"MN":a="span",r.className="mention",i&&(r.className+=" "+(0,ki.Cj)(i.val,!1,!0));break;case"EX":let e;if(i){if("application/json"==i.mime)return null;e=i.name,delete i.val,delete i.ref}a=t().Fragment,s=[t().createElement("i",{key:"ex",className:"material-icons"},"attachment"),(0,ki.TX)(e,16)||this.formatMessage(Ii.drafty_attachment)]}return t().createElement(a,r,s)}return xi.call(this,e,i,s,n)}function qi(e,t){let i,s,n,a;if(t?(s=e.preview,a=e.premime||"image/jpeg",n=e.preref):(s=e.val,a=e.mime,n=e.ref),s){const e=(0,Ni.Jr)(s,a);if(!e)throw new Error("Invalid image");i=Promise.resolve(e)}else{if(!n)throw new Error("Missing image data");i=fetch(this.authorizeURL((0,Di.Fv)(n,"image"))).then((e=>{if(e.ok)return e.blob();throw new Error(`Image fetch unsuccessful: ${e.status} ${e.statusText}`)}))}return i.then((e=>(0,Ni.EA)(e,t?mi.Zd:mi.$_,mi.$_,-1,!t))).then((i=>(t?e.premime=i.mime:e.mime=i.mime,e.size=i.blob.size,e.width=i.width,e.height=i.height,delete e.ref,delete e.preref,e.src=URL.createObjectURL(i.blob),(0,Ni.w8)(i.blob)))).then((i=>(t?e.preview=i.bits:e.val=i.bits,e))).catch((t=>{throw delete e.val,delete e.preview,delete e.src,e.width=mi.$_,e.height=mi.$_,t}))}function ji(e,i,s,n,a){if("IM"==e||"VD"==e){const a="IM"==e?Li.call(this,{key:n},i):Fi.call(this,{key:n},i);let r;try{r=(0,Di.Oi)(qi.call(this,i,"VD"==e))}catch(e){console.warn("Failed to quote image:",e.message),r=(0,Di.Oi)(e)}return a.whenDone=r,s=[t().createElement(Mi,a,null)," ",a.alt],t().createElement(t().Fragment,{key:n},s)}if("QQ"==e){if(a.includes("QQ"))return t().createElement("span",{key:n},[t().createElement("i",{key:"qq",className:"material-icons"},"format_quote")," "]);const e=ui.Drafty.attrValue("QQ",i)||{};return e.key=n,e.className="reply-quote",t().createElement(ui.Drafty.tagName("QQ"),e,s)}return Bi.call(this,e,i,s,n)}class Vi extends t().Component{constructor(e){super(e),this.handleClick=this.handleClick.bind(this),this.handleContextClick=this.handleContextClick.bind(this)}handleClick(e){e.preventDefault(),e.stopPropagation(),this.props.onSelected&&this.props.onSelected(this.props.item,this.props.index)}handleContextClick(e){e.preventDefault(),e.stopPropagation(),this.props.showContextMenu({topicName:this.props.item,y:e.pageY,x:e.pageX})}render(){let e=this.props.title;e?e.length>30&&(e=e.substring(0,28)+"…"):e=t().createElement("i",null,t().createElement(s.FormattedMessage,{id:"unnamed_topic",defaultMessage:[{type:0,value:"Unnamed"}]}));const i=this.props.now?"online":"offline",n=!this.props.avatar||this.props.avatar,a=this.props.badges?this.props.badges.slice():[],r=[];let o;this.props.isVerified&&r.push({icon:"verified",color:"verified-color"}),this.props.isStaff&&r.push({icon:"staff",color:"staff-color"}),this.props.isDangerous&&r.push({icon:"dangerous",color:"danger-color"}),this.props.acs&&(this.props.showMode&&a.push({name:this.props.acs.getMode(),key:"mode"}),this.props.acs.isMuted()&&r.push({icon:"muted"}),this.props.acs.isJoiner()||r.push({icon:"banned"})),"string"==typeof this.props.preview?o=this.props.preview:ui.Drafty.isValid(this.props.preview)?o=t().createElement(t().Fragment,null,ui.Drafty.format(this.props.preview,xi,{formatMessage:this.props.intl.formatMessage,previewIsResponse:this.props.previewIsResponse})):this.props.preview&&(o=t().createElement(t().Fragment,null,t().createElement("i",{className:"material-icons gray"},"warning_amber")," ",t().createElement("i",{className:"gray"},t().createElement(s.FormattedMessage,{id:"invalid_content",defaultMessage:[{type:0,value:"invalid content"}]}))));const c=(0,Di.es)(this.props.received),l=c?t().createElement("i",{className:"material-icons small space-right"+(c.color?" "+c.color:"")},c.name):null,d="contact-title"+(this.props.deleted?" deleted":"");return t().createElement("li",{className:!this.props.showCheckmark&&this.props.selected?"selected":null,onClick:this.handleClick},t().createElement("div",{className:"avatar-box"},t().createElement(Si.Z,{tinode:this.props.tinode,avatar:n,title:this.props.title,topic:this.props.item,deleted:this.props.deleted}),this.props.deleted?t().createElement("i",{className:"deleted material-icons"},"cancel"):this.props.showOnline?t().createElement("span",{className:i}):this.props.showCheckmark&&this.props.selected?t().createElement("i",{className:"checkmark material-icons"},"check_circle"):null),t().createElement("div",{className:"text-box"},t().createElement("div",null,t().createElement("span",{className:d},e),this.props.isGroup?t().createElement("i",{className:"material-icons as-badge"},"group"):null,this.props.isChannel?t().createElement("img",{src:"/img/channel.png",className:"channel",alt:"channel"}):null,t().createElement(yi,{badges:r}),this.props.deleted?null:t().createElement(wi,{count:this.props.unread})),this.props.showMode?t().createElement("span",null,t().createElement(yi,{badges:a})):this.props.small?null:t().createElement("div",{className:"contact-comment"},l,t().createElement("span",null,o||this.props.comment||" "))),this.props.showContextMenu?t().createElement("span",{className:"menuTrigger"},t().createElement("a",{href:"#",onClick:this.handleContextClick},t().createElement("i",{className:"material-icons"},"expand_more"))):null)}}const $i=(0,s.injectIntl)(Vi);class Wi extends t().PureComponent{constructor(e){super(e),this.handleClick=this.handleClick.bind(this)}handleClick(e){e.preventDefault(),e.stopPropagation(),this.props.onAction(this.props.action)}render(){const{formatMessage:e}=this.props.intl;return t().createElement("li",{onClick:this.handleClick,className:"action"},t().createElement("div",{className:"action-text"},e(this.props.title,this.props.values)))}}const Ji=(0,s.injectIntl)(Wi),Hi=(0,s.defineMessages)({badge_you:{id:"badge_you",defaultMessage:[{type:0,value:"you"}]},badge_owner:{id:"badge_owner",defaultMessage:[{type:0,value:"owner"}]}});class Gi extends t().Component{render(){const{formatMessage:e}=this.props.intl,i=Array.isArray(this.props.topicSelected),s=[];let n=0;return this.props.contacts&&this.props.contacts.length>0&&this.props.contacts.forEach((a=>{if(a.action)s.push(t().createElement(Ji,{title:a.title,action:a.action,values:a.values,key:a.action,onAction:this.props.onAction}));else{const r=this.props.showMode?a.user:a.topic||a.user;if(this.props.filterFunc&&this.props.filter){const e=[r];if(a.private&&a.private.comment&&e.push((""+a.private.comment).toLowerCase()),a.public&&a.public.fn&&e.push((""+a.public.fn).toLowerCase()),!this.props.filterFunc(this.props.filter,e))return}const o=ui.Tinode.isChannelTopicName(r),c=!o&&ui.Tinode.isGroupTopicName(r),l=i?this.props.topicSelected.indexOf(r)>-1:this.props.topicSelected===r,d=[];this.props.showMode&&(r==this.props.myUserId&&d.push({name:e(Hi.badge_you),color:"green"}),a.acs&&a.acs.isOwner()&&d.push({name:e(Hi.badge_owner),color:"blue"}));const h=Array.isArray(a.private)?a.private.join(","):a.private?a.private.comment:null;let u,p,m,g;if(!this.props.showMode&&a.latestMessage){const e=a.latestMessage();e&&(p=e.head?e.head.forwarded:null,g=e._status||a.msgStatus(e,!0),m=e.from!=this.props.myUserId,e.content&&(u="string"==typeof e.content?e.content.substr(0,mi.rV):ui.Drafty.preview(e.content,mi.rV)))}s.push(t().createElement($i,{tinode:this.props.tinode,title:a.public?a.public.fn:null,avatar:(0,Ni.PD)(a.public?a.public.photo:null),comment:h,preview:u,previewIsResponse:m,forwarded:p,received:g,unread:this.props.showUnread?a.unread:0,now:a.online&&this.props.connected,acs:a.acs,showMode:this.props.showMode,badges:d,showCheckmark:i,selected:l,showOnline:this.props.showOnline&&!o,isChannel:o,isGroup:c,showContextMenu:this.props.showContextMenu,isVerified:a.trusted&&a.trusted.verified,isStaff:a.trusted&&a.trusted.staff,isDangerous:a.trusted&&a.trusted.danger,deleted:a._deleted,onSelected:this.props.onTopicSelected,item:r,index:s.length,key:r})),n++}}),this),t().createElement("div",{className:this.props.noScroll?null:"scrollable-panel"},0==n?t().createElement("div",{className:"center-medium-text",dangerouslySetInnerHTML:{__html:this.props.emptyListMessage}}):null,s.length>0?t().createElement("ul",{className:"contact-box"},s):null)}}const zi=(0,s.injectIntl)(Gi);class Zi extends t().PureComponent{constructor(e){super(e),this.state={edited:!1,search:""},this.handleSearchChange=this.handleSearchChange.bind(this),this.handleSearch=this.handleSearch.bind(this),this.handleClear=this.handleClear.bind(this),this.handleKeyDown=this.handleKeyDown.bind(this)}componentWillUnmount(){this.state.edited&&(this.setState({search:"",edited:!1}),this.props.onSearchContacts(ui.Tinode.DEL_CHAR))}handleSearchChange(e){this.setState({search:e.target.value})}handleSearch(e){e.preventDefault();const t=this.state.search.trim();this.setState({edited:t.length>0}),this.props.onSearchContacts(t.length>0?t:ui.Tinode.DEL_CHAR)}handleClear(e){e.preventDefault(),this.state.edited&&this.props.onSearchContacts(ui.Tinode.DEL_CHAR),this.setState({search:"",edited:!1})}handleKeyDown(e){"Enter"===e.key?this.handleSearch(e):"Escape"===e.key&&this.handleClear()}render(){return t().createElement("div",{className:"panel-form"},t().createElement("div",{className:"panel-form-row"},t().createElement("i",{className:"material-icons search"},"search"),t().createElement("input",{className:"search",type:"text",placeholder:this.props.placeholder,value:this.state.search,onChange:this.handleSearchChange,onKeyDown:this.handleKeyDown,required:!0,autoFocus:!0}),this.state.search?t().createElement("a",{href:"#",onClick:this.handleClear},t().createElement("i",{className:"material-icons"},"highlight_off")):t().createElement("span",null,t().createElement("i",{className:"material-icons"}," "))))}}class Ki extends t().Component{constructor(e){super(e),this.state={query:null},this.handleEscapeKey=this.handleEscapeKey.bind(this),this.handleClose=this.handleClose.bind(this),this.handleSearchContacts=this.handleSearchContacts.bind(this),this.handleContactSelected=this.handleContactSelected.bind(this)}componentDidMount(){this.props.onInitFind()}handleEscapeKey(e){27===e.keyCode&&this.props.hide(!1)}handleClose(e){e.preventDefault(),this.props.hide(!1)}handleSearchContacts(e){this.setState({query:ui.Tinode.isNullValue(e)?null:e}),this.props.onSearchContacts(e)}handleContactSelected(e){this.props.onTopicSelected(e),this.props.hide(!0)}render(){let e=null!=this.state.query?this.props.searchResults:this.props.contacts;return e=e.filter((e=>e.name!=this.props.topicSelected&&e.acs.isJoiner()&&e.acs.isWriter())),t().createElement("div",{className:"alert-container"},t().createElement("div",{className:"forward-dialog"},t().createElement("div",{className:"title with-control"},t().createElement("div",null,t().createElement(s.FormattedMessage,{id:"forward_to",defaultMessage:[{type:0,value:"Forward to"}],desription:"Title of the contact selector dialog when forwarding a message"})),t().createElement("div",null,t().createElement("a",{href:"#",onClick:this.handleClose},t().createElement("i",{className:"material-icons"},"close")))),t().createElement(s.FormattedMessage,{id:"forward_to_search_placeholder",defaultMessage:[{type:0,value:"Search contacts"}]},(e=>t().createElement(Zi,{placeholder:e,onSearchContacts:this.handleSearchContacts}))),t().createElement(s.FormattedMessage,{id:"search_no_results",defaultMessage:[{type:0,value:"Search returned no results"}]},(i=>t().createElement(zi,{tinode:this.props.tinode,contacts:e,myUserId:this.props.myUserId,emptyListMessage:i,showOnline:!1,showUnread:!1,showContextMenu:!1,onTopicSelected:this.handleContactSelected})))))}}var Qi=r(955);const Xi=1,Yi=3,es="started",ts=new Audio("audio/call-in.m4a");class is extends t().Component{constructor(e){super(e),this.state={topic:null,fullName:void 0,avatar:null,trustedBadges:[],previousMetaDesc:void 0},this.resetDesc=this.resetDesc.bind(this),this.onMetaDesc=this.onMetaDesc.bind(this),this.handleRejectCall=this.handleRejectCall.bind(this),this.handleAcceptCall=this.handleAcceptCall.bind(this),this.ringTimer=null}componentDidMount(){const e=this.props.tinode.getTopic(this.props.topic);e&&(this.resetDesc(e),2==this.props.callState&&(ts.play().catch((e=>{})),this.ringTimer=setInterval((e=>{ts.play().catch((e=>{}))}),2e3),this.props.onRinging(this.props.topic,this.props.seq)))}componentDidUpdate(e){const t=this.props.tinode.getTopic(e.topic);t&&(this.onMetaDesc!=t.onMetaDesc&&(this.previousMetaDesc=t.onMetaDesc,t.onMetaDesc=this.onMetaDesc),this.state.topic!=e.topic&&(this.setState({topic:e.topic}),this.resetDesc(t,e)))}componentWillUnmount(){null!=this.ringTimer&&(clearInterval(this.ringTimer),ts.pause());const e=this.props.tinode.getTopic(this.props.topic);e&&(this.setState({topic:null}),e.onMetaDesc=this.previousMetaDesc)}resetDesc(e){const t=[];if(e.trusted)for(const[i,s]of Object.entries(e.trusted))s&&t.push(i);this.setState({fullName:(0,Di.Th)(e.public?e.public.fn:void 0,mi.S8),avatar:(0,Ni.PD)(e.public?e.public.photo:null),trustedBadges:t})}onMetaDesc(e){const t=this.props.tinode.getTopic(this.props.topic);t&&(this.resetDesc(t),this.previousMetaDesc&&this.previousMetaDesc!=this.onMetaDesc&&this.previousMetaDesc(e))}handleAcceptCall(){this.props.onAcceptCall(this.props.topic)}handleRejectCall(){this.props.onReject(this.props.topic,this.props.seq),this.props.onClose()}render(){return t().createElement("div",{className:"alert-container"},t().createElement("div",{className:"incoming-call"},t().createElement("div",{className:"caller-card incoming pulse"},t().createElement("div",{className:"avatar-box"},t().createElement(Si.Z,{tinode:this.props.tinode,avatar:this.state.avatar||!0,topic:this.props.topic,title:this.state.fullName})),t().createElement("div",{className:"caller-name"},(0,Di.Th)(this.state.fullName,mi.gD),t().createElement(Qi.Z,{short:!0,trustedBadges:this.state.trustedBadges}))),t().createElement("div",{className:"controls"},2==this.props.callState?t().createElement(t().Fragment,null,t().createElement("button",{className:"danger",onClick:this.handleRejectCall},t().createElement("i",{className:"material-icons"},"call_end")),t().createElement("button",{className:"positive",onClick:this.handleAcceptCall},t().createElement("i",{className:"material-icons"},"call"))):null)))}}var ss=r(7432),ns=r(2323);class as extends t().PureComponent{render(){return t().createElement("a",{href:"#",onClick:e=>{e.preventDefault(),this.props.onCancel()}},t().createElement("i",{className:"material-icons"},"close"))}}class rs extends t().PureComponent{constructor(e){super(e),this.state={show:!1},this.hide=this.hide.bind(this)}componentDidUpdate(e){e.level!==this.props.level&&this.setState({show:!!this.props.level})}hide(){this.setState({show:!1}),this.props.onClearError&&this.props.onClearError()}render(){const e={err:"error",warn:"warning",info:"info"}[this.props.level]||"",i="info-box "+e;return t().createElement("div",{className:i},t().createElement("div",{className:"icon"},t().createElement("i",{className:"material-icons"},e)),t().createElement("span",null,this.props.text,this.props.action?t().createElement(t().Fragment,null,"  ",t().createElement("a",{href:"#",style:{whiteSpace:"nowrap"},onClick:e=>{e.preventDefault(),this.props.action()}},this.props.actionText)):null),t().createElement("div",{className:"cancel"},t().createElement(as,{onCancel:this.hide})))}}class os extends t().PureComponent{constructor(e){super(e),this.handleCancel=this.handleCancel.bind(this)}handleCancel(e){e.preventDefault(),this.props.onCancel(this.props.topic,this.props.index)}render(){const e=this.props.title||this.props.topic,i=this.props.invalid?"chip invalid":"chip";return t().createElement("div",{className:i},this.props.noAvatar?t().createElement("span",{className:"spacer"}):t().createElement("div",{className:"avatar-box"},t().createElement(Si.Z,{tinode:this.props.tinode,avatar:this.props.avatar||!0,topic:this.props.topic,title:this.props.title})),t().createElement("span",null,e),this.props.onCancel&&!this.props.required?t().createElement("a",{href:"#",onClick:this.handleCancel},"×"):t().createElement("span",{className:"spacer"}))}}class cs extends t().Component{constructor(e){super(e),this.state=cs.deriveStateFromProps(e),this.state.input="",this.state.focused=!1,this.handleTextInput=this.handleTextInput.bind(this),this.removeChipAt=this.removeChipAt.bind(this),this.handleChipCancel=this.handleChipCancel.bind(this),this.handleFocusGained=this.handleFocusGained.bind(this),this.handleFocusLost=this.handleFocusLost.bind(this),this.handleKeyDown=this.handleKeyDown.bind(this)}static deriveStateFromProps(e){return{placeholder:e.chips?"":e.prompt,sortedChips:cs.sortChips(e.chips,e.staticMembers),chipIndex:cs.indexChips(e.chips)}}componentDidUpdate(e,t){e.chips==this.props.chips&&e.staticMembers==this.props.staticMembers&&e.prompt==this.props.prompt||this.setState(cs.deriveStateFromProps(this.props)),(!t||this.props.chips.length>t.sortedChips.length)&&this.setState({input:""})}static indexChips(e){const t={};let i=0;return e.forEach((e=>{t[e.user]=i,i++})),t}static sortChips(e,t){const i=[],s=[];return e.forEach((e=>{t&&t.includes(e.user)?i.push(e):s.push(e)})),i.concat(s)}handleTextInput(e){this.setState({input:e.target.value}),this.props.filterFunc&&this.props.filterFunc(e.target.value)}removeChipAt(e){const t=this.state.sortedChips[e];this.props.onChipRemoved(t.user,this.state.chipIndex[t.user])}handleChipCancel(e,t){this.removeChipAt(t)}handleFocusGained(){this.setState({focused:!0})}handleFocusLost(){this.setState({focused:!1}),this.props.onFocusLost&&this.props.onFocusLost(this.state.input)}handleKeyDown(e){if("Backspace"===e.key){if(0==this.state.input.length&&this.state.sortedChips.length>0){const e=this.state.sortedChips.length-1;this.state.sortedChips[e].user!==this.props.staticMembers&&this.removeChipAt(e)}}else"Enter"===e.key?this.props.onEnter&&this.props.onEnter(this.state.input):"Escape"===e.key&&this.props.onCancel&&this.props.onCancel()}render(){const e=[];let i=0;const s=this.props.staticMembers||[];this.state.sortedChips.forEach((n=>{e.push(t().createElement(os,{tinode:this.props.tinode,onCancel:this.handleChipCancel,avatar:(0,Ni.PD)(n.public?n.public.photo:null),title:n.public?n.public.fn:void 0,noAvatar:this.props.avatarDisabled,topic:n.user,required:s.includes(n.user),invalid:n.invalid,index:i,key:n.user})),i++}));const n="chip-input"+(this.state.focused?" focused":""),a=!(this.props.tabIndex>0);return t().createElement("div",{className:n},e,t().createElement("input",{type:"text",placeholder:this.state.placeholder,onChange:this.handleTextInput,onFocus:this.handleFocusGained,onBlur:this.handleFocusLost,onKeyDown:this.handleKeyDown,value:this.state.input,tabIndex:this.props.tabIndex,autoFocus:a}))}}const ls=(0,s.defineMessages)({no_contacts:{id:"no_contacts",defaultMessage:[{type:0,value:"You have no contacts :-("}]},contacts_not_found_short:{id:"contacts_not_found_short",defaultMessage:[{type:0,value:"No contacts match '"},{type:1,value:"query"},{type:0,value:"'"}]}});class ds extends t().Component{constructor(e){super(e),this.state={members:e.members,index:ds.indexMembers(e.members),staticMembers:ds.staticMembers(e.members,e.keepInitialMembers,e.requiredMember),contactFilter:"",noContactsMessage:e.intl.formatMessage(ls.no_contacts),selectedContacts:ds.selectedContacts(e.members)},this.handleContactSelected=this.handleContactSelected.bind(this),this.handleMemberRemoved=this.handleMemberRemoved.bind(this),this.handleContactFilter=this.handleContactFilter.bind(this),this.handleSubmit=this.handleSubmit.bind(this),this.handleCancel=this.handleCancel.bind(this)}static indexMembers(e){let t={};return e.forEach((e=>{t[e.user]={delta:0,present:!0}})),t}static staticMembers(e,t,i){let s=[];return e.forEach((e=>{(t||e.user==i)&&s.push(e.user)})),s}static selectedContacts(e){let t=[];return e.forEach((e=>{t.push(e.user)})),t}handleContactSelected(e,t){let i=this.state.index[e];if(i){if(i.present)return;i.delta+=1,i.present=!0}else i={delta:1,present:!0};let s=this.state.members.slice();s.push(this.props.contacts[t]);const n=ds.selectedContacts(s),a=this.state.index;a[e]=i,this.setState({members:s,index:a,selectedContacts:n})}handleMemberRemoved(e,t){const i=this.state.index[e];if(!i||!i.present)return;i.present=!1,i.delta-=1;let s=this.state.members.slice();s.splice(t,1);const n=ds.selectedContacts(s),a=this.state.index;a[e]=i,this.setState({members:s,index:a,selectedContacts:n})}handleContactFilter(e){const{formatMessage:t}=this.props.intl,i=e?t(ls.contacts_not_found_short,{query:e}):t(ls.no_contacts);this.setState({contactFilter:e,noContactsMessage:i})}static doContactFiltering(e,t){if(e){for(let i=0;i<t.length;i++)if(t[i].indexOf(e)>=0)return!0;return!1}return!0}handleSubmit(){const e=[],t=[],i=[];Object.keys(this.state.index).forEach((s=>{this.state.index[s].present&&e.push(s),this.state.index[s].delta>0?t.push(s):this.state.index[s].delta<0&&i.push(s)})),this.props.onSubmit(e,t,i)}handleCancel(){this.props.onCancel()}render(){return t().createElement("div",{id:"group-manager"},t().createElement("div",{className:"panel-form-row"},t().createElement("label",{className:"small"},t().createElement(s.FormattedMessage,{id:"title_group_members",defaultMessage:[{type:0,value:"Group Members"}]}))),t().createElement("div",{className:"panel-form-row"},t().createElement(cs,{tinode:this.props.tinode,chips:this.state.members,staticMembers:this.state.staticMembers,prompt:"add members",filterFunc:this.handleContactFilter,onChipRemoved:this.handleMemberRemoved})),t().createElement("div",{className:"panel-form-row"},t().createElement("label",{className:"small"},t().createElement(s.FormattedMessage,{id:"title_all_contacts",defaultMessage:[{type:0,value:"All Contacts"}]}))),t().createElement(zi,{tinode:this.props.tinode,contacts:this.props.contacts,myUserId:this.props.myUserId,topicSelected:this.state.selectedContacts,filter:this.state.contactFilter,filterFunc:ds.doContactFiltering,emptyListMessage:this.state.noContactsMessage,showOnline:!1,showUnread:!1,onTopicSelected:this.handleContactSelected}),t().createElement("div",{id:"group-manager-buttons",className:"panel-form-row"},t().createElement("button",{className:"secondary",onClick:this.handleCancel},t().createElement(s.FormattedMessage,{id:"button_cancel",defaultMessage:[{type:0,value:"Cancel"}]})),t().createElement("button",{className:"primary",onClick:this.handleSubmit},t().createElement(s.FormattedMessage,{id:"button_ok",defaultMessage:[{type:0,value:"OK"}]}))))}}const hs=(0,s.injectIntl)(ds),us=(0,s.defineMessages)({joiner:{id:"permission_join",defaultMessage:[{type:0,value:"Join ("},{type:1,value:"val"},{type:0,value:")"}]},reader:{id:"permission_read",defaultMessage:[{type:0,value:"Read ("},{type:1,value:"val"},{type:0,value:")"}]},writer:{id:"permission_write",defaultMessage:[{type:0,value:"Write ("},{type:1,value:"val"},{type:0,value:")"}]},preser:{id:"permission_pres",defaultMessage:[{type:0,value:"Get notified ("},{type:1,value:"val"},{type:0,value:")"}]},approver:{id:"permission_admin",defaultMessage:[{type:0,value:"Approve ("},{type:1,value:"val"},{type:0,value:")"}]},sharer:{id:"permission_share",defaultMessage:[{type:0,value:"Share ("},{type:1,value:"val"},{type:0,value:")"}]},deleter:{id:"permission_delete",defaultMessage:[{type:0,value:"Delete ("},{type:1,value:"val"},{type:0,value:")"}]},owner:{id:"permission_owner",defaultMessage:[{type:0,value:"Owner ("},{type:1,value:"val"},{type:0,value:")"}]}});class ps extends t().Component{constructor(e){super(e),this.state={mode:(e.mode||"").replace("N","")},this.handleChange=this.handleChange.bind(this),this.handleSubmit=this.handleSubmit.bind(this),this.handleCancel=this.handleCancel.bind(this)}handleChange(e){let t=this.state.mode;-1==t.indexOf(e)?t+=e:t=t.replace(e,""),this.setState({mode:t})}handleSubmit(){const e=(this.state.mode||"N").split("").sort().join("");e!==(this.props.mode||"N").split("").sort().join("")?this.props.onSubmit(e):this.props.onCancel()}handleCancel(){this.props.onCancel()}render(){const{formatMessage:e}=this.props.intl,i="JRWPASDO",n={J:e(us.joiner,{val:"J"}),R:e(us.reader,{val:"R"}),W:e(us.writer,{val:"W"}),P:e(us.preser,{val:"P"}),A:e(us.approver,{val:"A"}),S:e(us.sharer,{val:"S"}),D:e(us.deleter,{val:"D"}),O:e(us.owner,{val:"O"})};let a=this.props.skip||"",r=this.state.mode,o=(this.props.compare||"").replace("N",""),c=[];for(let e=0;e<i.length;e++){let s=i.charAt(e);a.indexOf(s)>=0&&r.indexOf(s)<0||c.push(t().createElement("tr",{key:s},t().createElement("td",null,n[s]),t().createElement("td",{className:"checkbox"},a.indexOf(s)<0?t().createElement(ns.Z,{name:s,checked:r.indexOf(s)>=0,onChange:this.handleChange}):t().createElement(ns.Z,{name:s,checked:r.indexOf(s)>=0})),this.props.compare?t().createElement("td",{className:"checkbox"},t().createElement(ns.Z,{name:s,checked:o.indexOf(s)>=0})):null))}return t().createElement("div",{className:"panel-form-column"},this.props.userTitle?t().createElement("ul",{className:"contact-box small"},t().createElement($i,{tinode:this.props.tinode,item:this.props.item,title:this.props.userTitle,small:!0,avatar:(0,Ni.PD)(this.props.userAvatar?this.props.userAvatar:null)})):null,t().createElement("label",{className:"small"},t().createElement(s.FormattedMessage,{id:"title_permissions",defaultMessage:[{type:0,value:"Permissions"}]})),t().createElement("table",{className:"permission-editor"},this.props.compare?t().createElement("thead",null,t().createElement("tr",null,t().createElement("th",null),t().createElement("th",null,this.props.modeTitle),t().createElement("th",null,this.props.compareTitle))):null,t().createElement("tbody",null,c)),t().createElement("br",null),t().createElement("div",{className:"dialog-buttons"},t().createElement("button",{className:"outline",onClick:this.handleCancel},t().createElement(s.FormattedMessage,{id:"button_cancel",defaultMessage:[{type:0,value:"Cancel"}]})),t().createElement("button",{className:"primary",onClick:this.handleSubmit},t().createElement(s.FormattedMessage,{id:"button_ok",defaultMessage:[{type:0,value:"OK"}]}))))}}const ms=(0,s.injectIntl)(ps);var gs=r(9875),fs=r(195);class vs extends t().Component{constructor(e){super(e),this.selfRef=t().createRef(),this.state={active:e.active,initialValue:e.value||"",value:e.value||""},this.handeTextChange=this.handeTextChange.bind(this),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleStartEditing=this.handleStartEditing.bind(this),this.handleEditingFinished=this.handleEditingFinished.bind(this),this.handlePasswordFinished=this.handlePasswordFinished.bind(this)}componentDidUpdate(e,t){const i=this.props.value||"";t.initialValue==i||t.active||this.setState({initialValue:i,value:i})}handeTextChange(e){this.setState({value:e.target.value||""})}handleKeyDown(e){27===e.keyCode?this.setState({value:this.props.value,active:!1}):13===e.keyCode&&this.handleEditingFinished(e)}handleStartEditing(){this.props.readOnly||this.setState({active:!0},(e=>{this.selfRef.current&&this.selfRef.current.focus()}))}handleEditingFinished(e){const t=this.state.value.trim();!this.props.required||e.target.checkValidity()&&t?(this.setState({active:!1}),(t||this.props.value)&&t!==this.props.value&&this.props.onFinished(t)):this.setState({value:this.props.value,active:!1})}handlePasswordFinished(e){this.setState({active:!1}),e&&e!==this.props.value&&this.props.onFinished(e)}render(){if(!this.state.active){let e="password"==this.props.type?"••••••••":this.state.value,i="in-place-edit"+(this.props.readOnly?" disabled":"");return e||(e=this.props.placeholder,i+=" placeholder"),this.props.multiline&&1!=this.props.multiline||(i+=" short"),t().createElement("span",{className:i,onClick:this.handleStartEditing},t().createElement("span",null,e))}let e;const i={};return"password"==this.props.type?(e=fs.Z,i.onFinished=this.handlePasswordFinished):(this.props.multiline>1?(e="textarea",i.rows=this.props.multiline,i.className="inplace-edit"):(e="input",i.type=this.props.type||"text"),i.value=this.state.value,i.ref=this.selfRef,i.onChange=this.handeTextChange,i.onKeyDown=this.handleKeyDown,i.onBlur=this.handleEditingFinished),i.placeholder=this.props.placeholder,i.required=this.props.required?"required":"",i.autoComplete=this.props.autoComplete,i.autoFocus=!0,t().createElement(e,i,null)}}class bs extends t().Component{constructor(e){super(e),this.state={tags:this.props.tags||[],tagInput:"",activated:this.props.activated},this.handleTagInput=this.handleTagInput.bind(this),this.handleAddTag=this.handleAddTag.bind(this),this.handleRemoveTag=this.handleRemoveTag.bind(this),this.handleSubmit=this.handleSubmit.bind(this),this.handleCancel=this.handleCancel.bind(this)}static getDerivedStateFromProps(e,t){const i=e.tags||[];return(0,Di.h6)(i,t.tags)||t.activated?null:{tags:i}}handleTagInput(e){if(this.setState({tagInput:e}),e.length>0){const t=e[e.length-1];'"'==e[0]?e.length>1&&'"'==t&&this.handleAddTag(e.substring(1,e.length-1)):","!=t&&" "!=t&&";"!=t&&'"'!=t||this.handleAddTag(e.substring(0,e.length-1).trim())}}handleAddTag(e){const t=this.props.tinode.getServerParam("maxTagCount",mi.pM);if(e.length>0&&this.state.tags.length<t){const t=this.state.tags.slice(0);return t.push(e),this.setState({tags:t,tagInput:""}),this.props.onTagsChanged&&this.props.onTagsChanged(t),t}return this.state.tags}handleRemoveTag(e,t){const i=this.state.tags.slice(0);i.splice(t,1),this.setState({tags:i}),this.props.onTagsChanged&&this.props.onTagsChanged(i)}handleSubmit(){this.props.onSubmit(this.handleAddTag(this.state.tagInput.trim())),this.setState({activated:!1,tags:this.props.tags||[]})}handleCancel(){this.setState({activated:!1,tagInput:"",tags:this.props.tags||[]}),this.props.onCancel&&this.props.onCancel()}render(){const e=this.props.tinode.getServerParam("minTagLength",mi.VL),i=this.props.tinode.getServerParam("maxTagLength",mi.cG);let n=[];return this.state.activated?this.state.tags.forEach((t=>{n.push({user:t,invalid:t.length<e||t.length>i})})):(this.state.tags.forEach((e=>{n.push(t().createElement("span",{className:"badge",key:n.length},e))})),0==n.length&&(n=t().createElement("i",null,t().createElement(s.FormattedMessage,{id:"tags_not_found",defaultMessage:[{type:0,value:"No tags defined. Add some."}]})))),t().createElement("div",{className:"panel-form-column"},t().createElement("div",{className:"panel-form-row"},t().createElement("label",{className:"small"},this.props.title)),this.state.activated?t().createElement("div",null,t().createElement(s.FormattedMessage,{id:"tags_editor_no_tags",defaultMessage:[{type:0,value:"Add some tags"}]},(e=>t().createElement(cs,{tinode:this.props.tinode,chips:n,avatarDisabled:!0,prompt:e,tabIndex:this.props.tabIndex,onEnter:this.handleAddTag,onFocusLost:this.handleAddTag,onCancel:this.handleCancel,onChipRemoved:this.handleRemoveTag,filterFunc:this.handleTagInput}))),this.props.onSubmit||this.props.onCancel?t().createElement("div",{id:"tag-manager-buttons",className:"dialog-buttons panel-form-row"},t().createElement("button",{className:"outline",onClick:this.handleCancel},t().createElement(s.FormattedMessage,{id:"button_cancel",defaultMessage:[{type:0,value:"Cancel"}]})),t().createElement("button",{className:"primary",onClick:this.handleSubmit},t().createElement(s.FormattedMessage,{id:"button_ok",defaultMessage:[{type:0,value:"OK"}]}))):null):t().createElement("div",{className:"quoted"},t().createElement("a",{href:"#",className:"flat-button",onClick:e=>{e.preventDefault(),this.setState({activated:!0})}},t().createElement("i",{className:"material-icons"},"edit"),"  ",t().createElement(s.FormattedMessage,{id:"title_manage_tags",defaultMessage:[{type:0,value:"Manage"}]})),t().createElement(t().Fragment,null,n)))}}class ys extends t().Component{constructor(e){super(e);const t=this.props.tinode.getTopic(this.props.topic),i=t.getAccessMode();this.state={isMe:ui.Tinode.isMeTopicName(this.props.topic),owner:i&&i.isOwner(),fullName:t.public?t.public.fn:void 0,private:t.private?t.private.comment:null,description:t.public?t.public.note:void 0,avatar:(0,Ni.PD)(t.public?t.public.photo:null),tags:t.tags()||[],newAvatar:null,newAvatarMime:null},this.previousOnTags=null,this.tnNewTags=this.tnNewTags.bind(this),this.handleFullNameUpdate=this.handleFullNameUpdate.bind(this),this.handleImageUpdated=this.handleImageUpdated.bind(this),this.handleAvatarCropped=this.handleAvatarCropped.bind(this),this.handleAvatarCropCancel=this.handleAvatarCropCancel.bind(this),this.uploadAvatar=this.uploadAvatar.bind(this),this.handlePrivateUpdate=this.handlePrivateUpdate.bind(this),this.handleDescriptionUpdate=this.handleDescriptionUpdate.bind(this),this.handleTagsUpdated=this.handleTagsUpdated.bind(this)}componentDidMount(){const e=this.props.tinode.getTopic(this.props.topic);this.previousOnTags=e.onTagsUpdated,e.onTagsUpdated=this.tnNewTags}componentWillUnmount(){this.props.tinode.getTopic(this.props.topic).onTagsUpdated=this.previousOnTags}tnNewTags(e){this.setState({tags:e})}handleFullNameUpdate(e){(e=e.trim().substring(0,mi.S8))&&this.state.fullName!==e&&(this.setState({fullName:e}),this.props.onUpdateTopicDesc(this.props.topic,(0,Di.n$)(e,null)))}handlePrivateUpdate(e){e=e.trim().substring(0,mi.S8),this.state.private!==e&&(this.setState({private:e}),this.props.onUpdateTopicDesc(this.props.topic,null,e||ui.Tinode.DEL_CHAR))}handleDescriptionUpdate(e){(e=e.trim().substring(0,mi.EI))&&(this.setState({description:e}),this.props.onUpdateTopicDesc(this.props.topic,(0,Di.n$)(null,null,null,e)))}handleImageUpdated(e,t){this.setState({newAvatar:t,newAvatarMime:e}),t||(this.setState({avatar:null}),this.props.onUpdateTopicDesc(this.props.topic,(0,Di.n$)(null,ui.Tinode.DEL_CHAR)))}handleAvatarCropped(e,t,i,s){const n=t?URL.createObjectURL(t):null;this.setState({avatar:n,newAvatar:null,newAvatarMime:null}),t&&this.uploadAvatar(e,t,i,s)}uploadAvatar(e,t,i,s){const n=e=>{let{mime:t,blob:i}=e;if(i.size>mi.uv){this.props.tinode.getLargeFileHelper().upload(i).then((e=>this.props.onUpdateTopicDesc(this.props.topic,(0,Di.n$)(null,e)))).catch((e=>this.props.onError(e.message,"err")))}else(0,Ni.w8)(i).then((e=>{const i=(0,Ni.PD)({data:e.bits,type:t});this.setState({source:i}),this.props.onUpdateTopicDesc(this.props.topic,(0,Di.n$)(null,i))}))};i>mi.IX||s>mi.IX||i!=s?(0,Ni.EA)(t,mi.IX,mi.IX,mi.GQ,!0).then((e=>n(e))).catch((e=>this.props.onError(e.message,"err"))):n({mime:e,blob:t,width:i,height:s})}handleAvatarCropCancel(){this.setState({newAvatar:null,newAvatarMime:null})}handleTagsUpdated(e){(0,Di.h6)(this.state.tags.slice(0),e.slice(0))||this.props.onUpdateTags(e)}render(){if(this.state.newAvatar)return t().createElement(gs.Z,{avatar:this.state.newAvatar,mime:this.state.newAvatarMime,onSubmit:this.handleAvatarCropped,onCancel:this.handleAvatarCropCancel,onError:this.props.onError});const e=this.state.isMe||this.state.owner;return t().createElement(t().Fragment,null,t().createElement("div",{className:"panel-form-column"},t().createElement("center",null,t().createElement(ss.Z,{tinode:this.props.tinode,avatar:this.state.avatar,readOnly:!e,uid:this.props.topic,title:this.state.fullName,onImageUpdated:this.handleImageUpdated,onError:this.props.onError})),this.state.isMe?t().createElement("div",{className:"group"},t().createElement("label",{className:"small"},t().createElement(s.FormattedMessage,{id:"label_your_name",defaultMessage:[{type:0,value:"Your name"}]})),t().createElement("div",null,t().createElement(s.FormattedMessage,{id:"full_name_prompt",defaultMessage:[{type:0,value:"Full name, e.g. John Doe"}]},(e=>t().createElement(vs,{placeholder:e,value:this.state.fullName,required:!0,onFinished:this.handleFullNameUpdate}))))):t().createElement(t().Fragment,null,t().createElement("div",{className:"group"},t().createElement("div",null,t().createElement("label",{className:"small"},t().createElement(s.FormattedMessage,{id:"label_topic_name",defaultMessage:[{type:0,value:"Name"}]}))),t().createElement("div",null,t().createElement(s.FormattedMessage,{id:"topic_name_editing_placeholder",defaultMessage:[{type:0,value:"Freeform name of the group"}]},(i=>t().createElement(vs,{placeholder:i,readOnly:!e,value:this.state.fullName,required:!0,onFinished:this.handleFullNameUpdate}))))),t().createElement("div",{className:"group"},t().createElement("div",null,t().createElement("label",{className:"small"},t().createElement(s.FormattedMessage,{id:"label_private",defaultMessage:[{type:0,value:"Private comment"}]}))),t().createElement("div",null,t().createElement(s.FormattedMessage,{id:"private_editing_placeholder",defaultMessage:[{type:0,value:"Visible to you only"}]},(e=>t().createElement(vs,{placeholder:e,value:this.state.private,onFinished:this.handlePrivateUpdate})))))),e||this.state.description?t().createElement("div",{className:"group"},t().createElement("div",null,t().createElement("label",{className:"small"},t().createElement(s.FormattedMessage,{id:"label_description",defaultMessage:[{type:0,value:"Description"}]}))),t().createElement("div",null,t().createElement(s.FormattedMessage,{id:"description_editing_placeholder",defaultMessage:[{type:0,value:"Description (optional)"}]},(i=>t().createElement(vs,{placeholder:i,readOnly:!e,value:this.state.description,multiline:2,onFinished:this.handleDescriptionUpdate}))))):null),e?t().createElement(t().Fragment,null,t().createElement("div",{className:"hr"}),t().createElement(s.FormattedMessage,{id:"title_tag_manager",defaultMessage:[{type:0,value:"Tags (search & discovery)"}]},(e=>t().createElement(bs,{tinode:this.props.tinode,title:e,activated:!1,tags:this.state.tags,onSubmit:this.handleTagsUpdated})))):null)}}class Ss extends t().Component{constructor(e){super(e);this.props.tinode.getTopic(this.props.topic).getAccessMode();this.state={tags:[]},this.previousTagsUpdated=void 0,this.onTagsUpdated=this.onTagsUpdated.bind(this),this.handleTagsUpdated=this.handleTagsUpdated.bind(this)}componentDidUpdate(e){const t=this.props.tinode.getTopic(e.topic);t&&(t.onTagsUpdated!=this.onTagsUpdated&&("grp"==t.getType()?(this.previousTagsUpdated=t.onTagsUpdated,t.onTagsUpdated=this.onTagsUpdated):this.previousTagsUpdated=void 0),this.state.topic!=e.topic&&this.setState({topic:e.topic}))}componentWillUnmount(){this.props.tinode.getTopic(this.props.topic).onTagsUpdated=this.previousTagsUpdated}onTagsUpdated(e){this.setState({tags:e}),this.previousTagsUpdated&&this.previousTagsUpdated!=this.onTagsUpdated&&this.previousTagsUpdated(e)}handleTagsUpdated(e){(0,Di.h6)(this.state.tags.slice(0),e.slice(0))||this.props.onUpdateTagsRequest(this.props.topic,e)}render(){return t().createElement("div",{className:"scrollable-panel"},t().createElement(ys,{tinode:this.props.tinode,topic:this.props.topic,onUpdateTopicDesc:this.props.onUpdateTopicDesc,onUpdateTags:this.handleTagsUpdated,onError:this.props.onError}))}}const ws=(0,s.defineMessages)({clear_messages:{id:"action_clear_messages",defaultMessage:[{type:0,value:"Clear Messages"}]},clear_messages_warning:{id:"clear_messages_warning",defaultMessage:[{type:0,value:"Are you sure you want to clear all messages? It cannot be undone."}]},delete_messages:{id:"action_delete_messages",defaultMessage:[{type:0,value:"Clear Messages for All"}]},delete_messages_warning:{id:"delete_messages_warning",defaultMessage:[{type:0,value:"Are you sure you want to delete all messages for everyone? It cannot be undone."}]},topic_delete:{id:"topic_delete",defaultMessage:[{type:0,value:"Delete Conversation"}]},topic_delete_warning:{id:"topic_delete_warning",defaultMessage:[{type:0,value:"Are you sure you want to delete this conversation? It cannot be undone."}]},leave_chat:{id:"action_leave_chat",defaultMessage:[{type:0,value:"Leave Conversation"}]},leave_chat_warning:{id:"leave_chat_warning",defaultMessage:[{type:0,value:"Are you sure you want to leave this conversation?"}]},block_contact:{id:"action_block_contact",defaultMessage:[{type:0,value:"Block Contact"}]},block_contact_warning:{id:"block_contact_warning",defaultMessage:[{type:0,value:"Are you sure you want to block this contact?"}]},report_chat:{id:"action_report_chat",defaultMessage:[{type:0,value:"Report Conversation"}]},report_chat_warning:{id:"report_chat_warning",defaultMessage:[{type:0,value:"Are you sure you want to block and report this conversation?"}]},other_user:{id:"label_other_user",defaultMessage:[{type:0,value:"Other"}]}});class Cs extends t().PureComponent{constructor(e){super(e),this.handleDeleteTopic=this.handleDeleteTopic.bind(this),this.handleDeleteMessages=this.handleDeleteMessages.bind(this),this.handleLeave=this.handleLeave.bind(this),this.handleBlock=this.handleBlock.bind(this),this.handleReport=this.handleReport.bind(this)}handleDeleteTopic(e){e.preventDefault();const{formatMessage:t}=this.props.intl;this.props.onShowAlert(t(ws.topic_delete),t(ws.topic_delete_warning),(e=>this.props.onDeleteTopic(this.props.topic)),null,!0,null)}handleDeleteMessages(e){e.preventDefault();const{formatMessage:t}=this.props.intl;this.props.onShowAlert(t(this.props.deleter?ws.delete_messages:ws.clear_messages),t(this.props.deleter?ws.delete_messages_warning:ws.clear_messages_warning),(e=>this.props.onDeleteMessages(this.props.topic)),null,!0,null)}handleLeave(e){e.preventDefault();const{formatMessage:t}=this.props.intl;this.props.onShowAlert(t(ws.leave_chat),t(ws.leave_chat_warning),(e=>this.props.onLeaveTopic(this.props.topic)),null,!0,null)}handleBlock(e){e.preventDefault();const{formatMessage:t}=this.props.intl;this.props.onShowAlert(t(ws.block_contact),t(ws.block_contact_warning),(e=>this.props.onBlockTopic(this.props.topic)),null,!0,null)}handleReport(e){e.preventDefault();const{formatMessage:t}=this.props.intl;this.props.onShowAlert(t(ws.report_chat),t(ws.report_chat_warning),(e=>{this.props.onReportTopic(this.props.topic)}),null,!0,null)}render(){const{formatMessage:e}=this.props.intl;return t().createElement("div",{className:"scrollable-panel"},t().createElement("div",{className:"panel-form-column"},this.props.channel?null:t().createElement("a",{href:"#",className:"flat-button",onClick:this.handleDeleteMessages},t().createElement("i",{className:"material-icons"},"delete_outline"),"  ",e(this.props.deleter?ws.delete_messages:ws.clear_messages)),this.props.owner?t().createElement("a",{href:"#",className:"danger flat-button",onClick:this.handleDeleteTopic},t().createElement("i",{className:"material-icons"},"delete"),"  ",e(ws.topic_delete)):t().createElement("a",{href:"#",className:"danger flat-button",onClick:this.handleLeave},t().createElement("i",{className:"material-icons"},"exit_to_app"),"  ",e(ws.leave_chat)),this.props.groupTopic?null:t().createElement("a",{href:"#",className:"danger flat-button",onClick:this.handleBlock},t().createElement("i",{className:"material-icons"},"block"),"  ",e(ws.block_contact)),this.props.owner?null:t().createElement("a",{href:"#",className:"danger flat-button",onClick:this.handleReport},t().createElement("i",{className:"material-icons"},"report"),"  ",e(ws.report_chat))),t().createElement("div",{className:"hr"}),t().createElement("div",{className:"panel-form-column"},this.props.groupTopic?t().createElement(t().Fragment,null,t().createElement("div",{className:"group"},t().createElement("label",null,t().createElement(s.FormattedMessage,{id:"label_your_permissions",defaultMessage:[{type:0,value:"Your permissions:"}]}))," ",t().createElement("tt",{className:"clickable",onClick:e=>{e.preventDefault(),this.props.onLaunchPermissionsEditor("want")}},this.props.access)),this.props.channel?null:t().createElement("div",{className:"group"},t().createElement("div",null,t().createElement("label",{className:"small"},t().createElement(s.FormattedMessage,{id:"label_default_access_mode",defaultMessage:[{type:0,value:"Default access mode:"}]}))),t().createElement("div",{className:"quoted"},t().createElement("div",null,"Auth: ",t().createElement("tt",{className:this.props.owner?"clickable":null,onClick:e=>{e.preventDefault(),this.props.owner&&this.props.onLaunchPermissionsEditor("auth")}},this.props.auth)),t().createElement("div",null,"Anon: ",t().createElement("tt",{className:this.props.owner?"clickable":null,onClick:e=>{e.preventDefault(),this.props.owner&&this.props.onLaunchPermissionsEditor("anon")}},this.props.anon))))):t().createElement("div",{className:"group"},t().createElement("div",null,t().createElement("label",{className:"small"},t().createElement(s.FormattedMessage,{id:"label_permissions",defaultMessage:[{type:0,value:"Permissions:"}]}))),t().createElement("div",{className:"quoted"},t().createElement("div",null,t().createElement(s.FormattedMessage,{id:"label_you",defaultMessage:[{type:0,value:"You:"}]})," ",t().createElement("tt",{className:"clickable",onClick:e=>{e.preventDefault(),this.props.onLaunchPermissionsEditor("want")}},this.props.access)),t().createElement("div",null,this.props.fullName?this.props.fullName:e(ws.other_user),":  ",t().createElement("tt",{className:"clickable",onClick:e=>{e.preventDefault(),this.props.onLaunchPermissionsEditor("given")}},this.props.modeGiven2))))))}}const ks=(0,s.injectIntl)(Cs),Es=(0,s.defineMessages)({info:{id:"panel_title_info",defaultMessage:[{type:0,value:"Info"}]},general:{id:"panel_title_general",defaultMessage:[{type:0,value:"General"}]},security:{id:"panel_title_security",defaultMessage:[{type:0,value:"Security"}]},members:{id:"panel_title_members",defaultMessage:[{type:0,value:"Members"}]},crop:{id:"panel_title_crop",defaultMessage:[{type:0,value:"Drag to Adjust"}]},perm_want:{id:"requested_permissions",defaultMessage:[{type:0,value:"Requested"}]},perm_given:{id:"granted_permissions",defaultMessage:[{type:0,value:"Granted"}]},perm_auth:{id:"permissions_authenticated",defaultMessage:[{type:0,value:"Authenticated"}]},perm_anon:{id:"permissions_anonymous",defaultMessage:[{type:0,value:"Anonymous"}]},perm_user:{id:"permissions_user",defaultMessage:[{type:0,value:"User's Permissions"}]},edit_permissions:{id:"menu_item_edit_permissions",defaultMessage:[{type:0,value:"Edit permissions"}]}});class Ts extends t().Component{constructor(e){super(e),this.state={topic:null,owner:!1,admin:!1,sharer:!1,deleter:!1,muted:!1,address:null,groupTopic:void 0,channel:void 0,fullName:void 0,description:void 0,avatar:null,private:null,selectedContact:null,access:null,modeGiven:null,modeWant:null,modeGiven2:null,modeWant2:null,auth:null,anon:null,contactList:[],trustedBadges:[],previousMetaDesc:void 0,previousSubsUpdated:void 0},this.resetSubs=this.resetSubs.bind(this),this.resetDesc=this.resetDesc.bind(this),this.resetTags=this.resetTags.bind(this),this.onMetaDesc=this.onMetaDesc.bind(this),this.onSubsUpdated=this.onSubsUpdated.bind(this),this.handleImageChanged=this.handleImageChanged.bind(this),this.handleMuted=this.handleMuted.bind(this),this.handleUnarchive=this.handleUnarchive.bind(this),this.handlePermissionsChanged=this.handlePermissionsChanged.bind(this),this.handleLaunchPermissionsEditor=this.handleLaunchPermissionsEditor.bind(this),this.handleShowAddMembers=this.handleShowAddMembers.bind(this),this.handleMemberUpdateRequest=this.handleMemberUpdateRequest.bind(this),this.handleMemberSelected=this.handleMemberSelected.bind(this),this.handleContextMenu=this.handleContextMenu.bind(this),this.handleBackNavigate=this.handleBackNavigate.bind(this)}componentDidUpdate(e){const t=this.props.tinode.getTopic(e.topic);t&&(this.onMetaDesc!=t.onMetaDesc&&(this.previousMetaDesc=t.onMetaDesc,t.onMetaDesc=this.onMetaDesc,this.previousSubsUpdated=t.onSubsUpdated,t.onSubsUpdated=this.onSubsUpdated),this.state.topic!=e.topic&&(this.setState({topic:e.topic}),this.resetDesc(t,e),this.resetSubs(t,e),this.resetTags(t)))}componentWillUnmount(){const e=this.props.tinode.getTopic(this.props.topic);e&&(this.setState({topic:null}),e.onMetaDesc=this.previousMetaDesc,e.onSubsUpdated=this.previousSubsUpdated)}resetSubs(e,t){const i={contactList:[]};if("p2p"==e.getType()){const s=e.subscriber(t.topic);s?(i.modeGiven2=s.acs.getGiven(),i.modeWant2=s.acs.getWant()):(i.modeGiven2=mi.xt,i.modeWant2=mi.xt)}else e.subscribers((e=>{i.contactList.push(e)}),this);this.setState(i)}resetDesc(e,t){const i=e.getDefaultAccess()||{},s=e.getAccessMode(),n=[];if(e.trusted)for(const[t,i]of Object.entries(e.trusted))i&&n.push(t);this.setState({owner:s&&s.isOwner(),admin:s&&s.isAdmin(),sharer:s&&s.isSharer(),deleter:s&&s.isDeleter(),muted:s&&s.isMuted(),fullName:(0,Di.Th)(e.public&&e.public.fn,mi.S8),description:(0,Di.Th)(e.public&&e.public.note,mi.EI),avatar:(0,Ni.PD)(e.public?e.public.photo:null),trustedBadges:n,private:(0,Di.Th)(e.private&&e.private.comment,mi.S8),archived:e.isArchived(),address:e.name,groupTopic:e.isGroupType(),channel:e.isChannelType()||e.chan,access:s?s.getMode():void 0,modeGiven:s?s.getGiven():void 0,modeWant:s?s.getWant():void 0,auth:i.auth,anon:i.anon})}resetTags(e){if("grp"!=e.getType())return;const t=e.getAccessMode();t&&t.isOwner()&&e.getMeta(e.startMetaQuery().withTags().build())}onMetaDesc(e){const t=this.props.tinode.getTopic(this.props.topic);t&&(this.resetDesc(t,this.props),this.previousMetaDesc&&this.previousMetaDesc!=this.onMetaDesc&&this.previousMetaDesc(e))}onSubsUpdated(e){const t=this.props.tinode.getTopic(this.props.topic);t&&(this.resetSubs(t,this.props),this.previousSubsUpdated&&this.previousSubsUpdated!=this.onSubsUpdated&&this.previousSubsUpdated(e))}handleImageChanged(e,t){this.setState({avatar:t}),this.props.onTopicDescUpdate(this.props.topic,(0,Di.n$)(null,t||ui.Tinode.DEL_CHAR),null)}handleMuted(e,t){this.setState({muted:t}),this.props.onChangePermissions(this.props.topic,t?"-P":"+P")}handleUnarchive(e,t){this.props.onTopicUnArchive(this.props.topic)}handlePermissionsChanged(e,t){switch(e){case"auth":this.props.onTopicDescUpdateRequest(this.props.topic,null,null,{auth:t});break;case"anon":this.props.onTopicDescUpdateRequest(this.props.topic,null,null,{anon:t});break;case"mode":case"want":this.props.onChangePermissions(this.props.topic,t);break;case"given":this.props.onChangePermissions(this.props.topic,t,this.props.topic);break;case"user":this.props.onChangePermissions(this.props.topic,t,this.state.userPermissionsEdited)}this.handleBackNavigate()}handleLaunchPermissionsEditor(e,t){const{formatMessage:i}=this.props.intl;let s,n,a,r,o,c,l;switch(e){case"mode":s=this.state.access;break;case"want":s=this.state.modeWant,n=this.state.modeGiven,this.state.owner?a="O":(a=ui.AccessMode.encode(ui.AccessMode.diff("ASDO",this.state.modeGiven)),this.state.channel&&(a+="W")),r=i(Es.perm_want),o=i(Es.perm_given);break;case"given":s=this.state.modeGiven2,n=this.state.modeWant2,a=this.state.groupTopic?this.state.owner?"":"O":"ASDO",r=i(Es.perm_given),o=i(Es.perm_want);break;case"auth":s=this.state.auth,a="O";break;case"anon":s=this.state.anon,a="O";break;case"user":{const e=this.props.tinode.getTopic(this.props.topic);if(!e)return;const d=e.subscriber(t);if(!d||!d.acs)return;s=d.acs.getGiven(),n=d.acs.getWant(),a=this.state.owner?"":"O",r=i(Es.perm_given),o=i(Es.perm_want),d.public&&(c=d.public.fn,l=d.public.photo);break}default:return void console.error("Unknown permission editing mode '"+e+"'")}this.setState({userPermissionsEdited:t,userPermissionsTitle:c,userPermissionsAvatar:l,editedPermissions:s,immutablePermissions:n,editedPermissionsTitle:r,immutablePermissionsTitle:o,editedPermissionsSkipped:a}),this.props.onNavigate(`perm/${e}`)}handleShowAddMembers(e){e.preventDefault(),this.props.onInitFind(),this.props.onNavigate("members")}handleMemberUpdateRequest(e,t,i){this.props.onMemberUpdateRequest(this.props.topic,t,i),this.props.onNavigate("info")}handleMemberSelected(e){this.setState({selectedContact:e})}handleBackNavigate(){const e=(this.props.panel||"info").split("/");"info"==e[0]?this.props.onNavigate(null):"perm"==e[0]?"user"==e[1]?this.props.onNavigate("info"):this.props.onNavigate("security"):this.props.onNavigate("info")}handleContextMenu(e){const{formatMessage:t}=this.props.intl,i=this.props.tinode.getTopic(this.props.topic);if(!i)return;const s=i.subscriber(e.topicName);if(!s||!s.acs)return;const n=this.props.tinode.isMe(e.topicName),a=[{title:t(Es.edit_permissions),handler:t=>this.handleLaunchPermissionsEditor(n?"want":"user",e.topicName)}];n||a.push("member_delete"),a.push(s.acs.isMuted()?"member_unmute":"member_mute"),n||a.push(s.acs.isJoiner()?"member_block":"member_unblock"),this.props.showContextMenu({topicName:this.props.topic,x:e.x,y:e.y,user:e.topicName},a)}render(){const e=(this.props.panel||"info").split("/"),i=e[0];e.shift();const{formatMessage:n}=this.props.intl,a=n(("perm"==i?Es["perm_"+e[0]]:Es[i])||Es.info);return t().createElement("div",{id:"info-view"},t().createElement("div",{className:"caption-panel",id:"info-caption-panel"},t().createElement("div",{className:"panel-title",id:"info-title"},a),t().createElement("div",null,t().createElement(as,{onCancel:this.handleBackNavigate}))),this.props.displayMobile?t().createElement(rs,{level:this.props.errorLevel,text:this.props.errorText,onClearError:this.props.onError}):null,"members"==i?t().createElement(hs,{tinode:this.props.tinode,members:this.state.contactList,requiredMember:this.props.myUserId,keepInitialMembers:!this.state.admin&&!this.state.owner,myUserId:this.props.myUserId,contacts:this.props.searchableContacts,onCancel:this.handleBackNavigate,onSubmit:this.handleMemberUpdateRequest}):"perm"==i&&e.length>0?t().createElement(ms,{tinode:this.props.tinode,mode:this.state.editedPermissions,compare:this.state.immutablePermissions,skip:this.state.editedPermissionsSkipped,modeTitle:this.state.editedPermissionsTitle,compareTitle:this.state.immutablePermissionsTitle,userTitle:this.state.userPermissionsTitle,item:this.state.userPermissionsEdited,userAvatar:this.state.userPermissionsAvatar,onSubmit:t=>this.handlePermissionsChanged(e[0],t),onCancel:this.handleBackNavigate}):"general"==i?t().createElement(Ss,{tinode:this.props.tinode,topic:this.props.topic,reqCredMethod:this.props.reqCredMethod,onCredAdd:this.props.onCredAdd,onUpdateTagsRequest:this.props.onTopicTagsUpdateRequest,onCredConfirm:this.props.onCredConfirm,onCredDelete:this.props.onCredDelete,onUpdateTopicDesc:this.props.onTopicDescUpdateRequest,onError:this.props.onError}):"security"==i?t().createElement(ks,{topic:this.props.topic,owner:this.state.owner,admin:this.state.admin,sharer:this.state.sharer,deleter:this.state.deleter,muted:this.state.muted,groupTopic:this.state.groupTopic,channel:this.state.channel,access:this.state.access,modeGiven:this.state.modeGiven,modeWant:this.state.modeWant,modeGiven2:this.state.modeGiven2,modeWant2:this.state.modeWant2,auth:this.state.auth,anon:this.state.anon,onShowAlert:this.props.onShowAlert,onDeleteMessages:this.props.onDeleteMessages,onLeaveTopic:this.props.onLeaveTopic,onBlockTopic:this.props.onBlockTopic,onReportTopic:this.props.onReportTopic,onLaunchPermissionsEditor:this.handleLaunchPermissionsEditor,onNavigate:this.props.onNavigate}):t().createElement("div",{id:"info-view-content",className:"scrollable-panel"},t().createElement("div",{className:"panel-form-column"},t().createElement("a",{href:"#",className:"flat-button float-right",onClick:e=>{e.preventDefault(),this.props.onNavigate("general")}},t().createElement("i",{className:"material-icons"},"edit")," ",t().createElement(s.FormattedMessage,{id:"button_edit",defaultMessage:[{type:0,value:"Edit"}]})),t().createElement("center",null,t().createElement(ss.Z,{tinode:this.props.tinode,avatar:this.state.avatar,readOnly:!0,uid:this.props.topic,title:this.state.fullName})),t().createElement("div",{className:"group"},t().createElement("div",null,t().createElement("label",{className:"small"},t().createElement(s.FormattedMessage,{id:"label_topic_name",defaultMessage:[{type:0,value:"Name"}]}))),t().createElement("div",{className:"large ellipsized"},this.state.fullName,this.state.channel?t().createElement("img",{src:"/img/channel.png",className:"channel",alt:"channel"}):null)),this.state.private?t().createElement("div",{className:"group"},t().createElement("div",null,t().createElement("label",{className:"small"},t().createElement(s.FormattedMessage,{id:"label_private",defaultMessage:[{type:0,value:"Private comment"}]}))),t().createElement("div",{className:"large ellipsized"},this.state.private)):null,t().createElement("div",{className:"group"},t().createElement("label",{className:"small"},t().createElement(s.FormattedMessage,{id:"label_user_id",defaultMessage:[{type:0,value:"ID:"}]}))," ",t().createElement("tt",null,this.state.address)),t().createElement("div",{className:"group"},t().createElement(Qi.Z,{trustedBadges:this.state.trustedBadges})),this.state.description?t().createElement("div",{className:"group"},t().createElement("label",{className:"small"},t().createElement(s.FormattedMessage,{id:"label_description",defaultMessage:[{type:0,value:"Description"}]})),t().createElement("div",null,this.state.description)):null),t().createElement("div",{className:"hr"}),t().createElement("div",{className:"panel-form-row"},t().createElement("label",null,t().createElement(s.FormattedMessage,{id:"label_muting_topic",defaultMessage:[{type:0,value:"Muted:"}]})),t().createElement(ns.Z,{name:"P",checked:this.state.muted,onChange:this.handleMuted})),this.state.archived?t().createElement("div",{className:"panel-form-row"},t().createElement("label",null,t().createElement(s.FormattedMessage,{id:"label_unarchive_topic",defaultMessage:[{type:0,value:"Archived:"}]})),t().createElement(ns.Z,{name:"archived",checked:!0,onChange:this.handleUnarchive})):null,t().createElement("div",{className:"hr"}),t().createElement("div",{className:"panel-form-row"},t().createElement("a",{href:"#",className:"flat-button",onClick:e=>{e.preventDefault(),this.props.onNavigate("security")}},t().createElement("i",{className:"material-icons"},"security")," ",t().createElement(s.FormattedMessage,{id:"button_security",defaultMessage:[{type:0,value:"Security"}]}))),this.state.groupTopic&&this.state.sharer?t().createElement(t().Fragment,null,t().createElement("div",{className:"hr"}),t().createElement("div",{className:"panel-form-row"},t().createElement("label",{className:"small"},t().createElement(s.FormattedMessage,{id:"label_group_members",defaultMessage:[{type:0,value:"Group members:"}]}))),t().createElement("div",{className:"panel-form-row"},t().createElement("a",{href:"#",className:"flat-button",onClick:this.handleShowAddMembers},t().createElement("i",{className:"material-icons"},"person_add"),"  ",t().createElement(s.FormattedMessage,{id:"button_add_members",defaultMessage:[{type:0,value:"Add members"}]}))),t().createElement(s.FormattedMessage,{id:"group_has_no_members",defaultMessage:[{type:0,value:"No members"}]},(e=>t().createElement(zi,{tinode:this.props.tinode,contacts:this.state.contactList,myUserId:this.props.myUserId,emptyListMessage:e,topicSelected:this.state.selectedContact,showOnline:!1,showUnread:!1,showMode:!0,noScroll:!0,onTopicSelected:this.handleMemberSelected,showContextMenu:!!this.state.admin&&this.handleContextMenu})))):null))}}const Ps=(0,s.injectIntl)(Ts),Ms=new Audio("audio/call-out.m4a");Ms.loop=!0;const Rs=new Audio("audio/call-end.m4a");Rs.loop=!0;const _s=new Audio("audio/dialing.m4a"),Ns="video:muted",Ds="video:unmuted",Is=(0,s.defineMessages)({already_in_call:{id:"already_in_call",defaultMessage:[{type:0,value:"You already in an ongoing call!"}]}});class As extends t().PureComponent{constructor(e){super(e),this.state={localStream:void 0,remoteStream:void 0,pc:void 0,dataChannel:void 0,previousOnInfo:void 0,waitingForPeer:!1,callInitialSetupComplete:!1,audioOnly:e.callAudioOnly,videoToggleInProgress:!1,remoteVideoLive:!1},this.localStreamConstraints={audio:!0,video:!e.callAudioOnly},this.isOutgoingCall=e.callState==Xi,this.localRef=t().createRef(),this.remoteRef=t().createRef(),this.remoteIceCandidatesCache=[],this.onInfo=this.onInfo.bind(this),this.start=this.start.bind(this),this.stop=this.stop.bind(this),this.createPeerConnection=this.createPeerConnection.bind(this),this.canSendOffer=this.canSendOffer.bind(this),this.drainRemoteIceCandidatesCache=this.drainRemoteIceCandidatesCache.bind(this),this.handleNegotiationNeededEvent=this.handleNegotiationNeededEvent.bind(this),this.handleICECandidateEvent=this.handleICECandidateEvent.bind(this),this.handleNewICECandidateMsg=this.handleNewICECandidateMsg.bind(this),this.handleICEConnectionStateChangeEvent=this.handleICEConnectionStateChangeEvent.bind(this),this.handleSignalingStateChangeEvent=this.handleSignalingStateChangeEvent.bind(this),this.handleICEGatheringStateChangeEvent=this.handleICEGatheringStateChangeEvent.bind(this),this.handleIceCandidateErrorEvent=this.handleIceCandidateErrorEvent.bind(this),this.handleTrackEvent=this.handleTrackEvent.bind(this),this.handleVideoOfferMsg=this.handleVideoOfferMsg.bind(this),this.handleVideoAnswerMsg=this.handleVideoAnswerMsg.bind(this),this.handleNewICECandidateMsg=this.handleNewICECandidateMsg.bind(this),this.reportError=this.reportError.bind(this),this.handleGetUserMediaError=this.handleGetUserMediaError.bind(this),this.stopTracks=this.stopTracks.bind(this),this.disconnectMedia=this.disconnectMedia.bind(this),this.handleCloseClick=this.handleCloseClick.bind(this),this.handleToggleCameraClick=this.handleToggleCameraClick.bind(this),this.handleToggleMicClick=this.handleToggleMicClick.bind(this),this.handleRemoteHangup=this.handleRemoteHangup.bind(this),this.handleVideoCallAccepted=this.handleVideoCallAccepted.bind(this),this.muteVideo=this.muteVideo.bind(this),this.unmuteVideo=this.unmuteVideo.bind(this),this.emptyVideoTrack=this.emptyVideoTrack.bind(this),this.handleDataChannelEvent=this.handleDataChannelEvent.bind(this),this.handleDataChannelError=this.handleDataChannelError.bind(this),this.handleDataChannelMessage=this.handleDataChannelMessage.bind(this),this.handleDataChannelOpen=this.handleDataChannelOpen.bind(this),this.handleDataChannelClose=this.handleDataChannelClose.bind(this)}componentDidMount(){const e=this.props.tinode.getTopic(this.props.topic);this.previousOnInfo=e.onInfo,e.onInfo=this.onInfo,this.props.callState!=Xi&&this.props.callState!=Yi||!this.localRef.current||this.start()}componentWillUnmount(){this.props.tinode.getTopic(this.props.topic).onInfo=this.previousOnInfo,this.stop()}handleVideoCallAccepted(e){Ms.pause();const t=this.createPeerConnection(!0),i=this.state.localStream;i.getTracks().forEach((e=>{t.addTrack(e,i),"video"==e.kind&&this.state.audioOnly&&(e.enabled=!1,e.stop(),i.removeTrack(e))}))}onInfo(e){if("call"==e.what)switch(e.event){case"accept":this.handleVideoCallAccepted(e);break;case"answer":this.handleVideoAnswerMsg(e);break;case"ice-candidate":this.handleNewICECandidateMsg(e);break;case"hang-up":this.handleRemoteHangup(e);break;case"offer":this.handleVideoOfferMsg(e);break;case"ringing":Ms.play().catch((e=>{}));break;default:console.warn("Unknown call event",e.event)}}emptyVideoTrack(){const e=Object.assign(document.createElement("canvas"),{width:640,height:480});e.getContext("2d").fillRect(0,0,640,480);const t=e.captureStream(0);return Object.assign(t.getVideoTracks()[0],{enabled:!1})}start(){this.state.localStream?this.props.onError(this.props.intl.formatMessage(Is.already_in_call),"info"):this.props.callState!=Yi?navigator.mediaDevices.getUserMedia(this.localStreamConstraints).then((e=>{this.localStreamConstraints.video||e.addTrack(this.emptyVideoTrack()),this.setState({localStream:e,waitingForPeer:!0}),this.localRef.current.srcObject=e,_s.play(),this.props.onInvite(this.props.topic,this.props.seq,this.props.callState,this.props.callAudioOnly)})).catch(this.handleGetUserMediaError):this.props.onInvite(this.props.topic,this.props.seq,Yi,this.props.callAudioOnly)}stop(){Rs.pause(),Rs.currentTime=0,Ms.pause(),Ms.currentTime=0,this.stopTracks(this.state.localStream),this.stopTracks(this.state.remoteStream),this.disconnectMedia(this.localRef.current),this.disconnectMedia(this.remoteRef.current),this.state.pc&&(this.state.pc.ontrack=null,this.state.pc.onremovetrack=null,this.state.pc.onremovestream=null,this.state.pc.onicecandidate=null,this.state.pc.oniceconnectionstatechange=null,this.state.pc.onsignalingstatechange=null,this.state.pc.onicegatheringstatechange=null,this.state.pc.onnegotiationneeded=null,this.state.pc.onicecandidateerror=null,this.state.pc.ondatachannel=null,!this.state.dataChannel||"open"!=this.state.dataChannel.readyState&&"connecting"!=this.state.dataChannel.readyState||this.state.dataChannel.close(),this.state.pc.close()),this.setState({pc:null,waitingForPeer:!1})}disconnectMedia(e){e&&(e.srcObject=null,e.src="")}stopTracks(e){if(!e)return;let t=e.getTracks();t&&t.forEach((e=>{e.stop(),e.enabled=!1}))}handleDataChannelError(e){console.error("data channel error",e)}handleDataChannelMessage(e){switch(e.data){case Ns:this.setState({remoteVideoLive:!1},(e=>{this.remoteRef.current.srcObject=this.state.remoteStream}));break;case Ds:this.setState({remoteVideoLive:!0},(e=>{this.remoteRef.current.srcObject=this.state.remoteStream}))}}handleDataChannelOpen(e){this.state.audioOnly||e.target.send(Ds)}handleDataChannelClose(e){console.log("close data channel:",e)}handleDataChannelEvent(e){console.log("data channel event:",e);const t=e.channel;t.onerror=this.handleDataChannelError,t.onmessage=this.handleDataChannelMessage,t.onopen=this.handleDataChannelOpen,t.onclose=this.handleDataChannelClose,this.setState({dataChannel:t})}createPeerConnection(e){const t=this.props.tinode.getServerParam("iceServers",null),i=t?new RTCPeerConnection({iceServers:t}):new RTCPeerConnection;i.onicecandidate=this.handleICECandidateEvent,i.oniceconnectionstatechange=this.handleICEConnectionStateChangeEvent,i.onicegatheringstatechange=this.handleICEGatheringStateChangeEvent,i.onsignalingstatechange=this.handleSignalingStateChangeEvent,i.onnegotiationneeded=this.handleNegotiationNeededEvent,i.onicecandidateerror=this.handleIceCandidateErrorEvent,i.ontrack=this.handleTrackEvent,i.ondatachannel=this.handleDataChannelEvent;let s={pc:i,waitingForPeer:!1};if(e){const e=i.createDataChannel("events",{ordered:!0});e.onerror=this.handleDataChannelError,e.onmessage=this.handleDataChannelMessage,e.onopen=this.handleDataChannelOpen,e.onclose=this.handleDataChannelClose,s.dataChannel=e}return this.setState(s),i}handleVideoAnswerMsg(e){const t=new RTCSessionDescription(e.payload);this.state.pc.setRemoteDescription(t).then((e=>{this.setState({callInitialSetupComplete:!0},(e=>this.drainRemoteIceCandidatesCache()))})).catch((e=>this.reportError(e)))}reportError(e){this.props.onError(e.message,"err")}canSendOffer(){return this.isOutgoingCall||this.state.callInitialSetupComplete}handleNegotiationNeededEvent(e){const t=e.target;this.canSendOffer()&&t.createOffer().then((e=>t.setLocalDescription(e))).then((e=>{this.props.onSendOffer(this.props.topic,this.props.seq,t.localDescription.toJSON())})).catch((e=>this.reportError(e)))}handleIceCandidateErrorEvent(e){console.warn("ICE candidate error:",e)}handleICECandidateEvent(e){e.candidate&&this.props.onIceCandidate(this.props.topic,this.props.seq,e.candidate.toJSON())}handleNewICECandidateMsg(e){const t=new RTCIceCandidate(e.payload);this.state.callInitialSetupComplete?this.state.pc.addIceCandidate(t).catch((e=>{t.candidate&&this.reportError(e),console.warn("Error adding new ice candidate",t,e)})):this.remoteIceCandidatesCache.push(t)}drainRemoteIceCandidatesCache(){this.remoteIceCandidatesCache.forEach((e=>{this.state.pc.addIceCandidate(e).catch((t=>{e.candidate&&this.reportError(t),console.warn("Error adding cached ice candidate",e,t)}))})),this.remoteIceCandidatesCache=[]}handleICEConnectionStateChangeEvent(e){switch(e.target.iceConnectionState){case"closed":case"failed":this.handleCloseClick()}}handleSignalingStateChangeEvent(e){"closed"==e.target.signalingState&&this.handleCloseClick()}handleICEGatheringStateChangeEvent(e){}handleTrackEvent(e){this.remoteRef.current.srcObject=e.streams[0],this.setState({remoteStream:e.streams[0]})}handleGetUserMediaError(e){switch(console.error("Error opening camera and/or microphone",e),e.name){case"NotFoundError":default:this.reportError(e);case"SecurityError":case"PermissionDeniedError":}this.handleCloseClick()}handleVideoOfferMsg(e){let t=null;const i=this.state.pc?this.state.pc:this.createPeerConnection(!1),s=new RTCSessionDescription(e.payload);i.setRemoteDescription(s).then((e=>navigator.mediaDevices.getUserMedia(this.localStreamConstraints))).then((e=>{let s;this.localStreamConstraints.video||(s=this.emptyVideoTrack(),e.addTrack(s)),t=e,this.localRef.current.srcObject=e,this.setState({localStream:e}),t.getTracks().forEach((e=>{i.addTrack(e,t)})),s&&(s.enabled=!1,s.stop(),e.removeTrack(s))})).then((e=>i.createAnswer())).then((e=>i.setLocalDescription(e))).then((e=>{this.props.onSendAnswer(this.props.topic,this.props.seq,i.localDescription.toJSON()),this.setState({callInitialSetupComplete:!0},(e=>this.drainRemoteIceCandidatesCache()))})).catch(this.handleGetUserMediaError)}handleRemoteHangup(){this.state.waitingForPeer?(this.setState({waitingForPeer:!1}),Ms.pause(),Ms.currentTime=0,Rs.loop=!0,Rs.play().catch((e=>{})),setTimeout((e=>{this.handleCloseClick()}),2e3)):this.handleCloseClick()}handleCloseClick(){this.stop(),this.props.onHangup(this.props.topic,this.props.seq)}muteVideo(){if(!this.state.pc||!this.state.dataChannel)return;const e=this.state.localStream,t=e.getVideoTracks()[0];t.enabled=!1,t.stop(),e.removeTrack(t),this.state.dataChannel.send(Ns),this.setState({videoToggleInProgress:!1})}unmuteVideo(){this.state.pc&&this.state.dataChannel&&navigator.mediaDevices.getUserMedia({video:!0}).then((e=>{this.localRef.current.srcObject=null;const t=this.state.pc.getSenders().find((e=>"video"==e.track.kind)),i=e.getVideoTracks()[0];return e.removeTrack(i),this.state.localStream.addTrack(i),t.replaceTrack(i)})).then((e=>{this.localRef.current.srcObject=this.state.localStream,this.state.dataChannel.send(Ds)})).catch((e=>this.handleGetUserMediaError(e))).finally((e=>{this.setState({videoToggleInProgress:!1})}))}handleToggleCameraClick(){if(this.state.videoToggleInProgress)return;const e=this.state.localStream.getVideoTracks();this.setState({videoToggleInProgress:!0},(t=>{e&&e.length>0&&e[0].enabled&&"live"==e[0].readyState?this.muteVideo():this.unmuteVideo(),this.setState({audioOnly:!this.state.audioOnly})}))}handleToggleMicClick(){const e=this.state.localStream.getAudioTracks()[0];e.enabled=!e.enabled,this.forceUpdate()}render(){const e=this.state.localStream&&this.state.localStream.getAudioTracks(),i=!this.state.audioOnly&&this.state.localStream&&this.state.localStream.getVideoTracks(),n=!this.state.pc||!this.state.dataChannel||!(e&&e[0]),a=e&&e[0]&&e[0].enabled?"mic":"mic_off",r=i&&i[0]&&i[0].enabled&&"live"==i[0].readyState?"videocam":"videocam_off",o=(0,Di.Th)(this.props.title,mi.gD),c=this.state.waitingForPeer?" pulse":"";let l=!1;if(this.remoteRef.current&&this.remoteRef.current.srcObject&&this.state.remoteVideoLive){const e=this.remoteRef.current.srcObject;if(e.getVideoTracks().length>0){const t=e.getVideoTracks()[0];l=t.enabled&&"live"==t.readyState}}return t().createElement(t().Fragment,null,t().createElement("div",{id:"video-container"},t().createElement("div",{id:"video-container-panel"},t().createElement("div",{className:"call-party self",disabled:this.state.audioOnly},t().createElement("video",{ref:this.localRef,autoPlay:!0,muted:!0,playsInline:!0}),t().createElement("div",{className:"caller-name inactive"},t().createElement(s.FormattedMessage,{id:"calls_you_label",defaultMessage:[{type:0,value:"You"}]}))),t().createElement("div",{className:"call-party peer",disabled:!l},l?t().createElement(t().Fragment,null,t().createElement("video",{ref:this.remoteRef,autoPlay:!0,playsInline:!0}),t().createElement("div",{className:"caller-name inactive"},o)):t().createElement(t().Fragment,null,t().createElement("audio",{ref:this.remoteRef,autoPlay:!0}),t().createElement("div",{className:`caller-card${c}`},t().createElement("div",{className:"avatar-box"},t().createElement(Si.Z,{tinode:this.props.tinode,avatar:this.props.avatar,topic:this.props.topic,title:this.props.title})),t().createElement("div",{className:"caller-name"},o))))),t().createElement("div",{className:"controls"},t().createElement("button",{className:"danger",onClick:this.handleCloseClick},t().createElement("i",{className:"material-icons"},"call_end")),t().createElement("button",{className:"secondary",onClick:this.handleToggleCameraClick,disabled:n},t().createElement("i",{className:"material-icons"},r)),t().createElement("button",{className:"secondary",onClick:this.handleToggleMicClick,disabled:n},t().createElement("i",{className:"material-icons"},a)))))}}const Os=(0,s.injectIntl)(As);class Us extends t().Component{constructor(e){super(e),this.state={downloader:null,progress:0},this.downloadFile=this.downloadFile.bind(this),this.handleCancel=this.handleCancel.bind(this)}downloadFile(e,t,i){if(!e)return void this.props.onError("Invalid download URL '"+e+"'");const s=this.props.tinode.getLargeFileHelper();this.setState({downloader:s}),s.download(e,t,i,(e=>this.setState({progress:e/this.props.size})),(e=>this.props.onError(e,"err"))).then((e=>this.setState({downloader:null,progress:0}))).catch((e=>{e&&this.props.onError("Error downloading file: "+e.message,"err"),this.setState({downloader:null,progress:0})}))}handleCancel(){this.props.uploading?this.props.onCancelUpload():this.state.downloader&&this.state.downloader.cancel()}render(){let e=this.props.filename||"file_attachment";e.length>36&&(e=e.substr(0,16)+"..."+e.substr(-16));let i,n,a=this.props.size>0?t().createElement("span",{className:"small gray"},"(",(0,ki.FK)(this.props.size),")"):null;this.props.uploading||this.state.downloader||!(0,Di.Xc)(this.props.downloadUrl)?(i=(0,Di.Nm)(this.props.downloadUrl),n=null):(i="#",n=e=>{e.preventDefault(),this.downloadFile(this.props.downloadUrl,this.props.filename,this.props.mimetype)});const r=t().createElement(t().Fragment,null,t().createElement("i",{className:"material-icons"},"file_download")," ",t().createElement(s.FormattedMessage,{id:"save_attachment",defaultMessage:[{type:0,value:"save"}]}));return t().createElement("div",{className:"attachment"},t().createElement("div",null,t().createElement("i",{className:"material-icons big gray"},"insert_drive_file")),t().createElement("div",{className:"flex-column"},t().createElement("div",null,e," ",a),this.props.uploading||this.state.downloader?t().createElement(Ri,{progress:this.props.uploading?this.props.progress:this.state.progress,onCancel:this.handleCancel}):t().createElement("div",null,i?t().createElement("a",{href:i,download:this.props.filename,onClick:n},r):t().createElement("span",{className:"light-gray"},r))))}}const xs=(0,s.defineMessages)({message_sending:{id:"message_sending",defaultMessage:[{type:0,value:"sending..."}]},message_sending_failed:{id:"message_sending_failed",defaultMessage:[{type:0,value:"failed"}]},message_edited_marker:{id:"message_edited_marker",defaultMessage:[{type:0,value:", edited"}]}});class Ls extends t().PureComponent{render(){const{formatMessage:e}=this.props.intl;let i;i=this.props.received<=ui.Tinode.MESSAGE_STATUS_SENDING?e(xs.message_sending):this.props.received==ui.Tinode.MESSAGE_STATUS_FAILED||this.props.received==ui.Tinode.MESSAGE_STATUS_FATAL?e(xs.message_sending_failed):this.props.timestamp.toLocaleTimeString(this.props.intl.locale,{timeStyle:"short"});const s=(0,Di.es)(this.props.received),n=s?t().createElement("i",{className:"material-icons small "+s.color},s.name):null,a=this.props.edited?e(xs.message_edited_marker):null;return t().createElement("span",{className:"timestamp"},i,a," ",n)}}const Fs=(0,s.injectIntl)(Ls);function Bs(){return Bs=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(e[s]=i[s])}return e},Bs.apply(this,arguments)}class qs extends t().PureComponent{constructor(e){super(e),this.state={progress:0},e.uploader&&(e.uploader.onProgress=this.handleProgress.bind(this)),this.handleExpandImage=this.handleExpandImage.bind(this),this.handlePlayVideo=this.handlePlayVideo.bind(this),this.handleFormButtonClick=this.handleFormButtonClick.bind(this),this.handleContextClick=this.handleContextClick.bind(this),this.handleCancelUpload=this.handleCancelUpload.bind(this),this.handleQuoteClick=this.handleQuoteClick.bind(this),this.handleCallJoin=this.handleCallJoin.bind(this),this.formatterContext={formatMessage:e.intl.formatMessage.bind(e.intl),viewportWidth:e.viewportWidth,authorizeURL:e.tinode.authorizeURL.bind(e.tinode),onImagePreview:this.handleExpandImage,onVideoPreview:this.handlePlayVideo,onFormButtonClick:this.handleFormButtonClick,onQuoteClick:this.handleQuoteClick,onCallJoin:this.handleCallJoin}}handleExpandImage(e){e.preventDefault(),this.props.onExpandMedia({url:e.target.src,filename:e.target.dataset.name,width:e.target.dataset.width,height:e.target.dataset.height,size:e.target.dataset.size,type:e.target.dataset.mime})}handlePlayVideo(e){e.preventDefault(),this.props.onExpandMedia({video:!0,url:e.target.dataset.src,preview:e.target.src,filename:e.target.dataset.name,width:e.target.dataset.width,height:e.target.dataset.height,duration:e.target.dataset.duration,size:e.target.dataset.size,type:e.target.dataset.mime})}handleFormButtonClick(e){e.preventDefault();const t={seq:this.props.seq,resp:{}};e.target.dataset.name&&(t.resp[e.target.dataset.name]=e.target.dataset.val?e.target.dataset.val:void 0===e.target.dataset.val?1:""+e.target.dataset.val),"url"==e.target.dataset.act&&(t.ref=(0,Di.Nm)(e.target.dataset.ref)||"about:blank");const i=e.target.dataset.title||"unknown";this.props.onFormResponse(e.target.dataset.act,i,t)}handleContextClick(e){e.preventDefault(),e.stopPropagation();const t=[];if(this.props.received==ui.Tinode.MESSAGE_STATUS_FAILED&&t.push("menu_item_send_retry"),this.props.received>ui.Tinode.MESSAGE_STATUS_FATAL){if(this.props.userIsWriter&&(t.push("menu_item_reply"),!this.props.response)){let e=!1;ui.Drafty.entities(this.props.content,((t,i,s)=>(e=["AU","EX","FM","IM","VC","VD"].includes(s),e))),e||ui.Drafty.styles(this.props.content,(t=>(e=["QQ"].includes(t),e))),e||t.push("menu_item_edit")}this.props.userIsAdmin&&t.push(this.props.pinned?"menu_item_unpin":"menu_item_pin")}t.push("menu_item_forward"),this.props.showContextMenu({seq:this.props.seq,replace:this.props.edited?parseInt(this.props.edited.split(":")[1]):0,content:this.props.content,userFrom:this.props.userFrom,userName:this.props.userName,y:e.pageY,x:e.pageX,pickReply:this.props.pickReply,editMessage:this.props.editMessage},t)}handleProgress(e){this.setState({progress:e})}handleCancelUpload(){this.props.onCancelUpload(this.props.seq,this.props.uploader)}handleQuoteClick(e){e.preventDefault(),e.stopPropagation();const t=this.props.replyToSeq;t&&this.props.onQuoteClick(t)}handleCallJoin(){this.props.onAcceptCall(this.props.topic,!0,this.props.seq)}render(){const e=this.props.sequence+" "+(this.props.response?"left":"right"),i="single"==this.props.sequence||"last"==this.props.sequence?"bubble tip":"bubble",n=this.props.userAvatar||!0,a=this.props.isGroup&&this.props.response&&("single"==this.props.sequence||"last"==this.props.sequence);let r=this.props.content;const o=[];if(this.props.mimeType==ui.Drafty.getContentType()&&ui.Drafty.isValid(r)){ui.Drafty.attachments(r,((e,i)=>{"application/json"!=e.mime&&o.push(t().createElement(Us,{tinode:this.props.tinode,downloadUrl:ui.Drafty.getDownloadUrl(e),filename:e.name,uploading:ui.Drafty.isProcessing(e),mimetype:e.mime,size:ui.Drafty.getEntitySize(e),progress:this.state.progress,onCancelUpload:this.handleCancelUpload,onError:this.props.onError,key:i}))}),this);const e=ui.Drafty.format(r,Ai,this.formatterContext);r=t().createElement(t().Fragment,null,e)}else"string"!=typeof r&&(r=t().createElement(t().Fragment,null,t().createElement("i",{className:"material-icons gray"},"warning_amber")," ",t().createElement("i",{className:"gray"},t().createElement(s.FormattedMessage,{id:"invalid_content",defaultMessage:[{type:0,value:"invalid content"}]}))));return t().createElement("li",{ref:this.props.innerRef,className:e},this.props.isGroup&&this.props.response?t().createElement("div",{className:"avatar-box"},a?t().createElement(Si.Z,{tinode:this.props.tinode,topic:this.props.userFrom,title:this.props.userName,avatar:n}):null):null,t().createElement("div",null,t().createElement("div",{className:i},t().createElement("div",{className:"content-meta"},t().createElement("div",{className:"message-content"},r,o),this.props.timestamp?t().createElement(Fs,{edited:this.props.edited,timestamp:this.props.timestamp,received:this.props.received}):null),this.props.showContextMenu?t().createElement("span",{className:"menuTrigger"},t().createElement("a",{href:"#",onClick:this.handleContextClick},t().createElement("i",{className:"material-icons"},"expand_more"))):null),a?t().createElement("div",{className:"author"},this.props.userName||t().createElement("i",null,t().createElement(s.FormattedMessage,{id:"user_not_found",defaultMessage:[{type:0,value:"Not found"}]}))):null))}}const js=(0,s.injectIntl)(qs),Vs=t().forwardRef(((e,i)=>t().createElement(js,Bs({innerRef:i},e)))),$s=t().lazy((e=>Promise.all([r.e(246),r.e(252)]).then(r.bind(r,252)))),Ws=(0,s.defineMessages)({messaging_disabled:{id:"messaging_disabled_prompt",defaultMessage:[{type:0,value:"Messaging disabled"}]},type_new_message:{id:"new_message_prompt",defaultMessage:[{type:0,value:"New message"}]},add_image_caption:{id:"image_caption_prompt",defaultMessage:[{type:0,value:"Image caption"}]},file_attachment_too_large:{id:"file_attachment_too_large",defaultMessage:[{type:0,value:"The file size "},{type:1,value:"size"},{type:0,value:" exceeds the "},{type:1,value:"limit"},{type:0,value:" limit."}]},cannot_initiate_upload:{id:"cannot_initiate_file_upload",defaultMessage:[{type:0,value:"Cannot initiate file upload."}]},icon_title_record_voice:{id:"icon_title_record_voice",defaultMessage:[{type:0,value:"Record voice message"}]},icon_title_attach_file:{id:"icon_title_attach_file",defaultMessage:[{type:0,value:"Attach file"}]},icon_title_add_image:{id:"icon_title_add_image",defaultMessage:[{type:0,value:"Add image"}]},icon_title_send:{id:"icon_title_send",defaultMessage:[{type:0,value:"Send message"}]}});class Js extends t().PureComponent{constructor(e){super(e),this.state={quote:null,message:"",audioRec:!1,audioAvailable:!(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)},this.keypressTimestamp=0,this.handlePasteEvent=this.handlePasteEvent.bind(this),this.handleAttachImage=this.handleAttachImage.bind(this),this.handleAttachFile=this.handleAttachFile.bind(this),this.handleAttachAudio=this.handleAttachAudio.bind(this),this.handleSend=this.handleSend.bind(this),this.handleKeyPress=this.handleKeyPress.bind(this),this.handleMessageTyping=this.handleMessageTyping.bind(this),this.handleDropAttach=this.handleDropAttach.bind(this),this.handleQuoteClick=this.handleQuoteClick.bind(this),this.formatReply=this.formatReply.bind(this)}componentDidMount(){this.messageEditArea&&(this.messageEditArea.addEventListener("paste",this.handlePasteEvent,!1),"all"==window.getComputedStyle(this.messageEditArea).getPropertyValue("transition-property")&&this.messageEditArea.focus()),this.setState({quote:this.formatReply()})}componentWillUnmount(){this.messageEditArea&&this.messageEditArea.removeEventListener("paste",this.handlePasteEvent,!1)}componentDidUpdate(e){if(this.messageEditArea&&("all"==window.getComputedStyle(this.messageEditArea).getPropertyValue("transition-property")&&this.messageEditArea.focus(),this.messageEditArea.style.height="0px",this.messageEditArea.style.height=this.messageEditArea.scrollHeight+"px"),e.topicName!=this.props.topicName)this.setState({message:this.props.initMessage||"",audioRec:!1,quote:null});else if(e.initMessage!=this.props.initMessage){const e=this.props.initMessage||"";this.setState({message:e},(t=>{this.messageEditArea.scrollTop=this.messageEditArea.scrollHeight,this.messageEditArea.setSelectionRange(e.length,e.length)}))}e.reply!=this.props.reply&&this.setState({quote:this.formatReply()})}formatReply(){return this.props.reply?ui.Drafty.format(this.props.reply.content,ji,{formatMessage:this.props.intl.formatMessage.bind(this.props.intl),authorizeURL:this.props.tinode.authorizeURL.bind(this.props.tinode)}):null}handlePasteEvent(e){this.props.disabled||(0,Ni.Y)(e,(e=>{this.props.onAttachImage(e)}),(e=>{this.props.onAttachFile(e)}),this.props.onError)&&e.preventDefault()}handleAttachImage(e){e.target.files&&e.target.files.length>0&&this.props.onAttachImage(e.target.files[0]),e.target.value=""}handleAttachFile(e){e.target.files&&e.target.files.length>0&&this.props.onAttachFile(e.target.files[0]),e.target.value=""}handleDropAttach(e){e&&e.length>0&&this.props.onAttachFile(e[0])}handleAttachAudio(e,t,i){this.setState({audioRec:!1}),this.props.onAttachAudio(e,t,i)}handleSend(e){e.preventDefault();const t=this.state.message.trim();(t||this.props.acceptBlank||this.props.noInput)&&(this.props.onSendMessage(t),this.setState({message:""}))}handleKeyPress(e){if(this.state.audioRec)return e.preventDefault(),void e.stopPropagation();"Enter"===e.key&&(e.shiftKey||(e.preventDefault(),e.stopPropagation(),this.handleSend(e)))}handleMessageTyping(e){if(this.setState({message:e.target.value}),this.props.onKeyPress){const e=(new Date).getTime();e-this.keypressTimestamp>mi.mc&&(this.props.onKeyPress(),this.keypressTimestamp=e)}}handleQuoteClick(e){if(e.preventDefault(),e.stopPropagation(),this.props.reply&&this.props.onQuoteClick){const e=this.props.reply.seq;this.props.onQuoteClick(e)}}render(){const{formatMessage:i}=this.props.intl,n=this.props.disabled?i(Ws.messaging_disabled):this.props.messagePrompt?i(Ws[this.props.messagePrompt]):i(Ws.type_new_message),a=this.props.reply&&this.props.reply.editing?"check_circle":"send",r=this.state.quote?t().createElement("div",{id:"reply-quote-preview"},t().createElement("div",{className:"cancel"},t().createElement("a",{href:"#",onClick:e=>{e.preventDefault(),this.props.onCancelReply()}},t().createElement("i",{className:"material-icons gray"},"close"))),this.state.quote):null,o=this.state.audioAvailable&&this.props.onAttachAudio;return t().createElement("div",{id:"send-message-wrapper"},this.props.noInput?null:r,t().createElement("div",{id:"send-message-panel"},this.props.disabled?t().createElement("div",{id:"writing-disabled"},n):t().createElement(t().Fragment,null,this.props.onAttachFile&&!this.state.audioRec?t().createElement(t().Fragment,null,t().createElement("a",{href:"#",onClick:e=>{e.preventDefault(),this.attachImage.click()},title:i(Ws.icon_title_add_image)},t().createElement("i",{className:"material-icons secondary"},"photo")),t().createElement("a",{href:"#",onClick:e=>{e.preventDefault(),this.attachFile.click()},title:i(Ws.icon_title_attach_file)},t().createElement("i",{className:"material-icons secondary"},"attach_file"))):null,this.props.noInput?r||t().createElement("div",{className:"hr thin"}):this.state.audioRec?t().createElement(e.Suspense,{fallback:t().createElement("div",null,t().createElement(s.FormattedMessage,{id:"loading_note",defaultMessage:[{type:0,value:"Loading..."}]}))},t().createElement($s,{onRecordingProgress:e=>this.props.onKeyPress(!0),onDeleted:e=>this.setState({audioRec:!1}),onFinished:this.handleAttachAudio})):t().createElement("textarea",{id:"send-message-input",placeholder:n,value:this.state.message,onChange:this.handleMessageTyping,onKeyDown:this.handleKeyPress,ref:e=>{this.messageEditArea=e}}),this.state.message||!o?t().createElement("a",{href:"#",onClick:this.handleSend,title:i(Ws.icon_title_send)},t().createElement("i",{className:"material-icons"},a)):this.state.audioRec?null:t().createElement("a",{href:"#",onClick:e=>{e.preventDefault(),this.setState({audioRec:!0})},title:i(Ws.icon_title_record_voice)},t().createElement("i",{className:"material-icons"},"mic")),t().createElement("input",{type:"file",ref:e=>{this.attachFile=e},onChange:this.handleAttachFile,style:{display:"none"}}),t().createElement("input",{type:"file",ref:e=>{this.attachImage=e},accept:"image/*, video/*",onChange:this.handleAttachImage,style:{display:"none"}}))))}}const Hs=(0,s.injectIntl)(Js);class Gs extends t().PureComponent{constructor(e){super(e),this.handleSendDoc=this.handleSendDoc.bind(this),this.handleKeyDown=this.handleKeyDown.bind(this)}componentDidMount(){document.addEventListener("keydown",this.handleKeyDown)}componentWillUnmount(){document.removeEventListener("keydown",this.handleKeyDown)}handleKeyDown(e){e.preventDefault(),"Escape"===e.key&&this.props.onClose()}handleSendDoc(e){this.props.onClose(),this.props.onSendMessage(this.props.content.file)}render(){return this.props.content?t().createElement("div",{id:"image-preview"},t().createElement("div",{id:"image-preview-caption-panel"},t().createElement("span",null,this.props.content.name),t().createElement("a",{href:"#",onClick:e=>{e.preventDefault(),this.props.onClose()}},t().createElement("i",{className:"material-icons gray"},"close"))),t().createElement("div",{id:"image-preview-container"},t().createElement("div",{className:"flex-column narrow"},t().createElement("i",{className:"material-icons gray"},function(e){const t={default:"insert_drive_file",image:"image",text:"description",video:"theaters"};return t[e]||t[(e||"").split("/")[0]]||t.default}(this.props.content.type)),t().createElement("div",null,t().createElement("b",null,t().createElement(s.FormattedMessage,{id:"label_file_name",defaultMessage:[{type:0,value:"File name:"}]}))," ",(0,ki.TX)(this.props.content.name,24)||"-"),t().createElement("div",null,t().createElement("b",null,t().createElement(s.FormattedMessage,{id:"label_content_type",defaultMessage:[{type:0,value:"Content type:"}]}))," ",this.props.content.type||"application/octet-stream"),t().createElement("div",null,t().createElement("b",null,t().createElement(s.FormattedMessage,{id:"label_size",defaultMessage:[{type:0,value:"Size:"}]}))," ",(0,ki.FK)(this.props.content.size)))),t().createElement(Hs,{noInput:!0,tinode:this.props.tinode,reply:this.props.reply,onCancelReply:this.props.onCancelReply,onSendMessage:this.handleSendDoc,onError:this.props.onError})):null}}class zs extends t().Component{constructor(e){super(e)}render(){const e=[],i=(this.props.subscribers||[]).length,n=Math.min(mi.dm,i);return(this.props.subscribers||[]).some((i=>(e.push(t().createElement("div",{className:"avatar-box",key:i.user},t().createElement(Si.Z,{tinode:this.props.tinode,topic:i.user,avatar:(0,Ni.PD)(i.public?i.public.photo:null)||!0,title:i.public?i.public.fn:null}))),e.length==n))),0==e.length?null:t().createElement("div",{id:"topic-users"},e," ",i>n?t().createElement("span",null,t().createElement(s.FormattedMessage,{id:"more_online_members",defaultMessage:[{type:0,value:"+"},{type:1,value:"overflow"},{type:0,value:" more"}],values:{overflow:i-n}})):null)}}class Zs extends t().PureComponent{constructor(e){super(e),this.state={width:0,height:0},this.handleSendImage=this.handleSendImage.bind(this),this.handleKeyDown=this.handleKeyDown.bind(this)}componentDidMount(){document.addEventListener("keydown",this.handleKeyDown)}componentWillUnmount(){document.removeEventListener("keydown",this.handleKeyDown)}handleKeyDown(e){this.props.onSendMessage||(e.preventDefault(),"Escape"===e.key&&this.props.onClose())}assignWidth(e){if(e&&!this.state.width){const t=e.getBoundingClientRect();this.setState({width:0|t.width,height:0|t.height})}}handleSendImage(e){this.props.onClose(),this.props.onSendMessage(e,this.props.content.blob)}render(){if(!this.props.content)return null;const e=(0,Ni.rS)(this.props.content.width,this.props.content.height,this.state.width,this.state.height,!1),i=e?{width:e.dstWidth+"px",height:e.dstHeight+"px"}:this.props.content.width>this.props.content.height?{width:"100%"}:{height:"100%"};i.maxWidth="100%",i.maxHeight="100%";const n=Math.max((this.state.width/mi.o6/1.5|0)-2,12),a=(0,ki.TX)(this.props.content.filename,n)||"-",r=this.props.content.width||"-",o=this.props.content.height||"-";return t().createElement("div",{id:"image-preview"},t().createElement("div",{id:"image-preview-caption-panel"},this.props.onSendMessage?t().createElement("span",null,a):t().createElement("a",{href:this.props.content.url,download:this.props.content.filename},t().createElement("i",{className:"material-icons"},"file_download")," ",t().createElement(s.FormattedMessage,{id:"download_action",defaultMessage:[{type:0,value:"download"}]})),t().createElement("a",{href:"#",onClick:e=>{e.preventDefault(),this.props.onClose()}},t().createElement("i",{className:"material-icons gray"},"close"))),t().createElement("div",{id:"image-preview-container",ref:e=>this.assignWidth(e)},t().createElement("img",{src:this.props.content.url,style:i,className:"image-preview",alt:this.props.content.filename})),this.props.onSendMessage?t().createElement(Hs,{messagePrompt:"add_image_caption",acceptBlank:!0,tinode:this.props.tinode,reply:this.props.reply,onCancelReply:this.props.onCancelReply,onSendMessage:this.handleSendImage,onError:this.props.onError}):t().createElement("div",{id:"image-preview-footer"},t().createElement("div",null,t().createElement("div",null,t().createElement("b",null,t().createElement(s.FormattedMessage,{id:"label_file_name",defaultMessage:[{type:0,value:"File name:"}]}))),t().createElement("div",null,t().createElement("span",{title:this.props.content.filename},a))),t().createElement("div",null,t().createElement("div",null,t().createElement("b",null,t().createElement(s.FormattedMessage,{id:"label_content_type",defaultMessage:[{type:0,value:"Content type:"}]}))),t().createElement("div",null,this.props.content.type)),t().createElement("div",null,t().createElement("div",null,t().createElement("b",null,t().createElement(s.FormattedMessage,{id:"label_size",defaultMessage:[{type:0,value:"Size:"}]}))),t().createElement("div",null,r," × ",o," px; ",(0,ki.FK)(this.props.content.size)))))}}class Ks extends t().PureComponent{constructor(e){super(e),this.handleButtonAction=this.handleButtonAction.bind(this)}handleButtonAction(e,t){e.preventDefault(),this.props.onAction(t)}render(){return t().createElement("div",{className:"accept-invite-panel"},t().createElement("div",{className:"title"},t().createElement(s.FormattedMessage,{id:"chat_invitation",defaultMessage:[{type:0,value:"You are invited to start a new chat. What would you like to do?"}]})),t().createElement("div",{className:"footer"},t().createElement("button",{className:"primary",onClick:e=>{this.handleButtonAction(e,"accept")}},t().createElement(s.FormattedMessage,{id:"chat_invitation_accept",defaultMessage:[{type:0,value:"Accept"}]})),t().createElement("button",{className:"secondary",onClick:e=>{this.handleButtonAction(e,"delete")}},t().createElement(s.FormattedMessage,{id:"chat_invitation_ignore",defaultMessage:[{type:0,value:"Ignore"}]})),t().createElement("button",{className:"secondary",onClick:e=>{this.handleButtonAction(e,"block")}},t().createElement(s.FormattedMessage,{id:"chat_invitation_block",defaultMessage:[{type:0,value:"Block"}]}))))}}var Qs=r(7646);class Xs extends t().PureComponent{render(){const e=mi.iC+" ("+ui.Tinode.getLibrary()+")";return t().createElement("div",{id:"dummy-view"},t().createElement("div",null,t().createElement("a",{href:"https://github.com/tinode/chat/"},t().createElement("img",{id:"logo",alt:"logo",src:"img/logo.svg"}),t().createElement("h2",null,"Tinode Web")),t().createElement("p",null,t().createElement(s.FormattedMessage,{id:"label_client",defaultMessage:[{type:0,value:"Client:"}]})," ",e),t().createElement("p",null,t().createElement(s.FormattedMessage,{id:"label_server",defaultMessage:[{type:0,value:"Server:"}]})," ",this.props.serverVersion," (",this.props.serverAddress,")")))}}class Ys extends t().PureComponent{constructor(e){super(e)}render(){let e=null,i="bubble";return this.props.date&&(e=t().createElement(t().Fragment,null,this.props.date),i+=" date"),e?t().createElement("li",{className:"meta"},t().createElement("div",{className:i},t().createElement("div",{className:"message-content"},e))):t().createElement(t().Fragment,null,null)}}class en extends t().PureComponent{constructor(e){super(e),this.getSelectedIndex=this.getSelectedIndex.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleSelected=this.handleSelected.bind(this),this.handleMoveNext=this.handleMoveNext.bind(this),this.handleMovePrev=this.handleMovePrev.bind(this)}getSelectedIndex(){return(this.props.messages||[]).length-this.props.selected-1}handleCancel(e){e.preventDefault(),this.props.onCancel(this.props.messages[this.getSelectedIndex()].seq)}handleSelected(e){e.preventDefault(),this.props.onSelected(this.props.messages[this.getSelectedIndex()].seq)}handleMoveNext(e){e.preventDefault(),e.stopPropagation();const t=Math.max(this.props.selected-1,0);t!=this.props.selected&&this.props.setSelected(t)}handleMovePrev(e){e.preventDefault(),e.stopPropagation();const t=Math.min(this.props.selected+1,(this.props.messages||[]).length-1);t!=this.props.selected&&this.props.setSelected(t)}render(){const e=this.getSelectedIndex();let i=(this.props.messages||[])[e];i=i?ui.Drafty.format(i.content,xi,{formatMessage:this.props.intl.formatMessage.bind(this.props.intl),authorizeURL:this.props.tinode.authorizeURL.bind(this.props.tinode)}):null;const s=[];return this.props.messages.forEach((i=>{const n=s.length==e?"adot":"dot";s.push(t().createElement("div",{key:s.length,className:n}))})),i?t().createElement("div",{id:"pinned-wrapper"},this.props.isAdmin?t().createElement("div",{className:"cancel"},t().createElement("a",{href:"#",onClick:this.handleCancel},t().createElement("i",{className:"material-icons gray"},"close"))):t().createElement("div",null,t().createElement("i",{className:"material-icons gray"},"push_pin")),t().createElement("div",{className:"pinned-scroll"},s),t().createElement("div",{className:"pinned",onClick:this.handleSelected},t().createElement("p",null,i)),e>0?t().createElement("span",{className:"menuTrigger upper"},t().createElement("a",{href:"#",onClick:this.handleMovePrev},t().createElement("i",{className:"material-icons"},"expand_less"))):null,this.props.selected>0?t().createElement("span",{className:"menuTrigger lower"},t().createElement("a",{href:"#",onClick:this.handleMoveNext},t().createElement("i",{className:"material-icons"},"expand_more"))):null):null}}const tn=(0,s.injectIntl)(en);function sn(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var s=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,s.get?s:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}var nn="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function an(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var rn,on,cn={};rn={get exports(){return cn},set exports(e){cn=e}},function(e,t){rn.exports?rn.exports=t():e.log=t()}(nn,(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"];function n(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(t){return function(){return Function.prototype.apply.apply(i,[e,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function r(t,i){for(var n=0;n<s.length;n++){var a=s[n];this[a]=n<t?e:this.methodFactory(a,t,i)}this.log=this.debug}function o(e,i,s){return function(){typeof console!==t&&(r.call(this,i,s),this[e].apply(this,arguments))}}function c(s,r,c){return function(s){return"debug"===s&&(s="log"),typeof console!==t&&("trace"===s&&i?a:void 0!==console[s]?n(console,s):void 0!==console.log?n(console,"log"):e)}(s)||o.apply(this,arguments)}function l(e,i,n){var a,o=this;i=null==i?"WARN":i;var l="loglevel";function d(){var e;if(typeof window!==t&&l){try{e=window.localStorage[l]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,s=i.indexOf(encodeURIComponent(l)+"=");-1!==s&&(e=/^([^;]+)/.exec(i.slice(s))[1])}catch(e){}return void 0===o.levels[e]&&(e=void 0),e}}"string"==typeof e?l+=":"+e:"symbol"==typeof e&&(l=void 0),o.name=e,o.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},o.methodFactory=n||c,o.getLevel=function(){return a},o.setLevel=function(i,n){if("string"==typeof i&&void 0!==o.levels[i.toUpperCase()]&&(i=o.levels[i.toUpperCase()]),!("number"==typeof i&&i>=0&&i<=o.levels.SILENT))throw"log.setLevel() called with invalid level: "+i;if(a=i,!1!==n&&function(e){var i=(s[e]||"silent").toUpperCase();if(typeof window!==t&&l){try{return void(window.localStorage[l]=i)}catch(e){}try{window.document.cookie=encodeURIComponent(l)+"="+i+";"}catch(e){}}}(i),r.call(o,i,e),typeof console===t&&i<o.levels.SILENT)return"No console available for logging"},o.setDefaultLevel=function(e){i=e,d()||o.setLevel(e,!1)},o.resetLevel=function(){o.setLevel(i,!1),function(){if(typeof window!==t&&l){try{return void window.localStorage.removeItem(l)}catch(e){}try{window.document.cookie=encodeURIComponent(l)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}()},o.enableAll=function(e){o.setLevel(o.levels.TRACE,e)},o.disableAll=function(e){o.setLevel(o.levels.SILENT,e)};var h=d();null==h&&(h=i),o.setLevel(h,!1)}var d=new l,h={};d.getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=h[e];return t||(t=h[e]=new l(e,d.getLevel(),d.methodFactory)),t};var u=typeof window!==t?window.log:void 0;return d.noConflict=function(){return typeof window!==t&&window.log===d&&(window.log=u),d},d.getLoggers=function(){return h},d.default=d,d})),function(e){e[e.trace=0]="trace",e[e.debug=1]="debug",e[e.info=2]="info",e[e.warn=3]="warn",e[e.error=4]="error",e[e.silent=5]="silent"}(on||(on={}));const ln=cn.getLogger("livekit");ln.setLevel(on.info);var dn=null;try{dn=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(Uu){}function hn(e,t,i){this.low=0|e,this.high=0|t,this.unsigned=!!i}function un(e){return!0===(e&&e.__isLong__)}function pn(e){var t=Math.clz32(e&-e);return e?31-t:t}hn.prototype.__isLong__,Object.defineProperty(hn.prototype,"__isLong__",{value:!0}),hn.isLong=un;var mn={},gn={};function fn(e,t){var i,s,n;return t?(n=0<=(e>>>=0)&&e<256)&&(s=gn[e])?s:(i=bn(e,0,!0),n&&(gn[e]=i),i):(n=-128<=(e|=0)&&e<128)&&(s=mn[e])?s:(i=bn(e,e<0?-1:0,!1),n&&(mn[e]=i),i)}function vn(e,t){if(isNaN(e))return t?Mn:Pn;if(t){if(e<0)return Mn;if(e>=kn)return In}else{if(e<=-En)return An;if(e+1>=En)return Dn}return e<0?vn(-e,t).neg():bn(e%Cn|0,e/Cn|0,t)}function bn(e,t,i){return new hn(e,t,i)}hn.fromInt=fn,hn.fromNumber=vn,hn.fromBits=bn;var yn=Math.pow;function Sn(e,t,i){if(0===e.length)throw Error("empty string");if("number"==typeof t?(i=t,t=!1):t=!!t,"NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return t?Mn:Pn;if((i=i||10)<2||36<i)throw RangeError("radix");var s;if((s=e.indexOf("-"))>0)throw Error("interior hyphen");if(0===s)return Sn(e.substring(1),t,i).neg();for(var n=vn(yn(i,8)),a=Pn,r=0;r<e.length;r+=8){var o=Math.min(8,e.length-r),c=parseInt(e.substring(r,r+o),i);if(o<8){var l=vn(yn(i,o));a=a.mul(l).add(vn(c))}else a=(a=a.mul(n)).add(vn(c))}return a.unsigned=t,a}function wn(e,t){return"number"==typeof e?vn(e,t):"string"==typeof e?Sn(e,t):bn(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}hn.fromString=Sn,hn.fromValue=wn;var Cn=4294967296,kn=Cn*Cn,En=kn/2,Tn=fn(1<<24),Pn=fn(0);hn.ZERO=Pn;var Mn=fn(0,!0);hn.UZERO=Mn;var Rn=fn(1);hn.ONE=Rn;var _n=fn(1,!0);hn.UONE=_n;var Nn=fn(-1);hn.NEG_ONE=Nn;var Dn=bn(-1,2147483647,!1);hn.MAX_VALUE=Dn;var In=bn(-1,-1,!0);hn.MAX_UNSIGNED_VALUE=In;var An=bn(0,-2147483648,!1);hn.MIN_VALUE=An;var On=hn.prototype;On.toInt=function(){return this.unsigned?this.low>>>0:this.low},On.toNumber=function(){return this.unsigned?(this.high>>>0)*Cn+(this.low>>>0):this.high*Cn+(this.low>>>0)},On.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(An)){var t=vn(e),i=this.div(t),s=i.mul(t).sub(this);return i.toString(e)+s.toInt().toString(e)}return"-"+this.neg().toString(e)}for(var n=vn(yn(e,6),this.unsigned),a=this,r="";;){var o=a.div(n),c=(a.sub(o.mul(n)).toInt()>>>0).toString(e);if((a=o).isZero())return c+r;for(;c.length<6;)c="0"+c;r=""+c+r}},On.getHighBits=function(){return this.high},On.getHighBitsUnsigned=function(){return this.high>>>0},On.getLowBits=function(){return this.low},On.getLowBitsUnsigned=function(){return this.low>>>0},On.getNumBitsAbs=function(){if(this.isNegative())return this.eq(An)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&0==(e&1<<t);t--);return 0!=this.high?t+33:t+1},On.isZero=function(){return 0===this.high&&0===this.low},On.eqz=On.isZero,On.isNegative=function(){return!this.unsigned&&this.high<0},On.isPositive=function(){return this.unsigned||this.high>=0},On.isOdd=function(){return 1==(1&this.low)},On.isEven=function(){return 0==(1&this.low)},On.equals=function(e){return un(e)||(e=wn(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&(this.high===e.high&&this.low===e.low)},On.eq=On.equals,On.notEquals=function(e){return!this.eq(e)},On.neq=On.notEquals,On.ne=On.notEquals,On.lessThan=function(e){return this.comp(e)<0},On.lt=On.lessThan,On.lessThanOrEqual=function(e){return this.comp(e)<=0},On.lte=On.lessThanOrEqual,On.le=On.lessThanOrEqual,On.greaterThan=function(e){return this.comp(e)>0},On.gt=On.greaterThan,On.greaterThanOrEqual=function(e){return this.comp(e)>=0},On.gte=On.greaterThanOrEqual,On.ge=On.greaterThanOrEqual,On.compare=function(e){if(un(e)||(e=wn(e)),this.eq(e))return 0;var t=this.isNegative(),i=e.isNegative();return t&&!i?-1:!t&&i?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},On.comp=On.compare,On.negate=function(){return!this.unsigned&&this.eq(An)?An:this.not().add(Rn)},On.neg=On.negate,On.add=function(e){un(e)||(e=wn(e));var t=this.high>>>16,i=65535&this.high,s=this.low>>>16,n=65535&this.low,a=e.high>>>16,r=65535&e.high,o=e.low>>>16,c=0,l=0,d=0,h=0;return d+=(h+=n+(65535&e.low))>>>16,l+=(d+=s+o)>>>16,c+=(l+=i+r)>>>16,c+=t+a,bn((d&=65535)<<16|(h&=65535),(c&=65535)<<16|(l&=65535),this.unsigned)},On.subtract=function(e){return un(e)||(e=wn(e)),this.add(e.neg())},On.sub=On.subtract,On.multiply=function(e){if(this.isZero())return this;if(un(e)||(e=wn(e)),dn)return bn(dn.mul(this.low,this.high,e.low,e.high),dn.get_high(),this.unsigned);if(e.isZero())return this.unsigned?Mn:Pn;if(this.eq(An))return e.isOdd()?An:Pn;if(e.eq(An))return this.isOdd()?An:Pn;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(Tn)&&e.lt(Tn))return vn(this.toNumber()*e.toNumber(),this.unsigned);var t=this.high>>>16,i=65535&this.high,s=this.low>>>16,n=65535&this.low,a=e.high>>>16,r=65535&e.high,o=e.low>>>16,c=65535&e.low,l=0,d=0,h=0,u=0;return h+=(u+=n*c)>>>16,d+=(h+=s*c)>>>16,h&=65535,d+=(h+=n*o)>>>16,l+=(d+=i*c)>>>16,d&=65535,l+=(d+=s*o)>>>16,d&=65535,l+=(d+=n*r)>>>16,l+=t*c+i*o+s*r+n*a,bn((h&=65535)<<16|(u&=65535),(l&=65535)<<16|(d&=65535),this.unsigned)},On.mul=On.multiply,On.divide=function(e){if(un(e)||(e=wn(e)),e.isZero())throw Error("division by zero");var t,i,s;if(dn)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?bn((this.unsigned?dn.div_u:dn.div_s)(this.low,this.high,e.low,e.high),dn.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?Mn:Pn;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return Mn;if(e.gt(this.shru(1)))return _n;s=Mn}else{if(this.eq(An))return e.eq(Rn)||e.eq(Nn)?An:e.eq(An)?Rn:(t=this.shr(1).div(e).shl(1)).eq(Pn)?e.isNegative()?Rn:Nn:(i=this.sub(e.mul(t)),s=t.add(i.div(e)));if(e.eq(An))return this.unsigned?Mn:Pn;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();s=Pn}for(i=this;i.gte(e);){t=Math.max(1,Math.floor(i.toNumber()/e.toNumber()));for(var n=Math.ceil(Math.log(t)/Math.LN2),a=n<=48?1:yn(2,n-48),r=vn(t),o=r.mul(e);o.isNegative()||o.gt(i);)o=(r=vn(t-=a,this.unsigned)).mul(e);r.isZero()&&(r=Rn),s=s.add(r),i=i.sub(o)}return s},On.div=On.divide,On.modulo=function(e){return un(e)||(e=wn(e)),dn?bn((this.unsigned?dn.rem_u:dn.rem_s)(this.low,this.high,e.low,e.high),dn.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},On.mod=On.modulo,On.rem=On.modulo,On.not=function(){return bn(~this.low,~this.high,this.unsigned)},On.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},On.clz=On.countLeadingZeros,On.countTrailingZeros=function(){return this.low?pn(this.low):pn(this.high)+32},On.ctz=On.countTrailingZeros,On.and=function(e){return un(e)||(e=wn(e)),bn(this.low&e.low,this.high&e.high,this.unsigned)},On.or=function(e){return un(e)||(e=wn(e)),bn(this.low|e.low,this.high|e.high,this.unsigned)},On.xor=function(e){return un(e)||(e=wn(e)),bn(this.low^e.low,this.high^e.high,this.unsigned)},On.shiftLeft=function(e){return un(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?bn(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):bn(0,this.low<<e-32,this.unsigned)},On.shl=On.shiftLeft,On.shiftRight=function(e){return un(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?bn(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):bn(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},On.shr=On.shiftRight,On.shiftRightUnsigned=function(e){return un(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?bn(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):bn(32===e?this.high:this.high>>>e-32,0,this.unsigned)},On.shru=On.shiftRightUnsigned,On.shr_u=On.shiftRightUnsigned,On.rotateLeft=function(e){var t;return un(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?bn(this.high,this.low,this.unsigned):e<32?(t=32-e,bn(this.low<<e|this.high>>>t,this.high<<e|this.low>>>t,this.unsigned)):(t=32-(e-=32),bn(this.high<<e|this.low>>>t,this.low<<e|this.high>>>t,this.unsigned))},On.rotl=On.rotateLeft,On.rotateRight=function(e){var t;return un(e)&&(e=e.toInt()),0==(e&=63)?this:32===e?bn(this.high,this.low,this.unsigned):e<32?(t=32-e,bn(this.high<<t|this.low>>>e,this.low<<t|this.high>>>e,this.unsigned)):(t=32-(e-=32),bn(this.low<<t|this.high>>>e,this.high<<t|this.low>>>e,this.unsigned))},On.rotr=On.rotateRight,On.toSigned=function(){return this.unsigned?bn(this.low,this.high,!1):this},On.toUnsigned=function(){return this.unsigned?this:bn(this.low,this.high,!0)},On.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},On.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]},On.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]},hn.fromBytes=function(e,t,i){return i?hn.fromBytesLE(e,t):hn.fromBytesBE(e,t)},hn.fromBytesLE=function(e,t){return new hn(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},hn.fromBytesBE=function(e,t){return new hn(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};var Un={},xn={get exports(){return Un},set exports(e){Un=e}},Ln={},Fn={},Bn=function(e,t){var i=new Array(arguments.length-1),s=0,n=2,a=!0;for(;n<arguments.length;)i[s++]=arguments[n++];return new Promise((function(n,r){i[s]=function(e){if(a)if(a=!1,e)r(e);else{for(var t=new Array(arguments.length-1),i=0;i<t.length;)t[i++]=arguments[i];n.apply(null,t)}};try{e.apply(t||null,i)}catch(e){a&&(a=!1,r(e))}}))};var qn={};!function(e){var t=e;t.length=function(e){var t=e.length;if(!t)return 0;for(var i=0;--t%4>1&&"="===e.charAt(t);)++i;return Math.ceil(3*e.length)/4-i};for(var i=new Array(64),s=new Array(123),n=0;n<64;)s[i[n]=n<26?n+65:n<52?n+71:n<62?n-4:n-59|43]=n++;t.encode=function(e,t,s){for(var n,a=null,r=[],o=0,c=0;t<s;){var l=e[t++];switch(c){case 0:r[o++]=i[l>>2],n=(3&l)<<4,c=1;break;case 1:r[o++]=i[n|l>>4],n=(15&l)<<2,c=2;break;case 2:r[o++]=i[n|l>>6],r[o++]=i[63&l],c=0}o>8191&&((a||(a=[])).push(String.fromCharCode.apply(String,r)),o=0)}return c&&(r[o++]=i[n],r[o++]=61,1===c&&(r[o++]=61)),a?(o&&a.push(String.fromCharCode.apply(String,r.slice(0,o))),a.join("")):String.fromCharCode.apply(String,r.slice(0,o))};var a="invalid encoding";t.decode=function(e,t,i){for(var n,r=i,o=0,c=0;c<e.length;){var l=e.charCodeAt(c++);if(61===l&&o>1)break;if(void 0===(l=s[l]))throw Error(a);switch(o){case 0:n=l,o=1;break;case 1:t[i++]=n<<2|(48&l)>>4,n=l,o=2;break;case 2:t[i++]=(15&n)<<4|(60&l)>>2,n=l,o=3;break;case 3:t[i++]=(3&n)<<6|l,o=0}}if(1===o)throw Error(a);return i-r},t.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}}(qn);var jn=Vn;function Vn(){this._listeners={}}Vn.prototype.on=function(e,t,i){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:i||this}),this},Vn.prototype.off=function(e,t){if(void 0===e)this._listeners={};else if(void 0===t)this._listeners[e]=[];else for(var i=this._listeners[e],s=0;s<i.length;)i[s].fn===t?i.splice(s,1):++s;return this},Vn.prototype.emit=function(e){var t=this._listeners[e];if(t){for(var i=[],s=1;s<arguments.length;)i.push(arguments[s++]);for(s=0;s<t.length;)t[s].fn.apply(t[s++].ctx,i)}return this};var $n=Wn(Wn);function Wn(e){return"undefined"!=typeof Float32Array?function(){var t=new Float32Array([-0]),i=new Uint8Array(t.buffer),s=128===i[3];function n(e,s,n){t[0]=e,s[n]=i[0],s[n+1]=i[1],s[n+2]=i[2],s[n+3]=i[3]}function a(e,s,n){t[0]=e,s[n]=i[3],s[n+1]=i[2],s[n+2]=i[1],s[n+3]=i[0]}function r(e,s){return i[0]=e[s],i[1]=e[s+1],i[2]=e[s+2],i[3]=e[s+3],t[0]}function o(e,s){return i[3]=e[s],i[2]=e[s+1],i[1]=e[s+2],i[0]=e[s+3],t[0]}e.writeFloatLE=s?n:a,e.writeFloatBE=s?a:n,e.readFloatLE=s?r:o,e.readFloatBE=s?o:r}():function(){function t(e,t,i,s){var n=t<0?1:0;if(n&&(t=-t),0===t)e(1/t>0?0:2147483648,i,s);else if(isNaN(t))e(2143289344,i,s);else if(t>34028234663852886e22)e((n<<31|2139095040)>>>0,i,s);else if(t<11754943508222875e-54)e((n<<31|Math.round(t/1401298464324817e-60))>>>0,i,s);else{var a=Math.floor(Math.log(t)/Math.LN2);e((n<<31|a+127<<23|8388607&Math.round(t*Math.pow(2,-a)*8388608))>>>0,i,s)}}function i(e,t,i){var s=e(t,i),n=2*(s>>31)+1,a=s>>>23&255,r=8388607&s;return 255===a?r?NaN:n*(1/0):0===a?1401298464324817e-60*n*r:n*Math.pow(2,a-150)*(r+8388608)}e.writeFloatLE=t.bind(null,Jn),e.writeFloatBE=t.bind(null,Hn),e.readFloatLE=i.bind(null,Gn),e.readFloatBE=i.bind(null,zn)}(),"undefined"!=typeof Float64Array?function(){var t=new Float64Array([-0]),i=new Uint8Array(t.buffer),s=128===i[7];function n(e,s,n){t[0]=e,s[n]=i[0],s[n+1]=i[1],s[n+2]=i[2],s[n+3]=i[3],s[n+4]=i[4],s[n+5]=i[5],s[n+6]=i[6],s[n+7]=i[7]}function a(e,s,n){t[0]=e,s[n]=i[7],s[n+1]=i[6],s[n+2]=i[5],s[n+3]=i[4],s[n+4]=i[3],s[n+5]=i[2],s[n+6]=i[1],s[n+7]=i[0]}function r(e,s){return i[0]=e[s],i[1]=e[s+1],i[2]=e[s+2],i[3]=e[s+3],i[4]=e[s+4],i[5]=e[s+5],i[6]=e[s+6],i[7]=e[s+7],t[0]}function o(e,s){return i[7]=e[s],i[6]=e[s+1],i[5]=e[s+2],i[4]=e[s+3],i[3]=e[s+4],i[2]=e[s+5],i[1]=e[s+6],i[0]=e[s+7],t[0]}e.writeDoubleLE=s?n:a,e.writeDoubleBE=s?a:n,e.readDoubleLE=s?r:o,e.readDoubleBE=s?o:r}():function(){function t(e,t,i,s,n,a){var r=s<0?1:0;if(r&&(s=-s),0===s)e(0,n,a+t),e(1/s>0?0:2147483648,n,a+i);else if(isNaN(s))e(0,n,a+t),e(2146959360,n,a+i);else if(s>17976931348623157e292)e(0,n,a+t),e((r<<31|2146435072)>>>0,n,a+i);else{var o;if(s<22250738585072014e-324)e((o=s/5e-324)>>>0,n,a+t),e((r<<31|o/4294967296)>>>0,n,a+i);else{var c=Math.floor(Math.log(s)/Math.LN2);1024===c&&(c=1023),e(4503599627370496*(o=s*Math.pow(2,-c))>>>0,n,a+t),e((r<<31|c+1023<<20|1048576*o&1048575)>>>0,n,a+i)}}}function i(e,t,i,s,n){var a=e(s,n+t),r=e(s,n+i),o=2*(r>>31)+1,c=r>>>20&2047,l=4294967296*(1048575&r)+a;return 2047===c?l?NaN:o*(1/0):0===c?5e-324*o*l:o*Math.pow(2,c-1075)*(l+4503599627370496)}e.writeDoubleLE=t.bind(null,Jn,0,4),e.writeDoubleBE=t.bind(null,Hn,4,0),e.readDoubleLE=i.bind(null,Gn,0,4),e.readDoubleBE=i.bind(null,zn,4,0)}(),e}function Jn(e,t,i){t[i]=255&e,t[i+1]=e>>>8&255,t[i+2]=e>>>16&255,t[i+3]=e>>>24}function Hn(e,t,i){t[i]=e>>>24,t[i+1]=e>>>16&255,t[i+2]=e>>>8&255,t[i+3]=255&e}function Gn(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function zn(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}var Zn=function(e){try{var t=void 0;t}catch(e){}return null};var Kn={};!function(e){var t=e;t.length=function(e){for(var t=0,i=0,s=0;s<e.length;++s)(i=e.charCodeAt(s))<128?t+=1:i<2048?t+=2:55296==(64512&i)&&56320==(64512&e.charCodeAt(s+1))?(++s,t+=4):t+=3;return t},t.read=function(e,t,i){if(i-t<1)return"";for(var s,n=null,a=[],r=0;t<i;)(s=e[t++])<128?a[r++]=s:s>191&&s<224?a[r++]=(31&s)<<6|63&e[t++]:s>239&&s<365?(s=((7&s)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,a[r++]=55296+(s>>10),a[r++]=56320+(1023&s)):a[r++]=(15&s)<<12|(63&e[t++])<<6|63&e[t++],r>8191&&((n||(n=[])).push(String.fromCharCode.apply(String,a)),r=0);return n?(r&&n.push(String.fromCharCode.apply(String,a.slice(0,r))),n.join("")):String.fromCharCode.apply(String,a.slice(0,r))},t.write=function(e,t,i){for(var s,n,a=i,r=0;r<e.length;++r)(s=e.charCodeAt(r))<128?t[i++]=s:s<2048?(t[i++]=s>>6|192,t[i++]=63&s|128):55296==(64512&s)&&56320==(64512&(n=e.charCodeAt(r+1)))?(s=65536+((1023&s)<<10)+(1023&n),++r,t[i++]=s>>18|240,t[i++]=s>>12&63|128,t[i++]=s>>6&63|128,t[i++]=63&s|128):(t[i++]=s>>12|224,t[i++]=s>>6&63|128,t[i++]=63&s|128);return i-a}}(Kn);var Qn,Xn,Yn,ea=function(e,t,i){var s=i||8192,n=s>>>1,a=null,r=s;return function(i){if(i<1||i>n)return e(i);r+i>s&&(a=e(s),r=0);var o=t.call(a,r,r+=i);return 7&r&&(r=1+(7|r)),o}};function ta(){return Yn||(Yn=1,function(e){var t=e;function i(e,t,i){for(var s=Object.keys(t),n=0;n<s.length;++n)void 0!==e[s[n]]&&i||(e[s[n]]=t[s[n]]);return e}function s(e){function t(e,s){if(!(this instanceof t))return new t(e,s);Object.defineProperty(this,"message",{get:function(){return e}}),Error.captureStackTrace?Error.captureStackTrace(this,t):Object.defineProperty(this,"stack",{value:(new Error).stack||""}),s&&i(this,s)}return t.prototype=Object.create(Error.prototype,{constructor:{value:t,writable:!0,enumerable:!1,configurable:!0},name:{get:()=>e,set:void 0,enumerable:!1,configurable:!0},toString:{value(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),t}t.asPromise=Bn,t.base64=qn,t.EventEmitter=jn,t.float=$n,t.inquire=Zn,t.utf8=Kn,t.pool=ea,t.LongBits=function(){if(Xn)return Qn;Xn=1,Qn=t;var e=ta();function t(e,t){this.lo=e>>>0,this.hi=t>>>0}var i=t.zero=new t(0,0);i.toNumber=function(){return 0},i.zzEncode=i.zzDecode=function(){return this},i.length=function(){return 1};var s=t.zeroHash="\0\0\0\0\0\0\0\0";t.fromNumber=function(e){if(0===e)return i;var s=e<0;s&&(e=-e);var n=e>>>0,a=(e-n)/4294967296>>>0;return s&&(a=~a>>>0,n=~n>>>0,++n>4294967295&&(n=0,++a>4294967295&&(a=0))),new t(n,a)},t.from=function(s){if("number"==typeof s)return t.fromNumber(s);if(e.isString(s)){if(!e.Long)return t.fromNumber(parseInt(s,10));s=e.Long.fromString(s)}return s.low||s.high?new t(s.low>>>0,s.high>>>0):i},t.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=1+~this.lo>>>0,i=~this.hi>>>0;return t||(i=i+1>>>0),-(t+4294967296*i)}return this.lo+4294967296*this.hi},t.prototype.toLong=function(t){return e.Long?new e.Long(0|this.lo,0|this.hi,Boolean(t)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(t)}};var n=String.prototype.charCodeAt;return t.fromHash=function(e){return e===s?i:new t((n.call(e,0)|n.call(e,1)<<8|n.call(e,2)<<16|n.call(e,3)<<24)>>>0,(n.call(e,4)|n.call(e,5)<<8|n.call(e,6)<<16|n.call(e,7)<<24)>>>0)},t.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},t.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},t.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},t.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,i=this.hi>>>24;return 0===i?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:i<128?9:10},Qn}(),t.isNode=Boolean(void 0!==nn&&nn&&nn.process&&nn.process.versions&&nn.process.versions.node),t.global=t.isNode&&nn||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||nn,t.emptyArray=Object.freeze?Object.freeze([]):[],t.emptyObject=Object.freeze?Object.freeze({}):{},t.isInteger=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e},t.isString=function(e){return"string"==typeof e||e instanceof String},t.isObject=function(e){return e&&"object"==typeof e},t.isset=t.isSet=function(e,t){var i=e[t];return!(null==i||!e.hasOwnProperty(t))&&("object"!=typeof i||(Array.isArray(i)?i.length:Object.keys(i).length)>0)},t.Buffer=function(){try{var e=t.inquire("buffer").Buffer;return e.prototype.utf8Write?e:null}catch(e){return null}}(),t._Buffer_from=null,t._Buffer_allocUnsafe=null,t.newBuffer=function(e){return"number"==typeof e?t.Buffer?t._Buffer_allocUnsafe(e):new t.Array(e):t.Buffer?t._Buffer_from(e):"undefined"==typeof Uint8Array?e:new Uint8Array(e)},t.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,t.Long=t.global.dcodeIO&&t.global.dcodeIO.Long||t.global.Long||t.inquire("long"),t.key2Re=/^true|false|0|1$/,t.key32Re=/^-?(?:0|[1-9][0-9]*)$/,t.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,t.longToHash=function(e){return e?t.LongBits.from(e).toHash():t.LongBits.zeroHash},t.longFromHash=function(e,i){var s=t.LongBits.fromHash(e);return t.Long?t.Long.fromBits(s.lo,s.hi,i):s.toNumber(Boolean(i))},t.merge=i,t.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},t.newError=s,t.ProtocolError=s("ProtocolError"),t.oneOfGetter=function(e){for(var t={},i=0;i<e.length;++i)t[e[i]]=1;return function(){for(var e=Object.keys(this),i=e.length-1;i>-1;--i)if(1===t[e[i]]&&void 0!==this[e[i]]&&null!==this[e[i]])return e[i]}},t.oneOfSetter=function(e){return function(t){for(var i=0;i<e.length;++i)e[i]!==t&&delete this[e[i]]}},t.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},t._configure=function(){var e=t.Buffer;e?(t._Buffer_from=e.from!==Uint8Array.from&&e.from||function(t,i){return new e(t,i)},t._Buffer_allocUnsafe=e.allocUnsafe||function(t){return new e(t)}):t._Buffer_from=t._Buffer_allocUnsafe=null}}(Fn)),Fn}var ia,sa=ha,na=ta(),aa=na.LongBits,ra=na.base64,oa=na.utf8;function ca(e,t,i){this.fn=e,this.len=t,this.next=void 0,this.val=i}function la(){}function da(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function ha(){this.len=0,this.head=new ca(la,0,0),this.tail=this.head,this.states=null}var ua=function(){return na.Buffer?function(){return(ha.create=function(){return new ia})()}:function(){return new ha}};function pa(e,t,i){t[i]=255&e}function ma(e,t){this.len=e,this.next=void 0,this.val=t}function ga(e,t,i){for(;e.hi;)t[i++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[i++]=127&e.lo|128,e.lo=e.lo>>>7;t[i++]=e.lo}function fa(e,t,i){t[i]=255&e,t[i+1]=e>>>8&255,t[i+2]=e>>>16&255,t[i+3]=e>>>24}ha.create=ua(),ha.alloc=function(e){return new na.Array(e)},na.Array!==Array&&(ha.alloc=na.pool(ha.alloc,na.Array.prototype.subarray)),ha.prototype._push=function(e,t,i){return this.tail=this.tail.next=new ca(e,t,i),this.len+=t,this},ma.prototype=Object.create(ca.prototype),ma.prototype.fn=function(e,t,i){for(;e>127;)t[i++]=127&e|128,e>>>=7;t[i]=e},ha.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new ma((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},ha.prototype.int32=function(e){return e<0?this._push(ga,10,aa.fromNumber(e)):this.uint32(e)},ha.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},ha.prototype.uint64=function(e){var t=aa.from(e);return this._push(ga,t.length(),t)},ha.prototype.int64=ha.prototype.uint64,ha.prototype.sint64=function(e){var t=aa.from(e).zzEncode();return this._push(ga,t.length(),t)},ha.prototype.bool=function(e){return this._push(pa,1,e?1:0)},ha.prototype.fixed32=function(e){return this._push(fa,4,e>>>0)},ha.prototype.sfixed32=ha.prototype.fixed32,ha.prototype.fixed64=function(e){var t=aa.from(e);return this._push(fa,4,t.lo)._push(fa,4,t.hi)},ha.prototype.sfixed64=ha.prototype.fixed64,ha.prototype.float=function(e){return this._push(na.float.writeFloatLE,4,e)},ha.prototype.double=function(e){return this._push(na.float.writeDoubleLE,8,e)};var va=na.Array.prototype.set?function(e,t,i){t.set(e,i)}:function(e,t,i){for(var s=0;s<e.length;++s)t[i+s]=e[s]};ha.prototype.bytes=function(e){var t=e.length>>>0;if(!t)return this._push(pa,1,0);if(na.isString(e)){var i=ha.alloc(t=ra.length(e));ra.decode(e,i,0),e=i}return this.uint32(t)._push(va,t,e)},ha.prototype.string=function(e){var t=oa.length(e);return t?this.uint32(t)._push(oa.write,t,e):this._push(pa,1,0)},ha.prototype.fork=function(){return this.states=new da(this),this.head=this.tail=new ca(la,0,0),this.len=0,this},ha.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new ca(la,0,0),this.len=0),this},ha.prototype.ldelim=function(){var e=this.head,t=this.tail,i=this.len;return this.reset().uint32(i),i&&(this.tail.next=e.next,this.tail=t,this.len+=i),this},ha.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),i=0;e;)e.fn(e.val,t,i),i+=e.len,e=e.next;return t},ha._configure=function(e){ia=e,ha.create=ua(),ia._configure()};var ba=wa,ya=sa;(wa.prototype=Object.create(ya.prototype)).constructor=wa;var Sa=ta();function wa(){ya.call(this)}function Ca(e,t,i){e.length<40?Sa.utf8.write(e,t,i):t.utf8Write?t.utf8Write(e,i):t.write(e,i)}wa._configure=function(){wa.alloc=Sa._Buffer_allocUnsafe,wa.writeBytesBuffer=Sa.Buffer&&Sa.Buffer.prototype instanceof Uint8Array&&"set"===Sa.Buffer.prototype.set.name?function(e,t,i){t.set(e,i)}:function(e,t,i){if(e.copy)e.copy(t,i,0,e.length);else for(var s=0;s<e.length;)t[i++]=e[s++]}},wa.prototype.bytes=function(e){Sa.isString(e)&&(e=Sa._Buffer_from(e,"base64"));var t=e.length>>>0;return this.uint32(t),t&&this._push(wa.writeBytesBuffer,t,e),this},wa.prototype.string=function(e){var t=Sa.Buffer.byteLength(e);return this.uint32(t),t&&this._push(Ca,t,e),this},wa._configure();var ka,Ea=_a,Ta=ta(),Pa=Ta.LongBits,Ma=Ta.utf8;function Ra(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function _a(e){this.buf=e,this.pos=0,this.len=e.length}var Na,Da="undefined"!=typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new _a(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new _a(e);throw Error("illegal buffer")},Ia=function(){return Ta.Buffer?function(e){return(_a.create=function(e){return Ta.Buffer.isBuffer(e)?new ka(e):Da(e)})(e)}:Da};function Aa(){var e=new Pa(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw Ra(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Ra(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}function Oa(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function Ua(){if(this.pos+8>this.len)throw Ra(this,8);return new Pa(Oa(this.buf,this.pos+=4),Oa(this.buf,this.pos+=4))}_a.create=Ia(),_a.prototype._slice=Ta.Array.prototype.subarray||Ta.Array.prototype.slice,_a.prototype.uint32=(Na=4294967295,function(){if(Na=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return Na;if(Na=(Na|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return Na;if(Na=(Na|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return Na;if(Na=(Na|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return Na;if(Na=(Na|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return Na;if((this.pos+=5)>this.len)throw this.pos=this.len,Ra(this,10);return Na}),_a.prototype.int32=function(){return 0|this.uint32()},_a.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)|0},_a.prototype.bool=function(){return 0!==this.uint32()},_a.prototype.fixed32=function(){if(this.pos+4>this.len)throw Ra(this,4);return Oa(this.buf,this.pos+=4)},_a.prototype.sfixed32=function(){if(this.pos+4>this.len)throw Ra(this,4);return 0|Oa(this.buf,this.pos+=4)},_a.prototype.float=function(){if(this.pos+4>this.len)throw Ra(this,4);var e=Ta.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},_a.prototype.double=function(){if(this.pos+8>this.len)throw Ra(this,4);var e=Ta.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},_a.prototype.bytes=function(){var e=this.uint32(),t=this.pos,i=this.pos+e;if(i>this.len)throw Ra(this,e);return this.pos+=e,Array.isArray(this.buf)?this.buf.slice(t,i):t===i?new this.buf.constructor(0):this._slice.call(this.buf,t,i)},_a.prototype.string=function(){var e=this.bytes();return Ma.read(e,0,e.length)},_a.prototype.skip=function(e){if("number"==typeof e){if(this.pos+e>this.len)throw Ra(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw Ra(this)}while(128&this.buf[this.pos++]);return this},_a.prototype.skipType=function(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this},_a._configure=function(e){ka=e,_a.create=Ia(),ka._configure();var t=Ta.Long?"toLong":"toNumber";Ta.merge(_a.prototype,{int64:function(){return Aa.call(this)[t](!1)},uint64:function(){return Aa.call(this)[t](!0)},sint64:function(){return Aa.call(this).zzDecode()[t](!1)},fixed64:function(){return Ua.call(this)[t](!0)},sfixed64:function(){return Ua.call(this)[t](!1)}})};var xa=Ba,La=Ea;(Ba.prototype=Object.create(La.prototype)).constructor=Ba;var Fa=ta();function Ba(e){La.call(this,e)}Ba._configure=function(){Fa.Buffer&&(Ba.prototype._slice=Fa.Buffer.prototype.slice)},Ba.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))},Ba._configure();var qa={},ja=$a,Va=ta();function $a(e,t,i){if("function"!=typeof e)throw TypeError("rpcImpl must be a function");Va.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=Boolean(t),this.responseDelimited=Boolean(i)}($a.prototype=Object.create(Va.EventEmitter.prototype)).constructor=$a,$a.prototype.rpcCall=function e(t,i,s,n,a){if(!n)throw TypeError("request must be specified");var r=this;if(!a)return Va.asPromise(e,r,t,i,s,n);if(r.rpcImpl)try{return r.rpcImpl(t,i[r.requestDelimited?"encodeDelimited":"encode"](n).finish(),(function(e,i){if(e)return r.emit("error",e,t),a(e);if(null!==i){if(!(i instanceof s))try{i=s[r.responseDelimited?"decodeDelimited":"decode"](i)}catch(e){return r.emit("error",e,t),a(e)}return r.emit("data",i,t),a(null,i)}r.end(!0)}))}catch(e){return r.emit("error",e,t),void setTimeout((function(){a(e)}),0)}else setTimeout((function(){a(Error("already ended"))}),0)},$a.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this},qa.Service=ja;var Wa={};!function(e){var t=e;function i(){t.util._configure(),t.Writer._configure(t.BufferWriter),t.Reader._configure(t.BufferReader)}t.build="minimal",t.Writer=sa,t.BufferWriter=ba,t.Reader=Ea,t.BufferReader=xa,t.util=ta(),t.rpc=qa,t.roots=Wa,t.configure=i,i()}(Ln),function(e){e.exports=Ln}(xn);var Ja,Ha,Ga,za,Za,Ka,Qa,Xa,Ya,er,tr,ir,sr=an(Un);function nr(e){switch(e){case 0:case"AUDIO":return Ja.AUDIO;case 1:case"VIDEO":return Ja.VIDEO;case 2:case"DATA":return Ja.DATA;default:return Ja.UNRECOGNIZED}}function ar(e){switch(e){case Ja.AUDIO:return"AUDIO";case Ja.VIDEO:return"VIDEO";case Ja.DATA:return"DATA";case Ja.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function rr(e){switch(e){case 0:case"UNKNOWN":return Ha.UNKNOWN;case 1:case"CAMERA":return Ha.CAMERA;case 2:case"MICROPHONE":return Ha.MICROPHONE;case 3:case"SCREEN_SHARE":return Ha.SCREEN_SHARE;case 4:case"SCREEN_SHARE_AUDIO":return Ha.SCREEN_SHARE_AUDIO;default:return Ha.UNRECOGNIZED}}function or(e){switch(e){case Ha.UNKNOWN:return"UNKNOWN";case Ha.CAMERA:return"CAMERA";case Ha.MICROPHONE:return"MICROPHONE";case Ha.SCREEN_SHARE:return"SCREEN_SHARE";case Ha.SCREEN_SHARE_AUDIO:return"SCREEN_SHARE_AUDIO";case Ha.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function cr(e){switch(e){case 0:case"LOW":return Ga.LOW;case 1:case"MEDIUM":return Ga.MEDIUM;case 2:case"HIGH":return Ga.HIGH;case 3:case"OFF":return Ga.OFF;default:return Ga.UNRECOGNIZED}}function lr(e){switch(e){case Ga.LOW:return"LOW";case Ga.MEDIUM:return"MEDIUM";case Ga.HIGH:return"HIGH";case Ga.OFF:return"OFF";case Ga.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function dr(e){switch(e){case 0:case"POOR":return za.POOR;case 1:case"GOOD":return za.GOOD;case 2:case"EXCELLENT":return za.EXCELLENT;default:return za.UNRECOGNIZED}}function hr(e){switch(e){case 0:case"UNSET":return Za.UNSET;case 1:case"DISABLED":return Za.DISABLED;case 2:case"ENABLED":return Za.ENABLED;default:return Za.UNRECOGNIZED}}function ur(e){switch(e){case Za.UNSET:return"UNSET";case Za.DISABLED:return"DISABLED";case Za.ENABLED:return"ENABLED";case Za.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function pr(e){switch(e){case 0:case"UNKNOWN_REASON":return Ka.UNKNOWN_REASON;case 1:case"CLIENT_INITIATED":return Ka.CLIENT_INITIATED;case 2:case"DUPLICATE_IDENTITY":return Ka.DUPLICATE_IDENTITY;case 3:case"SERVER_SHUTDOWN":return Ka.SERVER_SHUTDOWN;case 4:case"PARTICIPANT_REMOVED":return Ka.PARTICIPANT_REMOVED;case 5:case"ROOM_DELETED":return Ka.ROOM_DELETED;case 6:case"STATE_MISMATCH":return Ka.STATE_MISMATCH;case 7:case"JOIN_FAILURE":return Ka.JOIN_FAILURE;default:return Ka.UNRECOGNIZED}}function mr(e){switch(e){case 0:case"JOINING":return Xa.JOINING;case 1:case"JOINED":return Xa.JOINED;case 2:case"ACTIVE":return Xa.ACTIVE;case 3:case"DISCONNECTED":return Xa.DISCONNECTED;default:return Xa.UNRECOGNIZED}}function gr(e){switch(e){case 0:case"NONE":return Ya.NONE;case 1:case"GCM":return Ya.GCM;case 2:case"CUSTOM":return Ya.CUSTOM;default:return Ya.UNRECOGNIZED}}function fr(e){switch(e){case Ya.NONE:return"NONE";case Ya.GCM:return"GCM";case Ya.CUSTOM:return"CUSTOM";case Ya.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function vr(e){switch(e){case 0:case"RELIABLE":return er.RELIABLE;case 1:case"LOSSY":return er.LOSSY;default:return er.UNRECOGNIZED}}function br(e){switch(e){case 0:case"Standard":return tr.Standard;case 1:case"Cloud":return tr.Cloud;default:return tr.UNRECOGNIZED}}function yr(e){switch(e){case 0:case"UNKNOWN":return ir.UNKNOWN;case 1:case"JS":return ir.JS;case 2:case"SWIFT":return ir.SWIFT;case 3:case"ANDROID":return ir.ANDROID;case 4:case"FLUTTER":return ir.FLUTTER;case 5:case"GO":return ir.GO;case 6:case"UNITY":return ir.UNITY;default:return ir.UNRECOGNIZED}}(()=>{if("undefined"!=typeof globalThis)return globalThis;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw"Unable to locate global object"})(),sr.util.Long!==hn&&(sr.util.Long=hn,sr.configure()),function(e){e[e.AUDIO=0]="AUDIO",e[e.VIDEO=1]="VIDEO",e[e.DATA=2]="DATA",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Ja||(Ja={})),function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.CAMERA=1]="CAMERA",e[e.MICROPHONE=2]="MICROPHONE",e[e.SCREEN_SHARE=3]="SCREEN_SHARE",e[e.SCREEN_SHARE_AUDIO=4]="SCREEN_SHARE_AUDIO",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Ha||(Ha={})),function(e){e[e.LOW=0]="LOW",e[e.MEDIUM=1]="MEDIUM",e[e.HIGH=2]="HIGH",e[e.OFF=3]="OFF",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Ga||(Ga={})),function(e){e[e.POOR=0]="POOR",e[e.GOOD=1]="GOOD",e[e.EXCELLENT=2]="EXCELLENT",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(za||(za={})),function(e){e[e.UNSET=0]="UNSET",e[e.DISABLED=1]="DISABLED",e[e.ENABLED=2]="ENABLED",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Za||(Za={})),function(e){e[e.UNKNOWN_REASON=0]="UNKNOWN_REASON",e[e.CLIENT_INITIATED=1]="CLIENT_INITIATED",e[e.DUPLICATE_IDENTITY=2]="DUPLICATE_IDENTITY",e[e.SERVER_SHUTDOWN=3]="SERVER_SHUTDOWN",e[e.PARTICIPANT_REMOVED=4]="PARTICIPANT_REMOVED",e[e.ROOM_DELETED=5]="ROOM_DELETED",e[e.STATE_MISMATCH=6]="STATE_MISMATCH",e[e.JOIN_FAILURE=7]="JOIN_FAILURE",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Ka||(Ka={})),function(e){e[e.RR_UNKOWN=0]="RR_UNKOWN",e[e.RR_SIGNAL_DISCONNECTED=1]="RR_SIGNAL_DISCONNECTED",e[e.RR_PUBLISHER_FAILED=2]="RR_PUBLISHER_FAILED",e[e.RR_SUBSCRIBER_FAILED=3]="RR_SUBSCRIBER_FAILED",e[e.RR_SWITCH_CANDIDATE=4]="RR_SWITCH_CANDIDATE",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Qa||(Qa={})),function(e){e[e.JOINING=0]="JOINING",e[e.JOINED=1]="JOINED",e[e.ACTIVE=2]="ACTIVE",e[e.DISCONNECTED=3]="DISCONNECTED",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Xa||(Xa={})),function(e){e[e.NONE=0]="NONE",e[e.GCM=1]="GCM",e[e.CUSTOM=2]="CUSTOM",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Ya||(Ya={})),function(e){e[e.RELIABLE=0]="RELIABLE",e[e.LOSSY=1]="LOSSY",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(er||(er={})),function(e){e[e.Standard=0]="Standard",e[e.Cloud=1]="Cloud",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(tr||(tr={})),function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.JS=1]="JS",e[e.SWIFT=2]="SWIFT",e[e.ANDROID=3]="ANDROID",e[e.FLUTTER=4]="FLUTTER",e[e.GO=5]="GO",e[e.UNITY=6]="UNITY",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(ir||(ir={}));const Sr={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();""!==e.sid&&t.uint32(10).string(e.sid),""!==e.name&&t.uint32(18).string(e.name),0!==e.emptyTimeout&&t.uint32(24).uint32(e.emptyTimeout),0!==e.maxParticipants&&t.uint32(32).uint32(e.maxParticipants),0!==e.creationTime&&t.uint32(40).int64(e.creationTime),""!==e.turnPassword&&t.uint32(50).string(e.turnPassword);for(const i of e.enabledCodecs)wr.encode(i,t.uint32(58).fork()).ldelim();return""!==e.metadata&&t.uint32(66).string(e.metadata),0!==e.numParticipants&&t.uint32(72).uint32(e.numParticipants),!0===e.activeRecording&&t.uint32(80).bool(e.activeRecording),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={sid:"",name:"",emptyTimeout:0,maxParticipants:0,creationTime:0,turnPassword:"",enabledCodecs:[],metadata:"",numParticipants:0,activeRecording:!1};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.sid=i.string();break;case 2:n.name=i.string();break;case 3:n.emptyTimeout=i.uint32();break;case 4:n.maxParticipants=i.uint32();break;case 5:n.creationTime=qr(i.int64());break;case 6:n.turnPassword=i.string();break;case 7:n.enabledCodecs.push(wr.decode(i,i.uint32()));break;case 8:n.metadata=i.string();break;case 9:n.numParticipants=i.uint32();break;case 10:n.activeRecording=i.bool();break;default:i.skipType(7&e)}}return n},fromJSON:e=>({sid:jr(e.sid)?String(e.sid):"",name:jr(e.name)?String(e.name):"",emptyTimeout:jr(e.emptyTimeout)?Number(e.emptyTimeout):0,maxParticipants:jr(e.maxParticipants)?Number(e.maxParticipants):0,creationTime:jr(e.creationTime)?Number(e.creationTime):0,turnPassword:jr(e.turnPassword)?String(e.turnPassword):"",enabledCodecs:Array.isArray(null==e?void 0:e.enabledCodecs)?e.enabledCodecs.map((e=>wr.fromJSON(e))):[],metadata:jr(e.metadata)?String(e.metadata):"",numParticipants:jr(e.numParticipants)?Number(e.numParticipants):0,activeRecording:!!jr(e.activeRecording)&&Boolean(e.activeRecording)}),toJSON(e){const t={};return void 0!==e.sid&&(t.sid=e.sid),void 0!==e.name&&(t.name=e.name),void 0!==e.emptyTimeout&&(t.emptyTimeout=Math.round(e.emptyTimeout)),void 0!==e.maxParticipants&&(t.maxParticipants=Math.round(e.maxParticipants)),void 0!==e.creationTime&&(t.creationTime=Math.round(e.creationTime)),void 0!==e.turnPassword&&(t.turnPassword=e.turnPassword),e.enabledCodecs?t.enabledCodecs=e.enabledCodecs.map((e=>e?wr.toJSON(e):void 0)):t.enabledCodecs=[],void 0!==e.metadata&&(t.metadata=e.metadata),void 0!==e.numParticipants&&(t.numParticipants=Math.round(e.numParticipants)),void 0!==e.activeRecording&&(t.activeRecording=e.activeRecording),t},create:e=>Sr.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,s,n,a,r,o,c,l,d;const h={sid:"",name:"",emptyTimeout:0,maxParticipants:0,creationTime:0,turnPassword:"",enabledCodecs:[],metadata:"",numParticipants:0,activeRecording:!1};return h.sid=null!==(t=e.sid)&&void 0!==t?t:"",h.name=null!==(i=e.name)&&void 0!==i?i:"",h.emptyTimeout=null!==(s=e.emptyTimeout)&&void 0!==s?s:0,h.maxParticipants=null!==(n=e.maxParticipants)&&void 0!==n?n:0,h.creationTime=null!==(a=e.creationTime)&&void 0!==a?a:0,h.turnPassword=null!==(r=e.turnPassword)&&void 0!==r?r:"",h.enabledCodecs=(null===(o=e.enabledCodecs)||void 0===o?void 0:o.map((e=>wr.fromPartial(e))))||[],h.metadata=null!==(c=e.metadata)&&void 0!==c?c:"",h.numParticipants=null!==(l=e.numParticipants)&&void 0!==l?l:0,h.activeRecording=null!==(d=e.activeRecording)&&void 0!==d&&d,h}};const wr={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();return""!==e.mime&&t.uint32(10).string(e.mime),""!==e.fmtpLine&&t.uint32(18).string(e.fmtpLine),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={mime:"",fmtpLine:""};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.mime=i.string();break;case 2:n.fmtpLine=i.string();break;default:i.skipType(7&e)}}return n},fromJSON:e=>({mime:jr(e.mime)?String(e.mime):"",fmtpLine:jr(e.fmtpLine)?String(e.fmtpLine):""}),toJSON(e){const t={};return void 0!==e.mime&&(t.mime=e.mime),void 0!==e.fmtpLine&&(t.fmtpLine=e.fmtpLine),t},create:e=>wr.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const s={mime:"",fmtpLine:""};return s.mime=null!==(t=e.mime)&&void 0!==t?t:"",s.fmtpLine=null!==(i=e.fmtpLine)&&void 0!==i?i:"",s}};const Cr={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();!0===e.canSubscribe&&t.uint32(8).bool(e.canSubscribe),!0===e.canPublish&&t.uint32(16).bool(e.canPublish),!0===e.canPublishData&&t.uint32(24).bool(e.canPublishData),t.uint32(74).fork();for(const i of e.canPublishSources)t.int32(i);return t.ldelim(),!0===e.hidden&&t.uint32(56).bool(e.hidden),!0===e.recorder&&t.uint32(64).bool(e.recorder),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={canSubscribe:!1,canPublish:!1,canPublishData:!1,canPublishSources:[],hidden:!1,recorder:!1};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.canSubscribe=i.bool();break;case 2:n.canPublish=i.bool();break;case 3:n.canPublishData=i.bool();break;case 9:if(2==(7&e)){const e=i.uint32()+i.pos;for(;i.pos<e;)n.canPublishSources.push(i.int32())}else n.canPublishSources.push(i.int32());break;case 7:n.hidden=i.bool();break;case 8:n.recorder=i.bool();break;default:i.skipType(7&e)}}return n},fromJSON:e=>({canSubscribe:!!jr(e.canSubscribe)&&Boolean(e.canSubscribe),canPublish:!!jr(e.canPublish)&&Boolean(e.canPublish),canPublishData:!!jr(e.canPublishData)&&Boolean(e.canPublishData),canPublishSources:Array.isArray(null==e?void 0:e.canPublishSources)?e.canPublishSources.map((e=>rr(e))):[],hidden:!!jr(e.hidden)&&Boolean(e.hidden),recorder:!!jr(e.recorder)&&Boolean(e.recorder)}),toJSON(e){const t={};return void 0!==e.canSubscribe&&(t.canSubscribe=e.canSubscribe),void 0!==e.canPublish&&(t.canPublish=e.canPublish),void 0!==e.canPublishData&&(t.canPublishData=e.canPublishData),e.canPublishSources?t.canPublishSources=e.canPublishSources.map((e=>or(e))):t.canPublishSources=[],void 0!==e.hidden&&(t.hidden=e.hidden),void 0!==e.recorder&&(t.recorder=e.recorder),t},create:e=>Cr.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,s,n,a,r;const o={canSubscribe:!1,canPublish:!1,canPublishData:!1,canPublishSources:[],hidden:!1,recorder:!1};return o.canSubscribe=null!==(t=e.canSubscribe)&&void 0!==t&&t,o.canPublish=null!==(i=e.canPublish)&&void 0!==i&&i,o.canPublishData=null!==(s=e.canPublishData)&&void 0!==s&&s,o.canPublishSources=(null===(n=e.canPublishSources)||void 0===n?void 0:n.map((e=>e)))||[],o.hidden=null!==(a=e.hidden)&&void 0!==a&&a,o.recorder=null!==(r=e.recorder)&&void 0!==r&&r,o}};const kr={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();""!==e.sid&&t.uint32(10).string(e.sid),""!==e.identity&&t.uint32(18).string(e.identity),0!==e.state&&t.uint32(24).int32(e.state);for(const i of e.tracks)Tr.encode(i,t.uint32(34).fork()).ldelim();return""!==e.metadata&&t.uint32(42).string(e.metadata),0!==e.joinedAt&&t.uint32(48).int64(e.joinedAt),""!==e.name&&t.uint32(74).string(e.name),0!==e.version&&t.uint32(80).uint32(e.version),void 0!==e.permission&&Cr.encode(e.permission,t.uint32(90).fork()).ldelim(),""!==e.region&&t.uint32(98).string(e.region),!0===e.isPublisher&&t.uint32(104).bool(e.isPublisher),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={sid:"",identity:"",state:0,tracks:[],metadata:"",joinedAt:0,name:"",version:0,permission:void 0,region:"",isPublisher:!1};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.sid=i.string();break;case 2:n.identity=i.string();break;case 3:n.state=i.int32();break;case 4:n.tracks.push(Tr.decode(i,i.uint32()));break;case 5:n.metadata=i.string();break;case 6:n.joinedAt=qr(i.int64());break;case 9:n.name=i.string();break;case 10:n.version=i.uint32();break;case 11:n.permission=Cr.decode(i,i.uint32());break;case 12:n.region=i.string();break;case 13:n.isPublisher=i.bool();break;default:i.skipType(7&e)}}return n},fromJSON:e=>({sid:jr(e.sid)?String(e.sid):"",identity:jr(e.identity)?String(e.identity):"",state:jr(e.state)?mr(e.state):0,tracks:Array.isArray(null==e?void 0:e.tracks)?e.tracks.map((e=>Tr.fromJSON(e))):[],metadata:jr(e.metadata)?String(e.metadata):"",joinedAt:jr(e.joinedAt)?Number(e.joinedAt):0,name:jr(e.name)?String(e.name):"",version:jr(e.version)?Number(e.version):0,permission:jr(e.permission)?Cr.fromJSON(e.permission):void 0,region:jr(e.region)?String(e.region):"",isPublisher:!!jr(e.isPublisher)&&Boolean(e.isPublisher)}),toJSON(e){const t={};return void 0!==e.sid&&(t.sid=e.sid),void 0!==e.identity&&(t.identity=e.identity),void 0!==e.state&&(t.state=function(e){switch(e){case Xa.JOINING:return"JOINING";case Xa.JOINED:return"JOINED";case Xa.ACTIVE:return"ACTIVE";case Xa.DISCONNECTED:return"DISCONNECTED";case Xa.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.state)),e.tracks?t.tracks=e.tracks.map((e=>e?Tr.toJSON(e):void 0)):t.tracks=[],void 0!==e.metadata&&(t.metadata=e.metadata),void 0!==e.joinedAt&&(t.joinedAt=Math.round(e.joinedAt)),void 0!==e.name&&(t.name=e.name),void 0!==e.version&&(t.version=Math.round(e.version)),void 0!==e.permission&&(t.permission=e.permission?Cr.toJSON(e.permission):void 0),void 0!==e.region&&(t.region=e.region),void 0!==e.isPublisher&&(t.isPublisher=e.isPublisher),t},create:e=>kr.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,s,n,a,r,o,c,l,d;const h={sid:"",identity:"",state:0,tracks:[],metadata:"",joinedAt:0,name:"",version:0,permission:void 0,region:"",isPublisher:!1};return h.sid=null!==(t=e.sid)&&void 0!==t?t:"",h.identity=null!==(i=e.identity)&&void 0!==i?i:"",h.state=null!==(s=e.state)&&void 0!==s?s:0,h.tracks=(null===(n=e.tracks)||void 0===n?void 0:n.map((e=>Tr.fromPartial(e))))||[],h.metadata=null!==(a=e.metadata)&&void 0!==a?a:"",h.joinedAt=null!==(r=e.joinedAt)&&void 0!==r?r:0,h.name=null!==(o=e.name)&&void 0!==o?o:"",h.version=null!==(c=e.version)&&void 0!==c?c:0,h.permission=void 0!==e.permission&&null!==e.permission?Cr.fromPartial(e.permission):void 0,h.region=null!==(l=e.region)&&void 0!==l?l:"",h.isPublisher=null!==(d=e.isPublisher)&&void 0!==d&&d,h}};const Er={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();""!==e.mimeType&&t.uint32(10).string(e.mimeType),""!==e.mid&&t.uint32(18).string(e.mid),""!==e.cid&&t.uint32(26).string(e.cid);for(const i of e.layers)Pr.encode(i,t.uint32(34).fork()).ldelim();return t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={mimeType:"",mid:"",cid:"",layers:[]};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.mimeType=i.string();break;case 2:n.mid=i.string();break;case 3:n.cid=i.string();break;case 4:n.layers.push(Pr.decode(i,i.uint32()));break;default:i.skipType(7&e)}}return n},fromJSON:e=>({mimeType:jr(e.mimeType)?String(e.mimeType):"",mid:jr(e.mid)?String(e.mid):"",cid:jr(e.cid)?String(e.cid):"",layers:Array.isArray(null==e?void 0:e.layers)?e.layers.map((e=>Pr.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.mimeType&&(t.mimeType=e.mimeType),void 0!==e.mid&&(t.mid=e.mid),void 0!==e.cid&&(t.cid=e.cid),e.layers?t.layers=e.layers.map((e=>e?Pr.toJSON(e):void 0)):t.layers=[],t},create:e=>Er.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,s,n;const a={mimeType:"",mid:"",cid:"",layers:[]};return a.mimeType=null!==(t=e.mimeType)&&void 0!==t?t:"",a.mid=null!==(i=e.mid)&&void 0!==i?i:"",a.cid=null!==(s=e.cid)&&void 0!==s?s:"",a.layers=(null===(n=e.layers)||void 0===n?void 0:n.map((e=>Pr.fromPartial(e))))||[],a}};const Tr={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();""!==e.sid&&t.uint32(10).string(e.sid),0!==e.type&&t.uint32(16).int32(e.type),""!==e.name&&t.uint32(26).string(e.name),!0===e.muted&&t.uint32(32).bool(e.muted),0!==e.width&&t.uint32(40).uint32(e.width),0!==e.height&&t.uint32(48).uint32(e.height),!0===e.simulcast&&t.uint32(56).bool(e.simulcast),!0===e.disableDtx&&t.uint32(64).bool(e.disableDtx),0!==e.source&&t.uint32(72).int32(e.source);for(const i of e.layers)Pr.encode(i,t.uint32(82).fork()).ldelim();""!==e.mimeType&&t.uint32(90).string(e.mimeType),""!==e.mid&&t.uint32(98).string(e.mid);for(const i of e.codecs)Er.encode(i,t.uint32(106).fork()).ldelim();return!0===e.stereo&&t.uint32(112).bool(e.stereo),!0===e.disableRed&&t.uint32(120).bool(e.disableRed),0!==e.encryption&&t.uint32(128).int32(e.encryption),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={sid:"",type:0,name:"",muted:!1,width:0,height:0,simulcast:!1,disableDtx:!1,source:0,layers:[],mimeType:"",mid:"",codecs:[],stereo:!1,disableRed:!1,encryption:0};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.sid=i.string();break;case 2:n.type=i.int32();break;case 3:n.name=i.string();break;case 4:n.muted=i.bool();break;case 5:n.width=i.uint32();break;case 6:n.height=i.uint32();break;case 7:n.simulcast=i.bool();break;case 8:n.disableDtx=i.bool();break;case 9:n.source=i.int32();break;case 10:n.layers.push(Pr.decode(i,i.uint32()));break;case 11:n.mimeType=i.string();break;case 12:n.mid=i.string();break;case 13:n.codecs.push(Er.decode(i,i.uint32()));break;case 14:n.stereo=i.bool();break;case 15:n.disableRed=i.bool();break;case 16:n.encryption=i.int32();break;default:i.skipType(7&e)}}return n},fromJSON:e=>({sid:jr(e.sid)?String(e.sid):"",type:jr(e.type)?nr(e.type):0,name:jr(e.name)?String(e.name):"",muted:!!jr(e.muted)&&Boolean(e.muted),width:jr(e.width)?Number(e.width):0,height:jr(e.height)?Number(e.height):0,simulcast:!!jr(e.simulcast)&&Boolean(e.simulcast),disableDtx:!!jr(e.disableDtx)&&Boolean(e.disableDtx),source:jr(e.source)?rr(e.source):0,layers:Array.isArray(null==e?void 0:e.layers)?e.layers.map((e=>Pr.fromJSON(e))):[],mimeType:jr(e.mimeType)?String(e.mimeType):"",mid:jr(e.mid)?String(e.mid):"",codecs:Array.isArray(null==e?void 0:e.codecs)?e.codecs.map((e=>Er.fromJSON(e))):[],stereo:!!jr(e.stereo)&&Boolean(e.stereo),disableRed:!!jr(e.disableRed)&&Boolean(e.disableRed),encryption:jr(e.encryption)?gr(e.encryption):0}),toJSON(e){const t={};return void 0!==e.sid&&(t.sid=e.sid),void 0!==e.type&&(t.type=ar(e.type)),void 0!==e.name&&(t.name=e.name),void 0!==e.muted&&(t.muted=e.muted),void 0!==e.width&&(t.width=Math.round(e.width)),void 0!==e.height&&(t.height=Math.round(e.height)),void 0!==e.simulcast&&(t.simulcast=e.simulcast),void 0!==e.disableDtx&&(t.disableDtx=e.disableDtx),void 0!==e.source&&(t.source=or(e.source)),e.layers?t.layers=e.layers.map((e=>e?Pr.toJSON(e):void 0)):t.layers=[],void 0!==e.mimeType&&(t.mimeType=e.mimeType),void 0!==e.mid&&(t.mid=e.mid),e.codecs?t.codecs=e.codecs.map((e=>e?Er.toJSON(e):void 0)):t.codecs=[],void 0!==e.stereo&&(t.stereo=e.stereo),void 0!==e.disableRed&&(t.disableRed=e.disableRed),void 0!==e.encryption&&(t.encryption=fr(e.encryption)),t},create:e=>Tr.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,s,n,a,r,o,c,l,d,h,u,p,m,g,f;const v={sid:"",type:0,name:"",muted:!1,width:0,height:0,simulcast:!1,disableDtx:!1,source:0,layers:[],mimeType:"",mid:"",codecs:[],stereo:!1,disableRed:!1,encryption:0};return v.sid=null!==(t=e.sid)&&void 0!==t?t:"",v.type=null!==(i=e.type)&&void 0!==i?i:0,v.name=null!==(s=e.name)&&void 0!==s?s:"",v.muted=null!==(n=e.muted)&&void 0!==n&&n,v.width=null!==(a=e.width)&&void 0!==a?a:0,v.height=null!==(r=e.height)&&void 0!==r?r:0,v.simulcast=null!==(o=e.simulcast)&&void 0!==o&&o,v.disableDtx=null!==(c=e.disableDtx)&&void 0!==c&&c,v.source=null!==(l=e.source)&&void 0!==l?l:0,v.layers=(null===(d=e.layers)||void 0===d?void 0:d.map((e=>Pr.fromPartial(e))))||[],v.mimeType=null!==(h=e.mimeType)&&void 0!==h?h:"",v.mid=null!==(u=e.mid)&&void 0!==u?u:"",v.codecs=(null===(p=e.codecs)||void 0===p?void 0:p.map((e=>Er.fromPartial(e))))||[],v.stereo=null!==(m=e.stereo)&&void 0!==m&&m,v.disableRed=null!==(g=e.disableRed)&&void 0!==g&&g,v.encryption=null!==(f=e.encryption)&&void 0!==f?f:0,v}};const Pr={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();return 0!==e.quality&&t.uint32(8).int32(e.quality),0!==e.width&&t.uint32(16).uint32(e.width),0!==e.height&&t.uint32(24).uint32(e.height),0!==e.bitrate&&t.uint32(32).uint32(e.bitrate),0!==e.ssrc&&t.uint32(40).uint32(e.ssrc),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={quality:0,width:0,height:0,bitrate:0,ssrc:0};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.quality=i.int32();break;case 2:n.width=i.uint32();break;case 3:n.height=i.uint32();break;case 4:n.bitrate=i.uint32();break;case 5:n.ssrc=i.uint32();break;default:i.skipType(7&e)}}return n},fromJSON:e=>({quality:jr(e.quality)?cr(e.quality):0,width:jr(e.width)?Number(e.width):0,height:jr(e.height)?Number(e.height):0,bitrate:jr(e.bitrate)?Number(e.bitrate):0,ssrc:jr(e.ssrc)?Number(e.ssrc):0}),toJSON(e){const t={};return void 0!==e.quality&&(t.quality=lr(e.quality)),void 0!==e.width&&(t.width=Math.round(e.width)),void 0!==e.height&&(t.height=Math.round(e.height)),void 0!==e.bitrate&&(t.bitrate=Math.round(e.bitrate)),void 0!==e.ssrc&&(t.ssrc=Math.round(e.ssrc)),t},create:e=>Pr.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,s,n,a;const r={quality:0,width:0,height:0,bitrate:0,ssrc:0};return r.quality=null!==(t=e.quality)&&void 0!==t?t:0,r.width=null!==(i=e.width)&&void 0!==i?i:0,r.height=null!==(s=e.height)&&void 0!==s?s:0,r.bitrate=null!==(n=e.bitrate)&&void 0!==n?n:0,r.ssrc=null!==(a=e.ssrc)&&void 0!==a?a:0,r}};const Mr={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();var i;switch(0!==e.kind&&t.uint32(8).int32(e.kind),null===(i=e.value)||void 0===i?void 0:i.$case){case"user":Dr.encode(e.value.user,t.uint32(18).fork()).ldelim();break;case"speaker":Rr.encode(e.value.speaker,t.uint32(26).fork()).ldelim()}return t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={kind:0,value:void 0};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.kind=i.int32();break;case 2:n.value={$case:"user",user:Dr.decode(i,i.uint32())};break;case 3:n.value={$case:"speaker",speaker:Rr.decode(i,i.uint32())};break;default:i.skipType(7&e)}}return n},fromJSON:e=>({kind:jr(e.kind)?vr(e.kind):0,value:jr(e.user)?{$case:"user",user:Dr.fromJSON(e.user)}:jr(e.speaker)?{$case:"speaker",speaker:Rr.fromJSON(e.speaker)}:void 0}),toJSON(e){var t,i,s,n,a,r;const o={};return void 0!==e.kind&&(o.kind=function(e){switch(e){case er.RELIABLE:return"RELIABLE";case er.LOSSY:return"LOSSY";case er.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.kind)),"user"===(null===(t=e.value)||void 0===t?void 0:t.$case)&&(o.user=(null===(i=e.value)||void 0===i?void 0:i.user)?Dr.toJSON(null===(s=e.value)||void 0===s?void 0:s.user):void 0),"speaker"===(null===(n=e.value)||void 0===n?void 0:n.$case)&&(o.speaker=(null===(a=e.value)||void 0===a?void 0:a.speaker)?Rr.toJSON(null===(r=e.value)||void 0===r?void 0:r.speaker):void 0),o},create:e=>Mr.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,s,n,a,r,o;const c={kind:0,value:void 0};return c.kind=null!==(t=e.kind)&&void 0!==t?t:0,"user"===(null===(i=e.value)||void 0===i?void 0:i.$case)&&void 0!==(null===(s=e.value)||void 0===s?void 0:s.user)&&null!==(null===(n=e.value)||void 0===n?void 0:n.user)&&(c.value={$case:"user",user:Dr.fromPartial(e.value.user)}),"speaker"===(null===(a=e.value)||void 0===a?void 0:a.$case)&&void 0!==(null===(r=e.value)||void 0===r?void 0:r.speaker)&&null!==(null===(o=e.value)||void 0===o?void 0:o.speaker)&&(c.value={$case:"speaker",speaker:Rr.fromPartial(e.value.speaker)}),c}};const Rr={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();for(const i of e.speakers)_r.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={speakers:[]};for(;i.pos<s;){const e=i.uint32();if(e>>>3==1)n.speakers.push(_r.decode(i,i.uint32()));else i.skipType(7&e)}return n},fromJSON:e=>({speakers:Array.isArray(null==e?void 0:e.speakers)?e.speakers.map((e=>_r.fromJSON(e))):[]}),toJSON(e){const t={};return e.speakers?t.speakers=e.speakers.map((e=>e?_r.toJSON(e):void 0)):t.speakers=[],t},create:e=>Rr.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={speakers:[]};return i.speakers=(null===(t=e.speakers)||void 0===t?void 0:t.map((e=>_r.fromPartial(e))))||[],i}};const _r={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();return""!==e.sid&&t.uint32(10).string(e.sid),0!==e.level&&t.uint32(21).float(e.level),!0===e.active&&t.uint32(24).bool(e.active),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={sid:"",level:0,active:!1};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.sid=i.string();break;case 2:n.level=i.float();break;case 3:n.active=i.bool();break;default:i.skipType(7&e)}}return n},fromJSON:e=>({sid:jr(e.sid)?String(e.sid):"",level:jr(e.level)?Number(e.level):0,active:!!jr(e.active)&&Boolean(e.active)}),toJSON(e){const t={};return void 0!==e.sid&&(t.sid=e.sid),void 0!==e.level&&(t.level=e.level),void 0!==e.active&&(t.active=e.active),t},create:e=>_r.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,s;const n={sid:"",level:0,active:!1};return n.sid=null!==(t=e.sid)&&void 0!==t?t:"",n.level=null!==(i=e.level)&&void 0!==i?i:0,n.active=null!==(s=e.active)&&void 0!==s&&s,n}};function Nr(){return{participantSid:"",payload:new Uint8Array,destinationSids:[],topic:void 0}}const Dr={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();""!==e.participantSid&&t.uint32(10).string(e.participantSid),0!==e.payload.length&&t.uint32(18).bytes(e.payload);for(const i of e.destinationSids)t.uint32(26).string(i);return void 0!==e.topic&&t.uint32(34).string(e.topic),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n=Nr();for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.participantSid=i.string();break;case 2:n.payload=i.bytes();break;case 3:n.destinationSids.push(i.string());break;case 4:n.topic=i.string();break;default:i.skipType(7&e)}}return n},fromJSON:e=>({participantSid:jr(e.participantSid)?String(e.participantSid):"",payload:jr(e.payload)?Br(e.payload):new Uint8Array,destinationSids:Array.isArray(null==e?void 0:e.destinationSids)?e.destinationSids.map((e=>String(e))):[],topic:jr(e.topic)?String(e.topic):void 0}),toJSON(e){const t={};return void 0!==e.participantSid&&(t.participantSid=e.participantSid),void 0!==e.payload&&(t.payload=function(e){if(Fr.Buffer)return Fr.Buffer.from(e).toString("base64");{const t=[];return e.forEach((e=>{t.push(String.fromCharCode(e))})),Fr.btoa(t.join(""))}}(void 0!==e.payload?e.payload:new Uint8Array)),e.destinationSids?t.destinationSids=e.destinationSids.map((e=>e)):t.destinationSids=[],void 0!==e.topic&&(t.topic=e.topic),t},create:e=>Dr.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,s,n;const a=Nr();return a.participantSid=null!==(t=e.participantSid)&&void 0!==t?t:"",a.payload=null!==(i=e.payload)&&void 0!==i?i:new Uint8Array,a.destinationSids=(null===(s=e.destinationSids)||void 0===s?void 0:s.map((e=>e)))||[],a.topic=null!==(n=e.topic)&&void 0!==n?n:void 0,a}};const Ir={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();""!==e.participantSid&&t.uint32(10).string(e.participantSid);for(const i of e.trackSids)t.uint32(18).string(i);return t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={participantSid:"",trackSids:[]};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.participantSid=i.string();break;case 2:n.trackSids.push(i.string());break;default:i.skipType(7&e)}}return n},fromJSON:e=>({participantSid:jr(e.participantSid)?String(e.participantSid):"",trackSids:Array.isArray(null==e?void 0:e.trackSids)?e.trackSids.map((e=>String(e))):[]}),toJSON(e){const t={};return void 0!==e.participantSid&&(t.participantSid=e.participantSid),e.trackSids?t.trackSids=e.trackSids.map((e=>e)):t.trackSids=[],t},create:e=>Ir.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const s={participantSid:"",trackSids:[]};return s.participantSid=null!==(t=e.participantSid)&&void 0!==t?t:"",s.trackSids=(null===(i=e.trackSids)||void 0===i?void 0:i.map((e=>e)))||[],s}};const Ar={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();return 0!==e.edition&&t.uint32(8).int32(e.edition),""!==e.version&&t.uint32(18).string(e.version),0!==e.protocol&&t.uint32(24).int32(e.protocol),""!==e.region&&t.uint32(34).string(e.region),""!==e.nodeId&&t.uint32(42).string(e.nodeId),""!==e.debugInfo&&t.uint32(50).string(e.debugInfo),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={edition:0,version:"",protocol:0,region:"",nodeId:"",debugInfo:""};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.edition=i.int32();break;case 2:n.version=i.string();break;case 3:n.protocol=i.int32();break;case 4:n.region=i.string();break;case 5:n.nodeId=i.string();break;case 6:n.debugInfo=i.string();break;default:i.skipType(7&e)}}return n},fromJSON:e=>({edition:jr(e.edition)?br(e.edition):0,version:jr(e.version)?String(e.version):"",protocol:jr(e.protocol)?Number(e.protocol):0,region:jr(e.region)?String(e.region):"",nodeId:jr(e.nodeId)?String(e.nodeId):"",debugInfo:jr(e.debugInfo)?String(e.debugInfo):""}),toJSON(e){const t={};return void 0!==e.edition&&(t.edition=function(e){switch(e){case tr.Standard:return"Standard";case tr.Cloud:return"Cloud";case tr.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.edition)),void 0!==e.version&&(t.version=e.version),void 0!==e.protocol&&(t.protocol=Math.round(e.protocol)),void 0!==e.region&&(t.region=e.region),void 0!==e.nodeId&&(t.nodeId=e.nodeId),void 0!==e.debugInfo&&(t.debugInfo=e.debugInfo),t},create:e=>Ar.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,s,n,a,r;const o={edition:0,version:"",protocol:0,region:"",nodeId:"",debugInfo:""};return o.edition=null!==(t=e.edition)&&void 0!==t?t:0,o.version=null!==(i=e.version)&&void 0!==i?i:"",o.protocol=null!==(s=e.protocol)&&void 0!==s?s:0,o.region=null!==(n=e.region)&&void 0!==n?n:"",o.nodeId=null!==(a=e.nodeId)&&void 0!==a?a:"",o.debugInfo=null!==(r=e.debugInfo)&&void 0!==r?r:"",o}};const Or={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();return 0!==e.sdk&&t.uint32(8).int32(e.sdk),""!==e.version&&t.uint32(18).string(e.version),0!==e.protocol&&t.uint32(24).int32(e.protocol),""!==e.os&&t.uint32(34).string(e.os),""!==e.osVersion&&t.uint32(42).string(e.osVersion),""!==e.deviceModel&&t.uint32(50).string(e.deviceModel),""!==e.browser&&t.uint32(58).string(e.browser),""!==e.browserVersion&&t.uint32(66).string(e.browserVersion),""!==e.address&&t.uint32(74).string(e.address),""!==e.network&&t.uint32(82).string(e.network),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={sdk:0,version:"",protocol:0,os:"",osVersion:"",deviceModel:"",browser:"",browserVersion:"",address:"",network:""};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.sdk=i.int32();break;case 2:n.version=i.string();break;case 3:n.protocol=i.int32();break;case 4:n.os=i.string();break;case 5:n.osVersion=i.string();break;case 6:n.deviceModel=i.string();break;case 7:n.browser=i.string();break;case 8:n.browserVersion=i.string();break;case 9:n.address=i.string();break;case 10:n.network=i.string();break;default:i.skipType(7&e)}}return n},fromJSON:e=>({sdk:jr(e.sdk)?yr(e.sdk):0,version:jr(e.version)?String(e.version):"",protocol:jr(e.protocol)?Number(e.protocol):0,os:jr(e.os)?String(e.os):"",osVersion:jr(e.osVersion)?String(e.osVersion):"",deviceModel:jr(e.deviceModel)?String(e.deviceModel):"",browser:jr(e.browser)?String(e.browser):"",browserVersion:jr(e.browserVersion)?String(e.browserVersion):"",address:jr(e.address)?String(e.address):"",network:jr(e.network)?String(e.network):""}),toJSON(e){const t={};return void 0!==e.sdk&&(t.sdk=function(e){switch(e){case ir.UNKNOWN:return"UNKNOWN";case ir.JS:return"JS";case ir.SWIFT:return"SWIFT";case ir.ANDROID:return"ANDROID";case ir.FLUTTER:return"FLUTTER";case ir.GO:return"GO";case ir.UNITY:return"UNITY";case ir.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.sdk)),void 0!==e.version&&(t.version=e.version),void 0!==e.protocol&&(t.protocol=Math.round(e.protocol)),void 0!==e.os&&(t.os=e.os),void 0!==e.osVersion&&(t.osVersion=e.osVersion),void 0!==e.deviceModel&&(t.deviceModel=e.deviceModel),void 0!==e.browser&&(t.browser=e.browser),void 0!==e.browserVersion&&(t.browserVersion=e.browserVersion),void 0!==e.address&&(t.address=e.address),void 0!==e.network&&(t.network=e.network),t},create:e=>Or.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,s,n,a,r,o,c,l,d;const h={sdk:0,version:"",protocol:0,os:"",osVersion:"",deviceModel:"",browser:"",browserVersion:"",address:"",network:""};return h.sdk=null!==(t=e.sdk)&&void 0!==t?t:0,h.version=null!==(i=e.version)&&void 0!==i?i:"",h.protocol=null!==(s=e.protocol)&&void 0!==s?s:0,h.os=null!==(n=e.os)&&void 0!==n?n:"",h.osVersion=null!==(a=e.osVersion)&&void 0!==a?a:"",h.deviceModel=null!==(r=e.deviceModel)&&void 0!==r?r:"",h.browser=null!==(o=e.browser)&&void 0!==o?o:"",h.browserVersion=null!==(c=e.browserVersion)&&void 0!==c?c:"",h.address=null!==(l=e.address)&&void 0!==l?l:"",h.network=null!==(d=e.network)&&void 0!==d?d:"",h}};const Ur={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();return void 0!==e.video&&xr.encode(e.video,t.uint32(10).fork()).ldelim(),void 0!==e.screen&&xr.encode(e.screen,t.uint32(18).fork()).ldelim(),0!==e.resumeConnection&&t.uint32(24).int32(e.resumeConnection),void 0!==e.disabledCodecs&&Lr.encode(e.disabledCodecs,t.uint32(34).fork()).ldelim(),0!==e.forceRelay&&t.uint32(40).int32(e.forceRelay),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={video:void 0,screen:void 0,resumeConnection:0,disabledCodecs:void 0,forceRelay:0};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.video=xr.decode(i,i.uint32());break;case 2:n.screen=xr.decode(i,i.uint32());break;case 3:n.resumeConnection=i.int32();break;case 4:n.disabledCodecs=Lr.decode(i,i.uint32());break;case 5:n.forceRelay=i.int32();break;default:i.skipType(7&e)}}return n},fromJSON:e=>({video:jr(e.video)?xr.fromJSON(e.video):void 0,screen:jr(e.screen)?xr.fromJSON(e.screen):void 0,resumeConnection:jr(e.resumeConnection)?hr(e.resumeConnection):0,disabledCodecs:jr(e.disabledCodecs)?Lr.fromJSON(e.disabledCodecs):void 0,forceRelay:jr(e.forceRelay)?hr(e.forceRelay):0}),toJSON(e){const t={};return void 0!==e.video&&(t.video=e.video?xr.toJSON(e.video):void 0),void 0!==e.screen&&(t.screen=e.screen?xr.toJSON(e.screen):void 0),void 0!==e.resumeConnection&&(t.resumeConnection=ur(e.resumeConnection)),void 0!==e.disabledCodecs&&(t.disabledCodecs=e.disabledCodecs?Lr.toJSON(e.disabledCodecs):void 0),void 0!==e.forceRelay&&(t.forceRelay=ur(e.forceRelay)),t},create:e=>Ur.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const s={video:void 0,screen:void 0,resumeConnection:0,disabledCodecs:void 0,forceRelay:0};return s.video=void 0!==e.video&&null!==e.video?xr.fromPartial(e.video):void 0,s.screen=void 0!==e.screen&&null!==e.screen?xr.fromPartial(e.screen):void 0,s.resumeConnection=null!==(t=e.resumeConnection)&&void 0!==t?t:0,s.disabledCodecs=void 0!==e.disabledCodecs&&null!==e.disabledCodecs?Lr.fromPartial(e.disabledCodecs):void 0,s.forceRelay=null!==(i=e.forceRelay)&&void 0!==i?i:0,s}};const xr={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();return 0!==e.hardwareEncoder&&t.uint32(8).int32(e.hardwareEncoder),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={hardwareEncoder:0};for(;i.pos<s;){const e=i.uint32();if(e>>>3==1)n.hardwareEncoder=i.int32();else i.skipType(7&e)}return n},fromJSON:e=>({hardwareEncoder:jr(e.hardwareEncoder)?hr(e.hardwareEncoder):0}),toJSON(e){const t={};return void 0!==e.hardwareEncoder&&(t.hardwareEncoder=ur(e.hardwareEncoder)),t},create:e=>xr.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={hardwareEncoder:0};return i.hardwareEncoder=null!==(t=e.hardwareEncoder)&&void 0!==t?t:0,i}};const Lr={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();for(const i of e.codecs)wr.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={codecs:[]};for(;i.pos<s;){const e=i.uint32();if(e>>>3==1)n.codecs.push(wr.decode(i,i.uint32()));else i.skipType(7&e)}return n},fromJSON:e=>({codecs:Array.isArray(null==e?void 0:e.codecs)?e.codecs.map((e=>wr.fromJSON(e))):[]}),toJSON(e){const t={};return e.codecs?t.codecs=e.codecs.map((e=>e?wr.toJSON(e):void 0)):t.codecs=[],t},create:e=>Lr.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={codecs:[]};return i.codecs=(null===(t=e.codecs)||void 0===t?void 0:t.map((e=>wr.fromPartial(e))))||[],i}};var Fr=(()=>{if("undefined"!=typeof globalThis)return globalThis;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw"Unable to locate global object"})();function Br(e){if(Fr.Buffer)return Uint8Array.from(Fr.Buffer.from(e,"base64"));{const t=Fr.atob(e),i=new Uint8Array(t.length);for(let e=0;e<t.length;++e)i[e]=t.charCodeAt(e);return i}}function qr(e){if(e.gt(Number.MAX_SAFE_INTEGER))throw new Fr.Error("Value is larger than Number.MAX_SAFE_INTEGER");return e.toNumber()}function jr(e){return null!=e}sr.util.Long!==hn&&(sr.util.Long=hn,sr.configure());const Vr=7e3,$r=[0,300,1200,2700,4800,Vr,Vr,Vr,Vr,Vr];function Wr(e){var t,i,s,n=2;for("undefined"!=typeof Symbol&&(i=Symbol.asyncIterator,s=Symbol.iterator);n--;){if(i&&null!=(t=e[i]))return t.call(e);if(s&&null!=(t=e[s]))return new Jr(t.call(e));i="@@asyncIterator",s="@@iterator"}throw new TypeError("Object is not async iterable")}function Jr(e){function t(e){if(Object(e)!==e)return Promise.reject(new TypeError(e+" is not an object."));var t=e.done;return Promise.resolve(e.value).then((function(e){return{value:e,done:t}}))}return Jr=function(e){this.s=e,this.n=e.next},Jr.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var i=this.s.return;return void 0===i?Promise.resolve({value:e,done:!0}):t(i.apply(this.s,arguments))},throw:function(e){var i=this.s.return;return void 0===i?Promise.reject(e):t(i.apply(this.s,arguments))}},new Jr(e)}function Hr(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,s)}return i}function Gr(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Hr(Object(i),!0).forEach((function(t){zr(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Hr(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function zr(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var s=i.call(e,t||"default");if("object"!=typeof s)return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}let Zr=!0,Kr=!0;function Qr(e,t,i){const s=e.match(t);return s&&s.length>=i&&parseInt(s[i],10)}function Xr(e,t,i){if(!e.RTCPeerConnection)return;const s=e.RTCPeerConnection.prototype,n=s.addEventListener;s.addEventListener=function(e,s){if(e!==t)return n.apply(this,arguments);const a=e=>{const t=i(e);t&&(s.handleEvent?s.handleEvent(t):s(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(s,a),n.apply(this,[e,a])};const a=s.removeEventListener;s.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return a.apply(this,arguments);if(!this._eventMap[t].has(i))return a.apply(this,arguments);const s=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,a.apply(this,[e,s])},Object.defineProperty(s,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function Yr(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Zr=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function eo(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Kr=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function to(){if("object"==typeof window){if(Zr)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function io(e,t){Kr&&console.warn(e+" is deprecated, please use "+t+" instead.")}function so(e){return"[object Object]"===Object.prototype.toString.call(e)}function no(e){return so(e)?Object.keys(e).reduce((function(t,i){const s=so(e[i]),n=s?no(e[i]):e[i],a=s&&!Object.keys(n).length;return void 0===n||a?t:Object.assign(t,{[i]:n})}),{}):e}function ao(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((s=>{s.endsWith("Id")?ao(e,e.get(t[s]),i):s.endsWith("Ids")&&t[s].forEach((t=>{ao(e,e.get(t),i)}))})))}function ro(e,t,i){const s=i?"outbound-rtp":"inbound-rtp",n=new Map;if(null===t)return n;const a=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&a.push(e)})),a.forEach((t=>{e.forEach((i=>{i.type===s&&i.trackId===t.id&&ao(e,i,n)}))})),n}const oo=to;function co(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const s=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const s="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==s.exact&&"number"==typeof s.exact&&(s.min=s.max=s.exact);const n=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==s.ideal){t.optional=t.optional||[];let e={};"number"==typeof s.ideal?(e[n("min",i)]=s.ideal,t.optional.push(e),e={},e[n("max",i)]=s.ideal,t.optional.push(e)):(e[n("",i)]=s.ideal,t.optional.push(e))}void 0!==s.exact&&"number"!=typeof s.exact?(t.mandatory=t.mandatory||{},t.mandatory[n("",i)]=s.exact):["min","max"].forEach((e=>{void 0!==s[e]&&(t.mandatory=t.mandatory||{},t.mandatory[n(e,i)]=s[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},n=function(e,n){if(t.version>=61)return n(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=s(e.audio)}if(e&&"object"==typeof e.video){let a=e.video.facingMode;a=a&&("object"==typeof a?a:{ideal:a});const r=t.version<66;if(a&&("user"===a.exact||"environment"===a.exact||"user"===a.ideal||"environment"===a.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||r)){let t;if(delete e.video.facingMode,"environment"===a.exact||"environment"===a.ideal?t=["back","rear"]:"user"!==a.exact&&"user"!==a.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{let r=(i=i.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!r&&i.length&&t.includes("back")&&(r=i[i.length-1]),r&&(e.video.deviceId=a.exact?{exact:r.deviceId}:{ideal:r.deviceId}),e.video=s(e.video),oo("chrome: "+JSON.stringify(e)),n(e)}))}e.video=s(e.video)}return oo("chrome: "+JSON.stringify(e)),n(e)},a=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(e,t,s){n(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{s&&s(a(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return n(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(a(e))))))}}}function lo(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function ho(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(i=>{let s;s=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.track.id)):{track:i.track};const n=new Event("track");n.track=i.track,n.receiver=s,n.transceiver={receiver:s},n.streams=[t.stream],this.dispatchEvent(n)})),t.stream.getTracks().forEach((i=>{let s;s=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.id)):{track:i};const n=new Event("track");n.track=i,n.receiver=s,n.transceiver={receiver:s},n.streams=[t.stream],this.dispatchEvent(n)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else Xr(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function uo(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,s){let n=i.apply(this,arguments);return n||(n=t(this,e),this._senders.push(n)),n};const s=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){s.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const s=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],s.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function po(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,s]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const n=function(e){const t={};return e.result().forEach((e=>{const i={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{i[t]=e.stat(t)})),t[i.id]=i})),t},a=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const s=function(e){i(a(n(e)))};return t.apply(this,[s,e])}return new Promise(((e,i)=>{t.apply(this,[function(t){e(a(n(t)))},i])})).then(i,s)}}function mo(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>ro(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),Xr(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>ro(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,s;return this.getSenders().forEach((i=>{i.track===e&&(t?s=!0:t=i)})),this.getReceivers().forEach((t=>(t.track===e&&(i?s=!0:i=t),t.track===e))),s||t&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function go(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const s=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(s)&&this._shimmedLocalStreams[i.id].push(s):this._shimmedLocalStreams[i.id]=[i,s],s};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();i.apply(this,arguments);const s=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(s)};const s=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],s.apply(this,arguments)};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),n.apply(this,arguments)}}function fo(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return go(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const s=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}s.apply(this,[t])};const n=e.RTCPeerConnection.prototype.removeStream;function a(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const s=e._reverseStreams[t],n=e._streams[s.id];i=i.replace(new RegExp(n.id,"g"),s.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const s=[].slice.call(arguments,1);if(1!==s.length||!s[0].getTracks().find((e=>e===t)))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((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const n=this._streams[i.id];if(n)n.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const s=new e.MediaStream([t]);this._streams[i.id]=s,this._reverseStreams[s.id]=i,this.addStream(s)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],s={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=a(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>a(this,e)))}};e.RTCPeerConnection.prototype[t]=s[t]}));const r=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const s=e._reverseStreams[t],n=e._streams[s.id];i=i.replace(new RegExp(s.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),r.apply(this,arguments)):r.apply(this,arguments)};const o=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=o.get.apply(this);return""===e.type?e:a(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((i=>{this._streams[i].getTracks().find((t=>e.track===t))&&(t=this._streams[i])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function vo(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],s={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=s[t]}))}function bo(e,t){Xr(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var yo=Object.freeze({__proto__:null,fixNegotiationNeeded:bo,shimAddTrackRemoveTrack:fo,shimAddTrackRemoveTrackWithNative:go,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(i){return t(i).then((t=>{const s=i.video&&i.video.width,n=i.video&&i.video.height,a=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:a||3}},s&&(i.video.mandatory.maxWidth=s),n&&(i.video.mandatory.maxHeight=n),e.navigator.mediaDevices.getUserMedia(i)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))},shimGetSendersWithDtmf:uo,shimGetStats:po,shimGetUserMedia:co,shimMediaStream:lo,shimOnTrack:ho,shimPeerConnection:vo,shimSenderReceiverGetStats:mo});function So(e,t){const i=e&&e.navigator,s=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,s){io("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,s)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},s&&s.prototype.getSettings){const t=s.prototype.getSettings;s.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(s&&s.prototype.applyConstraints){const t=s.prototype.applyConstraints;s.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function wo(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Co(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],s={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=s[t]}));const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},s=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,n,a]=arguments;return s.apply(this,[e||null]).then((e=>{if(t.version<53&&!n)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,s)=>{e.set(s,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(n,a)}}function ko(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Eo(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),Xr(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function To(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){io("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function Po(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Mo(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];const e=arguments[1],i=e&&"sendEncodings"in e;i&&e.sendEncodings.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const s=t.apply(this,arguments);if(i){const{sender:t}=s,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e.sendEncodings,t.sendEncodings=e.sendEncodings,this.setParametersPromises.push(t.setParameters(i).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return s})}function Ro(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function _o(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function No(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var Do=Object.freeze({__proto__:null,shimAddTransceiver:Mo,shimCreateAnswer:No,shimCreateOffer:_o,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:Ro,shimGetUserMedia:So,shimOnTrack:wo,shimPeerConnection:Co,shimRTCDataChannel:Po,shimReceiverGetStats:Eo,shimRemoveStream:To,shimSenderGetStats:ko});function Io(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var i=arguments.length,s=new Array(i>1?i-1:0),n=1;n<i;n++)s[n-1]=arguments[n];return s&&s.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function Ao(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)}))}),t.apply(e,arguments)}}}function Oo(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,s=t.createAnswer,n=t.setLocalDescription,a=t.setRemoteDescription,r=t.addIceCandidate;t.createOffer=function(e,t){const s=arguments.length>=2?arguments[2]:arguments[0],n=i.apply(this,[s]);return t?(n.then(e,t),Promise.resolve()):n},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],n=s.apply(this,[i]);return t?(n.then(e,t),Promise.resolve()):n};let o=function(e,t,i){const s=n.apply(this,[e]);return i?(s.then(t,i),Promise.resolve()):s};t.setLocalDescription=o,o=function(e,t,i){const s=a.apply(this,[e]);return i?(s.then(t,i),Promise.resolve()):s},t.setRemoteDescription=o,o=function(e,t,i){const s=r.apply(this,[e]);return i?(s.then(t,i),Promise.resolve()):s},t.addIceCandidate=o}function Uo(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(xo(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,s){t.mediaDevices.getUserMedia(e).then(i,s)}.bind(t))}function xo(e){return e&&void 0!==e.video?Object.assign({},e,{video:no(e.video)}):e}function Lo(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let s=e.iceServers[i];!s.hasOwnProperty("urls")&&s.hasOwnProperty("url")?(io("RTCIceServer.url","RTCIceServer.urls"),s=JSON.parse(JSON.stringify(s)),s.urls=s.url,delete s.url,t.push(s)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function Fo(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Bo(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const i=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function qo(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var jo=Object.freeze({__proto__:null,shimAudioContext:qo,shimCallbacksAPI:Oo,shimConstraints:xo,shimCreateOfferLegacy:Bo,shimGetUserMedia:Uo,shimLocalStreamsAPI:Io,shimRTCIceServerUrls:Lo,shimRemoteStreamsAPI:Ao,shimTrackEventTransceiver:Fo}),Vo={};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":i.relatedAddress=t[e+1];break;case"rport":i.relatedPort=parseInt(t[e+1],10);break;case"tcptype":i.tcpType=t[e+1];break;case"ufrag":i.ufrag=t[e+1],i.usernameFragment=t[e+1];break;default:void 0===i[t[e]]&&(i[t[e]]=t[e+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const s=e.type;return t.push("typ"),t.push(s),"host"!==s&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substr(14).split(" ")},t.parseRtpMap=function(e){let t=e.substr(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substr(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1]}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+"\r\n"},t.parseFmtp=function(e){const t={};let i;const s=e.substr(e.indexOf(" ")+1).split(";");for(let e=0;e<s.length;e++)i=s[e].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const s=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?s.push(t+"="+e.parameters[t]):s.push(t)})),t+="a=fmtp:"+i+" "+s.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substr(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substr(7,t-7),10)},s=e.indexOf(":",t);return s>-1?(i.attribute=e.substr(t+1,s-t-1),i.value=e.substr(s+1)):i.attribute=e.substr(t+1),i},t.parseSsrcGroup=function(e){const t=e.substr(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substr(6)},t.parseFingerprint=function(e){const t=e.substr(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},t.parseCryptoLine=function(e){const t=e.substr(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substr(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const s=t.matchPrefix(e+i,"a=ice-ufrag:")[0],n=t.matchPrefix(e+i,"a=ice-pwd:")[0];return s&&n?{usernameFragment:s.substr(12),password:n.substr(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},s=t.splitLines(e)[0].split(" ");for(let n=3;n<s.length;n++){const a=s[n],r=t.matchPrefix(e,"a=rtpmap:"+a+" ")[0];if(r){const s=t.parseRtpMap(r),n=t.matchPrefix(e,"a=fmtp:"+a+" ");switch(s.parameters=n.length?t.parseFmtp(n[0]):{},s.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+a+" ").map(t.parseRtcpFb),i.codecs.push(s),s.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(s.name.toUpperCase())}}}return t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))})),i},t.writeRtpDescription=function(e,i){let s="";s+="m="+e+" ",s+=i.codecs.length>0?"9":"0",s+=" UDP/TLS/RTP/SAVPF ",s+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",s+="c=IN IP4 0.0.0.0\r\n",s+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((e=>{s+=t.writeRtpMap(e),s+=t.writeFmtp(e),s+=t.writeRtcpFb(e)}));let n=0;return i.codecs.forEach((e=>{e.maxptime>n&&(n=e.maxptime)})),n>0&&(s+="a=maxptime:"+n+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{s+=t.writeExtmap(e)})),s},t.parseRtpEncodingParameters=function(e){const i=[],s=t.parseRtpParameters(e),n=-1!==s.fecMechanisms.indexOf("RED"),a=-1!==s.fecMechanisms.indexOf("ULPFEC"),r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),o=r.length>0&&r[0].ssrc;let c;const l=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substr(17).split(" ").map((e=>parseInt(e,10)))));l.length>0&&l[0].length>1&&l[0][0]===o&&(c=l[0][1]),s.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:o,codecPayloadType:parseInt(e.parameters.apt,10)};o&&c&&(t.rtx={ssrc:c}),i.push(t),n&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:o,mechanism:a?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&o&&i.push({ssrc:o});let d=t.matchPrefix(e,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substr(7),10):0===d[0].indexOf("b=AS:")?1e3*parseInt(d[0].substr(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=d}))),i},t.parseRtcpParameters=function(e){const i={},s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];s&&(i.cname=s.value,i.ssrc=s.ssrc);const n=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=n.length>0,i.compound=0===n.length;const a=t.matchPrefix(e,"a=rtcp-mux");return i.mux=a.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const s=t.matchPrefix(e,"a=msid:");if(1===s.length)return i=s[0].substr(7).split(" "),{stream:i[0],track:i[1]};const n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return n.length>0?(i=n[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),s=t.matchPrefix(e,"a=max-message-size:");let n;s.length>0&&(n=parseInt(s[0].substr(19),10)),isNaN(n)&&(n=65536);const a=t.matchPrefix(e,"a=sctp-port:");if(a.length>0)return{port:parseInt(a[0].substr(12),10),protocol:i.fmt,maxMessageSize:n};const r=t.matchPrefix(e,"a=sctpmap:");if(r.length>0){const e=r[0].substr(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:n}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,21)},t.writeSessionBoilerplate=function(e,i,s){let n;const a=void 0!==i?i:2;n=e||t.generateSessionId();return"v=0\r\no="+(s||"thisisadapterortc")+" "+n+" "+a+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const s=t.splitLines(e);for(let e=0;e<s.length;e++)switch(s[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return s[e].substr(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substr(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substr(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substr(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let e=0;e<i.length;e++)if(i[e].length<2||"="!==i[e].charAt(1))return!1;return!0},e.exports=t}({get exports(){return Vo},set exports(e){Vo=e}});var $o=Vo,Wo=sn({__proto__:null,default:$o},[Vo]);function Jo(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substr(2)),e.candidate&&e.candidate.length){const i=new t(e),s=$o.parseCandidate(e.candidate),n=Object.assign(i,s);return n.toJSON=function(){return{candidate:n.candidate,sdpMid:n.sdpMid,sdpMLineIndex:n.sdpMLineIndex,usernameFragment:n.usernameFragment}},n}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,Xr(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function Ho(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=$o.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=$o.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i}(arguments[0]),i=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i}(e),s=function(e,i){let s=65536;"firefox"===t.browser&&57===t.version&&(s=65535);const n=$o.matchPrefix(e.sdp,"a=max-message-size:");return n.length>0?s=parseInt(n[0].substr(19),10):"firefox"===t.browser&&-1!==i&&(s=2147483637),s}(arguments[0],e);let n;n=0===i&&0===s?Number.POSITIVE_INFINITY:0===i||0===s?Math.max(i,s):Math.min(i,s);const a={};Object.defineProperty(a,"maxMessageSize",{get:()=>n}),this._sctp=a}return i.apply(this,arguments)}}function Go(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const s=arguments[0],n=s.length||s.size||s.byteLength;if("open"===e.readyState&&t.sctp&&n>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},Xr(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function zo(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}}))}function Zo(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const i=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function Ko(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Qo(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return i.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>i.apply(this,[e])))})}var Xo,Yo,ec,tc=Object.freeze({__proto__:null,removeExtmapAllowMixed:Zo,shimAddIceCandidateNullOrEmpty:Ko,shimConnectionState:zo,shimMaxMessageSize:Ho,shimParameterlessSetLocalDescription:Qo,shimRTCIceCandidate:Jo,shimSendThrowTypeError:Go});function ic(e){switch(e){case 0:case"PUBLISHER":return Xo.PUBLISHER;case 1:case"SUBSCRIBER":return Xo.SUBSCRIBER;default:return Xo.UNRECOGNIZED}}function sc(e){switch(e){case Xo.PUBLISHER:return"PUBLISHER";case Xo.SUBSCRIBER:return"SUBSCRIBER";case Xo.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function nc(e){switch(e){case 0:case"ACTIVE":return Yo.ACTIVE;case 1:case"PAUSED":return Yo.PAUSED;default:return Yo.UNRECOGNIZED}}function ac(e){switch(e){case 0:case"UDP":return ec.UDP;case 1:case"TCP":return ec.TCP;case 2:case"TLS":return ec.TLS;default:return ec.UNRECOGNIZED}}!function(){let{window:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const i=to,s=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.mozGetUserMedia)t.browser="firefox",t.version=Qr(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection&&!e.RTCIceGatherer)t.browser="chrome",t.version=Qr(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=Qr(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),n={browserDetails:s,commonShim:tc,extractVersion:Qr,disableLog:Yr,disableWarnings:eo,sdp:Wo};switch(s.browser){case"chrome":if(!yo||!vo||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),n;if(null===s.version)return i("Chrome shim can not determine version, not shimming."),n;i("adapter.js shimming chrome."),n.browserShim=yo,Ko(e,s),Qo(e),co(e,s),lo(e),vo(e,s),ho(e),fo(e,s),uo(e),po(e),mo(e),bo(e,s),Jo(e),zo(e),Ho(e,s),Go(e),Zo(e,s);break;case"firefox":if(!Do||!Co||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),n;i("adapter.js shimming firefox."),n.browserShim=Do,Ko(e,s),Qo(e),So(e,s),Co(e,s),wo(e),To(e),ko(e),Eo(e),Po(e),Mo(e),Ro(e),_o(e),No(e),Jo(e),zo(e),Ho(e,s),Go(e);break;case"safari":if(!jo||!t.shimSafari)return i("Safari shim is not included in this adapter release."),n;i("adapter.js shimming safari."),n.browserShim=jo,Ko(e,s),Qo(e),Lo(e),Bo(e),Oo(e),Io(e),Ao(e),Fo(e),Uo(e),qo(e),Jo(e),Ho(e,s),Go(e),Zo(e,s);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window}),function(e){e[e.PUBLISHER=0]="PUBLISHER",e[e.SUBSCRIBER=1]="SUBSCRIBER",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Xo||(Xo={})),function(e){e[e.ACTIVE=0]="ACTIVE",e[e.PAUSED=1]="PAUSED",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Yo||(Yo={})),function(e){e[e.UDP=0]="UDP",e[e.TCP=1]="TCP",e[e.TLS=2]="TLS",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(ec||(ec={}));const rc={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();var i;switch(null===(i=e.message)||void 0===i?void 0:i.$case){case"offer":fc.encode(e.message.offer,t.uint32(10).fork()).ldelim();break;case"answer":fc.encode(e.message.answer,t.uint32(18).fork()).ldelim();break;case"trickle":dc.encode(e.message.trickle,t.uint32(26).fork()).ldelim();break;case"addTrack":lc.encode(e.message.addTrack,t.uint32(34).fork()).ldelim();break;case"mute":hc.encode(e.message.mute,t.uint32(42).fork()).ldelim();break;case"subscription":bc.encode(e.message.subscription,t.uint32(50).fork()).ldelim();break;case"trackSetting":yc.encode(e.message.trackSetting,t.uint32(58).fork()).ldelim();break;case"leave":Sc.encode(e.message.leave,t.uint32(66).fork()).ldelim();break;case"updateLayers":wc.encode(e.message.updateLayers,t.uint32(82).fork()).ldelim();break;case"subscriptionPermission":Oc.encode(e.message.subscriptionPermission,t.uint32(90).fork()).ldelim();break;case"syncState":xc.encode(e.message.syncState,t.uint32(98).fork()).ldelim();break;case"simulate":Fc.encode(e.message.simulate,t.uint32(106).fork()).ldelim();break;case"ping":t.uint32(112).int64(e.message.ping);break;case"updateMetadata":Cc.encode(e.message.updateMetadata,t.uint32(122).fork()).ldelim();break;case"pingReq":Bc.encode(e.message.pingReq,t.uint32(130).fork()).ldelim()}return t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={message:void 0};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.message={$case:"offer",offer:fc.decode(i,i.uint32())};break;case 2:n.message={$case:"answer",answer:fc.decode(i,i.uint32())};break;case 3:n.message={$case:"trickle",trickle:dc.decode(i,i.uint32())};break;case 4:n.message={$case:"addTrack",addTrack:lc.decode(i,i.uint32())};break;case 5:n.message={$case:"mute",mute:hc.decode(i,i.uint32())};break;case 6:n.message={$case:"subscription",subscription:bc.decode(i,i.uint32())};break;case 7:n.message={$case:"trackSetting",trackSetting:yc.decode(i,i.uint32())};break;case 8:n.message={$case:"leave",leave:Sc.decode(i,i.uint32())};break;case 10:n.message={$case:"updateLayers",updateLayers:wc.decode(i,i.uint32())};break;case 11:n.message={$case:"subscriptionPermission",subscriptionPermission:Oc.decode(i,i.uint32())};break;case 12:n.message={$case:"syncState",syncState:xc.decode(i,i.uint32())};break;case 13:n.message={$case:"simulate",simulate:Fc.decode(i,i.uint32())};break;case 14:n.message={$case:"ping",ping:Gc(i.int64())};break;case 15:n.message={$case:"updateMetadata",updateMetadata:Cc.decode(i,i.uint32())};break;case 16:n.message={$case:"pingReq",pingReq:Bc.decode(i,i.uint32())};break;default:i.skipType(7&e)}}return n},fromJSON:e=>({message:zc(e.offer)?{$case:"offer",offer:fc.fromJSON(e.offer)}:zc(e.answer)?{$case:"answer",answer:fc.fromJSON(e.answer)}:zc(e.trickle)?{$case:"trickle",trickle:dc.fromJSON(e.trickle)}:zc(e.addTrack)?{$case:"addTrack",addTrack:lc.fromJSON(e.addTrack)}:zc(e.mute)?{$case:"mute",mute:hc.fromJSON(e.mute)}:zc(e.subscription)?{$case:"subscription",subscription:bc.fromJSON(e.subscription)}:zc(e.trackSetting)?{$case:"trackSetting",trackSetting:yc.fromJSON(e.trackSetting)}:zc(e.leave)?{$case:"leave",leave:Sc.fromJSON(e.leave)}:zc(e.updateLayers)?{$case:"updateLayers",updateLayers:wc.fromJSON(e.updateLayers)}:zc(e.subscriptionPermission)?{$case:"subscriptionPermission",subscriptionPermission:Oc.fromJSON(e.subscriptionPermission)}:zc(e.syncState)?{$case:"syncState",syncState:xc.fromJSON(e.syncState)}:zc(e.simulate)?{$case:"simulate",simulate:Fc.fromJSON(e.simulate)}:zc(e.ping)?{$case:"ping",ping:Number(e.ping)}:zc(e.updateMetadata)?{$case:"updateMetadata",updateMetadata:Cc.fromJSON(e.updateMetadata)}:zc(e.pingReq)?{$case:"pingReq",pingReq:Bc.fromJSON(e.pingReq)}:void 0}),toJSON(e){var t,i,s,n,a,r,o,c,l,d,h,u,p,m,g,f,v,b,y,S,w,C,k,E,T,P,M,R,_,N,D,I,A,O,U,x,L,F,B,q,j,V,$,W;const J={};return"offer"===(null===(t=e.message)||void 0===t?void 0:t.$case)&&(J.offer=(null===(i=e.message)||void 0===i?void 0:i.offer)?fc.toJSON(null===(s=e.message)||void 0===s?void 0:s.offer):void 0),"answer"===(null===(n=e.message)||void 0===n?void 0:n.$case)&&(J.answer=(null===(a=e.message)||void 0===a?void 0:a.answer)?fc.toJSON(null===(r=e.message)||void 0===r?void 0:r.answer):void 0),"trickle"===(null===(o=e.message)||void 0===o?void 0:o.$case)&&(J.trickle=(null===(c=e.message)||void 0===c?void 0:c.trickle)?dc.toJSON(null===(l=e.message)||void 0===l?void 0:l.trickle):void 0),"addTrack"===(null===(d=e.message)||void 0===d?void 0:d.$case)&&(J.addTrack=(null===(h=e.message)||void 0===h?void 0:h.addTrack)?lc.toJSON(null===(u=e.message)||void 0===u?void 0:u.addTrack):void 0),"mute"===(null===(p=e.message)||void 0===p?void 0:p.$case)&&(J.mute=(null===(m=e.message)||void 0===m?void 0:m.mute)?hc.toJSON(null===(g=e.message)||void 0===g?void 0:g.mute):void 0),"subscription"===(null===(f=e.message)||void 0===f?void 0:f.$case)&&(J.subscription=(null===(v=e.message)||void 0===v?void 0:v.subscription)?bc.toJSON(null===(b=e.message)||void 0===b?void 0:b.subscription):void 0),"trackSetting"===(null===(y=e.message)||void 0===y?void 0:y.$case)&&(J.trackSetting=(null===(S=e.message)||void 0===S?void 0:S.trackSetting)?yc.toJSON(null===(w=e.message)||void 0===w?void 0:w.trackSetting):void 0),"leave"===(null===(C=e.message)||void 0===C?void 0:C.$case)&&(J.leave=(null===(k=e.message)||void 0===k?void 0:k.leave)?Sc.toJSON(null===(E=e.message)||void 0===E?void 0:E.leave):void 0),"updateLayers"===(null===(T=e.message)||void 0===T?void 0:T.$case)&&(J.updateLayers=(null===(P=e.message)||void 0===P?void 0:P.updateLayers)?wc.toJSON(null===(M=e.message)||void 0===M?void 0:M.updateLayers):void 0),"subscriptionPermission"===(null===(R=e.message)||void 0===R?void 0:R.$case)&&(J.subscriptionPermission=(null===(_=e.message)||void 0===_?void 0:_.subscriptionPermission)?Oc.toJSON(null===(N=e.message)||void 0===N?void 0:N.subscriptionPermission):void 0),"syncState"===(null===(D=e.message)||void 0===D?void 0:D.$case)&&(J.syncState=(null===(I=e.message)||void 0===I?void 0:I.syncState)?xc.toJSON(null===(A=e.message)||void 0===A?void 0:A.syncState):void 0),"simulate"===(null===(O=e.message)||void 0===O?void 0:O.$case)&&(J.simulate=(null===(U=e.message)||void 0===U?void 0:U.simulate)?Fc.toJSON(null===(x=e.message)||void 0===x?void 0:x.simulate):void 0),"ping"===(null===(L=e.message)||void 0===L?void 0:L.$case)&&(J.ping=Math.round(null===(F=e.message)||void 0===F?void 0:F.ping)),"updateMetadata"===(null===(B=e.message)||void 0===B?void 0:B.$case)&&(J.updateMetadata=(null===(q=e.message)||void 0===q?void 0:q.updateMetadata)?Cc.toJSON(null===(j=e.message)||void 0===j?void 0:j.updateMetadata):void 0),"pingReq"===(null===(V=e.message)||void 0===V?void 0:V.$case)&&(J.pingReq=(null===($=e.message)||void 0===$?void 0:$.pingReq)?Bc.toJSON(null===(W=e.message)||void 0===W?void 0:W.pingReq):void 0),J},create:e=>rc.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,s,n,a,r,o,c,l,d,h,u,p,m,g,f,v,b,y,S,w,C,k,E,T,P,M,R,_,N,D,I,A,O,U,x,L,F,B,q,j,V,$,W,J;const H={message:void 0};return"offer"===(null===(t=e.message)||void 0===t?void 0:t.$case)&&void 0!==(null===(i=e.message)||void 0===i?void 0:i.offer)&&null!==(null===(s=e.message)||void 0===s?void 0:s.offer)&&(H.message={$case:"offer",offer:fc.fromPartial(e.message.offer)}),"answer"===(null===(n=e.message)||void 0===n?void 0:n.$case)&&void 0!==(null===(a=e.message)||void 0===a?void 0:a.answer)&&null!==(null===(r=e.message)||void 0===r?void 0:r.answer)&&(H.message={$case:"answer",answer:fc.fromPartial(e.message.answer)}),"trickle"===(null===(o=e.message)||void 0===o?void 0:o.$case)&&void 0!==(null===(c=e.message)||void 0===c?void 0:c.trickle)&&null!==(null===(l=e.message)||void 0===l?void 0:l.trickle)&&(H.message={$case:"trickle",trickle:dc.fromPartial(e.message.trickle)}),"addTrack"===(null===(d=e.message)||void 0===d?void 0:d.$case)&&void 0!==(null===(h=e.message)||void 0===h?void 0:h.addTrack)&&null!==(null===(u=e.message)||void 0===u?void 0:u.addTrack)&&(H.message={$case:"addTrack",addTrack:lc.fromPartial(e.message.addTrack)}),"mute"===(null===(p=e.message)||void 0===p?void 0:p.$case)&&void 0!==(null===(m=e.message)||void 0===m?void 0:m.mute)&&null!==(null===(g=e.message)||void 0===g?void 0:g.mute)&&(H.message={$case:"mute",mute:hc.fromPartial(e.message.mute)}),"subscription"===(null===(f=e.message)||void 0===f?void 0:f.$case)&&void 0!==(null===(v=e.message)||void 0===v?void 0:v.subscription)&&null!==(null===(b=e.message)||void 0===b?void 0:b.subscription)&&(H.message={$case:"subscription",subscription:bc.fromPartial(e.message.subscription)}),"trackSetting"===(null===(y=e.message)||void 0===y?void 0:y.$case)&&void 0!==(null===(S=e.message)||void 0===S?void 0:S.trackSetting)&&null!==(null===(w=e.message)||void 0===w?void 0:w.trackSetting)&&(H.message={$case:"trackSetting",trackSetting:yc.fromPartial(e.message.trackSetting)}),"leave"===(null===(C=e.message)||void 0===C?void 0:C.$case)&&void 0!==(null===(k=e.message)||void 0===k?void 0:k.leave)&&null!==(null===(E=e.message)||void 0===E?void 0:E.leave)&&(H.message={$case:"leave",leave:Sc.fromPartial(e.message.leave)}),"updateLayers"===(null===(T=e.message)||void 0===T?void 0:T.$case)&&void 0!==(null===(P=e.message)||void 0===P?void 0:P.updateLayers)&&null!==(null===(M=e.message)||void 0===M?void 0:M.updateLayers)&&(H.message={$case:"updateLayers",updateLayers:wc.fromPartial(e.message.updateLayers)}),"subscriptionPermission"===(null===(R=e.message)||void 0===R?void 0:R.$case)&&void 0!==(null===(_=e.message)||void 0===_?void 0:_.subscriptionPermission)&&null!==(null===(N=e.message)||void 0===N?void 0:N.subscriptionPermission)&&(H.message={$case:"subscriptionPermission",subscriptionPermission:Oc.fromPartial(e.message.subscriptionPermission)}),"syncState"===(null===(D=e.message)||void 0===D?void 0:D.$case)&&void 0!==(null===(I=e.message)||void 0===I?void 0:I.syncState)&&null!==(null===(A=e.message)||void 0===A?void 0:A.syncState)&&(H.message={$case:"syncState",syncState:xc.fromPartial(e.message.syncState)}),"simulate"===(null===(O=e.message)||void 0===O?void 0:O.$case)&&void 0!==(null===(U=e.message)||void 0===U?void 0:U.simulate)&&null!==(null===(x=e.message)||void 0===x?void 0:x.simulate)&&(H.message={$case:"simulate",simulate:Fc.fromPartial(e.message.simulate)}),"ping"===(null===(L=e.message)||void 0===L?void 0:L.$case)&&void 0!==(null===(F=e.message)||void 0===F?void 0:F.ping)&&null!==(null===(B=e.message)||void 0===B?void 0:B.ping)&&(H.message={$case:"ping",ping:e.message.ping}),"updateMetadata"===(null===(q=e.message)||void 0===q?void 0:q.$case)&&void 0!==(null===(j=e.message)||void 0===j?void 0:j.updateMetadata)&&null!==(null===(V=e.message)||void 0===V?void 0:V.updateMetadata)&&(H.message={$case:"updateMetadata",updateMetadata:Cc.fromPartial(e.message.updateMetadata)}),"pingReq"===(null===($=e.message)||void 0===$?void 0:$.$case)&&void 0!==(null===(W=e.message)||void 0===W?void 0:W.pingReq)&&null!==(null===(J=e.message)||void 0===J?void 0:J.pingReq)&&(H.message={$case:"pingReq",pingReq:Bc.fromPartial(e.message.pingReq)}),H}};const oc={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();var i;switch(null===(i=e.message)||void 0===i?void 0:i.$case){case"join":uc.encode(e.message.join,t.uint32(10).fork()).ldelim();break;case"answer":fc.encode(e.message.answer,t.uint32(18).fork()).ldelim();break;case"offer":fc.encode(e.message.offer,t.uint32(26).fork()).ldelim();break;case"trickle":dc.encode(e.message.trickle,t.uint32(34).fork()).ldelim();break;case"update":vc.encode(e.message.update,t.uint32(42).fork()).ldelim();break;case"trackPublished":mc.encode(e.message.trackPublished,t.uint32(50).fork()).ldelim();break;case"leave":Sc.encode(e.message.leave,t.uint32(66).fork()).ldelim();break;case"mute":hc.encode(e.message.mute,t.uint32(74).fork()).ldelim();break;case"speakersChanged":Ec.encode(e.message.speakersChanged,t.uint32(82).fork()).ldelim();break;case"roomUpdate":Tc.encode(e.message.roomUpdate,t.uint32(90).fork()).ldelim();break;case"connectionQuality":Mc.encode(e.message.connectionQuality,t.uint32(98).fork()).ldelim();break;case"streamStateUpdate":_c.encode(e.message.streamStateUpdate,t.uint32(106).fork()).ldelim();break;case"subscribedQualityUpdate":Ic.encode(e.message.subscribedQualityUpdate,t.uint32(114).fork()).ldelim();break;case"subscriptionPermissionUpdate":Uc.encode(e.message.subscriptionPermissionUpdate,t.uint32(122).fork()).ldelim();break;case"refreshToken":t.uint32(130).string(e.message.refreshToken);break;case"trackUnpublished":gc.encode(e.message.trackUnpublished,t.uint32(138).fork()).ldelim();break;case"pong":t.uint32(144).int64(e.message.pong);break;case"reconnect":pc.encode(e.message.reconnect,t.uint32(154).fork()).ldelim();break;case"pongResp":qc.encode(e.message.pongResp,t.uint32(162).fork()).ldelim()}return t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={message:void 0};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.message={$case:"join",join:uc.decode(i,i.uint32())};break;case 2:n.message={$case:"answer",answer:fc.decode(i,i.uint32())};break;case 3:n.message={$case:"offer",offer:fc.decode(i,i.uint32())};break;case 4:n.message={$case:"trickle",trickle:dc.decode(i,i.uint32())};break;case 5:n.message={$case:"update",update:vc.decode(i,i.uint32())};break;case 6:n.message={$case:"trackPublished",trackPublished:mc.decode(i,i.uint32())};break;case 8:n.message={$case:"leave",leave:Sc.decode(i,i.uint32())};break;case 9:n.message={$case:"mute",mute:hc.decode(i,i.uint32())};break;case 10:n.message={$case:"speakersChanged",speakersChanged:Ec.decode(i,i.uint32())};break;case 11:n.message={$case:"roomUpdate",roomUpdate:Tc.decode(i,i.uint32())};break;case 12:n.message={$case:"connectionQuality",connectionQuality:Mc.decode(i,i.uint32())};break;case 13:n.message={$case:"streamStateUpdate",streamStateUpdate:_c.decode(i,i.uint32())};break;case 14:n.message={$case:"subscribedQualityUpdate",subscribedQualityUpdate:Ic.decode(i,i.uint32())};break;case 15:n.message={$case:"subscriptionPermissionUpdate",subscriptionPermissionUpdate:Uc.decode(i,i.uint32())};break;case 16:n.message={$case:"refreshToken",refreshToken:i.string()};break;case 17:n.message={$case:"trackUnpublished",trackUnpublished:gc.decode(i,i.uint32())};break;case 18:n.message={$case:"pong",pong:Gc(i.int64())};break;case 19:n.message={$case:"reconnect",reconnect:pc.decode(i,i.uint32())};break;case 20:n.message={$case:"pongResp",pongResp:qc.decode(i,i.uint32())};break;default:i.skipType(7&e)}}return n},fromJSON:e=>({message:zc(e.join)?{$case:"join",join:uc.fromJSON(e.join)}:zc(e.answer)?{$case:"answer",answer:fc.fromJSON(e.answer)}:zc(e.offer)?{$case:"offer",offer:fc.fromJSON(e.offer)}:zc(e.trickle)?{$case:"trickle",trickle:dc.fromJSON(e.trickle)}:zc(e.update)?{$case:"update",update:vc.fromJSON(e.update)}:zc(e.trackPublished)?{$case:"trackPublished",trackPublished:mc.fromJSON(e.trackPublished)}:zc(e.leave)?{$case:"leave",leave:Sc.fromJSON(e.leave)}:zc(e.mute)?{$case:"mute",mute:hc.fromJSON(e.mute)}:zc(e.speakersChanged)?{$case:"speakersChanged",speakersChanged:Ec.fromJSON(e.speakersChanged)}:zc(e.roomUpdate)?{$case:"roomUpdate",roomUpdate:Tc.fromJSON(e.roomUpdate)}:zc(e.connectionQuality)?{$case:"connectionQuality",connectionQuality:Mc.fromJSON(e.connectionQuality)}:zc(e.streamStateUpdate)?{$case:"streamStateUpdate",streamStateUpdate:_c.fromJSON(e.streamStateUpdate)}:zc(e.subscribedQualityUpdate)?{$case:"subscribedQualityUpdate",subscribedQualityUpdate:Ic.fromJSON(e.subscribedQualityUpdate)}:zc(e.subscriptionPermissionUpdate)?{$case:"subscriptionPermissionUpdate",subscriptionPermissionUpdate:Uc.fromJSON(e.subscriptionPermissionUpdate)}:zc(e.refreshToken)?{$case:"refreshToken",refreshToken:String(e.refreshToken)}:zc(e.trackUnpublished)?{$case:"trackUnpublished",trackUnpublished:gc.fromJSON(e.trackUnpublished)}:zc(e.pong)?{$case:"pong",pong:Number(e.pong)}:zc(e.reconnect)?{$case:"reconnect",reconnect:pc.fromJSON(e.reconnect)}:zc(e.pongResp)?{$case:"pongResp",pongResp:qc.fromJSON(e.pongResp)}:void 0}),toJSON(e){var t,i,s,n,a,r,o,c,l,d,h,u,p,m,g,f,v,b,y,S,w,C,k,E,T,P,M,R,_,N,D,I,A,O,U,x,L,F,B,q,j,V,$,W,J,H,G,z,Z,K,Q,X,Y,ee,te;const ie={};return"join"===(null===(t=e.message)||void 0===t?void 0:t.$case)&&(ie.join=(null===(i=e.message)||void 0===i?void 0:i.join)?uc.toJSON(null===(s=e.message)||void 0===s?void 0:s.join):void 0),"answer"===(null===(n=e.message)||void 0===n?void 0:n.$case)&&(ie.answer=(null===(a=e.message)||void 0===a?void 0:a.answer)?fc.toJSON(null===(r=e.message)||void 0===r?void 0:r.answer):void 0),"offer"===(null===(o=e.message)||void 0===o?void 0:o.$case)&&(ie.offer=(null===(c=e.message)||void 0===c?void 0:c.offer)?fc.toJSON(null===(l=e.message)||void 0===l?void 0:l.offer):void 0),"trickle"===(null===(d=e.message)||void 0===d?void 0:d.$case)&&(ie.trickle=(null===(h=e.message)||void 0===h?void 0:h.trickle)?dc.toJSON(null===(u=e.message)||void 0===u?void 0:u.trickle):void 0),"update"===(null===(p=e.message)||void 0===p?void 0:p.$case)&&(ie.update=(null===(m=e.message)||void 0===m?void 0:m.update)?vc.toJSON(null===(g=e.message)||void 0===g?void 0:g.update):void 0),"trackPublished"===(null===(f=e.message)||void 0===f?void 0:f.$case)&&(ie.trackPublished=(null===(v=e.message)||void 0===v?void 0:v.trackPublished)?mc.toJSON(null===(b=e.message)||void 0===b?void 0:b.trackPublished):void 0),"leave"===(null===(y=e.message)||void 0===y?void 0:y.$case)&&(ie.leave=(null===(S=e.message)||void 0===S?void 0:S.leave)?Sc.toJSON(null===(w=e.message)||void 0===w?void 0:w.leave):void 0),"mute"===(null===(C=e.message)||void 0===C?void 0:C.$case)&&(ie.mute=(null===(k=e.message)||void 0===k?void 0:k.mute)?hc.toJSON(null===(E=e.message)||void 0===E?void 0:E.mute):void 0),"speakersChanged"===(null===(T=e.message)||void 0===T?void 0:T.$case)&&(ie.speakersChanged=(null===(P=e.message)||void 0===P?void 0:P.speakersChanged)?Ec.toJSON(null===(M=e.message)||void 0===M?void 0:M.speakersChanged):void 0),"roomUpdate"===(null===(R=e.message)||void 0===R?void 0:R.$case)&&(ie.roomUpdate=(null===(_=e.message)||void 0===_?void 0:_.roomUpdate)?Tc.toJSON(null===(N=e.message)||void 0===N?void 0:N.roomUpdate):void 0),"connectionQuality"===(null===(D=e.message)||void 0===D?void 0:D.$case)&&(ie.connectionQuality=(null===(I=e.message)||void 0===I?void 0:I.connectionQuality)?Mc.toJSON(null===(A=e.message)||void 0===A?void 0:A.connectionQuality):void 0),"streamStateUpdate"===(null===(O=e.message)||void 0===O?void 0:O.$case)&&(ie.streamStateUpdate=(null===(U=e.message)||void 0===U?void 0:U.streamStateUpdate)?_c.toJSON(null===(x=e.message)||void 0===x?void 0:x.streamStateUpdate):void 0),"subscribedQualityUpdate"===(null===(L=e.message)||void 0===L?void 0:L.$case)&&(ie.subscribedQualityUpdate=(null===(F=e.message)||void 0===F?void 0:F.subscribedQualityUpdate)?Ic.toJSON(null===(B=e.message)||void 0===B?void 0:B.subscribedQualityUpdate):void 0),"subscriptionPermissionUpdate"===(null===(q=e.message)||void 0===q?void 0:q.$case)&&(ie.subscriptionPermissionUpdate=(null===(j=e.message)||void 0===j?void 0:j.subscriptionPermissionUpdate)?Uc.toJSON(null===(V=e.message)||void 0===V?void 0:V.subscriptionPermissionUpdate):void 0),"refreshToken"===(null===($=e.message)||void 0===$?void 0:$.$case)&&(ie.refreshToken=null===(W=e.message)||void 0===W?void 0:W.refreshToken),"trackUnpublished"===(null===(J=e.message)||void 0===J?void 0:J.$case)&&(ie.trackUnpublished=(null===(H=e.message)||void 0===H?void 0:H.trackUnpublished)?gc.toJSON(null===(G=e.message)||void 0===G?void 0:G.trackUnpublished):void 0),"pong"===(null===(z=e.message)||void 0===z?void 0:z.$case)&&(ie.pong=Math.round(null===(Z=e.message)||void 0===Z?void 0:Z.pong)),"reconnect"===(null===(K=e.message)||void 0===K?void 0:K.$case)&&(ie.reconnect=(null===(Q=e.message)||void 0===Q?void 0:Q.reconnect)?pc.toJSON(null===(X=e.message)||void 0===X?void 0:X.reconnect):void 0),"pongResp"===(null===(Y=e.message)||void 0===Y?void 0:Y.$case)&&(ie.pongResp=(null===(ee=e.message)||void 0===ee?void 0:ee.pongResp)?qc.toJSON(null===(te=e.message)||void 0===te?void 0:te.pongResp):void 0),ie},create:e=>oc.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,s,n,a,r,o,c,l,d,h,u,p,m,g,f,v,b,y,S,w,C,k,E,T,P,M,R,_,N,D,I,A,O,U,x,L,F,B,q,j,V,$,W,J,H,G,z,Z,K,Q,X,Y,ee,te,ie,se;const ne={message:void 0};return"join"===(null===(t=e.message)||void 0===t?void 0:t.$case)&&void 0!==(null===(i=e.message)||void 0===i?void 0:i.join)&&null!==(null===(s=e.message)||void 0===s?void 0:s.join)&&(ne.message={$case:"join",join:uc.fromPartial(e.message.join)}),"answer"===(null===(n=e.message)||void 0===n?void 0:n.$case)&&void 0!==(null===(a=e.message)||void 0===a?void 0:a.answer)&&null!==(null===(r=e.message)||void 0===r?void 0:r.answer)&&(ne.message={$case:"answer",answer:fc.fromPartial(e.message.answer)}),"offer"===(null===(o=e.message)||void 0===o?void 0:o.$case)&&void 0!==(null===(c=e.message)||void 0===c?void 0:c.offer)&&null!==(null===(l=e.message)||void 0===l?void 0:l.offer)&&(ne.message={$case:"offer",offer:fc.fromPartial(e.message.offer)}),"trickle"===(null===(d=e.message)||void 0===d?void 0:d.$case)&&void 0!==(null===(h=e.message)||void 0===h?void 0:h.trickle)&&null!==(null===(u=e.message)||void 0===u?void 0:u.trickle)&&(ne.message={$case:"trickle",trickle:dc.fromPartial(e.message.trickle)}),"update"===(null===(p=e.message)||void 0===p?void 0:p.$case)&&void 0!==(null===(m=e.message)||void 0===m?void 0:m.update)&&null!==(null===(g=e.message)||void 0===g?void 0:g.update)&&(ne.message={$case:"update",update:vc.fromPartial(e.message.update)}),"trackPublished"===(null===(f=e.message)||void 0===f?void 0:f.$case)&&void 0!==(null===(v=e.message)||void 0===v?void 0:v.trackPublished)&&null!==(null===(b=e.message)||void 0===b?void 0:b.trackPublished)&&(ne.message={$case:"trackPublished",trackPublished:mc.fromPartial(e.message.trackPublished)}),"leave"===(null===(y=e.message)||void 0===y?void 0:y.$case)&&void 0!==(null===(S=e.message)||void 0===S?void 0:S.leave)&&null!==(null===(w=e.message)||void 0===w?void 0:w.leave)&&(ne.message={$case:"leave",leave:Sc.fromPartial(e.message.leave)}),"mute"===(null===(C=e.message)||void 0===C?void 0:C.$case)&&void 0!==(null===(k=e.message)||void 0===k?void 0:k.mute)&&null!==(null===(E=e.message)||void 0===E?void 0:E.mute)&&(ne.message={$case:"mute",mute:hc.fromPartial(e.message.mute)}),"speakersChanged"===(null===(T=e.message)||void 0===T?void 0:T.$case)&&void 0!==(null===(P=e.message)||void 0===P?void 0:P.speakersChanged)&&null!==(null===(M=e.message)||void 0===M?void 0:M.speakersChanged)&&(ne.message={$case:"speakersChanged",speakersChanged:Ec.fromPartial(e.message.speakersChanged)}),"roomUpdate"===(null===(R=e.message)||void 0===R?void 0:R.$case)&&void 0!==(null===(_=e.message)||void 0===_?void 0:_.roomUpdate)&&null!==(null===(N=e.message)||void 0===N?void 0:N.roomUpdate)&&(ne.message={$case:"roomUpdate",roomUpdate:Tc.fromPartial(e.message.roomUpdate)}),"connectionQuality"===(null===(D=e.message)||void 0===D?void 0:D.$case)&&void 0!==(null===(I=e.message)||void 0===I?void 0:I.connectionQuality)&&null!==(null===(A=e.message)||void 0===A?void 0:A.connectionQuality)&&(ne.message={$case:"connectionQuality",connectionQuality:Mc.fromPartial(e.message.connectionQuality)}),"streamStateUpdate"===(null===(O=e.message)||void 0===O?void 0:O.$case)&&void 0!==(null===(U=e.message)||void 0===U?void 0:U.streamStateUpdate)&&null!==(null===(x=e.message)||void 0===x?void 0:x.streamStateUpdate)&&(ne.message={$case:"streamStateUpdate",streamStateUpdate:_c.fromPartial(e.message.streamStateUpdate)}),"subscribedQualityUpdate"===(null===(L=e.message)||void 0===L?void 0:L.$case)&&void 0!==(null===(F=e.message)||void 0===F?void 0:F.subscribedQualityUpdate)&&null!==(null===(B=e.message)||void 0===B?void 0:B.subscribedQualityUpdate)&&(ne.message={$case:"subscribedQualityUpdate",subscribedQualityUpdate:Ic.fromPartial(e.message.subscribedQualityUpdate)}),"subscriptionPermissionUpdate"===(null===(q=e.message)||void 0===q?void 0:q.$case)&&void 0!==(null===(j=e.message)||void 0===j?void 0:j.subscriptionPermissionUpdate)&&null!==(null===(V=e.message)||void 0===V?void 0:V.subscriptionPermissionUpdate)&&(ne.message={$case:"subscriptionPermissionUpdate",subscriptionPermissionUpdate:Uc.fromPartial(e.message.subscriptionPermissionUpdate)}),"refreshToken"===(null===($=e.message)||void 0===$?void 0:$.$case)&&void 0!==(null===(W=e.message)||void 0===W?void 0:W.refreshToken)&&null!==(null===(J=e.message)||void 0===J?void 0:J.refreshToken)&&(ne.message={$case:"refreshToken",refreshToken:e.message.refreshToken}),"trackUnpublished"===(null===(H=e.message)||void 0===H?void 0:H.$case)&&void 0!==(null===(G=e.message)||void 0===G?void 0:G.trackUnpublished)&&null!==(null===(z=e.message)||void 0===z?void 0:z.trackUnpublished)&&(ne.message={$case:"trackUnpublished",trackUnpublished:gc.fromPartial(e.message.trackUnpublished)}),"pong"===(null===(Z=e.message)||void 0===Z?void 0:Z.$case)&&void 0!==(null===(K=e.message)||void 0===K?void 0:K.pong)&&null!==(null===(Q=e.message)||void 0===Q?void 0:Q.pong)&&(ne.message={$case:"pong",pong:e.message.pong}),"reconnect"===(null===(X=e.message)||void 0===X?void 0:X.$case)&&void 0!==(null===(Y=e.message)||void 0===Y?void 0:Y.reconnect)&&null!==(null===(ee=e.message)||void 0===ee?void 0:ee.reconnect)&&(ne.message={$case:"reconnect",reconnect:pc.fromPartial(e.message.reconnect)}),"pongResp"===(null===(te=e.message)||void 0===te?void 0:te.$case)&&void 0!==(null===(ie=e.message)||void 0===ie?void 0:ie.pongResp)&&null!==(null===(se=e.message)||void 0===se?void 0:se.pongResp)&&(ne.message={$case:"pongResp",pongResp:qc.fromPartial(e.message.pongResp)}),ne}};const cc={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();return""!==e.codec&&t.uint32(10).string(e.codec),""!==e.cid&&t.uint32(18).string(e.cid),!0===e.enableSimulcastLayers&&t.uint32(24).bool(e.enableSimulcastLayers),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={codec:"",cid:"",enableSimulcastLayers:!1};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.codec=i.string();break;case 2:n.cid=i.string();break;case 3:n.enableSimulcastLayers=i.bool();break;default:i.skipType(7&e)}}return n},fromJSON:e=>({codec:zc(e.codec)?String(e.codec):"",cid:zc(e.cid)?String(e.cid):"",enableSimulcastLayers:!!zc(e.enableSimulcastLayers)&&Boolean(e.enableSimulcastLayers)}),toJSON(e){const t={};return void 0!==e.codec&&(t.codec=e.codec),void 0!==e.cid&&(t.cid=e.cid),void 0!==e.enableSimulcastLayers&&(t.enableSimulcastLayers=e.enableSimulcastLayers),t},create:e=>cc.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,s;const n={codec:"",cid:"",enableSimulcastLayers:!1};return n.codec=null!==(t=e.codec)&&void 0!==t?t:"",n.cid=null!==(i=e.cid)&&void 0!==i?i:"",n.enableSimulcastLayers=null!==(s=e.enableSimulcastLayers)&&void 0!==s&&s,n}};const lc={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();""!==e.cid&&t.uint32(10).string(e.cid),""!==e.name&&t.uint32(18).string(e.name),0!==e.type&&t.uint32(24).int32(e.type),0!==e.width&&t.uint32(32).uint32(e.width),0!==e.height&&t.uint32(40).uint32(e.height),!0===e.muted&&t.uint32(48).bool(e.muted),!0===e.disableDtx&&t.uint32(56).bool(e.disableDtx),0!==e.source&&t.uint32(64).int32(e.source);for(const i of e.layers)Pr.encode(i,t.uint32(74).fork()).ldelim();for(const i of e.simulcastCodecs)cc.encode(i,t.uint32(82).fork()).ldelim();return""!==e.sid&&t.uint32(90).string(e.sid),!0===e.stereo&&t.uint32(96).bool(e.stereo),!0===e.disableRed&&t.uint32(104).bool(e.disableRed),0!==e.encryption&&t.uint32(112).int32(e.encryption),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={cid:"",name:"",type:0,width:0,height:0,muted:!1,disableDtx:!1,source:0,layers:[],simulcastCodecs:[],sid:"",stereo:!1,disableRed:!1,encryption:0};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.cid=i.string();break;case 2:n.name=i.string();break;case 3:n.type=i.int32();break;case 4:n.width=i.uint32();break;case 5:n.height=i.uint32();break;case 6:n.muted=i.bool();break;case 7:n.disableDtx=i.bool();break;case 8:n.source=i.int32();break;case 9:n.layers.push(Pr.decode(i,i.uint32()));break;case 10:n.simulcastCodecs.push(cc.decode(i,i.uint32()));break;case 11:n.sid=i.string();break;case 12:n.stereo=i.bool();break;case 13:n.disableRed=i.bool();break;case 14:n.encryption=i.int32();break;default:i.skipType(7&e)}}return n},fromJSON:e=>({cid:zc(e.cid)?String(e.cid):"",name:zc(e.name)?String(e.name):"",type:zc(e.type)?nr(e.type):0,width:zc(e.width)?Number(e.width):0,height:zc(e.height)?Number(e.height):0,muted:!!zc(e.muted)&&Boolean(e.muted),disableDtx:!!zc(e.disableDtx)&&Boolean(e.disableDtx),source:zc(e.source)?rr(e.source):0,layers:Array.isArray(null==e?void 0:e.layers)?e.layers.map((e=>Pr.fromJSON(e))):[],simulcastCodecs:Array.isArray(null==e?void 0:e.simulcastCodecs)?e.simulcastCodecs.map((e=>cc.fromJSON(e))):[],sid:zc(e.sid)?String(e.sid):"",stereo:!!zc(e.stereo)&&Boolean(e.stereo),disableRed:!!zc(e.disableRed)&&Boolean(e.disableRed),encryption:zc(e.encryption)?gr(e.encryption):0}),toJSON(e){const t={};return void 0!==e.cid&&(t.cid=e.cid),void 0!==e.name&&(t.name=e.name),void 0!==e.type&&(t.type=ar(e.type)),void 0!==e.width&&(t.width=Math.round(e.width)),void 0!==e.height&&(t.height=Math.round(e.height)),void 0!==e.muted&&(t.muted=e.muted),void 0!==e.disableDtx&&(t.disableDtx=e.disableDtx),void 0!==e.source&&(t.source=or(e.source)),e.layers?t.layers=e.layers.map((e=>e?Pr.toJSON(e):void 0)):t.layers=[],e.simulcastCodecs?t.simulcastCodecs=e.simulcastCodecs.map((e=>e?cc.toJSON(e):void 0)):t.simulcastCodecs=[],void 0!==e.sid&&(t.sid=e.sid),void 0!==e.stereo&&(t.stereo=e.stereo),void 0!==e.disableRed&&(t.disableRed=e.disableRed),void 0!==e.encryption&&(t.encryption=fr(e.encryption)),t},create:e=>lc.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,s,n,a,r,o,c,l,d,h,u,p,m;const g={cid:"",name:"",type:0,width:0,height:0,muted:!1,disableDtx:!1,source:0,layers:[],simulcastCodecs:[],sid:"",stereo:!1,disableRed:!1,encryption:0};return g.cid=null!==(t=e.cid)&&void 0!==t?t:"",g.name=null!==(i=e.name)&&void 0!==i?i:"",g.type=null!==(s=e.type)&&void 0!==s?s:0,g.width=null!==(n=e.width)&&void 0!==n?n:0,g.height=null!==(a=e.height)&&void 0!==a?a:0,g.muted=null!==(r=e.muted)&&void 0!==r&&r,g.disableDtx=null!==(o=e.disableDtx)&&void 0!==o&&o,g.source=null!==(c=e.source)&&void 0!==c?c:0,g.layers=(null===(l=e.layers)||void 0===l?void 0:l.map((e=>Pr.fromPartial(e))))||[],g.simulcastCodecs=(null===(d=e.simulcastCodecs)||void 0===d?void 0:d.map((e=>cc.fromPartial(e))))||[],g.sid=null!==(h=e.sid)&&void 0!==h?h:"",g.stereo=null!==(u=e.stereo)&&void 0!==u&&u,g.disableRed=null!==(p=e.disableRed)&&void 0!==p&&p,g.encryption=null!==(m=e.encryption)&&void 0!==m?m:0,g}};const dc={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();return""!==e.candidateInit&&t.uint32(10).string(e.candidateInit),0!==e.target&&t.uint32(16).int32(e.target),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={candidateInit:"",target:0};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.candidateInit=i.string();break;case 2:n.target=i.int32();break;default:i.skipType(7&e)}}return n},fromJSON:e=>({candidateInit:zc(e.candidateInit)?String(e.candidateInit):"",target:zc(e.target)?ic(e.target):0}),toJSON(e){const t={};return void 0!==e.candidateInit&&(t.candidateInit=e.candidateInit),void 0!==e.target&&(t.target=sc(e.target)),t},create:e=>dc.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const s={candidateInit:"",target:0};return s.candidateInit=null!==(t=e.candidateInit)&&void 0!==t?t:"",s.target=null!==(i=e.target)&&void 0!==i?i:0,s}};const hc={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();return""!==e.sid&&t.uint32(10).string(e.sid),!0===e.muted&&t.uint32(16).bool(e.muted),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={sid:"",muted:!1};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.sid=i.string();break;case 2:n.muted=i.bool();break;default:i.skipType(7&e)}}return n},fromJSON:e=>({sid:zc(e.sid)?String(e.sid):"",muted:!!zc(e.muted)&&Boolean(e.muted)}),toJSON(e){const t={};return void 0!==e.sid&&(t.sid=e.sid),void 0!==e.muted&&(t.muted=e.muted),t},create:e=>hc.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const s={sid:"",muted:!1};return s.sid=null!==(t=e.sid)&&void 0!==t?t:"",s.muted=null!==(i=e.muted)&&void 0!==i&&i,s}};const uc={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();void 0!==e.room&&Sr.encode(e.room,t.uint32(10).fork()).ldelim(),void 0!==e.participant&&kr.encode(e.participant,t.uint32(18).fork()).ldelim();for(const i of e.otherParticipants)kr.encode(i,t.uint32(26).fork()).ldelim();""!==e.serverVersion&&t.uint32(34).string(e.serverVersion);for(const i of e.iceServers)kc.encode(i,t.uint32(42).fork()).ldelim();return!0===e.subscriberPrimary&&t.uint32(48).bool(e.subscriberPrimary),""!==e.alternativeUrl&&t.uint32(58).string(e.alternativeUrl),void 0!==e.clientConfiguration&&Ur.encode(e.clientConfiguration,t.uint32(66).fork()).ldelim(),""!==e.serverRegion&&t.uint32(74).string(e.serverRegion),0!==e.pingTimeout&&t.uint32(80).int32(e.pingTimeout),0!==e.pingInterval&&t.uint32(88).int32(e.pingInterval),void 0!==e.serverInfo&&Ar.encode(e.serverInfo,t.uint32(98).fork()).ldelim(),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={room:void 0,participant:void 0,otherParticipants:[],serverVersion:"",iceServers:[],subscriberPrimary:!1,alternativeUrl:"",clientConfiguration:void 0,serverRegion:"",pingTimeout:0,pingInterval:0,serverInfo:void 0};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.room=Sr.decode(i,i.uint32());break;case 2:n.participant=kr.decode(i,i.uint32());break;case 3:n.otherParticipants.push(kr.decode(i,i.uint32()));break;case 4:n.serverVersion=i.string();break;case 5:n.iceServers.push(kc.decode(i,i.uint32()));break;case 6:n.subscriberPrimary=i.bool();break;case 7:n.alternativeUrl=i.string();break;case 8:n.clientConfiguration=Ur.decode(i,i.uint32());break;case 9:n.serverRegion=i.string();break;case 10:n.pingTimeout=i.int32();break;case 11:n.pingInterval=i.int32();break;case 12:n.serverInfo=Ar.decode(i,i.uint32());break;default:i.skipType(7&e)}}return n},fromJSON:e=>({room:zc(e.room)?Sr.fromJSON(e.room):void 0,participant:zc(e.participant)?kr.fromJSON(e.participant):void 0,otherParticipants:Array.isArray(null==e?void 0:e.otherParticipants)?e.otherParticipants.map((e=>kr.fromJSON(e))):[],serverVersion:zc(e.serverVersion)?String(e.serverVersion):"",iceServers:Array.isArray(null==e?void 0:e.iceServers)?e.iceServers.map((e=>kc.fromJSON(e))):[],subscriberPrimary:!!zc(e.subscriberPrimary)&&Boolean(e.subscriberPrimary),alternativeUrl:zc(e.alternativeUrl)?String(e.alternativeUrl):"",clientConfiguration:zc(e.clientConfiguration)?Ur.fromJSON(e.clientConfiguration):void 0,serverRegion:zc(e.serverRegion)?String(e.serverRegion):"",pingTimeout:zc(e.pingTimeout)?Number(e.pingTimeout):0,pingInterval:zc(e.pingInterval)?Number(e.pingInterval):0,serverInfo:zc(e.serverInfo)?Ar.fromJSON(e.serverInfo):void 0}),toJSON(e){const t={};return void 0!==e.room&&(t.room=e.room?Sr.toJSON(e.room):void 0),void 0!==e.participant&&(t.participant=e.participant?kr.toJSON(e.participant):void 0),e.otherParticipants?t.otherParticipants=e.otherParticipants.map((e=>e?kr.toJSON(e):void 0)):t.otherParticipants=[],void 0!==e.serverVersion&&(t.serverVersion=e.serverVersion),e.iceServers?t.iceServers=e.iceServers.map((e=>e?kc.toJSON(e):void 0)):t.iceServers=[],void 0!==e.subscriberPrimary&&(t.subscriberPrimary=e.subscriberPrimary),void 0!==e.alternativeUrl&&(t.alternativeUrl=e.alternativeUrl),void 0!==e.clientConfiguration&&(t.clientConfiguration=e.clientConfiguration?Ur.toJSON(e.clientConfiguration):void 0),void 0!==e.serverRegion&&(t.serverRegion=e.serverRegion),void 0!==e.pingTimeout&&(t.pingTimeout=Math.round(e.pingTimeout)),void 0!==e.pingInterval&&(t.pingInterval=Math.round(e.pingInterval)),void 0!==e.serverInfo&&(t.serverInfo=e.serverInfo?Ar.toJSON(e.serverInfo):void 0),t},create:e=>uc.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,s,n,a,r,o,c;const l={room:void 0,participant:void 0,otherParticipants:[],serverVersion:"",iceServers:[],subscriberPrimary:!1,alternativeUrl:"",clientConfiguration:void 0,serverRegion:"",pingTimeout:0,pingInterval:0,serverInfo:void 0};return l.room=void 0!==e.room&&null!==e.room?Sr.fromPartial(e.room):void 0,l.participant=void 0!==e.participant&&null!==e.participant?kr.fromPartial(e.participant):void 0,l.otherParticipants=(null===(t=e.otherParticipants)||void 0===t?void 0:t.map((e=>kr.fromPartial(e))))||[],l.serverVersion=null!==(i=e.serverVersion)&&void 0!==i?i:"",l.iceServers=(null===(s=e.iceServers)||void 0===s?void 0:s.map((e=>kc.fromPartial(e))))||[],l.subscriberPrimary=null!==(n=e.subscriberPrimary)&&void 0!==n&&n,l.alternativeUrl=null!==(a=e.alternativeUrl)&&void 0!==a?a:"",l.clientConfiguration=void 0!==e.clientConfiguration&&null!==e.clientConfiguration?Ur.fromPartial(e.clientConfiguration):void 0,l.serverRegion=null!==(r=e.serverRegion)&&void 0!==r?r:"",l.pingTimeout=null!==(o=e.pingTimeout)&&void 0!==o?o:0,l.pingInterval=null!==(c=e.pingInterval)&&void 0!==c?c:0,l.serverInfo=void 0!==e.serverInfo&&null!==e.serverInfo?Ar.fromPartial(e.serverInfo):void 0,l}};const pc={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();for(const i of e.iceServers)kc.encode(i,t.uint32(10).fork()).ldelim();return void 0!==e.clientConfiguration&&Ur.encode(e.clientConfiguration,t.uint32(18).fork()).ldelim(),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={iceServers:[],clientConfiguration:void 0};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.iceServers.push(kc.decode(i,i.uint32()));break;case 2:n.clientConfiguration=Ur.decode(i,i.uint32());break;default:i.skipType(7&e)}}return n},fromJSON:e=>({iceServers:Array.isArray(null==e?void 0:e.iceServers)?e.iceServers.map((e=>kc.fromJSON(e))):[],clientConfiguration:zc(e.clientConfiguration)?Ur.fromJSON(e.clientConfiguration):void 0}),toJSON(e){const t={};return e.iceServers?t.iceServers=e.iceServers.map((e=>e?kc.toJSON(e):void 0)):t.iceServers=[],void 0!==e.clientConfiguration&&(t.clientConfiguration=e.clientConfiguration?Ur.toJSON(e.clientConfiguration):void 0),t},create:e=>pc.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={iceServers:[],clientConfiguration:void 0};return i.iceServers=(null===(t=e.iceServers)||void 0===t?void 0:t.map((e=>kc.fromPartial(e))))||[],i.clientConfiguration=void 0!==e.clientConfiguration&&null!==e.clientConfiguration?Ur.fromPartial(e.clientConfiguration):void 0,i}};const mc={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();return""!==e.cid&&t.uint32(10).string(e.cid),void 0!==e.track&&Tr.encode(e.track,t.uint32(18).fork()).ldelim(),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={cid:"",track:void 0};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.cid=i.string();break;case 2:n.track=Tr.decode(i,i.uint32());break;default:i.skipType(7&e)}}return n},fromJSON:e=>({cid:zc(e.cid)?String(e.cid):"",track:zc(e.track)?Tr.fromJSON(e.track):void 0}),toJSON(e){const t={};return void 0!==e.cid&&(t.cid=e.cid),void 0!==e.track&&(t.track=e.track?Tr.toJSON(e.track):void 0),t},create:e=>mc.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={cid:"",track:void 0};return i.cid=null!==(t=e.cid)&&void 0!==t?t:"",i.track=void 0!==e.track&&null!==e.track?Tr.fromPartial(e.track):void 0,i}};const gc={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();return""!==e.trackSid&&t.uint32(10).string(e.trackSid),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={trackSid:""};for(;i.pos<s;){const e=i.uint32();if(e>>>3==1)n.trackSid=i.string();else i.skipType(7&e)}return n},fromJSON:e=>({trackSid:zc(e.trackSid)?String(e.trackSid):""}),toJSON(e){const t={};return void 0!==e.trackSid&&(t.trackSid=e.trackSid),t},create:e=>gc.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={trackSid:""};return i.trackSid=null!==(t=e.trackSid)&&void 0!==t?t:"",i}};const fc={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();return""!==e.type&&t.uint32(10).string(e.type),""!==e.sdp&&t.uint32(18).string(e.sdp),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={type:"",sdp:""};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.type=i.string();break;case 2:n.sdp=i.string();break;default:i.skipType(7&e)}}return n},fromJSON:e=>({type:zc(e.type)?String(e.type):"",sdp:zc(e.sdp)?String(e.sdp):""}),toJSON(e){const t={};return void 0!==e.type&&(t.type=e.type),void 0!==e.sdp&&(t.sdp=e.sdp),t},create:e=>fc.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const s={type:"",sdp:""};return s.type=null!==(t=e.type)&&void 0!==t?t:"",s.sdp=null!==(i=e.sdp)&&void 0!==i?i:"",s}};const vc={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();for(const i of e.participants)kr.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={participants:[]};for(;i.pos<s;){const e=i.uint32();if(e>>>3==1)n.participants.push(kr.decode(i,i.uint32()));else i.skipType(7&e)}return n},fromJSON:e=>({participants:Array.isArray(null==e?void 0:e.participants)?e.participants.map((e=>kr.fromJSON(e))):[]}),toJSON(e){const t={};return e.participants?t.participants=e.participants.map((e=>e?kr.toJSON(e):void 0)):t.participants=[],t},create:e=>vc.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={participants:[]};return i.participants=(null===(t=e.participants)||void 0===t?void 0:t.map((e=>kr.fromPartial(e))))||[],i}};const bc={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();for(const i of e.trackSids)t.uint32(10).string(i);!0===e.subscribe&&t.uint32(16).bool(e.subscribe);for(const i of e.participantTracks)Ir.encode(i,t.uint32(26).fork()).ldelim();return t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={trackSids:[],subscribe:!1,participantTracks:[]};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.trackSids.push(i.string());break;case 2:n.subscribe=i.bool();break;case 3:n.participantTracks.push(Ir.decode(i,i.uint32()));break;default:i.skipType(7&e)}}return n},fromJSON:e=>({trackSids:Array.isArray(null==e?void 0:e.trackSids)?e.trackSids.map((e=>String(e))):[],subscribe:!!zc(e.subscribe)&&Boolean(e.subscribe),participantTracks:Array.isArray(null==e?void 0:e.participantTracks)?e.participantTracks.map((e=>Ir.fromJSON(e))):[]}),toJSON(e){const t={};return e.trackSids?t.trackSids=e.trackSids.map((e=>e)):t.trackSids=[],void 0!==e.subscribe&&(t.subscribe=e.subscribe),e.participantTracks?t.participantTracks=e.participantTracks.map((e=>e?Ir.toJSON(e):void 0)):t.participantTracks=[],t},create:e=>bc.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,s;const n={trackSids:[],subscribe:!1,participantTracks:[]};return n.trackSids=(null===(t=e.trackSids)||void 0===t?void 0:t.map((e=>e)))||[],n.subscribe=null!==(i=e.subscribe)&&void 0!==i&&i,n.participantTracks=(null===(s=e.participantTracks)||void 0===s?void 0:s.map((e=>Ir.fromPartial(e))))||[],n}};const yc={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();for(const i of e.trackSids)t.uint32(10).string(i);return!0===e.disabled&&t.uint32(24).bool(e.disabled),0!==e.quality&&t.uint32(32).int32(e.quality),0!==e.width&&t.uint32(40).uint32(e.width),0!==e.height&&t.uint32(48).uint32(e.height),0!==e.fps&&t.uint32(56).uint32(e.fps),0!==e.priority&&t.uint32(64).uint32(e.priority),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={trackSids:[],disabled:!1,quality:0,width:0,height:0,fps:0,priority:0};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.trackSids.push(i.string());break;case 3:n.disabled=i.bool();break;case 4:n.quality=i.int32();break;case 5:n.width=i.uint32();break;case 6:n.height=i.uint32();break;case 7:n.fps=i.uint32();break;case 8:n.priority=i.uint32();break;default:i.skipType(7&e)}}return n},fromJSON:e=>({trackSids:Array.isArray(null==e?void 0:e.trackSids)?e.trackSids.map((e=>String(e))):[],disabled:!!zc(e.disabled)&&Boolean(e.disabled),quality:zc(e.quality)?cr(e.quality):0,width:zc(e.width)?Number(e.width):0,height:zc(e.height)?Number(e.height):0,fps:zc(e.fps)?Number(e.fps):0,priority:zc(e.priority)?Number(e.priority):0}),toJSON(e){const t={};return e.trackSids?t.trackSids=e.trackSids.map((e=>e)):t.trackSids=[],void 0!==e.disabled&&(t.disabled=e.disabled),void 0!==e.quality&&(t.quality=lr(e.quality)),void 0!==e.width&&(t.width=Math.round(e.width)),void 0!==e.height&&(t.height=Math.round(e.height)),void 0!==e.fps&&(t.fps=Math.round(e.fps)),void 0!==e.priority&&(t.priority=Math.round(e.priority)),t},create:e=>yc.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,s,n,a,r,o;const c={trackSids:[],disabled:!1,quality:0,width:0,height:0,fps:0,priority:0};return c.trackSids=(null===(t=e.trackSids)||void 0===t?void 0:t.map((e=>e)))||[],c.disabled=null!==(i=e.disabled)&&void 0!==i&&i,c.quality=null!==(s=e.quality)&&void 0!==s?s:0,c.width=null!==(n=e.width)&&void 0!==n?n:0,c.height=null!==(a=e.height)&&void 0!==a?a:0,c.fps=null!==(r=e.fps)&&void 0!==r?r:0,c.priority=null!==(o=e.priority)&&void 0!==o?o:0,c}};const Sc={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();return!0===e.canReconnect&&t.uint32(8).bool(e.canReconnect),0!==e.reason&&t.uint32(16).int32(e.reason),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={canReconnect:!1,reason:0};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.canReconnect=i.bool();break;case 2:n.reason=i.int32();break;default:i.skipType(7&e)}}return n},fromJSON:e=>({canReconnect:!!zc(e.canReconnect)&&Boolean(e.canReconnect),reason:zc(e.reason)?pr(e.reason):0}),toJSON(e){const t={};return void 0!==e.canReconnect&&(t.canReconnect=e.canReconnect),void 0!==e.reason&&(t.reason=function(e){switch(e){case Ka.UNKNOWN_REASON:return"UNKNOWN_REASON";case Ka.CLIENT_INITIATED:return"CLIENT_INITIATED";case Ka.DUPLICATE_IDENTITY:return"DUPLICATE_IDENTITY";case Ka.SERVER_SHUTDOWN:return"SERVER_SHUTDOWN";case Ka.PARTICIPANT_REMOVED:return"PARTICIPANT_REMOVED";case Ka.ROOM_DELETED:return"ROOM_DELETED";case Ka.STATE_MISMATCH:return"STATE_MISMATCH";case Ka.JOIN_FAILURE:return"JOIN_FAILURE";case Ka.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.reason)),t},create:e=>Sc.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const s={canReconnect:!1,reason:0};return s.canReconnect=null!==(t=e.canReconnect)&&void 0!==t&&t,s.reason=null!==(i=e.reason)&&void 0!==i?i:0,s}};const wc={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();""!==e.trackSid&&t.uint32(10).string(e.trackSid);for(const i of e.layers)Pr.encode(i,t.uint32(18).fork()).ldelim();return t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={trackSid:"",layers:[]};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.trackSid=i.string();break;case 2:n.layers.push(Pr.decode(i,i.uint32()));break;default:i.skipType(7&e)}}return n},fromJSON:e=>({trackSid:zc(e.trackSid)?String(e.trackSid):"",layers:Array.isArray(null==e?void 0:e.layers)?e.layers.map((e=>Pr.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.trackSid&&(t.trackSid=e.trackSid),e.layers?t.layers=e.layers.map((e=>e?Pr.toJSON(e):void 0)):t.layers=[],t},create:e=>wc.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const s={trackSid:"",layers:[]};return s.trackSid=null!==(t=e.trackSid)&&void 0!==t?t:"",s.layers=(null===(i=e.layers)||void 0===i?void 0:i.map((e=>Pr.fromPartial(e))))||[],s}};const Cc={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();return""!==e.metadata&&t.uint32(10).string(e.metadata),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={metadata:""};for(;i.pos<s;){const e=i.uint32();if(e>>>3==1)n.metadata=i.string();else i.skipType(7&e)}return n},fromJSON:e=>({metadata:zc(e.metadata)?String(e.metadata):""}),toJSON(e){const t={};return void 0!==e.metadata&&(t.metadata=e.metadata),t},create:e=>Cc.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={metadata:""};return i.metadata=null!==(t=e.metadata)&&void 0!==t?t:"",i}};const kc={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();for(const i of e.urls)t.uint32(10).string(i);return""!==e.username&&t.uint32(18).string(e.username),""!==e.credential&&t.uint32(26).string(e.credential),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={urls:[],username:"",credential:""};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.urls.push(i.string());break;case 2:n.username=i.string();break;case 3:n.credential=i.string();break;default:i.skipType(7&e)}}return n},fromJSON:e=>({urls:Array.isArray(null==e?void 0:e.urls)?e.urls.map((e=>String(e))):[],username:zc(e.username)?String(e.username):"",credential:zc(e.credential)?String(e.credential):""}),toJSON(e){const t={};return e.urls?t.urls=e.urls.map((e=>e)):t.urls=[],void 0!==e.username&&(t.username=e.username),void 0!==e.credential&&(t.credential=e.credential),t},create:e=>kc.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,s;const n={urls:[],username:"",credential:""};return n.urls=(null===(t=e.urls)||void 0===t?void 0:t.map((e=>e)))||[],n.username=null!==(i=e.username)&&void 0!==i?i:"",n.credential=null!==(s=e.credential)&&void 0!==s?s:"",n}};const Ec={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();for(const i of e.speakers)_r.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={speakers:[]};for(;i.pos<s;){const e=i.uint32();if(e>>>3==1)n.speakers.push(_r.decode(i,i.uint32()));else i.skipType(7&e)}return n},fromJSON:e=>({speakers:Array.isArray(null==e?void 0:e.speakers)?e.speakers.map((e=>_r.fromJSON(e))):[]}),toJSON(e){const t={};return e.speakers?t.speakers=e.speakers.map((e=>e?_r.toJSON(e):void 0)):t.speakers=[],t},create:e=>Ec.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={speakers:[]};return i.speakers=(null===(t=e.speakers)||void 0===t?void 0:t.map((e=>_r.fromPartial(e))))||[],i}};const Tc={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();return void 0!==e.room&&Sr.encode(e.room,t.uint32(10).fork()).ldelim(),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={room:void 0};for(;i.pos<s;){const e=i.uint32();if(e>>>3==1)n.room=Sr.decode(i,i.uint32());else i.skipType(7&e)}return n},fromJSON:e=>({room:zc(e.room)?Sr.fromJSON(e.room):void 0}),toJSON(e){const t={};return void 0!==e.room&&(t.room=e.room?Sr.toJSON(e.room):void 0),t},create:e=>Tc.fromPartial(null!=e?e:{}),fromPartial(e){const t={room:void 0};return t.room=void 0!==e.room&&null!==e.room?Sr.fromPartial(e.room):void 0,t}};const Pc={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();return""!==e.participantSid&&t.uint32(10).string(e.participantSid),0!==e.quality&&t.uint32(16).int32(e.quality),0!==e.score&&t.uint32(29).float(e.score),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={participantSid:"",quality:0,score:0};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.participantSid=i.string();break;case 2:n.quality=i.int32();break;case 3:n.score=i.float();break;default:i.skipType(7&e)}}return n},fromJSON:e=>({participantSid:zc(e.participantSid)?String(e.participantSid):"",quality:zc(e.quality)?dr(e.quality):0,score:zc(e.score)?Number(e.score):0}),toJSON(e){const t={};return void 0!==e.participantSid&&(t.participantSid=e.participantSid),void 0!==e.quality&&(t.quality=function(e){switch(e){case za.POOR:return"POOR";case za.GOOD:return"GOOD";case za.EXCELLENT:return"EXCELLENT";case za.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.quality)),void 0!==e.score&&(t.score=e.score),t},create:e=>Pc.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,s;const n={participantSid:"",quality:0,score:0};return n.participantSid=null!==(t=e.participantSid)&&void 0!==t?t:"",n.quality=null!==(i=e.quality)&&void 0!==i?i:0,n.score=null!==(s=e.score)&&void 0!==s?s:0,n}};const Mc={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();for(const i of e.updates)Pc.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={updates:[]};for(;i.pos<s;){const e=i.uint32();if(e>>>3==1)n.updates.push(Pc.decode(i,i.uint32()));else i.skipType(7&e)}return n},fromJSON:e=>({updates:Array.isArray(null==e?void 0:e.updates)?e.updates.map((e=>Pc.fromJSON(e))):[]}),toJSON(e){const t={};return e.updates?t.updates=e.updates.map((e=>e?Pc.toJSON(e):void 0)):t.updates=[],t},create:e=>Mc.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={updates:[]};return i.updates=(null===(t=e.updates)||void 0===t?void 0:t.map((e=>Pc.fromPartial(e))))||[],i}};const Rc={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();return""!==e.participantSid&&t.uint32(10).string(e.participantSid),""!==e.trackSid&&t.uint32(18).string(e.trackSid),0!==e.state&&t.uint32(24).int32(e.state),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={participantSid:"",trackSid:"",state:0};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.participantSid=i.string();break;case 2:n.trackSid=i.string();break;case 3:n.state=i.int32();break;default:i.skipType(7&e)}}return n},fromJSON:e=>({participantSid:zc(e.participantSid)?String(e.participantSid):"",trackSid:zc(e.trackSid)?String(e.trackSid):"",state:zc(e.state)?nc(e.state):0}),toJSON(e){const t={};return void 0!==e.participantSid&&(t.participantSid=e.participantSid),void 0!==e.trackSid&&(t.trackSid=e.trackSid),void 0!==e.state&&(t.state=function(e){switch(e){case Yo.ACTIVE:return"ACTIVE";case Yo.PAUSED:return"PAUSED";case Yo.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.state)),t},create:e=>Rc.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,s;const n={participantSid:"",trackSid:"",state:0};return n.participantSid=null!==(t=e.participantSid)&&void 0!==t?t:"",n.trackSid=null!==(i=e.trackSid)&&void 0!==i?i:"",n.state=null!==(s=e.state)&&void 0!==s?s:0,n}};const _c={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();for(const i of e.streamStates)Rc.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={streamStates:[]};for(;i.pos<s;){const e=i.uint32();if(e>>>3==1)n.streamStates.push(Rc.decode(i,i.uint32()));else i.skipType(7&e)}return n},fromJSON:e=>({streamStates:Array.isArray(null==e?void 0:e.streamStates)?e.streamStates.map((e=>Rc.fromJSON(e))):[]}),toJSON(e){const t={};return e.streamStates?t.streamStates=e.streamStates.map((e=>e?Rc.toJSON(e):void 0)):t.streamStates=[],t},create:e=>_c.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={streamStates:[]};return i.streamStates=(null===(t=e.streamStates)||void 0===t?void 0:t.map((e=>Rc.fromPartial(e))))||[],i}};const Nc={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();return 0!==e.quality&&t.uint32(8).int32(e.quality),!0===e.enabled&&t.uint32(16).bool(e.enabled),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={quality:0,enabled:!1};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.quality=i.int32();break;case 2:n.enabled=i.bool();break;default:i.skipType(7&e)}}return n},fromJSON:e=>({quality:zc(e.quality)?cr(e.quality):0,enabled:!!zc(e.enabled)&&Boolean(e.enabled)}),toJSON(e){const t={};return void 0!==e.quality&&(t.quality=lr(e.quality)),void 0!==e.enabled&&(t.enabled=e.enabled),t},create:e=>Nc.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const s={quality:0,enabled:!1};return s.quality=null!==(t=e.quality)&&void 0!==t?t:0,s.enabled=null!==(i=e.enabled)&&void 0!==i&&i,s}};const Dc={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();""!==e.codec&&t.uint32(10).string(e.codec);for(const i of e.qualities)Nc.encode(i,t.uint32(18).fork()).ldelim();return t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={codec:"",qualities:[]};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.codec=i.string();break;case 2:n.qualities.push(Nc.decode(i,i.uint32()));break;default:i.skipType(7&e)}}return n},fromJSON:e=>({codec:zc(e.codec)?String(e.codec):"",qualities:Array.isArray(null==e?void 0:e.qualities)?e.qualities.map((e=>Nc.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.codec&&(t.codec=e.codec),e.qualities?t.qualities=e.qualities.map((e=>e?Nc.toJSON(e):void 0)):t.qualities=[],t},create:e=>Dc.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const s={codec:"",qualities:[]};return s.codec=null!==(t=e.codec)&&void 0!==t?t:"",s.qualities=(null===(i=e.qualities)||void 0===i?void 0:i.map((e=>Nc.fromPartial(e))))||[],s}};const Ic={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();""!==e.trackSid&&t.uint32(10).string(e.trackSid);for(const i of e.subscribedQualities)Nc.encode(i,t.uint32(18).fork()).ldelim();for(const i of e.subscribedCodecs)Dc.encode(i,t.uint32(26).fork()).ldelim();return t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={trackSid:"",subscribedQualities:[],subscribedCodecs:[]};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.trackSid=i.string();break;case 2:n.subscribedQualities.push(Nc.decode(i,i.uint32()));break;case 3:n.subscribedCodecs.push(Dc.decode(i,i.uint32()));break;default:i.skipType(7&e)}}return n},fromJSON:e=>({trackSid:zc(e.trackSid)?String(e.trackSid):"",subscribedQualities:Array.isArray(null==e?void 0:e.subscribedQualities)?e.subscribedQualities.map((e=>Nc.fromJSON(e))):[],subscribedCodecs:Array.isArray(null==e?void 0:e.subscribedCodecs)?e.subscribedCodecs.map((e=>Dc.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.trackSid&&(t.trackSid=e.trackSid),e.subscribedQualities?t.subscribedQualities=e.subscribedQualities.map((e=>e?Nc.toJSON(e):void 0)):t.subscribedQualities=[],e.subscribedCodecs?t.subscribedCodecs=e.subscribedCodecs.map((e=>e?Dc.toJSON(e):void 0)):t.subscribedCodecs=[],t},create:e=>Ic.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,s;const n={trackSid:"",subscribedQualities:[],subscribedCodecs:[]};return n.trackSid=null!==(t=e.trackSid)&&void 0!==t?t:"",n.subscribedQualities=(null===(i=e.subscribedQualities)||void 0===i?void 0:i.map((e=>Nc.fromPartial(e))))||[],n.subscribedCodecs=(null===(s=e.subscribedCodecs)||void 0===s?void 0:s.map((e=>Dc.fromPartial(e))))||[],n}};const Ac={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();""!==e.participantSid&&t.uint32(10).string(e.participantSid),!0===e.allTracks&&t.uint32(16).bool(e.allTracks);for(const i of e.trackSids)t.uint32(26).string(i);return""!==e.participantIdentity&&t.uint32(34).string(e.participantIdentity),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={participantSid:"",allTracks:!1,trackSids:[],participantIdentity:""};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.participantSid=i.string();break;case 2:n.allTracks=i.bool();break;case 3:n.trackSids.push(i.string());break;case 4:n.participantIdentity=i.string();break;default:i.skipType(7&e)}}return n},fromJSON:e=>({participantSid:zc(e.participantSid)?String(e.participantSid):"",allTracks:!!zc(e.allTracks)&&Boolean(e.allTracks),trackSids:Array.isArray(null==e?void 0:e.trackSids)?e.trackSids.map((e=>String(e))):[],participantIdentity:zc(e.participantIdentity)?String(e.participantIdentity):""}),toJSON(e){const t={};return void 0!==e.participantSid&&(t.participantSid=e.participantSid),void 0!==e.allTracks&&(t.allTracks=e.allTracks),e.trackSids?t.trackSids=e.trackSids.map((e=>e)):t.trackSids=[],void 0!==e.participantIdentity&&(t.participantIdentity=e.participantIdentity),t},create:e=>Ac.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,s,n;const a={participantSid:"",allTracks:!1,trackSids:[],participantIdentity:""};return a.participantSid=null!==(t=e.participantSid)&&void 0!==t?t:"",a.allTracks=null!==(i=e.allTracks)&&void 0!==i&&i,a.trackSids=(null===(s=e.trackSids)||void 0===s?void 0:s.map((e=>e)))||[],a.participantIdentity=null!==(n=e.participantIdentity)&&void 0!==n?n:"",a}};const Oc={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();!0===e.allParticipants&&t.uint32(8).bool(e.allParticipants);for(const i of e.trackPermissions)Ac.encode(i,t.uint32(18).fork()).ldelim();return t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={allParticipants:!1,trackPermissions:[]};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.allParticipants=i.bool();break;case 2:n.trackPermissions.push(Ac.decode(i,i.uint32()));break;default:i.skipType(7&e)}}return n},fromJSON:e=>({allParticipants:!!zc(e.allParticipants)&&Boolean(e.allParticipants),trackPermissions:Array.isArray(null==e?void 0:e.trackPermissions)?e.trackPermissions.map((e=>Ac.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.allParticipants&&(t.allParticipants=e.allParticipants),e.trackPermissions?t.trackPermissions=e.trackPermissions.map((e=>e?Ac.toJSON(e):void 0)):t.trackPermissions=[],t},create:e=>Oc.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const s={allParticipants:!1,trackPermissions:[]};return s.allParticipants=null!==(t=e.allParticipants)&&void 0!==t&&t,s.trackPermissions=(null===(i=e.trackPermissions)||void 0===i?void 0:i.map((e=>Ac.fromPartial(e))))||[],s}};const Uc={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();return""!==e.participantSid&&t.uint32(10).string(e.participantSid),""!==e.trackSid&&t.uint32(18).string(e.trackSid),!0===e.allowed&&t.uint32(24).bool(e.allowed),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={participantSid:"",trackSid:"",allowed:!1};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.participantSid=i.string();break;case 2:n.trackSid=i.string();break;case 3:n.allowed=i.bool();break;default:i.skipType(7&e)}}return n},fromJSON:e=>({participantSid:zc(e.participantSid)?String(e.participantSid):"",trackSid:zc(e.trackSid)?String(e.trackSid):"",allowed:!!zc(e.allowed)&&Boolean(e.allowed)}),toJSON(e){const t={};return void 0!==e.participantSid&&(t.participantSid=e.participantSid),void 0!==e.trackSid&&(t.trackSid=e.trackSid),void 0!==e.allowed&&(t.allowed=e.allowed),t},create:e=>Uc.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,s;const n={participantSid:"",trackSid:"",allowed:!1};return n.participantSid=null!==(t=e.participantSid)&&void 0!==t?t:"",n.trackSid=null!==(i=e.trackSid)&&void 0!==i?i:"",n.allowed=null!==(s=e.allowed)&&void 0!==s&&s,n}};const xc={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();void 0!==e.answer&&fc.encode(e.answer,t.uint32(10).fork()).ldelim(),void 0!==e.subscription&&bc.encode(e.subscription,t.uint32(18).fork()).ldelim();for(const i of e.publishTracks)mc.encode(i,t.uint32(26).fork()).ldelim();for(const i of e.dataChannels)Lc.encode(i,t.uint32(34).fork()).ldelim();return void 0!==e.offer&&fc.encode(e.offer,t.uint32(42).fork()).ldelim(),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={answer:void 0,subscription:void 0,publishTracks:[],dataChannels:[],offer:void 0};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.answer=fc.decode(i,i.uint32());break;case 2:n.subscription=bc.decode(i,i.uint32());break;case 3:n.publishTracks.push(mc.decode(i,i.uint32()));break;case 4:n.dataChannels.push(Lc.decode(i,i.uint32()));break;case 5:n.offer=fc.decode(i,i.uint32());break;default:i.skipType(7&e)}}return n},fromJSON:e=>({answer:zc(e.answer)?fc.fromJSON(e.answer):void 0,subscription:zc(e.subscription)?bc.fromJSON(e.subscription):void 0,publishTracks:Array.isArray(null==e?void 0:e.publishTracks)?e.publishTracks.map((e=>mc.fromJSON(e))):[],dataChannels:Array.isArray(null==e?void 0:e.dataChannels)?e.dataChannels.map((e=>Lc.fromJSON(e))):[],offer:zc(e.offer)?fc.fromJSON(e.offer):void 0}),toJSON(e){const t={};return void 0!==e.answer&&(t.answer=e.answer?fc.toJSON(e.answer):void 0),void 0!==e.subscription&&(t.subscription=e.subscription?bc.toJSON(e.subscription):void 0),e.publishTracks?t.publishTracks=e.publishTracks.map((e=>e?mc.toJSON(e):void 0)):t.publishTracks=[],e.dataChannels?t.dataChannels=e.dataChannels.map((e=>e?Lc.toJSON(e):void 0)):t.dataChannels=[],void 0!==e.offer&&(t.offer=e.offer?fc.toJSON(e.offer):void 0),t},create:e=>xc.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const s={answer:void 0,subscription:void 0,publishTracks:[],dataChannels:[],offer:void 0};return s.answer=void 0!==e.answer&&null!==e.answer?fc.fromPartial(e.answer):void 0,s.subscription=void 0!==e.subscription&&null!==e.subscription?bc.fromPartial(e.subscription):void 0,s.publishTracks=(null===(t=e.publishTracks)||void 0===t?void 0:t.map((e=>mc.fromPartial(e))))||[],s.dataChannels=(null===(i=e.dataChannels)||void 0===i?void 0:i.map((e=>Lc.fromPartial(e))))||[],s.offer=void 0!==e.offer&&null!==e.offer?fc.fromPartial(e.offer):void 0,s}};const Lc={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();return""!==e.label&&t.uint32(10).string(e.label),0!==e.id&&t.uint32(16).uint32(e.id),0!==e.target&&t.uint32(24).int32(e.target),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={label:"",id:0,target:0};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.label=i.string();break;case 2:n.id=i.uint32();break;case 3:n.target=i.int32();break;default:i.skipType(7&e)}}return n},fromJSON:e=>({label:zc(e.label)?String(e.label):"",id:zc(e.id)?Number(e.id):0,target:zc(e.target)?ic(e.target):0}),toJSON(e){const t={};return void 0!==e.label&&(t.label=e.label),void 0!==e.id&&(t.id=Math.round(e.id)),void 0!==e.target&&(t.target=sc(e.target)),t},create:e=>Lc.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,s;const n={label:"",id:0,target:0};return n.label=null!==(t=e.label)&&void 0!==t?t:"",n.id=null!==(i=e.id)&&void 0!==i?i:0,n.target=null!==(s=e.target)&&void 0!==s?s:0,n}};const Fc={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();var i;switch(null===(i=e.scenario)||void 0===i?void 0:i.$case){case"speakerUpdate":t.uint32(8).int32(e.scenario.speakerUpdate);break;case"nodeFailure":t.uint32(16).bool(e.scenario.nodeFailure);break;case"migration":t.uint32(24).bool(e.scenario.migration);break;case"serverLeave":t.uint32(32).bool(e.scenario.serverLeave);break;case"switchCandidateProtocol":t.uint32(40).int32(e.scenario.switchCandidateProtocol)}return t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={scenario:void 0};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.scenario={$case:"speakerUpdate",speakerUpdate:i.int32()};break;case 2:n.scenario={$case:"nodeFailure",nodeFailure:i.bool()};break;case 3:n.scenario={$case:"migration",migration:i.bool()};break;case 4:n.scenario={$case:"serverLeave",serverLeave:i.bool()};break;case 5:n.scenario={$case:"switchCandidateProtocol",switchCandidateProtocol:i.int32()};break;default:i.skipType(7&e)}}return n},fromJSON:e=>({scenario:zc(e.speakerUpdate)?{$case:"speakerUpdate",speakerUpdate:Number(e.speakerUpdate)}:zc(e.nodeFailure)?{$case:"nodeFailure",nodeFailure:Boolean(e.nodeFailure)}:zc(e.migration)?{$case:"migration",migration:Boolean(e.migration)}:zc(e.serverLeave)?{$case:"serverLeave",serverLeave:Boolean(e.serverLeave)}:zc(e.switchCandidateProtocol)?{$case:"switchCandidateProtocol",switchCandidateProtocol:ac(e.switchCandidateProtocol)}:void 0}),toJSON(e){var t,i,s,n,a,r,o,c,l,d,h;const u={};return"speakerUpdate"===(null===(t=e.scenario)||void 0===t?void 0:t.$case)&&(u.speakerUpdate=Math.round(null===(i=e.scenario)||void 0===i?void 0:i.speakerUpdate)),"nodeFailure"===(null===(s=e.scenario)||void 0===s?void 0:s.$case)&&(u.nodeFailure=null===(n=e.scenario)||void 0===n?void 0:n.nodeFailure),"migration"===(null===(a=e.scenario)||void 0===a?void 0:a.$case)&&(u.migration=null===(r=e.scenario)||void 0===r?void 0:r.migration),"serverLeave"===(null===(o=e.scenario)||void 0===o?void 0:o.$case)&&(u.serverLeave=null===(c=e.scenario)||void 0===c?void 0:c.serverLeave),"switchCandidateProtocol"===(null===(l=e.scenario)||void 0===l?void 0:l.$case)&&(u.switchCandidateProtocol=void 0!==(null===(d=e.scenario)||void 0===d?void 0:d.switchCandidateProtocol)?function(e){switch(e){case ec.UDP:return"UDP";case ec.TCP:return"TCP";case ec.TLS:return"TLS";case ec.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(null===(h=e.scenario)||void 0===h?void 0:h.switchCandidateProtocol):void 0),u},create:e=>Fc.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,s,n,a,r,o,c,l,d,h,u,p,m,g;const f={scenario:void 0};return"speakerUpdate"===(null===(t=e.scenario)||void 0===t?void 0:t.$case)&&void 0!==(null===(i=e.scenario)||void 0===i?void 0:i.speakerUpdate)&&null!==(null===(s=e.scenario)||void 0===s?void 0:s.speakerUpdate)&&(f.scenario={$case:"speakerUpdate",speakerUpdate:e.scenario.speakerUpdate}),"nodeFailure"===(null===(n=e.scenario)||void 0===n?void 0:n.$case)&&void 0!==(null===(a=e.scenario)||void 0===a?void 0:a.nodeFailure)&&null!==(null===(r=e.scenario)||void 0===r?void 0:r.nodeFailure)&&(f.scenario={$case:"nodeFailure",nodeFailure:e.scenario.nodeFailure}),"migration"===(null===(o=e.scenario)||void 0===o?void 0:o.$case)&&void 0!==(null===(c=e.scenario)||void 0===c?void 0:c.migration)&&null!==(null===(l=e.scenario)||void 0===l?void 0:l.migration)&&(f.scenario={$case:"migration",migration:e.scenario.migration}),"serverLeave"===(null===(d=e.scenario)||void 0===d?void 0:d.$case)&&void 0!==(null===(h=e.scenario)||void 0===h?void 0:h.serverLeave)&&null!==(null===(u=e.scenario)||void 0===u?void 0:u.serverLeave)&&(f.scenario={$case:"serverLeave",serverLeave:e.scenario.serverLeave}),"switchCandidateProtocol"===(null===(p=e.scenario)||void 0===p?void 0:p.$case)&&void 0!==(null===(m=e.scenario)||void 0===m?void 0:m.switchCandidateProtocol)&&null!==(null===(g=e.scenario)||void 0===g?void 0:g.switchCandidateProtocol)&&(f.scenario={$case:"switchCandidateProtocol",switchCandidateProtocol:e.scenario.switchCandidateProtocol}),f}};const Bc={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();return 0!==e.timestamp&&t.uint32(8).int64(e.timestamp),0!==e.rtt&&t.uint32(16).int64(e.rtt),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={timestamp:0,rtt:0};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.timestamp=Gc(i.int64());break;case 2:n.rtt=Gc(i.int64());break;default:i.skipType(7&e)}}return n},fromJSON:e=>({timestamp:zc(e.timestamp)?Number(e.timestamp):0,rtt:zc(e.rtt)?Number(e.rtt):0}),toJSON(e){const t={};return void 0!==e.timestamp&&(t.timestamp=Math.round(e.timestamp)),void 0!==e.rtt&&(t.rtt=Math.round(e.rtt)),t},create:e=>Bc.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const s={timestamp:0,rtt:0};return s.timestamp=null!==(t=e.timestamp)&&void 0!==t?t:0,s.rtt=null!==(i=e.rtt)&&void 0!==i?i:0,s}};const qc={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sr.Writer.create();return 0!==e.lastPingTimestamp&&t.uint32(8).int64(e.lastPingTimestamp),0!==e.timestamp&&t.uint32(16).int64(e.timestamp),t},decode(e,t){const i=e instanceof sr.Reader?e:new sr.Reader(e);let s=void 0===t?i.len:i.pos+t;const n={lastPingTimestamp:0,timestamp:0};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:n.lastPingTimestamp=Gc(i.int64());break;case 2:n.timestamp=Gc(i.int64());break;default:i.skipType(7&e)}}return n},fromJSON:e=>({lastPingTimestamp:zc(e.lastPingTimestamp)?Number(e.lastPingTimestamp):0,timestamp:zc(e.timestamp)?Number(e.timestamp):0}),toJSON(e){const t={};return void 0!==e.lastPingTimestamp&&(t.lastPingTimestamp=Math.round(e.lastPingTimestamp)),void 0!==e.timestamp&&(t.timestamp=Math.round(e.timestamp)),t},create:e=>qc.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const s={lastPingTimestamp:0,timestamp:0};return s.lastPingTimestamp=null!==(t=e.lastPingTimestamp)&&void 0!==t?t:0,s.timestamp=null!==(i=e.timestamp)&&void 0!==i?i:0,s}};var jc,Vc,$c,Wc,Jc,Hc=(()=>{if("undefined"!=typeof globalThis)return globalThis;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw"Unable to locate global object"})();function Gc(e){if(e.gt(Number.MAX_SAFE_INTEGER))throw new Hc.Error("Value is larger than Number.MAX_SAFE_INTEGER");return e.toNumber()}function zc(e){return null!=e}sr.util.Long!==hn&&(sr.util.Long=hn,sr.configure());class Zc extends Error{constructor(e,t){super(t||"an error has occured"),this.code=e}}class Kc extends Zc{constructor(e,t,i){super(1,e),this.status=i,this.reason=t}}class Qc extends Zc{constructor(e){super(21,null!=e?e:"device is unsupported")}}class Xc extends Zc{constructor(e){super(20,null!=e?e:"track is invalid")}}class Yc extends Zc{constructor(e){super(10,null!=e?e:"unsupported server")}}class el extends Zc{constructor(e){super(12,null!=e?e:"unexpected connection state")}}class tl extends Zc{constructor(e){super(13,null!=e?e:"unable to negotiate")}}!function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"}(jc||(jc={})),function(e){e.getFailure=function(t){if(t&&"name"in t)return"NotFoundError"===t.name||"DevicesNotFoundError"===t.name?e.NotFound:"NotAllowedError"===t.name||"PermissionDeniedError"===t.name?e.PermissionDenied:"NotReadableError"===t.name||"TrackStartError"===t.name?e.DeviceInUse:e.Other}}(jc||(jc={})),function(e){e.Connected="connected",e.Reconnecting="reconnecting",e.Reconnected="reconnected",e.Disconnected="disconnected",e.ConnectionStateChanged="connectionStateChanged",e.StateChanged="connectionStateChanged",e.MediaDevicesChanged="mediaDevicesChanged",e.ParticipantConnected="participantConnected",e.ParticipantDisconnected="participantDisconnected",e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalAudioSilenceDetected="localAudioSilenceDetected",e.ActiveSpeakersChanged="activeSpeakersChanged",e.ParticipantMetadataChanged="participantMetadataChanged",e.RoomMetadataChanged="roomMetadataChanged",e.DataReceived="dataReceived",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.AudioPlaybackStatusChanged="audioPlaybackChanged",e.MediaDevicesError="mediaDevicesError",e.ParticipantPermissionsChanged="participantPermissionsChanged",e.SignalConnected="signalConnected",e.RecordingStatusChanged="recordingStatusChanged"}(Vc||(Vc={})),function(e){e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.ParticipantMetadataChanged="participantMetadataChanged",e.DataReceived="dataReceived",e.IsSpeakingChanged="isSpeakingChanged",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.MediaDevicesError="mediaDevicesError",e.ParticipantPermissionsChanged="participantPermissionsChanged"}($c||($c={})),function(e){e.TransportsCreated="transportsCreated",e.Connected="connected",e.Disconnected="disconnected",e.Resuming="resuming",e.Resumed="resumed",e.Restarting="restarting",e.Restarted="restarted",e.SignalResumed="signalResumed",e.Closing="closing",e.MediaTrackAdded="mediaTrackAdded",e.ActiveSpeakersUpdate="activeSpeakersUpdate",e.DataPacketReceived="dataPacketReceived"}(Wc||(Wc={})),function(e){e.Message="message",e.Muted="muted",e.Unmuted="unmuted",e.Restarted="restarted",e.Ended="ended",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed",e.UpdateSettings="updateSettings",e.UpdateSubscription="updateSubscription",e.AudioPlaybackStarted="audioPlaybackStarted",e.AudioPlaybackFailed="audioPlaybackFailed",e.AudioSilenceDetected="audioSilenceDetected",e.VisibilityChanged="visibilityChanged",e.VideoDimensionsChanged="videoDimensionsChanged",e.ElementAttached="elementAttached",e.ElementDetached="elementDetached",e.UpstreamPaused="upstreamPaused",e.UpstreamResumed="upstreamResumed",e.SubscriptionPermissionChanged="subscriptionPermissionChanged",e.SubscriptionStatusChanged="subscriptionStatusChanged"}(Jc||(Jc={}));const il=2e3;function sl(e,t){if(!t)return 0;let i,s;return"bytesReceived"in e?(i=e.bytesReceived,s=t.bytesReceived):"bytesSent"in e&&(i=e.bytesSent,s=t.bytesSent),void 0===i||void 0===s||void 0===e.timestamp||void 0===t.timestamp?0:8*(i-s)*1e3/(e.timestamp-t.timestamp)}var nl={};!function(e,t){!function(i,s){var n="function",a="undefined",r="object",o="string",c="model",l="name",d="type",h="vendor",u="version",p="architecture",m="console",g="mobile",f="tablet",v="smarttv",b="wearable",y="embedded",S="Amazon",w="Apple",C="ASUS",k="BlackBerry",E="Browser",T="Chrome",P="Firefox",M="Google",R="Huawei",_="LG",N="Microsoft",D="Motorola",I="Opera",A="Samsung",O="Sharp",U="Sony",x="Xiaomi",L="Zebra",F="Facebook",B=function(e){for(var t={},i=0;i<e.length;i++)t[e[i].toUpperCase()]=e[i];return t},q=function(e,t){return typeof e===o&&-1!==j(t).indexOf(j(e))},j=function(e){return e.toLowerCase()},V=function(e,t){if(typeof e===o)return e=e.replace(/^\s\s*/,""),typeof t===a?e:e.substring(0,350)},$=function(e,t){for(var i,a,o,c,l,d,h=0;h<t.length&&!l;){var u=t[h],p=t[h+1];for(i=a=0;i<u.length&&!l;)if(l=u[i++].exec(e))for(o=0;o<p.length;o++)d=l[++a],typeof(c=p[o])===r&&c.length>0?2===c.length?typeof c[1]==n?this[c[0]]=c[1].call(this,d):this[c[0]]=c[1]:3===c.length?typeof c[1]!==n||c[1].exec&&c[1].test?this[c[0]]=d?d.replace(c[1],c[2]):s:this[c[0]]=d?c[1].call(this,d,c[2]):s:4===c.length&&(this[c[0]]=d?c[3].call(this,d.replace(c[1],c[2])):s):this[c]=d||s;h+=2}},W=function(e,t){for(var i in t)if(typeof t[i]===r&&t[i].length>0){for(var n=0;n<t[i].length;n++)if(q(t[i][n],e))return"?"===i?s:i}else if(q(t[i],e))return"?"===i?s:i;return e},J={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},H={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[u,[l,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[u,[l,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[l,u],[/opios[\/ ]+([\w\.]+)/i],[u,[l,I+" Mini"]],[/\bopr\/([\w\.]+)/i],[u,[l,I]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/ ]?([\w\.]*)/i,/(avant |iemobile|slim)(?:browser)?[\/ ]?([\w\.]*)/i,/(ba?idubrowser)[\/ ]?([\w\.]+)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale|qqbrowserlite|qq|duckduckgo)\/([-\w\.]+)/i,/(weibo)__([\d\.]+)/i],[l,u],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[u,[l,"UC"+E]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i],[u,[l,"WeChat(Win) Desktop"]],[/micromessenger\/([\w\.]+)/i],[u,[l,"WeChat"]],[/konqueror\/([\w\.]+)/i],[u,[l,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[u,[l,"IE"]],[/yabrowser\/([\w\.]+)/i],[u,[l,"Yandex"]],[/(avast|avg)\/([\w\.]+)/i],[[l,/(.+)/,"$1 Secure "+E],u],[/\bfocus\/([\w\.]+)/i],[u,[l,P+" Focus"]],[/\bopt\/([\w\.]+)/i],[u,[l,I+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[u,[l,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[u,[l,"Dolphin"]],[/coast\/([\w\.]+)/i],[u,[l,I+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[u,[l,"MIUI "+E]],[/fxios\/([-\w\.]+)/i],[u,[l,P]],[/\bqihu|(qi?ho?o?|360)browser/i],[[l,"360 "+E]],[/(oculus|samsung|sailfish|huawei)browser\/([\w\.]+)/i],[[l,/(.+)/,"$1 "+E],u],[/(comodo_dragon)\/([\w\.]+)/i],[[l,/_/g," "],u],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|baiduboxapp|2345Explorer)[\/ ]?([\w\.]+)/i],[l,u],[/(metasr)[\/ ]?([\w\.]+)/i,/(lbbrowser)/i,/\[(linkedin)app\]/i],[l],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[l,F],u],[/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(chromium|instagram)[\/ ]([-\w\.]+)/i],[l,u],[/\bgsa\/([\w\.]+) .*safari\//i],[u,[l,"GSA"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[u,[l,T+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[l,T+" WebView"],u],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[u,[l,"Android "+E]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[l,u],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[u,[l,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[u,l],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[l,[u,W,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[l,u],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[l,"Netscape"],u],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[u,[l,P+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i],[l,u],[/(cobalt)\/([\w\.]+)/i],[l,[u,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[p,"amd64"]],[/(ia32(?=;))/i],[[p,j]],[/((?:i[346]|x)86)[;\)]/i],[[p,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[p,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[p,"armhf"]],[/windows (ce|mobile); ppc;/i],[[p,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[p,/ower/,"",j]],[/(sun4\w)[;\)]/i],[[p,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[p,j]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[c,[h,A],[d,f]],[/\b((?:s[cgp]h|gt|sm)-\w+|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],[c,[h,A],[d,g]],[/\((ip(?:hone|od)[\w ]*);/i],[c,[h,w],[d,g]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[c,[h,w],[d,f]],[/(macintosh);/i],[c,[h,w]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[c,[h,R],[d,f]],[/(?:huawei|honor)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[c,[h,R],[d,g]],[/\b(poco[\w ]+)(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],[[c,/_/g," "],[h,x],[d,g]],[/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[c,/_/g," "],[h,x],[d,f]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[c,[h,"OPPO"],[d,g]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[c,[h,"Vivo"],[d,g]],[/\b(rmx[12]\d{3})(?: bui|;|\))/i],[c,[h,"Realme"],[d,g]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[c,[h,D],[d,g]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[c,[h,D],[d,f]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[c,[h,_],[d,f]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[c,[h,_],[d,g]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[c,[h,"Lenovo"],[d,f]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[c,/_/g," "],[h,"Nokia"],[d,g]],[/(pixel c)\b/i],[c,[h,M],[d,f]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[c,[h,M],[d,g]],[/droid.+ (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[c,[h,U],[d,g]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[c,"Xperia Tablet"],[h,U],[d,f]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[c,[h,"OnePlus"],[d,g]],[/(alexa)webm/i,/(kf[a-z]{2}wi)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[c,[h,S],[d,f]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[c,/(.+)/g,"Fire Phone $1"],[h,S],[d,g]],[/(playbook);[-\w\),; ]+(rim)/i],[c,h,[d,f]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[c,[h,k],[d,g]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[c,[h,C],[d,f]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[c,[h,C],[d,g]],[/(nexus 9)/i],[c,[h,"HTC"],[d,f]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic|sony(?!-bra))[-_ ]?([-\w]*)/i],[h,[c,/_/g," "],[d,g]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[c,[h,"Acer"],[d,f]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[c,[h,"Meizu"],[d,g]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[c,[h,O],[d,g]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[-_ ]?([-\w]*)/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[h,c,[d,g]],[/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[h,c,[d,f]],[/(surface duo)/i],[c,[h,N],[d,f]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[c,[h,"Fairphone"],[d,g]],[/(u304aa)/i],[c,[h,"AT&T"],[d,g]],[/\bsie-(\w*)/i],[c,[h,"Siemens"],[d,g]],[/\b(rct\w+) b/i],[c,[h,"RCA"],[d,f]],[/\b(venue[\d ]{2,7}) b/i],[c,[h,"Dell"],[d,f]],[/\b(q(?:mv|ta)\w+) b/i],[c,[h,"Verizon"],[d,f]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[c,[h,"Barnes & Noble"],[d,f]],[/\b(tm\d{3}\w+) b/i],[c,[h,"NuVision"],[d,f]],[/\b(k88) b/i],[c,[h,"ZTE"],[d,f]],[/\b(nx\d{3}j) b/i],[c,[h,"ZTE"],[d,g]],[/\b(gen\d{3}) b.+49h/i],[c,[h,"Swiss"],[d,g]],[/\b(zur\d{3}) b/i],[c,[h,"Swiss"],[d,f]],[/\b((zeki)?tb.*\b) b/i],[c,[h,"Zeki"],[d,f]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[h,"Dragon Touch"],c,[d,f]],[/\b(ns-?\w{0,9}) b/i],[c,[h,"Insignia"],[d,f]],[/\b((nxa|next)-?\w{0,9}) b/i],[c,[h,"NextBook"],[d,f]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[h,"Voice"],c,[d,g]],[/\b(lvtel\-)?(v1[12]) b/i],[[h,"LvTel"],c,[d,g]],[/\b(ph-1) /i],[c,[h,"Essential"],[d,g]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[c,[h,"Envizen"],[d,f]],[/\b(trio[-\w\. ]+) b/i],[c,[h,"MachSpeed"],[d,f]],[/\btu_(1491) b/i],[c,[h,"Rotor"],[d,f]],[/(shield[\w ]+) b/i],[c,[h,"Nvidia"],[d,f]],[/(sprint) (\w+)/i],[h,c,[d,g]],[/(kin\.[onetw]{3})/i],[[c,/\./g," "],[h,N],[d,g]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[c,[h,L],[d,f]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[c,[h,L],[d,g]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[h,c,[d,m]],[/droid.+; (shield) bui/i],[c,[h,"Nvidia"],[d,m]],[/(playstation [345portablevi]+)/i],[c,[h,U],[d,m]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[c,[h,N],[d,m]],[/smart-tv.+(samsung)/i],[h,[d,v]],[/hbbtv.+maple;(\d+)/i],[[c,/^/,"SmartTV"],[h,A],[d,v]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[h,_],[d,v]],[/(apple) ?tv/i],[h,[c,w+" TV"],[d,v]],[/crkey/i],[[c,T+"cast"],[h,M],[d,v]],[/droid.+aft(\w)( bui|\))/i],[c,[h,S],[d,v]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[c,[h,O],[d,v]],[/(bravia[\w ]+)( bui|\))/i],[c,[h,U],[d,v]],[/(mitv-\w{5}) bui/i],[c,[h,x],[d,v]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w ]*; *(\w[^;]*);([^;]*)/i],[[h,V],[c,V],[d,v]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[d,v]],[/((pebble))app/i],[h,c,[d,b]],[/droid.+; (glass) \d/i],[c,[h,M],[d,b]],[/droid.+; (wt63?0{2,3})\)/i],[c,[h,L],[d,b]],[/(quest( 2)?)/i],[c,[h,F],[d,b]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[h,[d,y]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+? mobile safari/i],[c,[d,g]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[c,[d,f]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[d,f]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[d,g]],[/(android[-\w\. ]{0,9});.+buil/i],[c,[h,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[u,[l,"EdgeHTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[u,[l,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i],[l,u],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[u,l]],os:[[/microsoft (windows) (vista|xp)/i],[l,u],[/(windows) nt 6\.2; (arm)/i,/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i,/(windows)[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i],[l,[u,W,J]],[/(win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[l,"Windows"],[u,W,J]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/cfnetwork\/.+darwin/i],[[u,/_/g,"."],[l,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[l,"Mac OS"],[u,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[u,l],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[l,u],[/\(bb(10);/i],[u,[l,k]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[u,[l,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[u,[l,P+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[u,[l,"webOS"]],[/crkey\/([\d\.]+)/i],[u,[l,T+"cast"]],[/(cros) [\w]+ ([\w\.]+\w)/i],[[l,"Chromium OS"],u],[/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[l,u],[/(sunos) ?([\w\.\d]*)/i],[[l,"Solaris"],u],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux)/i,/(unix) ?([\w\.]*)/i],[l,u]]},G=function(e,t){if(typeof e===r&&(t=e,e=s),!(this instanceof G))return new G(e,t).getResult();var n=e||(typeof i!==a&&i.navigator&&i.navigator.userAgent?i.navigator.userAgent:""),m=t?function(e,t){var i={};for(var s in e)t[s]&&t[s].length%2==0?i[s]=t[s].concat(e[s]):i[s]=e[s];return i}(H,t):H;return this.getBrowser=function(){var e={};return e[l]=s,e[u]=s,$.call(e,n,m.browser),e.major=function(e){return typeof e===o?e.replace(/[^\d\.]/g,"").split(".")[0]:s}(e.version),e},this.getCPU=function(){var e={};return e[p]=s,$.call(e,n,m.cpu),e},this.getDevice=function(){var e={};return e[h]=s,e[c]=s,e[d]=s,$.call(e,n,m.device),e},this.getEngine=function(){var e={};return e[l]=s,e[u]=s,$.call(e,n,m.engine),e},this.getOS=function(){var e={};return e[l]=s,e[u]=s,$.call(e,n,m.os),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return n},this.setUA=function(e){return n=typeof e===o&&e.length>350?V(e,350):e,this},this.setUA(n),this};G.VERSION="1.0.33",G.BROWSER=B([l,u,"major"]),G.CPU=B([p]),G.DEVICE=B([c,h,d,m,g,v,f,b,y]),G.ENGINE=G.OS=B([l,u]),e.exports&&(t=e.exports=G),t.UAParser=G;var z=typeof i!==a&&(i.jQuery||i.Zepto);if(z&&!z.ua){var Z=new G;z.ua=Z.getResult(),z.ua.get=function(){return Z.getUA()},z.ua.set=function(e){Z.setUA(e);var t=Z.getResult();for(var i in t)z.ua[i]=t[i]}}}("object"==typeof window?window:nn)}({get exports(){return nl},set exports(e){nl=e}},nl);var al=nl;const rl="1.7.1",ol=9;function cl(e,t,i){const s=Gr({},e);return!0===s.audio&&(s.audio={}),!0===s.video&&(s.video={}),s.audio&&ll(s.audio,t),s.video&&ll(s.video,i),s}function ll(e,t){return Object.keys(t).forEach((i=>{void 0===e[i]&&(e[i]=t[i])})),e}function dl(e){const t={};if(e.video)if("object"==typeof e.video){const i={},s=i,n=e.video;Object.keys(n).forEach((e=>{if("resolution"===e)ll(s,n.resolution);else s[e]=n[e]})),t.video=i}else t.video=e.video;else t.video=!1;return e.audio?"object"==typeof e.audio?t.audio=e.audio:t.audio=!0:t.audio=!1,t}function hl(){const e="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(e)return new e({latencyHint:"interactive"})}const ul="|";async function pl(e){return new Promise((t=>setTimeout(t,e)))}function ml(){return"addTransceiver"in RTCPeerConnection.prototype}function gl(){return"addTrack"in RTCPeerConnection.prototype}function fl(e){return!!document&&(e||(e=document.createElement("audio")),"setSinkId"in e)}const vl={Chrome:"100",Chromium:"100",Safari:"15",Firefox:"100",Edge:"100",Brave:"1.40"};function bl(e){if(!Cl())return!1;if(!("setCodecPreferences"in e))return!1;const t=al();if(!t.browser.name||!t.browser.version)return!1;const i=vl[t.browser.name];return!!i&&function(e,t){const i=e.split("."),s=t.split("."),n=Math.min(e.length,t.length);for(let e=0;e<n;++e){const t=parseInt(i[e],10),n=parseInt(s[e],10);if(t>n)return 1;if(t<n)return-1}return i.length==s.length?0:i.length<s.length?-1:1}(t.browser.version,i)>=0}function yl(){return!!Cl()&&-1!==navigator.userAgent.indexOf("Firefox")}function Sl(){return!!Cl()&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function wl(){return!!Cl()&&/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent)}function Cl(){return"undefined"!=typeof document}function kl(){return"ReactNative"==navigator.product}function El(e){for(const t of e)t.target.handleResize(t)}function Tl(e){for(const t of e)t.target.handleVisibilityChanged(t)}let Pl=null;const Ml=()=>(Pl||(Pl=new ResizeObserver(El)),Pl);let Rl=null;const _l=()=>(Rl||(Rl=new IntersectionObserver(Tl,{root:document,rootMargin:"0px"})),Rl);function Nl(){var e;const t=Or.fromPartial({sdk:ir.JS,protocol:ol,version:rl});return kl()&&(t.os=null!==(e=function(){if(kl())return global&&global.LiveKitReactNativeGlobal?global.LiveKitReactNativeGlobal.platform:void 0}())&&void 0!==e?e:""),t}let Dl,Il;function Al(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],s=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const n=document.createElement("canvas");n.width=e,n.height=t;const a=n.getContext("2d");null==a||a.fillRect(0,0,n.width,n.height),s&&a&&(a.beginPath(),a.arc(e/2,t/2,50,0,2*Math.PI,!0),a.closePath(),a.fillStyle="grey",a.fill());const r=n.captureStream(),[o]=r.getTracks();if(!o)throw Error("Could not get empty media stream video track");return o.enabled=i,o}function Ol(){if(!Il){const e=new AudioContext,t=e.createOscillator(),i=e.createMediaStreamDestination();if(t.connect(i),t.start(),[Il]=i.stream.getAudioTracks(),!Il)throw Error("Could not get empty media stream audio track");Il.enabled=!1}return Il}class Ul{constructor(e,t){this.onFinally=t,this.promise=new Promise((async(t,i)=>{this.resolve=t,this.reject=i,e&&await e(t,i)})).finally((()=>{var e;return null===(e=this.onFinally)||void 0===e?void 0:e.call(this)}))}}class xl{constructor(){this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;const t=new Promise((t=>e=()=>{this._locks-=1,t()})),i=this._locking.then((()=>e));return this._locking=this._locking.then((()=>t)),i}}class Ll{constructor(e,t){this.maxConcurrent=e||1,this.minCycle=t||0,this.queueRunning=[],this.queueWaiting={},this.lastRun=0}dequeue(e){const t=this.queueRunning,i=t.findIndex((t=>t.hash===e));if(-1==i)throw"queue desync";const s=t[i];return t.splice(i,1),s}getFirstWaiting(){for(let e of Object.keys(this.queueWaiting).sort(((e,t)=>e-t)))if(void 0!==this.queueWaiting[e]&&this.queueWaiting[e].length>0)return this.queueWaiting[e]}end(e){this.dequeue(e).resolve();const t=this.getFirstWaiting();if(void 0!==t){t.shift().resolve()}}async wait(e,t){const i=void 0===t?0:t;let s={hash:e,priority:i};for(null==this.queueWaiting[i]&&(this.queueWaiting[i]=[]),this.queueRunning.length>=this.maxConcurrent&&(s.promise=new Promise((e=>{s.resolve=e})),this.queueWaiting[i].push(s),await s.promise),this.queueRunning.push(s),s.promise=new Promise((e=>{s.resolve=e}));Date.now()-this.lastRun<this.minCycle;)await new Promise((e=>setTimeout(e,this.minCycle-Date.now()+this.lastRun)));this.lastRun=Date.now()}run(e,t){const i=void 0===t?0:t,s=Symbol();return this.wait(s,i).then((()=>e())).finally((()=>{this.end(s)}))}stat(){return{running:this.queueRunning.length,waiting:Object.keys(this.queueWaiting).reduce(((e,t)=>e+this.queueWaiting[t].length),0),last:this.lastRun}}async flush(){for(;this.stat().waiting>0;)for(let e of Object.keys(this.queueWaiting).sort(((e,t)=>t-e))){const t=this.queueWaiting[e];void 0!==t&&t.length>0&&await t[t.length-1].promise}for(;this.queueRunning.length>0;)await Promise.allSettled(this.queueRunning.map((e=>e.promise)))}}const Fl="default";class Bl{static getInstance(){return void 0===this.instance&&(this.instance=new Bl),this.instance}async getDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];var i;if((null===(i=Bl.userMediaPromiseMap)||void 0===i?void 0:i.size)>0){ln.debug("awaiting getUserMedia promise");try{e?await Bl.userMediaPromiseMap.get(e):await Promise.all(Bl.userMediaPromiseMap.values())}catch(e){ln.warn("error waiting for media permissons")}}let s=await navigator.mediaDevices.enumerateDevices();if(t&&e&&(!Bl.userMediaPromiseMap.get(e)||!Sl())){if(0===s.length||s.some((t=>{const i=""===t.label,s=!e||t.kind===e;return i&&s}))){const t={video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e},i=await navigator.mediaDevices.getUserMedia(t);s=await navigator.mediaDevices.enumerateDevices(),i.getTracks().forEach((e=>{e.stop()}))}}return e&&(s=s.filter((t=>t.kind===e))),s}async normalizeDeviceId(e,t,i){if(t!==Fl)return t;const s=(await this.getDevices(e)).find((e=>e.groupId===i&&e.deviceId!==Fl));return null==s?void 0:s.deviceId}}Bl.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],Bl.userMediaPromiseMap=new Map;var ql,jl={},Vl={get exports(){return jl},set exports(e){jl=e}},$l="object"==typeof Reflect?Reflect:null,Wl=$l&&"function"==typeof $l.apply?$l.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};ql=$l&&"function"==typeof $l.ownKeys?$l.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var Jl=Number.isNaN||function(e){return e!=e};function Hl(){Hl.init.call(this)}Vl.exports=Hl,jl.once=function(e,t){return new Promise((function(i,s){function n(i){e.removeListener(t,a),s(i)}function a(){"function"==typeof e.removeListener&&e.removeListener("error",n),i([].slice.call(arguments))}id(e,t,a,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&id(e,"error",t,i)}(e,n,{once:!0})}))},Hl.EventEmitter=Hl,Hl.prototype._events=void 0,Hl.prototype._eventsCount=0,Hl.prototype._maxListeners=void 0;var Gl=10;function zl(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function Zl(e){return void 0===e._maxListeners?Hl.defaultMaxListeners:e._maxListeners}function Kl(e,t,i,s){var n,a,r,o;if(zl(i),void 0===(a=e._events)?(a=e._events=Object.create(null),e._eventsCount=0):(void 0!==a.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),a=e._events),r=a[t]),void 0===r)r=a[t]=i,++e._eventsCount;else if("function"==typeof r?r=a[t]=s?[i,r]:[r,i]:s?r.unshift(i):r.push(i),(n=Zl(e))>0&&r.length>n&&!r.warned){r.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+r.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=r.length,o=c,console&&console.warn&&console.warn(o)}return e}function Ql(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Xl(e,t,i){var s={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},n=Ql.bind(s);return n.listener=i,s.wrapFn=n,n}function Yl(e,t,i){var s=e._events;if(void 0===s)return[];var n=s[t];return void 0===n?[]:"function"==typeof n?i?[n.listener||n]:[n]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(n):td(n,n.length)}function ed(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function td(e,t){for(var i=new Array(t),s=0;s<t;++s)i[s]=e[s];return i}function id(e,t,i,s){if("function"==typeof e.on)s.once?e.once(t,i):e.on(t,i);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function n(a){s.once&&e.removeEventListener(t,n),i(a)}))}}Object.defineProperty(Hl,"defaultMaxListeners",{enumerable:!0,get:function(){return Gl},set:function(e){if("number"!=typeof e||e<0||Jl(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");Gl=e}}),Hl.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Hl.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||Jl(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},Hl.prototype.getMaxListeners=function(){return Zl(this)},Hl.prototype.emit=function(e){for(var t=[],i=1;i<arguments.length;i++)t.push(arguments[i]);var s="error"===e,n=this._events;if(void 0!==n)s=s&&void 0===n.error;else if(!s)return!1;if(s){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var r=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw r.context=a,r}var o=n[e];if(void 0===o)return!1;if("function"==typeof o)Wl(o,this,t);else{var c=o.length,l=td(o,c);for(i=0;i<c;++i)Wl(l[i],this,t)}return!0},Hl.prototype.addListener=function(e,t){return Kl(this,e,t,!1)},Hl.prototype.on=Hl.prototype.addListener,Hl.prototype.prependListener=function(e,t){return Kl(this,e,t,!0)},Hl.prototype.once=function(e,t){return zl(t),this.on(e,Xl(this,e,t)),this},Hl.prototype.prependOnceListener=function(e,t){return zl(t),this.prependListener(e,Xl(this,e,t)),this},Hl.prototype.removeListener=function(e,t){var i,s,n,a,r;if(zl(t),void 0===(s=this._events))return this;if(void 0===(i=s[e]))return this;if(i===t||i.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete s[e],s.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(n=-1,a=i.length-1;a>=0;a--)if(i[a]===t||i[a].listener===t){r=i[a].listener,n=a;break}if(n<0)return this;0===n?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,n),1===i.length&&(s[e]=i[0]),void 0!==s.removeListener&&this.emit("removeListener",e,r||t)}return this},Hl.prototype.off=Hl.prototype.removeListener,Hl.prototype.removeAllListeners=function(e){var t,i,s;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var n,a=Object.keys(i);for(s=0;s<a.length;++s)"removeListener"!==(n=a[s])&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(s=t.length-1;s>=0;s--)this.removeListener(e,t[s]);return this},Hl.prototype.listeners=function(e){return Yl(this,e,!0)},Hl.prototype.rawListeners=function(e){return Yl(this,e,!1)},Hl.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):ed.call(e,t)},Hl.prototype.listenerCount=ed,Hl.prototype.eventNames=function(){return this._eventsCount>0?ql(this._events):[]};const sd=[];class nd extends jl.EventEmitter{constructor(e,t){super(),this.attachedElements=[],this.isMuted=!1,this.streamState=nd.StreamState.Active,this._currentBitrate=0,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=nd.Source.Unknown,Cl()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===nd.Kind.Video&&(t="video"),e||("audio"===t&&(sd.forEach((t=>{null!==t.parentElement||e||(e=t)})),e&&sd.splice(sd.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),ad(this._mediaStreamTrack,e);const i=e.srcObject.getTracks();return i.some((e=>"audio"===e.kind))&&e.play().then((()=>{this.emit(Jc.AudioPlaybackStarted)})).catch((t=>{"NotAllowedError"===t.name?this.emit(Jc.AudioPlaybackFailed,t):ln.warn("could not playback audio",t),e&&i.some((e=>"video"===e.kind))&&"NotAllowedError"===t.name&&(e.muted=!0,e.play().catch((()=>{})))})),this.emit(Jc.ElementAttached,e),e}detach(e){if(e){rd(this._mediaStreamTrack,e);const t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(Jc.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach((e=>{rd(this._mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(Jc.ElementDetached,e)})),this.attachedElements=[],t}stop(){this.stopMonitor(),this._mediaStreamTrack.stop(),Cl()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),sd.forEach((e=>{e.parentElement||(t=!1)})),t&&sd.push(e)}}async handleAppVisibilityChanged(){this.isInBackground="hidden"===document.visibilityState}}function ad(e,t){let i,s;i=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream,s="audio"===e.kind?i.getAudioTracks():i.getVideoTracks(),s.includes(e)||(s.forEach((e=>{i.removeTrack(e)})),i.addTrack(e)),t.autoplay=!0,t.muted=0===i.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==i&&(t.srcObject=i,(Sl()||yl())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=i,t.play().catch((()=>{}))}),0))}function rd(e,t){if(t.srcObject instanceof MediaStream){const i=t.srcObject;i.removeTrack(e),i.getTracks().length>0?t.srcObject=i:t.srcObject=null}}!function(e){let t,i,s;!function(e){e.Audio="audio",e.Video="video",e.Unknown="unknown"}(t=e.Kind||(e.Kind={})),function(e){e.Camera="camera",e.Microphone="microphone",e.ScreenShare="screen_share",e.ScreenShareAudio="screen_share_audio",e.Unknown="unknown"}(i=e.Source||(e.Source={})),function(e){e.Active="active",e.Paused="paused",e.Unknown="unknown"}(s=e.StreamState||(e.StreamState={})),e.kindToProto=function(e){switch(e){case t.Audio:return Ja.AUDIO;case t.Video:return Ja.VIDEO;default:return Ja.UNRECOGNIZED}},e.kindFromProto=function(e){switch(e){case Ja.AUDIO:return t.Audio;case Ja.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case i.Camera:return Ha.CAMERA;case i.Microphone:return Ha.MICROPHONE;case i.ScreenShare:return Ha.SCREEN_SHARE;case i.ScreenShareAudio:return Ha.SCREEN_SHARE_AUDIO;default:return Ha.UNRECOGNIZED}},e.sourceFromProto=function(e){switch(e){case Ha.CAMERA:return i.Camera;case Ha.MICROPHONE:return i.Microphone;case Ha.SCREEN_SHARE:return i.ScreenShare;case Ha.SCREEN_SHARE_AUDIO:return i.ScreenShareAudio;default:return i.Unknown}},e.streamStateFromProto=function(e){switch(e){case Yo.ACTIVE:return s.Active;case Yo.PAUSED:return s.Paused;default:return s.Unknown}}}(nd||(nd={}));class od extends nd{constructor(e,t,i){let s=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(e,t),this._isUpstreamPaused=!1,this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this.emit(Jc.Ended,this)},this._mediaStreamTrack.addEventListener("ended",this.handleEnded),this.constraints=null!=i?i:e.getConstraints(),this.reacquireTrack=!1,this.providedByUser=s,this.muteQueue=new Ll}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==nd.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();return e&&t?{width:e,height:t}:void 0}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}async waitForDimensions(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3;if(this.kind===nd.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");const t=Date.now();for(;Date.now()-t<e;){const e=this.dimensions;if(e)return e;await pl(50)}throw new Xc("unable to get track dimensions after timeout")}async getDeviceId(){if(this.source===nd.Source.ScreenShare)return;const{deviceId:e,groupId:t}=this._mediaStreamTrack.getSettings(),i=this.kind===nd.Kind.Audio?"audioinput":"videoinput";return Bl.getInstance().normalizeDeviceId(i,e,t)}async mute(){return this.setTrackMuted(!0),this}async unmute(){return this.setTrackMuted(!1),this}async replaceTrack(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!this.sender)throw new Xc("unable to replace an unpublished track");return this.attachedElements.forEach((e=>{rd(this._mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this.providedByUser||this._mediaStreamTrack.stop(),e.addEventListener("ended",this.handleEnded),ln.debug("replace MediaStreamTrack"),this.sender&&await this.sender.replaceTrack(e),this._mediaStreamTrack=e,this._mediaStreamTrack.enabled=!this.isMuted,await this.resumeUpstream(),this.attachedElements.forEach((t=>{ad(e,t)})),this.mediaStream=new MediaStream([e]),this.providedByUser=t,this}async restart(e){e||(e=this.constraints),ln.debug("restarting track with constraints",e);const t={audio:!1,video:!1};this.kind===nd.Kind.Video?t.video=e:t.audio=e,this.attachedElements.forEach((e=>{rd(this._mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const i=await navigator.mediaDevices.getUserMedia(t),s=i.getTracks()[0];return s.addEventListener("ended",this.handleEnded),ln.debug("re-acquired MediaStreamTrack"),this.sender&&await this.sender.replaceTrack(s),this._mediaStreamTrack=s,await this.resumeUpstream(),this.attachedElements.forEach((e=>{ad(s,e)})),this.mediaStream=i,this.constraints=e,this.emit(Jc.Restarted,this),this}setTrackMuted(e){ln.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted")),this.isMuted===e&&this._mediaStreamTrack.enabled!==e||(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?Jc.Muted:Jc.Unmuted,this))}get needsReAcquisition(){return"live"!==this._mediaStreamTrack.readyState||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}async handleAppVisibilityChanged(){await super.handleAppVisibilityChanged(),wl()&&(ln.debug("visibility changed, is in Background: ".concat(this.isInBackground)),this.isInBackground||!this.needsReAcquisition||this.isUserProvided||this.isMuted||(ln.debug("track needs to be reaquired, restarting ".concat(this.source)),await this.restart(),this.reacquireTrack=!1))}async pauseUpstream(){this.muteQueue.run((async()=>{if(!0===this._isUpstreamPaused)return;if(!this.sender)return void ln.warn("unable to pause upstream for an unpublished track");this._isUpstreamPaused=!0,this.emit(Jc.UpstreamPaused,this);const e=this.kind===nd.Kind.Audio?Ol():(Dl||(Dl=Al()),Dl);await this.sender.replaceTrack(e)}))}async resumeUpstream(){this.muteQueue.run((async()=>{!1!==this._isUpstreamPaused&&(this.sender?(this._isUpstreamPaused=!1,this.emit(Jc.UpstreamResumed,this),await this.sender.replaceTrack(this._mediaStreamTrack)):ln.warn("unable to resume upstream for an unpublished track"))}))}}class cd extends od{constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];super(e,nd.Kind.Audio,t,i),this.stopOnMute=!1,this.monitorSender=async()=>{if(!this.sender)return void(this._currentBitrate=0);let e;try{e=await this.getSenderStats()}catch(e){return void ln.error("could not get audio sender stats",{error:e})}e&&this.prevStats&&(this._currentBitrate=sl(e,this.prevStats)),this.prevStats=e},this.checkForSilence()}async setDeviceId(e){this.constraints.deviceId!==e&&(this.constraints.deviceId=e,this.isMuted||await this.restartTrack())}async mute(){return await this.muteQueue.run((async()=>{this.source===nd.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(ln.debug("stopping mic track"),this._mediaStreamTrack.stop()),await super.mute()})),this}async unmute(){return await this.muteQueue.run((async()=>{this.source!==nd.Source.Microphone||!this.stopOnMute&&"ended"!==this._mediaStreamTrack.readyState||this.isUserProvided||(ln.debug("reacquiring mic track"),await this.restartTrack()),await super.unmute()})),this}async restartTrack(e){let t;if(e){const i=dl({audio:e});"boolean"!=typeof i.audio&&(t=i.audio)}await this.restart(t)}async restart(e){const t=await super.restart(e);return this.checkForSilence(),t}startMonitor(){Cl()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),il)))}async getSenderStats(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;let t;return(await this.sender.getStats()).forEach((e=>{"outbound-rtp"===e.type&&(t={type:"audio",streamId:e.id,packetsSent:e.packetsSent,packetsLost:e.packetsLost,bytesSent:e.bytesSent,timestamp:e.timestamp,roundTripTime:e.roundTripTime,jitter:e.jitter})})),t}async checkForSilence(){const e=await async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;const i=hl();if(i){const s=i.createAnalyser();s.fftSize=2048;const n=s.frequencyBinCount,a=new Uint8Array(n);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(s),await pl(t),s.getByteTimeDomainData(a);const r=a.some((e=>128!==e&&0!==e));return i.close(),!r}return!1}(this);return e&&(this.isMuted||ln.warn("silence detected on local audio track"),this.emit(Jc.AudioSilenceDetected)),e}}class ld extends od{constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];super(e,nd.Kind.Video,t,i),this.simulcastCodecs=new Map,this.monitorSender=async()=>{if(!this.sender)return void(this._currentBitrate=0);let e;try{e=await this.getSenderStats()}catch(e){return void ln.error("could not get audio sender stats",{error:e})}const t=new Map(e.map((e=>[e.rid,e])));if(this.prevStats){let e=0;t.forEach(((t,i)=>{var s;const n=null===(s=this.prevStats)||void 0===s?void 0:s.get(i);e+=sl(t,n)})),this._currentBitrate=e}this.prevStats=t},this.senderLock=new xl}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!Cl())return;const i=null===(t=this.sender)||void 0===t?void 0:t.getParameters();i&&(this.encodings=i.encodings),this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),il))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((e=>{e.mediaStreamTrack.stop()})),super.stop()}async mute(){return await this.muteQueue.run((async()=>{this.source!==nd.Source.Camera||this.isUserProvided||(ln.debug("stopping camera track"),this._mediaStreamTrack.stop()),await super.mute()})),this}async unmute(){return await this.muteQueue.run((async()=>{this.source!==nd.Source.Camera||this.isUserProvided||(ln.debug("reacquiring camera track"),await this.restartTrack()),await super.unmute()})),this}async getSenderStats(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return[];const t=[],i=await this.sender.getStats();return i.forEach((e=>{var s;if("outbound-rtp"===e.type){const n={type:"video",streamId:e.id,frameHeight:e.frameHeight,frameWidth:e.frameWidth,firCount:e.firCount,pliCount:e.pliCount,nackCount:e.nackCount,packetsSent:e.packetsSent,bytesSent:e.bytesSent,framesSent:e.framesSent,timestamp:e.timestamp,rid:null!==(s=e.rid)&&void 0!==s?s:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,qualityLimitationReason:e.qualityLimitationReason,qualityLimitationResolutionChanges:e.qualityLimitationResolutionChanges},a=i.get(e.remoteId);a&&(n.jitter=a.jitter,n.packetsLost=a.packetsLost,n.roundTripTime=a.roundTripTime),t.push(n)}})),t}setPublishingQuality(e){const t=[];for(let i=Ga.LOW;i<=Ga.HIGH;i+=1)t.push({quality:i,enabled:i<=e});ln.debug("setting publishing quality. max quality ".concat(e)),this.setPublishingLayers(t)}async setDeviceId(e){this.constraints.deviceId!==e&&(this.constraints.deviceId=e,this.isMuted||await this.restartTrack())}async restartTrack(e){let t;if(e){const i=dl({video:e});"boolean"!=typeof i.video&&(t=i.video)}await this.restart(t)}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e))throw new Error("".concat(e," already added"));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)}),5e3))}async setPublishingCodecs(e){if(ln.debug("setting publishing codecs",{codecs:e,currentCodec:this.codec}),!this.codec&&e.length>0)return await this.setPublishingLayers(e[0].qualities),[];this.subscribedCodecs=e;const t=[];var i,s=!1,n=!1;try{for(var a,r=Wr(e);s=!(a=await r.next()).done;s=!1){const e=a.value;if(this.codec&&this.codec!==e.codec){const i=this.simulcastCodecs.get(e.codec);if(ln.debug("try setPublishingCodec for ".concat(e.codec),i),i&&i.sender)i.encodings&&(ln.debug("try setPublishingLayersForSender ".concat(e.codec)),await dd(i.sender,i.encodings,e.qualities,this.senderLock));else for(const i of e.qualities)if(i.enabled){t.push(e.codec);break}}else await this.setPublishingLayers(e.qualities)}}catch(e){n=!0,i=e}finally{try{s&&null!=r.return&&await r.return()}finally{if(n)throw i}}return t}async setPublishingLayers(e){ln.debug("setting publishing layers",e),this.sender&&this.encodings&&await dd(this.sender,this.encodings,e,this.senderLock)}async handleAppVisibilityChanged(){await super.handleAppVisibilityChanged(),wl()&&this.isInBackground&&this.source===nd.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}}async function dd(e,t,i,s){const n=await s.lock();ln.debug("setPublishingLayersForSender",{sender:e,qualities:i,senderEncodings:t});try{const s=e.getParameters(),{encodings:n}=s;if(!n)return;if(n.length!==t.length)return void ln.warn("cannot set publishing layers, encodings mismatch");let a=!1;n.forEach(((e,s)=>{var n;let r=null!==(n=e.rid)&&void 0!==n?n:"";""===r&&(r="q");const o=hd(r),c=i.find((e=>e.quality===o));c&&e.active!==c.enabled&&(a=!0,e.active=c.enabled,ln.debug("setting layer ".concat(c.quality," to ").concat(e.active?"enabled":"disabled")),yl()&&(c.enabled?(e.scaleResolutionDownBy=t[s].scaleResolutionDownBy,e.maxBitrate=t[s].maxBitrate,e.maxFrameRate=t[s].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))})),a&&(s.encodings=n,await e.setParameters(s))}finally{n()}}function hd(e){switch(e){case"f":return Ga.HIGH;case"h":return Ga.MEDIUM;case"q":return Ga.LOW;default:return Ga.UNRECOGNIZED}}function ud(e,t,i){return i?i.map((s=>{var n,a,r;const o=null!==(n=s.scaleResolutionDownBy)&&void 0!==n?n:1;let c=hd(null!==(a=s.rid)&&void 0!==a?a:"");return c===Ga.UNRECOGNIZED&&1===i.length&&(c=Ga.HIGH),{quality:c,width:e/o,height:t/o,bitrate:null!==(r=s.maxBitrate)&&void 0!==r?r:0,ssrc:0}})):[{quality:Ga.HIGH,width:e,height:t,bitrate:0,ssrc:0}]}class pd extends nd{constructor(e,t,i,s){super(e,i),this.sid=t,this.receiver=s}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?Jc.Muted:Jc.Unmuted,this))}setMediaStream(e){this.mediaStream=e,e.onremovetrack=()=>{this.receiver=void 0,this._currentBitrate=0,this.emit(Jc.Ended,this)}}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval((()=>this.monitorReceiver()),il))}}class md extends pd{constructor(e,t,i,s,n){super(e,t,nd.Kind.Audio,i),this.monitorReceiver=async()=>{if(!this.receiver)return void(this._currentBitrate=0);const e=await this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=sl(e,this.prevStats)),this.prevStats=e},this.audioContext=s,this.webAudioPluginNodes=[],n&&(this.sinkId=n.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1):i.volume=e;this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;let e=0;return this.attachedElements.forEach((t=>{t.volume>e&&(e=t.volume)})),e}async setSinkId(e){this.sinkId=e,await Promise.all(this.attachedElements.map((t=>{if(fl(t))return t.setSinkId(e)})))}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.elementVolume&&(e.volume=this.elementVolume),this.sinkId&&fl(e)&&e.setSinkId(this.sinkId),this.audioContext&&t&&(ln.debug("using audio context mapping"),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),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((e=>{i.connect(e),i=e})),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==e.state&&e.resume().then((()=>{"running"!==e.state&&this.emit(Jc.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))})).catch((e=>{this.emit(Jc.AudioPlaybackFailed,e)}))}disconnectWebAudio(){var e,t;null===(e=this.gainNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}async getReceiverStats(){if(!this.receiver||!this.receiver.getStats)return;let e;return(await this.receiver.getStats()).forEach((t=>{"inbound-rtp"===t.type&&(e={type:"audio",timestamp:t.timestamp,jitter:t.jitter,bytesReceived:t.bytesReceived,concealedSamples:t.concealedSamples,concealmentEvents:t.concealmentEvents,silentConcealedSamples:t.silentConcealedSamples,silentConcealmentEvents:t.silentConcealmentEvents,totalAudioEnergy:t.totalAudioEnergy,totalSamplesDuration:t.totalSamplesDuration})})),e}}function gd(e,t,i){var s,n,a;void 0===t&&(t=50),void 0===i&&(i={});var r=null!=(s=i.isImmediate)&&s,o=null!=(n=i.callback)&&n,c=i.maxWait,l=Date.now(),d=[];function h(){if(void 0!==c){var e=Date.now()-l;if(e+t>=c)return c-e}return t}var u=function(){var t=[].slice.call(arguments),i=this;return new Promise((function(s,n){var c=r&&void 0===a;if(void 0!==a&&clearTimeout(a),a=setTimeout((function(){if(a=void 0,l=Date.now(),!r){var s=e.apply(i,t);o&&o(s),d.forEach((function(e){return(0,e.resolve)(s)})),d=[]}}),h()),c){var u=e.apply(i,t);return o&&o(u),s(u)}d.push({resolve:s,reject:n})}))};return u.cancel=function(e){void 0!==a&&clearTimeout(a),d.forEach((function(t){return(0,t.reject)(e)})),d=[]},u}class fd{}fd.setTimeout=function(){return setTimeout(...arguments)},fd.setInterval=function(){return setInterval(...arguments)},fd.clearTimeout=function(){return clearTimeout(...arguments)},fd.clearInterval=function(){return clearInterval(...arguments)};class vd extends pd{constructor(e,t,i,s){super(e,t,nd.Kind.Video,i),this.elementInfos=[],this.hasUsedAttach=!1,this.monitorReceiver=async()=>{if(!this.receiver)return void(this._currentBitrate=0);const e=await this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=sl(e,this.prevStats)),this.prevStats=e},this.debouncedHandleResize=gd((()=>{this.updateDimensions()}),100),this.adaptiveStreamSettings=s}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}get mediaStreamTrack(){return this.isAdaptiveStream&&!this.hasUsedAttach&&ln.warn("When using adaptiveStream, you need to use remoteVideoTrack.attach() to add the track to a HTMLVideoElement, otherwise your video tracks might never start"),this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach((t=>{e?rd(this._mediaStreamTrack,t):ad(this._mediaStreamTrack,t)}))}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&void 0===this.elementInfos.find((t=>t.element===e))){const t=new bd(e);this.observeElementInfo(t)}return this.hasUsedAttach=!0,e}observeElementInfo(e){this.adaptiveStreamSettings&&void 0===this.elementInfos.find((t=>t===e))?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):ln.warn("visibility resize observer not triggered")}stopObservingElementInfo(e){if(!this.isAdaptiveStream)return void ln.warn("stopObservingElementInfo ignored");const t=this.elementInfos.filter((t=>t===e));for(const e of t)e.stopObserving();this.elementInfos=this.elementInfos.filter((t=>t!==e)),this.updateVisibility()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const e of t)this.stopObservingElement(e);return t}getDecoderImplementation(){var e;return null===(e=this.prevStats)||void 0===e?void 0:e.decoderImplementation}async getReceiverStats(){if(!this.receiver||!this.receiver.getStats)return;let e;return(await this.receiver.getStats()).forEach((t=>{"inbound-rtp"===t.type&&(e={type:"video",framesDecoded:t.framesDecoded,framesDropped:t.framesDropped,framesReceived:t.framesReceived,packetsReceived:t.packetsReceived,packetsLost:t.packetsLost,frameWidth:t.frameWidth,frameHeight:t.frameHeight,pliCount:t.pliCount,firCount:t.firCount,nackCount:t.nackCount,jitter:t.jitter,timestamp:t.timestamp,bytesReceived:t.bytesReceived,decoderImplementation:t.decoderImplementation})})),e}stopObservingElement(e){const t=this.elementInfos.filter((t=>t.element===e));for(const e of t)e.stopObserving();this.elementInfos=this.elementInfos.filter((t=>t.element!==e))}async handleAppVisibilityChanged(){await super.handleAppVisibilityChanged(),this.isAdaptiveStream&&this.updateVisibility()}updateVisibility(){var e,t;const i=this.elementInfos.reduce(((e,t)=>Math.max(e,t.visibilityChangedAt||0)),0),s=!(null!==(t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pauseVideoInBackground)&&void 0!==t&&!t)&&this.isInBackground,n=this.elementInfos.some((e=>e.pictureInPicture)),a=this.elementInfos.some((e=>e.visible))&&!s||n;this.lastVisible!==a&&(!a&&Date.now()-i<100?fd.setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=a,this.emit(Jc.VisibilityChanged,a,this)))}updateDimensions(){var e,t,i,s;let n=0,a=0;for(const i of this.elementInfos){const s=null!==(t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pixelDensity)&&void 0!==t?t:1,r="screen"===s?window.devicePixelRatio:s,o=i.width()*r,c=i.height()*r;o+c>n+a&&(n=o,a=c)}(null===(i=this.lastDimensions)||void 0===i?void 0:i.width)===n&&(null===(s=this.lastDimensions)||void 0===s?void 0:s.height)===a||(this.lastDimensions={width:n,height:a},this.emit(Jc.VideoDimensionsChanged,this.lastDimensions,this))}}class bd{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;const{target:i,isIntersecting:s}=e;i===this.element&&(this.isIntersecting=s,this.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.onEnterPiP=()=>{var e;this.isPiP=!0,null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=!1,null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:yd(e),this.isPiP=Cl()&&document.pictureInPictureElement===e,this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){this.isIntersecting=yd(this.element),this.isPiP=document.pictureInPictureElement===this.element,this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,_l().observe(this.element),Ml().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP)}stopObserving(){var e,t;null===(e=_l())||void 0===e||e.unobserve(this.element),null===(t=Ml())||void 0===t||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP)}}function yd(e){let t=e.offsetTop,i=e.offsetLeft;const s=e.offsetWidth,n=e.offsetHeight,{hidden:a}=e,{opacity:r,display:o}=getComputedStyle(e);for(;e.offsetParent;)t+=(e=e.offsetParent).offsetTop,i+=e.offsetLeft;return t<window.pageYOffset+window.innerHeight&&i<window.pageXOffset+window.innerWidth&&t+n>window.pageYOffset&&i+s>window.pageXOffset&&!a&&(""===r||parseFloat(r)>0)&&"none"!==o}class Sd extends jl.EventEmitter{constructor(e,t,i){super(),this.metadataMuted=!1,this.handleMuted=()=>{this.emit(Jc.Muted)},this.handleUnmuted=()=>{this.emit(Jc.Unmuted)},this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=nd.Source.Unknown}setTrack(e){this.track&&(this.track.off(Jc.Muted,this.handleMuted),this.track.off(Jc.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(Jc.Muted,this.handleMuted),e.on(Jc.Unmuted,this.handleUnmuted))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get audioTrack(){if(this.track instanceof cd||this.track instanceof md)return this.track}get videoTrack(){if(this.track instanceof ld||this.track instanceof vd)return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=nd.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===nd.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.trackInfo=e,ln.trace("update publication info",{info:e})}}!function(e){var t,i;(t=e.SubscriptionStatus||(e.SubscriptionStatus={})).Desired="desired",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed",(i=e.PermissionStatus||(e.PermissionStatus={})).Allowed="allowed",i.NotAllowed="not_allowed"}(Sd||(Sd={}));class wd extends Sd{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(e,t,i){super(e,t.sid,t.name),this.track=void 0,this.handleTrackEnded=()=>{this.emit(Jc.Ended)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&this.track.off(Jc.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(Jc.Ended,this.handleTrackEnded)}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}async mute(){var e;return null===(e=this.track)||void 0===e?void 0:e.mute()}async unmute(){var e;return null===(e=this.track)||void 0===e?void 0:e.unmute()}async pauseUpstream(){var e;await(null===(e=this.track)||void 0===e?void 0:e.pauseUpstream())}async resumeUpstream(){var e;await(null===(e=this.track)||void 0===e?void 0:e.resumeUpstream())}}class Cd{constructor(e,t,i,s){this.width=e,this.height=t,this.encoding={maxBitrate:i,maxFramerate:s}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.width/this.height}}}const kd=["vp8","h264"];function Ed(e){return!!kd.find((t=>t===e))}var Td;!function(e){e.telephone={maxBitrate:12e3},e.speech={maxBitrate:2e4},e.music={maxBitrate:32e3},e.musicStereo={maxBitrate:48e3},e.musicHighQuality={maxBitrate:64e3},e.musicHighQualityStereo={maxBitrate:96e3}}(Td||(Td={}));const Pd={h90:new Cd(160,90,6e4,15),h180:new Cd(320,180,12e4,15),h216:new Cd(384,216,18e4,15),h360:new Cd(640,360,3e5,20),h540:new Cd(960,540,6e5,25),h720:new Cd(1280,720,17e5,30),h1080:new Cd(1920,1080,3e6,30),h1440:new Cd(2560,1440,5e6,30),h2160:new Cd(3840,2160,8e6,30)},Md={h120:new Cd(160,120,8e4,15),h180:new Cd(240,180,1e5,15),h240:new Cd(320,240,15e4,15),h360:new Cd(480,360,225e3,20),h480:new Cd(640,480,3e5,20),h540:new Cd(720,540,45e4,25),h720:new Cd(960,720,15e5,30),h1080:new Cd(1440,1080,25e5,30),h1440:new Cd(1920,1440,35e5,30)},Rd={h360fps3:new Cd(640,360,2e5,3),h720fps5:new Cd(1280,720,4e5,5),h720fps15:new Cd(1280,720,1e6,15),h1080fps15:new Cd(1920,1080,15e5,15),h1080fps30:new Cd(1920,1080,3e6,30)};var _d;!function(e){e.Excellent="excellent",e.Good="good",e.Poor="poor",e.Unknown="unknown"}(_d||(_d={}));class Nd extends jl.EventEmitter{constructor(e,t,i,s){super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=_d.Unknown,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=s,this.audioTracks=new Map,this.videoTracks=new Map,this.tracks=new Map}getTracks(){return Array.from(this.tracks.values())}getTrack(e){for(const[,t]of this.tracks)if(t.source===e)return t}getTrackByName(e){for(const[,t]of this.tracks)if(t.trackName===e)return t}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrack(nd.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrack(nd.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrack(nd.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*this.participantInfo.joinedAt):new Date}updateInfo(e){this.identity=e.identity,this.sid=e.sid,this.name=e.name,this.setMetadata(e.metadata),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,ln.trace("update participant info",{info:e})}setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit($c.ParticipantMetadataChanged,i)}setPermissions(e){var t,i,s,n,a;const r=this.permissions,o=e.canPublish!==(null===(t=this.permissions)||void 0===t?void 0:t.canPublish)||e.canSubscribe!==(null===(i=this.permissions)||void 0===i?void 0:i.canSubscribe)||e.canPublishData!==(null===(s=this.permissions)||void 0===s?void 0:s.canPublishData)||e.hidden!==(null===(n=this.permissions)||void 0===n?void 0:n.hidden)||e.recorder!==(null===(a=this.permissions)||void 0===a?void 0:a.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some(((e,t)=>{var i;return e!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublishSources[t])}));return this.permissions=e,o&&this.emit($c.ParticipantPermissionsChanged,r),o}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit($c.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=function(e){switch(e){case za.EXCELLENT:return _d.Excellent;case za.GOOD:return _d.Good;case za.POOR:return _d.Poor;default:return _d.Unknown}}(e),t!==this._connectionQuality&&this.emit($c.ConnectionQualityChanged,this._connectionQuality)}addTrackPublication(e){e.on(Jc.Muted,(()=>{this.emit($c.TrackMuted,e)})),e.on(Jc.Unmuted,(()=>{this.emit($c.TrackUnmuted,e)}));const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.tracks.set(e.trackSid,e),e.kind){case nd.Kind.Audio:this.audioTracks.set(e.trackSid,e);break;case nd.Kind.Video:this.videoTracks.set(e.trackSid,e)}}}function Dd(e,t){switch(e.kind){case"audio":return new cd(e,t,!1);case"video":return new ld(e,t,!1);default:throw new Xc("unsupported track type: ".concat(e.kind))}}const Id=Object.values(Pd),Ad=Object.values(Md),Od=Object.values(Rd),Ud=[Pd.h180,Pd.h360],xd=[Md.h180,Md.h360],Ld=e=>[{scaleResolutionDownBy:2,fps:3}].map((t=>{var i;return new Cd(Math.floor(e.width/t.scaleResolutionDownBy),Math.floor(e.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(e.encoding.maxBitrate/(t.scaleResolutionDownBy**2*((null!==(i=e.encoding.maxFramerate)&&void 0!==i?i:30)/t.fps)))),t.fps)})),Fd=["q","h","f"];function Bd(e,t,i,s){var n,a;let r=null==s?void 0:s.videoEncoding;e&&(r=null==s?void 0:s.screenShareEncoding);const o=null==s?void 0:s.simulcast,c=null==s?void 0:s.scalabilityMode,l=null==s?void 0:s.videoCodec;if(!r&&!o&&!c||!t||!i)return[{}];r||(r=function(e,t,i,s){const n=function(e,t,i){if(e)return Od;const s=t>i?t/i:i/t;if(Math.abs(s-16/9)<Math.abs(s-4/3))return Id;return Ad}(e,t,i);let{encoding:a}=n[0];const r=Math.max(t,i);for(let e=0;e<n.length;e+=1){const t=n[e];if(a=t.encoding,t.width>=r)break}if(s&&"av1"===s)a.maxBitrate=.7*a.maxBitrate;return a}(e,t,i,l),ln.debug("using video encoding",r));const d=new Cd(t,i,r.maxBitrate,r.maxFramerate);if(c&&"av1"===l){ln.debug("using svc with scalabilityMode ".concat(c));const e=[];if("L3T3"===c){for(let t=0;t<3;t+=1)e.push({rid:Fd[2-t],scaleResolutionDownBy:2**t,maxBitrate:r.maxBitrate/3**t,maxFramerate:d.encoding.maxFramerate,scalabilityMode:"L3T3"});return ln.debug("encodings",e),e}throw new Error("unsupported scalabilityMode: ".concat(c))}if(!o)return[r];let h,u=[];if(u=e?null!==(n=$d(null==s?void 0:s.screenShareSimulcastLayers))&&void 0!==n?n:jd(e,d):null!==(a=$d(null==s?void 0:s.videoSimulcastLayers))&&void 0!==a?a:jd(e,d),u.length>0){const e=u[0];u.length>1&&([,h]=u);const s=Math.max(t,i);if(s>=960&&h)return Vd(t,i,[e,h,d]);if(s>=480)return Vd(t,i,[e,d])}return Vd(t,i,[d])}function qd(e,t,i){var s,n,a,r;if(!i.backupCodec||i.backupCodec.codec===i.videoCodec)return;t!==i.backupCodec.codec&&ln.warn("requested a different codec than specified as backup",{serverRequested:t,backup:i.backupCodec.codec}),i.videoCodec=t,i.videoEncoding=i.backupCodec.encoding;const o=e.mediaStreamTrack.getSettings(),c=null!==(s=o.width)&&void 0!==s?s:null===(n=e.dimensions)||void 0===n?void 0:n.width,l=null!==(a=o.height)&&void 0!==a?a:null===(r=e.dimensions)||void 0===r?void 0:r.height;return Bd(e.source===nd.Source.ScreenShare,c,l,i)}function jd(e,t){if(e)return Ld(t);const{width:i,height:s}=t,n=i>s?i/s:s/i;return Math.abs(n-16/9)<Math.abs(n-4/3)?Ud:xd}function Vd(e,t,i){const s=[];return i.forEach(((i,n)=>{if(n>=Fd.length)return;const a=Math.min(e,t),r=Fd[n];s.push({rid:r,scaleResolutionDownBy:Math.max(1,a/Math.min(i.width,i.height)),maxBitrate:i.encoding.maxBitrate,maxFramerate:i.encoding.maxFramerate})})),s}function $d(e){if(e)return e.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 Wd extends Sd{constructor(e,t,i){super(e,t.sid,t.name),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=Ga.HIGH,this.handleEnded=e=>{this.setTrack(void 0),this.emit(Jc.Ended,e)},this.handleVisibilityChange=e=>{ln.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(e),{trackSid:this.trackSid}),this.disabled=!e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{ln.debug("adaptivestream video dimensions ".concat(e.width,"x").concat(e.height),{trackSid:this.trackSid}),this.videoDimensions=e,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={trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[{participantSid:"",trackSids:[this.trackSid]}]};this.emit(Jc.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?Sd.SubscriptionStatus.Unsubscribed:super.isSubscribed?Sd.SubscriptionStatus.Subscribed:Sd.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Sd.PermissionStatus.Allowed:Sd.PermissionStatus.NotAllowed}get isSubscribed(){return!1!==this.subscribed&&super.isSubscribed}get isDesired(){return!1!==this.subscribed}get isEnabled(){return!this.disabled}setEnabled(e){this.isManualOperationAllowed()&&this.disabled!==!e&&(this.disabled=!e,this.emitTrackUpdate())}setVideoQuality(e){this.isManualOperationAllowed()&&this.currentVideoQuality!==e&&(this.currentVideoQuality=e,this.videoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&((null===(t=this.videoDimensions)||void 0===t?void 0:t.width)===e.width&&(null===(i=this.videoDimensions)||void 0===i?void 0:i.height)===e.height||(this.track instanceof vd&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&this.track instanceof vd&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,s=this.track;s!==e&&(s&&(s.off(Jc.VideoDimensionsChanged,this.handleVideoDimensionsChange),s.off(Jc.VisibilityChanged,this.handleVisibilityChange),s.off(Jc.Ended,this.handleEnded),s.detach(),this.emit(Jc.Unsubscribed,s)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(Jc.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(Jc.VisibilityChanged,this.handleVisibilityChange),e.on(Jc.Ended,this.handleEnded),this.emit(Jc.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)}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?Jc.Muted:Jc.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(Jc.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(Jc.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isAdaptiveStream?(ln.warn("adaptive stream is enabled, cannot change track settings",{trackSid:this.trackSid}),!1):!!this.isDesired||(ln.warn("cannot update track settings when not subscribed",{trackSid:this.trackSid}),!1)}get isAdaptiveStream(){return this.track instanceof vd&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=yc.fromPartial({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(e.width=this.videoDimensions.width,e.height=this.videoDimensions.height):void 0!==this.currentVideoQuality?e.quality=this.currentVideoQuality:e.quality=Ga.HIGH,this.emit(Jc.UpdateSettings,e)}}class Jd extends Nd{static fromParticipantInfo(e,t){return new Jd(e,t.sid,t.identity,t.name,t.metadata)}constructor(e,t,i,s,n){super(t,i||"",s,n),this.signalClient=e,this.tracks=new Map,this.audioTracks=new Map,this.videoTracks=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(Jc.UpdateSettings,(e=>{ln.debug("send update settings",e),this.signalClient.sendUpdateTrackSettings(e)})),e.on(Jc.UpdateSubscription,(e=>{e.participantTracks.forEach((e=>{e.participantSid=this.sid})),this.signalClient.sendUpdateSubscription(e)})),e.on(Jc.SubscriptionPermissionChanged,(t=>{this.emit($c.TrackSubscriptionPermissionChanged,e,t)})),e.on(Jc.SubscriptionStatusChanged,(t=>{this.emit($c.TrackSubscriptionStatusChanged,e,t)})),e.on(Jc.Subscribed,(t=>{this.emit($c.TrackSubscribed,t,e)})),e.on(Jc.Unsubscribed,(t=>{this.emit($c.TrackUnsubscribed,t,e)}))}getTrack(e){const t=super.getTrack(e);if(t)return t}getTrackByName(e){const t=super.getTrackByName(e);if(t)return t}setVolume(e){this.volume=e;const t=this.getTrack(nd.Source.Microphone);t&&t.track&&t.track.setVolume(e)}getVolume(){const e=this.getTrack(nd.Source.Microphone);return e&&e.track?e.track.getVolume():this.volume}addSubscribedMediaTrack(e,t,i,s,n,a){let r=this.getTrackPublication(t);if(r||t.startsWith("TR")||this.tracks.forEach((t=>{r||e.kind!==t.kind.toString()||(r=t)})),!r)return 0===a?(ln.error("could not find published track",{participant:this.sid,trackSid:t}),void this.emit($c.TrackSubscriptionFailed,t)):(void 0===a&&(a=20),void setTimeout((()=>{this.addSubscribedMediaTrack(e,t,i,s,n,a-1)}),150));if("ended"===e.readyState)return ln.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",{participant:this.sid,trackSid:t}),void this.emit($c.TrackSubscriptionFailed,t);let o;return o="video"===e.kind?new vd(e,t,s,n):new md(e,t,s,this.audioContext,this.audioOutput),o.source=r.source,o.isMuted=r.isMuted,o.setMediaStream(i),o.start(),r.setTrack(o),void 0!==this.volume&&o instanceof md&&o.source===nd.Source.Microphone&&o.setVolume(this.volume),r}get hasMetadata(){return!!this.participantInfo}getTrackPublication(e){return this.tracks.get(e)}updateInfo(e){super.updateInfo(e);const t=new Map,i=new Map;e.tracks.forEach((s=>{var n;let a=this.getTrackPublication(s.sid);if(a)a.updateInfo(s);else{const t=nd.kindFromProto(s.type);if(!t)return;a=new Wd(t,s,null===(n=this.signalClient.connectOptions)||void 0===n?void 0:n.autoSubscribe),a.updateInfo(s),i.set(s.sid,a);const r=Array.from(this.tracks.values()).find((e=>e.source===(null==a?void 0:a.source)));r&&a.source!==nd.Source.Unknown&&ln.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(a.source),{oldTrack:r,newTrack:a,participant:this,participantInfo:e}),this.addTrackPublication(a)}t.set(s.sid,a)})),this.tracks.forEach((e=>{t.has(e.trackSid)||(ln.trace("detected removed track on remote participant, unpublishing",{publication:e,participantSid:this.sid}),this.unpublishTrack(e.trackSid,!0))})),i.forEach((e=>{this.emit($c.TrackPublished,e)}))}unpublishTrack(e,t){const i=this.tracks.get(e);if(!i)return;switch(this.tracks.delete(e),i.kind){case nd.Kind.Audio:this.audioTracks.delete(e);break;case nd.Kind.Video:this.videoTracks.delete(e)}const{track:s}=i;s&&(s.stop(),i.setTrack(void 0)),t&&this.emit($c.TrackUnpublished,i)}setAudioContext(e){this.audioContext=e,this.audioTracks.forEach((t=>t.track instanceof md&&t.track.setAudioContext(e)))}async setAudioOutput(e){this.audioOutput=e;const t=[];this.audioTracks.forEach((i=>{var s;i.track instanceof md&&t.push(i.track.setSinkId(null!==(s=e.deviceId)&&void 0!==s?s:"default"))})),await 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 ln.trace("participant event",{participant:this.sid,event:e,args:i}),super.emit(e,...i)}}class Hd extends Nd{constructor(e,t,i,s){super(e,t),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Ul)},this.handleReconnected=()=>{var e,t;null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.resolve)||void 0===t||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var e,t;null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.reject)||void 0===t||t.call(e,"Got disconnected during publishing attempt"),this.reconnectFuture=void 0},this.updateTrackSubscriptionPermissions=()=>{ln.debug("updating track subscription permissions",{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions}),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map((e=>function(e){var t,i,s;if(!e.participantSid&&!e.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return{participantIdentity:null!==(t=e.participantIdentity)&&void 0!==t?t:"",participantSid:null!==(i=e.participantSid)&&void 0!==i?i:"",allTracks:null!==(s=e.allowAll)&&void 0!==s&&s,trackSids:e.allowedTrackSids||[]}}(e))))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{void 0===t&&(t=!0),e.sid?this.engine.updateMuteStatus(e.sid,t):ln.error("could not update mute status for unpublished track",e)},this.onTrackUpstreamPaused=e=>{ln.debug("upstream paused"),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{ln.debug("upstream resumed"),this.onTrackMuted(e,e.isMuted)},this.handleSubscribedQualityUpdate=async e=>{var t,i;if(!(null===(t=this.roomOptions)||void 0===t?void 0:t.dynacast))return;const s=this.videoTracks.get(e.trackSid);if(s)if(e.subscribedCodecs.length>0){if(!s.videoTrack)return;const t=await s.videoTrack.setPublishingCodecs(e.subscribedCodecs);var n,a=!1,r=!1;try{for(var o,c=Wr(t);a=!(o=await c.next()).done;a=!1){const e=o.value;Ed(e)&&(ln.debug("publish ".concat(e," for ").concat(s.videoTrack.sid)),await this.publishAdditionalCodecForTrack(s.videoTrack,e,s.options))}}catch(e){r=!0,n=e}finally{try{a&&null!=c.return&&await c.return()}finally{if(r)throw n}}}else e.subscribedQualities.length>0&&await(null===(i=s.videoTrack)||void 0===i?void 0:i.setPublishingLayers(e.subscribedQualities));else ln.warn("received subscribed quality update for unknown track",{method:"handleSubscribedQualityUpdate",sid:e.trackSid})},this.handleLocalTrackUnpublished=e=>{const t=this.tracks.get(e.trackSid);t?this.unpublishTrack(t.track):ln.warn("received unpublished event for unknown track",{method:"handleLocalTrackUnpublished",trackSid:e.trackSid})},this.handleTrackEnded=async e=>{if(e.source===nd.Source.ScreenShare||e.source===nd.Source.ScreenShareAudio)ln.debug("unpublishing local track due to TrackEnded",{track:e.sid}),this.unpublishTrack(e);else if(e.isUserProvided)await e.mute();else if(e instanceof cd||e instanceof ld)try{if(Cl())try{const t=await(null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===nd.Source.Camera?"camera":"microphone"}));if(t&&"denied"===t.state)throw ln.warn("user has revoked access to ".concat(e.source)),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},new Error("GetUserMedia Permission denied")}catch(e){}e.isMuted||(ln.debug("track ended, attempting to use a different device"),await e.restartTrack())}catch(t){ln.warn("could not restart track, muting instead"),await e.mute()}},this.audioTracks=new Map,this.videoTracks=new Map,this.tracks=new Map,this.engine=i,this.roomOptions=s,this.setupEngine(i)}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}getTrack(e){const t=super.getTrack(e);if(t)return t}getTrackByName(e){const t=super.getTrackByName(e);if(t)return t}setupEngine(e){this.engine=e,this.engine.client.onRemoteMuteChanged=(e,t)=>{const i=this.tracks.get(e);i&&i.track&&(t?i.mute():i.unmute())},this.engine.client.onSubscribedQualityUpdate=this.handleSubscribedQualityUpdate,this.engine.client.onLocalTrackUnpublished=this.handleLocalTrackUnpublished,this.engine.on(Wc.Connected,this.handleReconnected).on(Wc.Restarted,this.handleReconnected).on(Wc.Resumed,this.handleReconnected).on(Wc.Restarting,this.handleReconnecting).on(Wc.Resuming,this.handleReconnecting).on(Wc.Disconnected,this.handleDisconnected)}setCameraEnabled(e,t,i){return this.setTrackEnabled(nd.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(nd.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(nd.Source.ScreenShare,e,t,i)}async setTrackEnabled(e,t,i,s){var n,a;ln.debug("setTrackEnabled",{source:e,enabled:t});let r=this.getTrack(e);if(t)if(r)await r.unmute();else{let t;if(this.pendingPublishing.has(e))return void ln.info("skipping duplicate published source",{source:e});this.pendingPublishing.add(e);try{switch(e){case nd.Source.Camera:t=await this.createTracks({video:null===(n=i)||void 0===n||n});break;case nd.Source.Microphone:t=await this.createTracks({audio:null===(a=i)||void 0===a||a});break;case nd.Source.ScreenShare:t=await this.createScreenTracks(Gr({},i));break;default:throw new Xc(e)}const o=[];for(const e of t)ln.info("publishing track",{localTrack:e}),o.push(this.publishTrack(e,s));const c=await Promise.all(o);[r]=c}catch(e){throw e instanceof Error&&!(e instanceof Xc)&&this.emit($c.MediaDevicesError,e),e}finally{this.pendingPublishing.delete(e)}}else if(r&&r.track)if(e===nd.Source.ScreenShare){r=await this.unpublishTrack(r.track);const e=this.getTrack(nd.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else await r.mute();return r}async enableCameraAndMicrophone(){if(!this.pendingPublishing.has(nd.Source.Camera)&&!this.pendingPublishing.has(nd.Source.Microphone)){this.pendingPublishing.add(nd.Source.Camera),this.pendingPublishing.add(nd.Source.Microphone);try{const e=await this.createTracks({audio:!0,video:!0});await Promise.all(e.map((e=>this.publishTrack(e))))}finally{this.pendingPublishing.delete(nd.Source.Camera),this.pendingPublishing.delete(nd.Source.Microphone)}}}async createTracks(e){var t,i;const s=dl(cl(e,null===(t=this.roomOptions)||void 0===t?void 0:t.audioCaptureDefaults,null===(i=this.roomOptions)||void 0===i?void 0:i.videoCaptureDefaults));let n;try{n=await navigator.mediaDevices.getUserMedia(s)}catch(e){throw e instanceof Error&&(s.audio&&(this.microphoneError=e),s.video&&(this.cameraError=e)),e}return s.audio&&(this.microphoneError=void 0),s.video&&(this.cameraError=void 0),n.getTracks().map((t=>{const i="audio"===t.kind;let a;i?e.audio:e.video;const r=i?s.audio:s.video;"boolean"!=typeof r&&(a=r);const o=Dd(t,a);return o.kind===nd.Kind.Video?o.source=nd.Source.Camera:o.kind===nd.Kind.Audio&&(o.source=nd.Source.Microphone),o.mediaStream=n,o}))}async createScreenTracks(e){var t;void 0===e&&(e={}),void 0===e.resolution&&(e.resolution=Rd.h1080fps15.resolution);let i=!0;if(e.resolution&&(i=Sl()?{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}:{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate}),void 0===navigator.mediaDevices.getDisplayMedia)throw new Qc("getDisplayMedia not supported");const s=await navigator.mediaDevices.getDisplayMedia({audio:null!==(t=e.audio)&&void 0!==t&&t,video:i,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio}),n=s.getVideoTracks();if(0===n.length)throw new Xc("no video track found");const a=new ld(n[0],void 0,!1);a.source=nd.Source.ScreenShare;const r=[a];if(s.getAudioTracks().length>0){const e=new cd(s.getAudioTracks()[0],void 0,!1);e.source=nd.Source.ScreenShareAudio,r.push(e)}return r}async publishTrack(e,t){var i,s,n;if(await(null===(i=this.reconnectFuture)||void 0===i?void 0:i.promise),e instanceof od&&this.pendingPublishPromises.has(e)&&await this.pendingPublishPromises.get(e),e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new cd(e,void 0,!0);break;case"video":e=new ld(e,void 0,!0);break;default:throw new Xc("unsupported MediaStreamTrack kind ".concat(e.kind))}let a;if(this.tracks.forEach((t=>{t.track&&t.track===e&&(a=t)})),a)return ln.warn("track has already been published, skipping"),a;const r=(null==t?void 0:t.forceStereo)||"channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount;r&&(t||(t={}),void 0===t.dtx&&ln.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work."),void 0===t.red&&ln.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(s=t.dtx)&&void 0!==s||(t.dtx=!1),null!==(n=t.red)&&void 0!==n||(t.red=!1));const o=Gr(Gr({},this.roomOptions.publishDefaults),t);o.source&&(e.source=o.source);const c=this.publish(e,o,t,r);this.pendingPublishPromises.set(e,c);try{return await c}catch(e){throw e}finally{this.pendingPublishPromises.delete(e)}}async publish(e,t,i,s){var n,a,r,o;const c=Array.from(this.tracks.values()).find((t=>e instanceof od&&t.source===e.source));if(c&&e.source!==nd.Source.Unknown)try{throw Error("publishing a second track with the same source: ".concat(e.source))}catch(t){t instanceof Error&&ln.warn(t.message,{oldTrack:c,newTrack:e,trace:t.stack})}t.stopMicTrackOnMute&&e instanceof cd&&(e.stopOnMute=!0),e.source===nd.Source.ScreenShare&&yl()&&(t.simulcast=!1),"av1"!==t.videoCodec||function(){const e=RTCRtpReceiver.getCapabilities("video");let t=!1,i=!1;if(e){for(const i of e.codecs)if("video/AV1"===i.mimeType){t=!0;break}for(const t of e.headerExtensions)if("https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension"===t.uri){i=!0;break}}return t&&i}()||(t.videoCodec=void 0),e.on(Jc.Muted,this.onTrackMuted),e.on(Jc.Unmuted,this.onTrackUnmuted),e.on(Jc.Ended,this.handleTrackEnded),e.on(Jc.UpstreamPaused,this.onTrackUpstreamPaused),e.on(Jc.UpstreamResumed,this.onTrackUpstreamResumed);const l=lc.fromPartial({cid:e.mediaStreamTrack.id,name:null==i?void 0:i.name,type:nd.kindToProto(e.kind),muted:e.isMuted,source:nd.sourceToProto(e.source),disableDtx:!(null===(n=t.dtx)||void 0===n||n),stereo:s,disableRed:!(null===(a=t.red)||void 0===a||a)});let d,h;if(e.kind===nd.Kind.Video){let i={width:0,height:0};try{i=await e.waitForDimensions()}catch(e){ln.error("could not determine track dimensions")}if(l.width=i.width,l.height=i.height,e instanceof ld&&("av1"===(null==t?void 0:t.videoCodec)&&(t.scalabilityMode=null!==(r=t.scalabilityMode)&&void 0!==r?r:"L3T3"),t.videoCodec&&t.backupCodec&&t.videoCodec!==t.backupCodec.codec)){const i=Gr({},t);i.simulcast=!0,h=qd(e,t.backupCodec.codec,i),l.simulcastCodecs=[{codec:t.videoCodec,cid:e.mediaStreamTrack.id,enableSimulcastLayers:!0},{codec:t.backupCodec.codec,cid:"",enableSimulcastLayers:!0}]}d=Bd(e.source===nd.Source.ScreenShare,i.width,i.height,t),l.layers=ud(l.width,l.height,null!=h?h:d)}else e.kind===nd.Kind.Audio&&t.audioBitrate&&(d=[{maxBitrate:t.audioBitrate}]);if(!this.engine||this.engine.isClosed)throw new el("cannot publish track when not connected");const u=await this.engine.addTrack(l),p=new wd(e.kind,u,e);if(p.options=t,e.sid=u.sid,!this.engine.publisher)throw new el("publisher is closed");return ln.debug("publishing ".concat(e.kind," with encodings"),{encodings:d,trackInfo:u}),e.sender=await this.engine.createSender(e,t,d),"av1"===e.codec&&d&&(null===(o=d[0])||void 0===o?void 0:o.maxBitrate)&&this.engine.publisher.setTrackCodecBitrate(l.cid,e.codec,d[0].maxBitrate/1e3),this.engine.negotiate(),e instanceof ld?e.startMonitor(this.engine.client):e instanceof cd&&e.startMonitor(),this.addTrackPublication(p),this.emit($c.LocalTrackPublished,p),p}get isLocal(){return!0}async publishAdditionalCodecForTrack(e,t,i){var s;let n;if(this.tracks.forEach((t=>{t.track&&t.track===e&&(n=t)})),!n)throw new Xc("track is not published");if(!(e instanceof ld))throw new Xc("track is not a video track");const a=Gr(Gr({},null===(s=this.roomOptions)||void 0===s?void 0:s.publishDefaults),i),r=qd(e,t,a);if(!r)return void ln.info("backup codec has been disabled, ignoring request to add additional codec for track");const o=e.addSimulcastTrack(t,r),c=lc.fromPartial({cid:o.mediaStreamTrack.id,type:nd.kindToProto(e.kind),muted:e.isMuted,source:nd.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:o.mediaStreamTrack.id,enableSimulcastLayers:a.simulcast}]});if(c.layers=ud(c.width,c.height,r),!this.engine||this.engine.isClosed)throw new el("cannot publish track when not connected");const l=await this.engine.addTrack(c);await this.engine.createSimulcastSender(e,o,a,r),this.engine.negotiate(),ln.debug("published ".concat(t," for track ").concat(e.sid),{encodings:r,trackInfo:l})}async unpublishTrack(e,t){var i,s;const n=this.getPublicationForTrack(e);if(ln.debug("unpublishing track",{track:e,method:"unpublishTrack"}),!n||!n.track)return void ln.warn("track was not unpublished because no publication was found",{track:e,method:"unpublishTrack"});(e=n.track).off(Jc.Muted,this.onTrackMuted),e.off(Jc.Unmuted,this.onTrackUnmuted),e.off(Jc.Ended,this.handleTrackEnded),e.off(Jc.UpstreamPaused,this.onTrackUpstreamPaused),e.off(Jc.UpstreamResumed,this.onTrackUpstreamResumed),void 0===t&&(t=null===(s=null===(i=this.roomOptions)||void 0===i?void 0:i.stopLocalTrackOnUnpublish)||void 0===s||s),t&&e.stop();let a=!1;const r=e.sender;if(e.sender=void 0,this.engine.publisher&&"closed"!==this.engine.publisher.pc.connectionState&&r)try{if(this.engine.removeTrack(r)&&(a=!0),e instanceof ld){for(const[,t]of e.simulcastCodecs)t.sender&&(this.engine.removeTrack(t.sender)&&(a=!0),t.sender=void 0);e.simulcastCodecs.clear()}}catch(e){ln.warn("failed to unpublish track",{error:e,method:"unpublishTrack"})}switch(this.tracks.delete(n.trackSid),n.kind){case nd.Kind.Audio:this.audioTracks.delete(n.trackSid);break;case nd.Kind.Video:this.videoTracks.delete(n.trackSid)}return this.emit($c.LocalTrackUnpublished,n),n.setTrack(void 0),a&&await this.engine.negotiate(),n}async unpublishTracks(e){return(await Promise.all(e.map((e=>this.unpublishTrack(e))))).filter((e=>e instanceof wd))}async republishAllTracks(e){const t=[];this.tracks.forEach((i=>{i.track&&(e&&(i.options=Gr(Gr({},i.options),e)),t.push(i))})),await Promise.all(t.map((async e=>{const t=e.track;await this.unpublishTrack(t,!1),await this.publishTrack(t,e.options)})))}async publishData(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const s=Array.isArray(i)?i:null==i?void 0:i.destination,n=[],a=Array.isArray(i)?void 0:i.topic;void 0!==s&&s.forEach((e=>{e instanceof Jd?n.push(e.sid):n.push(e)}));const r={kind:t,value:{$case:"user",user:{participantSid:this.sid,payload:e,destinationSids:n,topic:a}}};await this.engine.sendDataPacket(r,t)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isConnected&&this.updateTrackSubscriptionPermissions()}updateInfo(e){e.sid===this.sid&&(super.updateInfo(e),e.tracks.forEach((e=>{var t,i;const s=this.tracks.get(e.sid);if(s){const n=s.isMuted||null!==(i=null===(t=s.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==i&&i;n!==e.muted&&(ln.debug("updating server mute state after reconcile",{sid:e.sid,muted:n}),this.engine.client.sendMuteTrack(e.sid,n))}})))}getPublicationForTrack(e){let t;return this.tracks.forEach((i=>{const s=i.track;s&&(e instanceof MediaStreamTrack?(s instanceof cd||s instanceof ld)&&s.mediaStreamTrack===e&&(t=i):e===s&&(t=i))})),t}publishedTracksInfo(){const e=[];return this.tracks.forEach((t=>{void 0!==t.track&&e.push({cid:t.track.mediaStreamID,track:t.trackInfo})})),e}dataChannelsInfo(){const e=[],t=(t,i)=>{void 0!==(null==t?void 0:t.id)&&null!==t.id&&e.push({label:t.label,id:t.id,target:i})};return t(this.engine.dataChannelForKind(er.LOSSY),Xo.PUBLISHER),t(this.engine.dataChannelForKind(er.RELIABLE),Xo.PUBLISHER),t(this.engine.dataChannelForKind(er.LOSSY,!0),Xo.SUBSCRIBER),t(this.engine.dataChannelForKind(er.RELIABLE,!0),Xo.SUBSCRIBER),e}}const Gd=["syncState","trickle","offer","answer","simulate","leave"];class zd{constructor(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.rtt=0,this.isConnected=!1,this.isReconnecting=!1,this.useJSON=e,this.requestQueue=new Ll,this.queuedRequests=[],this.closingLock=new xl}async join(e,t,i,s){this.isConnected=!1,this.options=i;return await this.connect(e,t,i,s)}async reconnect(e,t,i,s){if(!this.options)return void ln.warn("attempted to reconnect without signal options being set, ignoring");this.isReconnecting=!0,this.clearPingInterval();return await this.connect(e,t,Gr(Gr({},this.options),{},{reconnect:!0,sid:i,reconnectReason:s}))}connect(e,t,i,s){this.connectOptions=i,e.startsWith("http")&&(e=e.replace("http","ws")),e=e.replace(/\/$/,""),e+="/rtc";const n=function(e,t,i){var s;const n=new URLSearchParams;n.set("access_token",e),i.reconnect&&(n.set("reconnect","1"),i.sid&&n.set("sid",i.sid));n.set("auto_subscribe",i.autoSubscribe?"1":"0"),n.set("sdk",kl()?"reactnative":"js"),n.set("version",t.version),n.set("protocol",t.protocol.toString()),t.deviceModel&&n.set("device_model",t.deviceModel);t.os&&n.set("os",t.os);t.osVersion&&n.set("os_version",t.osVersion);t.browser&&n.set("browser",t.browser);t.browserVersion&&n.set("browser_version",t.browserVersion);void 0!==i.publishOnly&&n.set("publish",i.publishOnly);i.adaptiveStream&&n.set("adaptive_stream","1");i.reconnectReason&&n.set("reconnect_reason",i.reconnectReason.toString());(null===(s=navigator.connection)||void 0===s?void 0:s.type)&&n.set("network",navigator.connection.type);return"?".concat(n.toString())}(t,Nl(),i);return new Promise((async(t,a)=>{const r=async()=>{await this.close(),a(new Kc("room connection has been cancelled"))};(null==s?void 0:s.aborted)&&r(),null==s||s.addEventListener("abort",r),ln.debug("connecting to ".concat(e+n)),this.ws&&await this.close(),this.ws=new WebSocket(e+n),this.ws.binaryType="arraybuffer",this.ws.onerror=async t=>{if(this.isConnected)this.handleWSError(t);else try{const t=await fetch("http".concat(e.substring(2),"/validate").concat(n));if(t.ok)a(new Kc("Internal error",2,t.status));else{const e=await t.text();a(new Kc(e,0,t.status))}}catch(e){a(new Kc("server was not reachable",1))}},this.ws.onmessage=async e=>{var n,o,c,l;let d;if("string"==typeof e.data){const t=JSON.parse(e.data);d=oc.fromJSON(t)}else{if(!(e.data instanceof ArrayBuffer))return void ln.error("could not decode websocket message: ".concat(typeof e.data));d=oc.decode(new Uint8Array(e.data))}if(!this.isConnected){let e=!1;if("join"===(null===(n=d.message)||void 0===n?void 0:n.$case)?(this.isConnected=!0,null==s||s.removeEventListener("abort",r),this.pingTimeoutDuration=d.message.join.pingTimeout,this.pingIntervalDuration=d.message.join.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(ln.debug("ping config",{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}),this.startPingInterval()),t(d.message.join)):i.reconnect?(this.isConnected=!0,null==s||s.removeEventListener("abort",r),this.startPingInterval(),"reconnect"===(null===(o=d.message)||void 0===o?void 0:o.$case)?t(null===(c=d.message)||void 0===c?void 0:c.reconnect):(t(),e=!0)):i.reconnect||a(new Kc("did not receive join response, got ".concat(null===(l=d.message)||void 0===l?void 0:l.$case," instead"))),!e)return}this.signalLatency&&await pl(this.signalLatency),this.handleSignalResponse(d)},this.ws.onclose=e=>{this.isConnected&&(ln.debug("websocket connection closed: ".concat(e.reason)),this.isConnected=!1,this.onClose&&this.onClose(e.reason),this.ws=void 0)}}))}async close(){const e=await this.closingLock.lock();try{if(this.isConnected=!1,this.ws){this.ws.onclose=null,this.ws.onmessage=null,this.ws.onopen=null;const e=new Promise((e=>{this.ws?this.ws.onclose=e:e(!0)}));this.ws.close(),await Promise.race([e,pl(250)])}this.ws=void 0,this.clearPingInterval()}finally{e()}}sendOffer(e){ln.debug("sending offer",e),this.sendRequest({$case:"offer",offer:Kd(e)})}sendAnswer(e){ln.debug("sending answer"),this.sendRequest({$case:"answer",answer:Kd(e)})}sendIceCandidate(e,t){ln.trace("sending ice candidate",e),this.sendRequest({$case:"trickle",trickle:{candidateInit:JSON.stringify(e),target:t}})}sendMuteTrack(e,t){this.sendRequest({$case:"mute",mute:{sid:e,muted:t}})}sendAddTrack(e){this.sendRequest({$case:"addTrack",addTrack:lc.fromPartial(e)})}sendUpdateTrackSettings(e){this.sendRequest({$case:"trackSetting",trackSetting:e})}sendUpdateSubscription(e){this.sendRequest({$case:"subscription",subscription:e})}sendSyncState(e){this.sendRequest({$case:"syncState",syncState:e})}sendUpdateVideoLayers(e,t){this.sendRequest({$case:"updateLayers",updateLayers:{trackSid:e,layers:t}})}sendUpdateSubscriptionPermissions(e,t){this.sendRequest({$case:"subscriptionPermission",subscriptionPermission:{allParticipants:e,trackPermissions:t}})}sendSimulateScenario(e){this.sendRequest({$case:"simulate",simulate:e})}sendPing(){this.sendRequest({$case:"ping",ping:Date.now()}),this.sendRequest({$case:"pingReq",pingReq:{timestamp:Date.now(),rtt:this.rtt}})}async sendLeave(){await this.sendRequest({$case:"leave",leave:{canReconnect:!1,reason:Ka.CLIENT_INITIATED}})}async sendRequest(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=!t&&!function(e){const t=Gd.includes(e.$case);return ln.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(i&&this.isReconnecting)return void this.queuedRequests.push((async()=>{await this.sendRequest(e,!0)}));if(t||await this.requestQueue.flush(),this.signalLatency&&await pl(this.signalLatency),!this.ws||this.ws.readyState!==this.ws.OPEN)return void ln.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.$case));const s={message:e};try{this.useJSON?this.ws.send(JSON.stringify(rc.toJSON(s))):this.ws.send(rc.encode(s).finish())}catch(e){ln.error("error sending signal message",{error:e})}}handleSignalResponse(e){var t,i;const s=e.message;if(null!=s)if("answer"===s.$case){const e=Zd(s.answer);this.onAnswer&&this.onAnswer(e)}else if("offer"===s.$case){const e=Zd(s.offer);this.onOffer&&this.onOffer(e)}else if("trickle"===s.$case){const e=JSON.parse(s.trickle.candidateInit);this.onTrickle&&this.onTrickle(e,s.trickle.target)}else"update"===s.$case?this.onParticipantUpdate&&this.onParticipantUpdate(null!==(t=s.update.participants)&&void 0!==t?t:[]):"trackPublished"===s.$case?this.onLocalTrackPublished&&this.onLocalTrackPublished(s.trackPublished):"speakersChanged"===s.$case?this.onSpeakersChanged&&this.onSpeakersChanged(null!==(i=s.speakersChanged.speakers)&&void 0!==i?i:[]):"leave"===s.$case?this.onLeave&&this.onLeave(s.leave):"mute"===s.$case?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(s.mute.sid,s.mute.muted):"roomUpdate"===s.$case?this.onRoomUpdate&&s.roomUpdate.room&&this.onRoomUpdate(s.roomUpdate.room):"connectionQuality"===s.$case?this.onConnectionQuality&&this.onConnectionQuality(s.connectionQuality):"streamStateUpdate"===s.$case?this.onStreamStateUpdate&&this.onStreamStateUpdate(s.streamStateUpdate):"subscribedQualityUpdate"===s.$case?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(s.subscribedQualityUpdate):"subscriptionPermissionUpdate"===s.$case?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(s.subscriptionPermissionUpdate):"refreshToken"===s.$case?this.onTokenRefresh&&this.onTokenRefresh(s.refreshToken):"trackUnpublished"===s.$case?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(s.trackUnpublished):"pong"===s.$case?this.resetPingTimeout():"pongResp"===s.$case?(this.rtt=Date.now()-s.pongResp.lastPingTimestamp,this.resetPingTimeout()):ln.debug("unsupported message",s);else ln.debug("received unsupported message")}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}this.isReconnecting=!1}handleWSError(e){ln.error("websocket error",e)}resetPingTimeout(){this.clearPingTimeout(),this.pingTimeoutDuration?this.pingTimeout=fd.setTimeout((()=>{ln.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString())),this.onClose&&this.onClose("ping timeout")}),1e3*this.pingTimeoutDuration):ln.warn("ping timeout duration not set")}clearPingTimeout(){this.pingTimeout&&fd.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(ln.debug("start ping interval"),this.pingInterval=fd.setInterval((()=>{this.sendPing()}),1e3*this.pingIntervalDuration)):ln.warn("ping interval duration not set")}clearPingInterval(){ln.debug("clearing ping interval"),this.clearPingTimeout(),this.pingInterval&&fd.clearInterval(this.pingInterval)}}function Zd(e){const t={type:"offer",sdp:e.sdp};switch(e.type){case"answer":case"offer":case"pranswer":case"rollback":t.type=e.type}return t}function Kd(e){return{sdp:e.sdp,type:e.type}}const Qd={audioBitrate:Td.music.maxBitrate,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Rd.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:"vp8",backupCodec:{codec:"vp8",encoding:Pd.h540.encoding}},Xd={autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0},Yd={resolution:Pd.h720.resolution},eh={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new class{constructor(e){this._retryDelays=void 0!==e?[...e]:$r}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+1e3*Math.random()}},disconnectOnPageLeave:!0,expWebAudioMix:!1},th={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3};var ih={},sh={},nh={get exports(){return sh},set exports(e){sh=e}}.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 null!=e.address?"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 null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(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 null!=e.sessionConfig?"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+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{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 null!=e.attribute&&(t+=" %s",null!=e.value&&(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 null!=e.maxMessageSize?"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"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%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+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(nh).forEach((function(e){nh[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))})),function(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,s){var n=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:n&&!i[e.name]&&(i[e.name]={});var a=e.push?{}:n?i[e.name]:i;!function(e,i,s,n){if(n&&!s)i[n]=t(e[1]);else for(var a=0;a<s.length;a+=1)null!=e[a+1]&&(i[s[a]]=t(e[a+1]))}(s.match(e.reg),a,e.names,e.name),e.push&&i[e.push].push(a)},s=sh,n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},a=[],r=t;return e.split(/(\r\n|\r|\n)/).filter(n).forEach((function(e){var t=e[0],n=e.slice(2);"m"===t&&(a.push({rtp:[],fmtp:[]}),r=a[a.length-1]);for(var o=0;o<(s[t]||[]).length;o+=1){var c=s[t][o];if(c.reg.test(n))return i(c,r,n)}})),t.media=a,t};var a=function(e,i){var s=i.split(/=(.+)/,2);return 2===s.length?e[s[0]]=t(s[1]):1===s.length&&i.length>1&&(e[s[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(a,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],s=e.split(" ").map(t),n=0;n<s.length;n+=3)i.push({component:s[n],ip:s[n+1],port:s[n+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(a,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,s=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),s=!0),{scid:i,paused:s}}))}))}}(ih);var ah=sh,rh=/%[sdv%]/g,oh=function(e){var t=1,i=arguments,s=i.length;return e.replace(rh,(function(e){if(t>=s)return e;var n=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}}))},ch=function(e,t,i){var s=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var n=0;n<t.names.length;n+=1){var a=t.names[n];t.name?s.push(i[t.name][a]):s.push(i[t.names[n]])}else s.push(i[t.name]);return oh.apply(null,s)},lh=["v","o","s","i","u","e","p","c","b","t","r","z","a"],dh=["i","c","b","a"],hh=ih,uh=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var i=t.outerOrder||lh,s=t.innerOrder||dh,n=[];return i.forEach((function(t){ah[t].forEach((function(i){i.name in e&&null!=e[i.name]?n.push(ch(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){n.push(ch(t,i,e))}))}))})),e.media.forEach((function(e){n.push(ch("m",ah.m[0],e)),s.forEach((function(t){ah[t].forEach((function(i){i.name in e&&null!=e[i.name]?n.push(ch(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){n.push(ch(t,i,e))}))}))}))})),n.join("\r\n")+"\r\n"},ph=uh,mh=hh.parse;const gh="negotiationStarted",fh="negotiationComplete";class vh extends jl{constructor(e){super(),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=gd((e=>{this.emit(gh);try{this.createAndSendOffer()}catch(t){if(!e)throw t;e(t)}}),100),this.pc=new RTCPeerConnection(e)}get isICEConnected(){return"connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState}async addIceCandidate(e){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)}async setRemoteDescription(e){if("offer"===e.type){let{stereoMids:t,nackMids:i}=function(e){var t;const i=[],s=[],n=mh(null!==(t=e.sdp)&&void 0!==t?t:"");let a=0;return n.media.forEach((e=>{var t;"audio"===e.type&&(e.rtp.some((e=>"opus"===e.codec&&(a=e.payload,!0))),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some((e=>e.payload===a&&"nack"===e.type)))&&s.push(e.mid),e.fmtp.some((t=>t.payload===a&&(t.config.includes("sprop-stereo=1")&&i.push(e.mid),!0))))})),{stereoMids:i,nackMids:s}}(e);this.remoteStereoMids=t,this.remoteNackMids=i}await this.pc.setRemoteDescription(e),this.pendingCandidates.forEach((e=>{this.pc.addIceCandidate(e)})),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,this.createAndSendOffer()):"answer"===e.type&&this.emit(fh)}async createAndSendOffer(e){var t;if(void 0===this.onOffer)return;if((null==e?void 0:e.iceRestart)&&(ln.debug("restarting ICE"),this.restartingIce=!0),"have-local-offer"===this.pc.signalingState){const t=this.pc.remoteDescription;if(!(null==e?void 0:e.iceRestart)||!t)return void(this.renegotiate=!0);await this.pc.setRemoteDescription(t)}else if("closed"===this.pc.signalingState)return void ln.warn("could not createOffer with closed peer connection");ln.debug("starting to negotiate");const i=await this.pc.createOffer(e),s=mh(null!==(t=i.sdp)&&void 0!==t?t:"");s.media.forEach((e=>{"audio"===e.type?bh(e,[],[]):"video"===e.type&&this.trackBitrates.some((t=>{if(!e.msid||!e.msid.includes(t.sid))return!1;let i=0;return e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0))),i>0&&(e.fmtp.some((e=>e.payload===i&&(e.config.includes("x-google-max-bitrate")||(e.config+=";x-google-max-bitrate=".concat(t.maxbr)),!0)))||e.fmtp.push({payload:i,config:"x-google-max-bitrate=".concat(t.maxbr)})),!0}))})),this.trackBitrates=[],await this.setMungedLocalDescription(i,ph(s)),this.onOffer(i)}async createAndSetAnswer(){var e;const t=await this.pc.createAnswer(),i=mh(null!==(e=t.sdp)&&void 0!==e?e:"");return i.media.forEach((e=>{"audio"===e.type&&bh(e,this.remoteStereoMids,this.remoteNackMids)})),await this.setMungedLocalDescription(t,ph(i)),t}setTrackCodecBitrate(e,t,i){this.trackBitrates.push({sid:e,codec:t,maxbr:i})}close(){this.pc.onconnectionstatechange=null,this.pc.oniceconnectionstatechange=null,this.pc.close()}async setMungedLocalDescription(e,t){const i=e.sdp;e.sdp=t;try{return ln.debug("setting munged local description"),void await this.pc.setLocalDescription(e)}catch(t){ln.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),{error:t}),e.sdp=i}try{await this.pc.setLocalDescription(e)}catch(e){let t="unknown error";throw e instanceof Error?t=e.message:"string"==typeof e&&(t=e),new tl(t)}}}function bh(e,t,i){let s=0;e.rtp.some((e=>"opus"===e.codec&&(s=e.payload,!0))),s>0&&(e.rtcpFb||(e.rtcpFb=[]),i.includes(e.mid)&&!e.rtcpFb.some((e=>e.payload===s&&"nack"===e.type))&&e.rtcpFb.push({payload:s,type:"nack"}),t.includes(e.mid)&&e.fmtp.some((e=>e.payload===s&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0))))}const yh="_lossy",Sh="_reliable",wh="leave-reconnect";var Ch,kh;!function(e){e[e.New=0]="New",e[e.Connected=1]="Connected",e[e.Disconnected=2]="Disconnected",e[e.Reconnecting=3]="Reconnecting",e[e.Closed=4]="Closed"}(Ch||(Ch={}));class Eh extends jl.EventEmitter{get isClosed(){return this._isClosed}constructor(e){super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=th.peerConnectionTimeout,this.subscriberPrimary=!1,this.pcState=Ch.New,this._isClosed=!0,this.pendingTrackResolvers={},this.hasPublished=!1,this.reconnectAttempts=0,this.reconnectStart=0,this.fullReconnectOnNext=!1,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.handleDataChannel=async e=>{let{channel:t}=e;if(t){if(t.label===Sh)this.reliableDCSub=t;else{if(t.label!==yh)return;this.lossyDCSub=t}ln.debug("on data channel ".concat(t.id,", ").concat(t.label)),t.onmessage=this.handleDataMessage}},this.handleDataMessage=async e=>{var t,i;const s=await this.dataProcessLock.lock();try{let s;if(e.data instanceof ArrayBuffer)s=e.data;else{if(!(e.data instanceof Blob))return void ln.error("unsupported data type",e.data);s=await e.data.arrayBuffer()}const n=Mr.decode(new Uint8Array(s));"speaker"===(null===(t=n.value)||void 0===t?void 0:t.$case)?this.emit(Wc.ActiveSpeakersUpdate,n.value.speaker.speakers):"user"===(null===(i=n.value)||void 0===i?void 0:i.$case)&&this.emit(Wc.DataPacketReceived,n.value.user,n.kind)}finally{s()}},this.handleDataError=e=>{const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent){const{error:i}=e.error;ln.error("DataChannel error on ".concat(t,": ").concat(e.message),i)}else ln.error("Unknown DataChannel Error on ".concat(t),e)},this.handleDisconnect=(e,t)=>{if(this._isClosed)return;ln.warn("".concat(e," disconnected")),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());const i=e=>{ln.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(e,"ms. giving up")),this.emit(Wc.Disconnected),this.close()},s=Date.now()-this.reconnectStart;let n=this.getNextRetryDelay({elapsedMs:s,retryCount:this.reconnectAttempts});null!==n?(e===wh&&(n=0),ln.debug("reconnecting in ".concat(n,"ms")),this.clearReconnectTimeout(),this.reconnectTimeout=fd.setTimeout((()=>this.attemptReconnect(t)),n)):i(s)},this.handleBrowserOnLine=()=>{this.client.isReconnecting&&(this.clearReconnectTimeout(),this.attemptReconnect(Qa.RR_SIGNAL_DISCONNECTED))},this.client=new zd,this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new xl,this.dataProcessLock=new xl}async join(e,t,i,s){this.url=e,this.token=t,this.signalOpts=i;try{this.joinAttempts+=1;const n=await this.client.join(e,t,i,s);return this._isClosed=!1,this.subscriberPrimary=n.subscriberPrimary,this.publisher||this.configure(n),this.subscriberPrimary||this.negotiate(),this.clientConfiguration=n.clientConfiguration,n}catch(n){if(n instanceof Kc&&1===n.reason&&(ln.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts)),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,i,s);throw n}}async close(){const e=await this.closingLock.lock();if(this.isClosed)e();else try{this._isClosed=!0,this.emit(Wc.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.publisher&&"closed"!==this.publisher.pc.signalingState&&(this.publisher.pc.getSenders().forEach((e=>{var t,i;try{(null===(t=this.publisher)||void 0===t?void 0:t.pc.removeTrack)&&(null===(i=this.publisher)||void 0===i||i.pc.removeTrack(e))}catch(e){ln.warn("could not removeTrack",{error:e})}})),this.publisher.close(),this.publisher=void 0),this.subscriber&&(this.subscriber.close(),this.subscriber=void 0),await this.client.close()}finally{e()}}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Xc("a track with the same ID has already been published");return new Promise(((t,i)=>{const s=setTimeout((()=>{delete this.pendingTrackResolvers[e.cid],i(new Kc("publication of local track timed out, no response from server"))}),1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(s),t(e)},reject:()=>{clearTimeout(s),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)}))}removeTrack(e){var t;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 null===(t=this.publisher)||void 0===t||t.pc.removeTrack(e),!0}catch(e){ln.warn("failed to remove track",{error:e,method:"removeTrack"})}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null===(e=this.reliableDCSub)||void 0===e?void 0:e.readyState}async getConnectedServerAddress(){if(void 0!==this.primaryPC)return async function(e){var t;let i="";const s=new Map,n=new Map;if((await e.getStats()).forEach((e=>{switch(e.type){case"transport":i=e.selectedCandidatePairId;break;case"candidate-pair":""===i&&e.selected&&(i=e.id),s.set(e.id,e);break;case"remote-candidate":n.set(e.id,"".concat(e.address,":").concat(e.port))}})),""===i)return;const a=null===(t=s.get(i))||void 0===t?void 0:t.remoteCandidateId;if(void 0===a)return;return n.get(a)}(this.primaryPC)}configure(e){var t;if(this.publisher||this.subscriber)return;this.participantSid=null===(t=e.participant)||void 0===t?void 0:t.sid;const i=this.makeRTCConfiguration(e);this.publisher=new vh(i),this.subscriber=new vh(i),this.emit(Wc.TransportsCreated,this.publisher,this.subscriber),this.publisher.pc.onicecandidate=e=>{e.candidate&&(ln.trace("adding ICE candidate for peer",e.candidate),this.client.sendIceCandidate(e.candidate,Xo.PUBLISHER))},this.subscriber.pc.onicecandidate=e=>{e.candidate&&this.client.sendIceCandidate(e.candidate,Xo.SUBSCRIBER)},this.publisher.onOffer=e=>{this.client.sendOffer(e)};let s=this.publisher.pc,n=this.subscriber.pc,a=e.subscriberPrimary;a&&(s=this.subscriber.pc,n=this.publisher.pc,this.subscriber.pc.ondatachannel=this.handleDataChannel),this.primaryPC=s,s.onconnectionstatechange=async()=>{if(ln.debug("primary PC state changed ".concat(s.connectionState)),"connected"===s.connectionState){const t=this.pcState===Ch.New;this.pcState=Ch.Connected,t&&this.emit(Wc.Connected,e)}else"failed"===s.connectionState&&this.pcState===Ch.Connected&&(this.pcState=Ch.Disconnected,this.handleDisconnect("primary peerconnection",a?Qa.RR_SUBSCRIBER_FAILED:Qa.RR_PUBLISHER_FAILED))},n.onconnectionstatechange=async()=>{ln.debug("secondary PC state changed ".concat(n.connectionState)),"failed"===n.connectionState&&this.handleDisconnect("secondary peerconnection",a?Qa.RR_PUBLISHER_FAILED:Qa.RR_SUBSCRIBER_FAILED)},this.subscriber.pc.ontrack=e=>{this.emit(Wc.MediaTrackAdded,e.track,e.streams[0],e.receiver)},this.createDataChannels(),this.client.onAnswer=async e=>{this.publisher&&(ln.debug("received server answer",{RTCSdpType:e.type,signalingState:this.publisher.pc.signalingState}),await this.publisher.setRemoteDescription(e))},this.client.onTrickle=(e,t)=>{this.publisher&&this.subscriber&&(ln.trace("got ICE candidate from peer",{candidate:e,target:t}),t===Xo.PUBLISHER?this.publisher.addIceCandidate(e):this.subscriber.addIceCandidate(e))},this.client.onOffer=async e=>{if(!this.subscriber)return;ln.debug("received server offer",{RTCSdpType:e.type,signalingState:this.subscriber.pc.signalingState}),await this.subscriber.setRemoteDescription(e);const t=await this.subscriber.createAndSetAnswer();this.client.sendAnswer(t)},this.client.onLocalTrackPublished=e=>{ln.debug("received trackPublishedResponse",e);const{resolve:t}=this.pendingTrackResolvers[e.cid];t?(delete this.pendingTrackResolvers[e.cid],t(e.track)):ln.error("missing track resolver for ".concat(e.cid))},this.client.onTokenRefresh=e=>{this.token=e},this.client.onClose=()=>{this.handleDisconnect("signal",Qa.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{(null==e?void 0:e.canReconnect)?(this.fullReconnectOnNext=!0,this.primaryPC=void 0,this.handleDisconnect(wh)):(this.emit(Wc.Disconnected,null==e?void 0:e.reason),this.close()),ln.trace("leave request",{leave:e})}}makeRTCConfiguration(e){const t=Gr({},this.rtcConfig);if(e.iceServers&&!t.iceServers){const i=[];e.iceServers.forEach((e=>{const t={urls:e.urls};e.username&&(t.username=e.username),e.credential&&(t.credential=e.credential),i.push(t)})),t.iceServers=i}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Za.ENABLED&&(t.iceTransportPolicy="relay"),t.sdpSemantics="unified-plan",t.continualGatheringPolicy="gather_continually",t}createDataChannels(){this.publisher&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.publisher.pc.createDataChannel(yh,{ordered:!0,maxRetransmits:0}),this.reliableDC=this.publisher.pc.createDataChannel(Sh,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError)}setPreferredCodec(e,t,i){if(!("getCapabilities"in RTCRtpSender))return;const s=RTCRtpSender.getCapabilities(t);if(!s)return;ln.debug("get capabilities",s);const n=[],a=[],r=[];s.codecs.forEach((e=>{const t=e.mimeType.toLowerCase();if("audio/opus"===t)return void n.push(e);t==="video/".concat(i)?"h264"!==i||e.sdpFmtpLine&&e.sdpFmtpLine.includes("profile-level-id=42e01f")?n.push(e):a.push(e):r.push(e)})),bl(e)&&e.setCodecPreferences(n.concat(a,r))}async createSender(e,t,i){if(ml())return this.createTransceiverRTCRtpSender(e,t,i);if(gl())return ln.debug("using add-track fallback"),this.createRTCRtpSender(e.mediaStreamTrack);throw new el("Required webRTC APIs not supported on this device")}async createSimulcastSender(e,t,i,s){if(ml())return this.createSimulcastTransceiverSender(e,t,i,s);if(gl())return ln.debug("using add-track fallback"),this.createRTCRtpSender(e.mediaStreamTrack);throw new el("Cannot stream on this device")}async createTransceiverRTCRtpSender(e,t,i){if(!this.publisher)throw new el("publisher is closed");const s={direction:"sendonly"};i&&(s.sendEncodings=i);const n=await this.publisher.pc.addTransceiver(e.mediaStreamTrack,s);return e.kind===nd.Kind.Video&&t.videoCodec&&(this.setPreferredCodec(n,e.kind,t.videoCodec),e.codec=t.videoCodec),n.sender}async createSimulcastTransceiverSender(e,t,i,s){if(!this.publisher)throw new el("publisher is closed");const n={direction:"sendonly"};s&&(n.sendEncodings=s);const a=await this.publisher.pc.addTransceiver(t.mediaStreamTrack,n);if(i.videoCodec)return this.setPreferredCodec(a,e.kind,i.videoCodec),e.setSimulcastTrackSender(i.videoCodec,a.sender),a.sender}async createRTCRtpSender(e){if(!this.publisher)throw new el("publisher is closed");return this.publisher.pc.addTrack(e)}async attemptReconnect(e){var t,i,s;if(!this._isClosed&&!this.attemptingReconnect){(null===(t=this.clientConfiguration)||void 0===t?void 0:t.resumeConnection)!==Za.DISABLED&&"closed"!==(null!==(s=null===(i=this.primaryPC)||void 0===i?void 0:i.signalingState)&&void 0!==s?s:"closed")||(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?await this.restartConnection():await this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(e){this.reconnectAttempts+=1;let t=!0;e instanceof el?(ln.debug("received unrecoverable error",{error:e}),t=!1):e instanceof Th||(this.fullReconnectOnNext=!0),t?this.handleDisconnect("reconnect",Qa.RR_UNKOWN):(ln.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up")),this.emit(Wc.Disconnected),this.close())}finally{this.attemptingReconnect=!1}}}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){ln.warn("encountered error in reconnect policy",{error:e})}return null}async restartConnection(){var e,t;if(!this.url||!this.token)throw new el("could not reconnect, url or token not saved");let i;ln.info("reconnecting, attempt: ".concat(this.reconnectAttempts)),this.emit(Wc.Restarting),this.client.isConnected&&await this.client.sendLeave(),await this.client.close(),this.primaryPC=void 0,null===(e=this.publisher)||void 0===e||e.close(),this.publisher=void 0,null===(t=this.subscriber)||void 0===t||t.close(),this.subscriber=void 0;try{if(!this.signalOpts)throw ln.warn("attempted connection restart, without signal options present"),new Th;i=await this.join(this.url,this.token,this.signalOpts)}catch(e){throw new Th}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");await this.waitForPCConnected(),this.client.setReconnected(),this.emit(Wc.Restarted,i)}async resumeConnection(e){var t;if(!this.url||!this.token)throw new el("could not reconnect, url or token not saved");if(!this.publisher||!this.subscriber)throw new el("publisher and subscriber connections unset");ln.info("resuming signal connection, attempt ".concat(this.reconnectAttempts)),this.emit(Wc.Resuming);try{const t=await this.client.reconnect(this.url,this.token,this.participantSid,e);if(t){const e=this.makeRTCConfiguration(t);this.publisher.pc.setConfiguration(e),this.subscriber.pc.setConfiguration(e)}}catch(e){let t="";throw e instanceof Error&&(t=e.message),new Th(t)}if(this.emit(Wc.SignalResumed),this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");this.subscriber.restartingIce=!0,this.hasPublished&&await this.publisher.createAndSendOffer({iceRestart:!0}),await this.waitForPCConnected(),this.client.setReconnected(),"open"===(null===(t=this.reliableDC)||void 0===t?void 0:t.readyState)&&null===this.reliableDC.id&&this.createDataChannels(),this.emit(Wc.Resumed)}async waitForPCConnected(){var e;const t=Date.now();let i=t;for(this.pcState=Ch.Reconnecting,ln.debug("waiting for peer connection to reconnect");i-t<this.peerConnectionTimeout&&void 0!==this.primaryPC;){if(i-t>2e3&&"connected"===(null===(e=this.primaryPC)||void 0===e?void 0:e.connectionState)&&(this.pcState=Ch.Connected),this.pcState===Ch.Connected)return;await pl(100),i=Date.now()}throw new Kc("could not establish PC connection")}async sendDataPacket(e,t){const i=Mr.encode(e).finish();await this.ensurePublisherConnected(t),t===er.LOSSY&&this.lossyDC?this.lossyDC.send(i):t===er.RELIABLE&&this.reliableDC&&this.reliableDC.send(i)}async ensureDataTransportConnected(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;var i,s,n;const a=t?this.subscriber:this.publisher,r=t?"Subscriber":"Publisher";if(!a)throw new Kc("".concat(r," connection not set"));t||(null===(i=this.publisher)||void 0===i?void 0:i.isICEConnected)||"checking"===(null===(s=this.publisher)||void 0===s?void 0:s.pc.iceConnectionState)||this.negotiate();const o=this.dataChannelForKind(e,t);if("open"===(null==o?void 0:o.readyState))return;const c=(new Date).getTime()+this.peerConnectionTimeout;for(;(new Date).getTime()<c;){if(a.isICEConnected&&"open"===(null===(n=this.dataChannelForKind(e,t))||void 0===n?void 0:n.readyState))return;await pl(50)}throw new Kc("could not establish ".concat(r," connection, state: ").concat(a.pc.iceConnectionState))}async ensurePublisherConnected(e){await this.ensureDataTransportConnected(e,!1)}negotiate(){return new Promise(((e,t)=>{if(!this.publisher)return void t(new tl("publisher is not defined"));this.hasPublished=!0;const i=()=>{ln.debug("engine disconnected while negotiation was ongoing"),n(),e()};this.on(Wc.Closing,i);const s=setTimeout((()=>{t("negotiation timed out"),this.handleDisconnect("negotiation",Qa.RR_SIGNAL_DISCONNECTED)}),this.peerConnectionTimeout),n=()=>{clearTimeout(s),this.off(Wc.Closing,i)};this.publisher.once(gh,(()=>{var t;null===(t=this.publisher)||void 0===t||t.once(fh,(()=>{n(),e()}))})),this.publisher.negotiate((e=>{n(),t(e),e instanceof tl&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Qa.RR_UNKOWN)}))}))}dataChannelForKind(e,t){if(t){if(e===er.LOSSY)return this.lossyDCSub;if(e===er.RELIABLE)return this.reliableDCSub}else{if(e===er.LOSSY)return this.lossyDC;if(e===er.RELIABLE)return this.reliableDC}}failNext(){this.shouldFailNext=!0}clearReconnectTimeout(){this.reconnectTimeout&&fd.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Cl()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){Cl()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Th extends Error{}!function(e){e.Disconnected="disconnected",e.Connecting="connecting",e.Connected="connected",e.Reconnecting="reconnecting"}(kh||(kh={}));class Ph extends jl.EventEmitter{constructor(e){var t;super(),t=this,this.state=kh.Disconnected,this.activeSpeakers=[],this.sid="",this.name="",this.metadata=void 0,this._isRecording=!1,this.audioEnabled=!0,this.connect=async(e,t,i)=>{const s=await this.disconnectLock.lock();if(this.state===kh.Connected)return ln.info("already connected to room ".concat(this.name)),s(),Promise.resolve();if(this.connectFuture)return s(),this.connectFuture.promise;this.setAndEmitConnectionState(kh.Connecting);return this.connectFuture=new Ul((async(n,a)=>{var r,o;this.abortController&&!this.abortController.signal.aborted||(this.abortController=new AbortController),s(),this.state===kh.Reconnecting?(ln.info("Reconnection attempt replaced by new connection attempt"),this.recreateEngine()):this.maybeCreateEngine(),this.acquireAudioContext(),this.connOptions=Gr(Gr({},th),i),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const i=await this.engine.join(e,t,{autoSubscribe:this.connOptions.autoSubscribe,publishOnly:this.connOptions.publishOnly,adaptiveStream:"object"==typeof this.options.adaptiveStream||this.options.adaptiveStream,maxRetries:this.connOptions.maxRetries},this.abortController.signal);let s=i.serverInfo;if(s||(s={version:i.serverVersion,region:i.serverRegion}),ln.debug("connected to Livekit Server ".concat(Object.entries(s).map((e=>{let[t,i]=e;return"".concat(t,": ").concat(i)})).join(", "))),!i.serverVersion)throw new Yc("unknown server version");"0.15.1"===i.serverVersion&&this.options.dynacast&&(ln.debug("disabling dynacast due to server version"),this.options.dynacast=!1);const n=i.participant;this.localParticipant.sid=n.sid,this.localParticipant.identity=n.identity,this.localParticipant.updateInfo(n),this.setupLocalParticipantEvents(),i.otherParticipants.forEach((e=>{e.sid!==this.localParticipant.sid&&e.identity!==this.localParticipant.identity?this.getOrCreateParticipant(e.sid,e):ln.warn("received info to create local participant as remote participant",{info:e,localParticipant:this.localParticipant})})),this.name=i.room.name,this.sid=i.room.sid,this.metadata=i.room.metadata,this._isRecording!==i.room.activeRecording&&(this._isRecording=i.room.activeRecording,this.emit(Vc.RecordingStatusChanged,i.room.activeRecording)),this.emit(Vc.SignalConnected)}catch(e){this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish);const t=new Kc("could not establish signal connection");return e instanceof Error&&(t.message="".concat(t.message,": ").concat(e.message)),e instanceof Kc&&(t.reason=e.reason,t.status=e.status),ln.debug("error trying to establish signal connection",{error:e}),void a(t)}const c=fd.setTimeout((()=>{this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),a(new Kc("could not connect PeerConnection after timeout"))}),this.connOptions.peerConnectionTimeout),l=()=>{ln.warn("closing engine"),fd.clearTimeout(c),this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),a(new Kc("room connection has been cancelled"))};(null===(r=this.abortController)||void 0===r?void 0:r.signal.aborted)&&l(),null===(o=this.abortController)||void 0===o||o.signal.addEventListener("abort",l),this.engine.once(Wc.Connected,(()=>{var e,t;fd.clearTimeout(c),null===(e=this.abortController)||void 0===e||e.signal.removeEventListener("abort",l),Cl()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave),null===(t=navigator.mediaDevices)||void 0===t||t.addEventListener("devicechange",this.handleDeviceChange)),this.setAndEmitConnectionState(kh.Connected),this.emit(Vc.Connected),n()}))}),(()=>{this.clearConnectionFutures()})),this.connectFuture.promise},this.disconnect=async function(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];var i,s,n,a;const r=await t.disconnectLock.lock();try{if(t.state===kh.Disconnected)return void ln.debug("already disconnected");ln.info("disconnect from room",{identity:t.localParticipant.identity}),t.state!==kh.Connecting&&t.state!==kh.Reconnecting||(ln.warn("abort connection attempt"),null===(i=t.abortController)||void 0===i||i.abort(),null===(n=null===(s=t.connectFuture)||void 0===s?void 0:s.reject)||void 0===n||n.call(s,new Kc("Client initiated disconnect")),t.connectFuture=void 0),(null===(a=t.engine)||void 0===a?void 0:a.client.isConnected)&&await t.engine.client.sendLeave(),t.engine&&await t.engine.close(),t.handleDisconnect(e,Ka.CLIENT_INITIATED),t.engine=void 0}finally{r()}},this.onPageLeave=async()=>{await this.disconnect()},this.handleRestarting=()=>{for(const e of this.participants.values())this.handleParticipantDisconnected(e.sid,e);this.setAndEmitConnectionState(kh.Reconnecting)&&this.emit(Vc.Reconnecting)},this.handleRestarted=async e=>{ln.debug("reconnected to server",{region:e.serverRegion});try{e.participant&&(this.localParticipant.sid=e.participant.sid,this.handleParticipantUpdates([e.participant])),this.handleParticipantUpdates(e.otherParticipants);const t=[];this.localParticipant.tracks.forEach((e=>{e.track&&t.push(e)})),await Promise.all(t.map((async e=>{const t=e.track;this.localParticipant.unpublishTrack(t,!1),t.isMuted||((t instanceof cd||t instanceof ld)&&!t.isUserProvided&&(ln.debug("restarting existing track",{track:e.trackSid}),await t.restartTrack()),ln.debug("publishing new track",{track:e.trackSid}),await this.localParticipant.publishTrack(t,e.options))})))}catch(e){ln.error("error trying to re-publish tracks after reconnection",{error:e})}finally{this.setAndEmitConnectionState(kh.Connected),this.emit(Vc.Reconnected)}},this.handleParticipantUpdates=e=>{e.forEach((e=>{if(e.identity===this.localParticipant.identity)return void this.localParticipant.updateInfo(e);const t=this.identityToSid.get(e.identity);t&&t!==e.sid&&this.handleParticipantDisconnected(t,this.participants.get(t));let i=this.participants.get(e.sid);const s=!i;e.state===Xa.DISCONNECTED?this.handleParticipantDisconnected(e.sid,i):(i=this.getOrCreateParticipant(e.sid,e),s||i.updateInfo(e))}))},this.handleActiveSpeakersUpdate=e=>{const t=[],i={};e.forEach((e=>{if(i[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),t.push(this.localParticipant);else{const i=this.participants.get(e.sid);i&&(i.audioLevel=e.level,i.setIsSpeaking(!0),t.push(i))}})),i[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.participants.forEach((e=>{i[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))})),this.activeSpeakers=t,this.emitWhenConnected(Vc.ActiveSpeakersChanged,t)},this.handleSpeakersChanged=e=>{const t=new Map;this.activeSpeakers.forEach((e=>{t.set(e.sid,e)})),e.forEach((e=>{let i=this.participants.get(e.sid);e.sid===this.localParticipant.sid&&(i=this.localParticipant),i&&(i.audioLevel=e.level,i.setIsSpeaking(e.active),e.active?t.set(e.sid,i):t.delete(e.sid))}));const i=Array.from(t.values());i.sort(((e,t)=>t.audioLevel-e.audioLevel)),this.activeSpeakers=i,this.emitWhenConnected(Vc.ActiveSpeakersChanged,i)},this.handleStreamStateUpdate=e=>{e.streamStates.forEach((e=>{const t=this.participants.get(e.participantSid);if(!t)return;const i=t.getTrackPublication(e.trackSid);i&&i.track&&(i.track.streamState=nd.streamStateFromProto(e.state),t.emit($c.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(Vc.TrackStreamStateChanged,i,i.track.streamState,t))}))},this.handleSubscriptionPermissionUpdate=e=>{const t=this.participants.get(e.participantSid);if(!t)return;const i=t.getTrackPublication(e.trackSid);i&&i.setAllowed(e.allowed)},this.handleDataPacket=(e,t)=>{const i=this.participants.get(e.participantSid);this.emit(Vc.DataReceived,e.payload,i,t,e.topic),null==i||i.emit($c.DataReceived,e.payload,t)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(Vc.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=e=>{ln.warn("could not playback audio",e),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(Vc.AudioPlaybackStatusChanged,!1))},this.handleDeviceChange=async()=>{this.emit(Vc.MediaDevicesChanged)},this.handleRoomUpdate=e=>{this._isRecording!==e.activeRecording&&(this._isRecording=e.activeRecording,this.emit(Vc.RecordingStatusChanged,e.activeRecording)),this.metadata!==e.metadata&&(this.metadata=e.metadata,this.emitWhenConnected(Vc.RoomMetadataChanged,e.metadata))},this.handleConnectionQualityUpdate=e=>{e.updates.forEach((e=>{if(e.participantSid===this.localParticipant.sid)return void this.localParticipant.setConnectionQuality(e.quality);const t=this.participants.get(e.participantSid);t&&t.setConnectionQuality(e.quality)}))},this.onLocalParticipantMetadataChanged=e=>{this.emit(Vc.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(Vc.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(Vc.TrackUnmuted,e,this.localParticipant)},this.onLocalTrackPublished=async e=>{if(this.emit(Vc.LocalTrackPublished,e,this.localParticipant),e.track instanceof cd){await e.track.checkForSilence()&&this.emit(Vc.LocalAudioSilenceDetected,e)}},this.onLocalTrackUnpublished=e=>{this.emit(Vc.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalConnectionQualityChanged=e=>{this.emit(Vc.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=e=>{this.emit(Vc.MediaDevicesError,e)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(Vc.ParticipantPermissionsChanged,e,this.localParticipant)},this.setMaxListeners(100),this.participants=new Map,this.identityToSid=new Map,this.options=Gr(Gr({},eh),e),this.options.audioCaptureDefaults=Gr(Gr({},Xd),null==e?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Gr(Gr({},Yd),null==e?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Gr(Gr({},Qd),null==e?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new xl,this.localParticipant=new Hd("","",this.engine,this.options)}maybeCreateEngine(){this.engine||(this.engine=new Eh(this.options),this.engine.client.onParticipantUpdate=this.handleParticipantUpdates,this.engine.client.onRoomUpdate=this.handleRoomUpdate,this.engine.client.onSpeakersChanged=this.handleSpeakersChanged,this.engine.client.onStreamStateUpdate=this.handleStreamStateUpdate,this.engine.client.onSubscriptionPermissionUpdate=this.handleSubscriptionPermissionUpdate,this.engine.client.onConnectionQuality=this.handleConnectionQualityUpdate,this.engine.on(Wc.MediaTrackAdded,((e,t,i)=>{this.onTrackAdded(e,t,i)})).on(Wc.Disconnected,(e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)})).on(Wc.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(Wc.DataPacketReceived,this.handleDataPacket).on(Wc.Resuming,(()=>{this.setAndEmitConnectionState(kh.Reconnecting)&&this.emit(Vc.Reconnecting)})).on(Wc.Resumed,(()=>{this.setAndEmitConnectionState(kh.Connected),this.emit(Vc.Reconnected),this.updateSubscriptions()})).on(Wc.SignalResumed,(()=>{this.state===kh.Reconnecting&&this.sendSyncState()})).on(Wc.Restarting,this.handleRestarting).on(Wc.Restarted,this.handleRestarted),this.localParticipant&&this.localParticipant.setupEngine(this.engine))}static getLocalDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Bl.getInstance().getDevices(e,t)}async prepareConnection(e){await fetch("http".concat(e.substring(2)),{method:"HEAD"})}getParticipantByIdentity(e){if(this.localParticipant.identity===e)return this.localParticipant;const t=this.identityToSid.get(e);return t?this.participants.get(t):void 0}clearConnectionFutures(){this.connectFuture=void 0}get isRecording(){return this._isRecording}async simulateScenario(e){let t,i=()=>{};switch(e){case"signal-reconnect":await this.engine.client.close(),this.engine.client.onClose&&this.engine.client.onClose("simulate disconnect");break;case"speaker":t=Fc.fromPartial({scenario:{$case:"speakerUpdate",speakerUpdate:3}});break;case"node-failure":t=Fc.fromPartial({scenario:{$case:"nodeFailure",nodeFailure:!0}});break;case"server-leave":t=Fc.fromPartial({scenario:{$case:"serverLeave",serverLeave:!0}});break;case"migration":t=Fc.fromPartial({scenario:{$case:"migration",migration:!0}});break;case"resume-reconnect":this.engine.failNext(),await this.engine.client.close(),this.engine.client.onClose&&this.engine.client.onClose("simulate resume-reconnect");break;case"force-tcp":case"force-tls":t=Fc.fromPartial({scenario:{$case:"switchCandidateProtocol",switchCandidateProtocol:"force-tls"===e?2:1}}),i=async()=>{const e=this.engine.client.onLeave;e&&e({reason:Ka.CLIENT_INITIATED,canReconnect:!0})}}t&&(this.engine.client.sendSimulateScenario(t),i())}async startAudio(){await this.acquireAudioContext();const e=[];this.participants.forEach((t=>{t.audioTracks.forEach((t=>{t.track&&t.track.attachedElements.forEach((t=>{e.push(t)}))}))}));try{await Promise.all(e.map((e=>(e.muted=!1,e.play())))),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}}get canPlaybackAudio(){return this.audioEnabled}getActiveAudioOutputDevice(){var e,t;return null!==(t=null===(e=this.options.audioOutput)||void 0===e?void 0:e.deviceId)&&void 0!==t?t:""}async switchActiveDevice(e,t){var i,s;const n=arguments.length>2&&void 0!==arguments[2]&&arguments[2]?{exact:t}:t;if("audioinput"===e){const e=this.options.audioCaptureDefaults.deviceId;this.options.audioCaptureDefaults.deviceId=n;const t=Array.from(this.localParticipant.audioTracks.values()).filter((e=>e.source===nd.Source.Microphone));try{await Promise.all(t.map((e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(n)})))}catch(t){throw this.options.audioCaptureDefaults.deviceId=e,t}}else if("videoinput"===e){const e=this.options.videoCaptureDefaults.deviceId;this.options.videoCaptureDefaults.deviceId=n;const t=Array.from(this.localParticipant.videoTracks.values()).filter((e=>e.source===nd.Source.Camera));try{await Promise.all(t.map((e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(n)})))}catch(t){throw this.options.videoCaptureDefaults.deviceId=e,t}}else if("audiooutput"===e){if(!fl())throw new Error("cannot switch audio output, setSinkId not supported");null!==(i=(s=this.options).audioOutput)&&void 0!==i||(s.audioOutput={});const e=this.options.audioOutput.deviceId;this.options.audioOutput.deviceId=t;try{await Promise.all(Array.from(this.participants.values()).map((e=>e.setAudioOutput({deviceId:t}))))}catch(t){throw this.options.audioOutput.deviceId=e,t}}}setupLocalParticipantEvents(){this.localParticipant.on($c.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on($c.TrackMuted,this.onLocalTrackMuted).on($c.TrackUnmuted,this.onLocalTrackUnmuted).on($c.LocalTrackPublished,this.onLocalTrackPublished).on($c.LocalTrackUnpublished,this.onLocalTrackUnpublished).on($c.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on($c.MediaDevicesError,this.onMediaDevicesError).on($c.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;null===(e=this.engine)||void 0===e||e.close(),this.engine=void 0,this.participants.clear(),this.maybeCreateEngine()}onTrackAdded(e,t,i){if(this.state===kh.Connecting||this.state===kh.Reconnecting){const s=()=>{this.onTrackAdded(e,t,i),n()},n=()=>{this.off(Vc.Reconnected,s),this.off(Vc.Connected,s),this.off(Vc.Disconnected,n)};return this.once(Vc.Reconnected,s),this.once(Vc.Connected,s),void this.once(Vc.Disconnected,n)}if(this.state===kh.Disconnected)return void ln.warn("skipping incoming track after Room disconnected");const s=function(e){const t=e.split(ul);return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(t.id),n=s[0];let a=s[1];if(a&&""!==a||(a=e.id),n===this.localParticipant.sid)return void ln.warn("tried to create RemoteParticipant for local participant");const r=this.getOrCreateParticipant(n);let o;this.options.adaptiveStream&&(o="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{}),r.addSubscribedMediaTrack(e,a,t,i,o)}handleDisconnect(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1?arguments[1]:void 0;var i;this.state!==kh.Disconnected&&(this.participants.forEach((e=>{e.tracks.forEach((t=>{e.unpublishTrack(t.trackSid)}))})),this.localParticipant.tracks.forEach((t=>{var i,s;t.track&&this.localParticipant.unpublishTrack(t.track,e),e&&(null===(i=t.track)||void 0===i||i.detach(),null===(s=t.track)||void 0===s||s.stop())})),this.localParticipant.off($c.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off($c.TrackMuted,this.onLocalTrackMuted).off($c.TrackUnmuted,this.onLocalTrackUnmuted).off($c.LocalTrackPublished,this.onLocalTrackPublished).off($c.LocalTrackUnpublished,this.onLocalTrackUnpublished).off($c.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off($c.MediaDevicesError,this.onMediaDevicesError).off($c.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.tracks.clear(),this.localParticipant.videoTracks.clear(),this.localParticipant.audioTracks.clear(),this.participants.clear(),this.activeSpeakers=[],this.audioContext&&"boolean"==typeof this.options.expWebAudioMix&&(this.audioContext.close(),this.audioContext=void 0),Cl()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),null===(i=navigator.mediaDevices)||void 0===i||i.removeEventListener("devicechange",this.handleDeviceChange)),this.setAndEmitConnectionState(kh.Disconnected),this.emit(Vc.Disconnected,t))}handleParticipantDisconnected(e,t){this.participants.delete(e),t&&(this.identityToSid.delete(t.identity),t.tracks.forEach((e=>{t.unpublishTrack(e.trackSid,!0)})),this.emit(Vc.ParticipantDisconnected,t))}async acquireAudioContext(){var e,t;"boolean"!=typeof this.options.expWebAudioMix&&this.options.expWebAudioMix.audioContext?(this.audioContext=this.options.expWebAudioMix.audioContext,await this.audioContext.resume()):this.audioContext=null!==(e=hl())&&void 0!==e?e:void 0,this.options.expWebAudioMix&&this.participants.forEach((e=>e.setAudioContext(this.audioContext)));const i="running"===(null===(t=this.audioContext)||void 0===t?void 0:t.state);i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(Vc.AudioPlaybackStatusChanged,i))}createParticipant(e,t){let i;return i=t?Jd.fromParticipantInfo(this.engine.client,t):new Jd(this.engine.client,e,"",void 0,void 0),this.options.expWebAudioMix&&i.setAudioContext(this.audioContext),i}getOrCreateParticipant(e,t){if(this.participants.has(e))return this.participants.get(e);const i=this.createParticipant(e,t);return this.participants.set(e,i),t&&(this.identityToSid.set(t.identity,t.sid),this.emitWhenConnected(Vc.ParticipantConnected,i)),i.on($c.TrackPublished,(e=>{this.emitWhenConnected(Vc.TrackPublished,e,i)})).on($c.TrackSubscribed,((e,t)=>{e.kind===nd.Kind.Audio&&(e.on(Jc.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(Jc.AudioPlaybackFailed,this.handleAudioPlaybackFailed)),this.emit(Vc.TrackSubscribed,e,t,i)})).on($c.TrackUnpublished,(e=>{this.emit(Vc.TrackUnpublished,e,i)})).on($c.TrackUnsubscribed,((e,t)=>{this.emit(Vc.TrackUnsubscribed,e,t,i)})).on($c.TrackSubscriptionFailed,(e=>{this.emit(Vc.TrackSubscriptionFailed,e,i)})).on($c.TrackMuted,(e=>{this.emitWhenConnected(Vc.TrackMuted,e,i)})).on($c.TrackUnmuted,(e=>{this.emitWhenConnected(Vc.TrackUnmuted,e,i)})).on($c.ParticipantMetadataChanged,(e=>{this.emitWhenConnected(Vc.ParticipantMetadataChanged,e,i)})).on($c.ConnectionQualityChanged,(e=>{this.emitWhenConnected(Vc.ConnectionQualityChanged,e,i)})).on($c.ParticipantPermissionsChanged,(e=>{this.emitWhenConnected(Vc.ParticipantPermissionsChanged,e,i)})).on($c.TrackSubscriptionStatusChanged,((e,t)=>{this.emitWhenConnected(Vc.TrackSubscriptionStatusChanged,e,t,i)})).on($c.TrackSubscriptionPermissionChanged,((e,t)=>{this.emitWhenConnected(Vc.TrackSubscriptionPermissionChanged,e,t,i)})),t&&i.updateInfo(t),i}sendSyncState(){var e,t;if(void 0===this.engine.subscriber||null===this.engine.subscriber.pc.localDescription)return;const i=this.engine.subscriber.pc.localDescription,s=this.engine.subscriber.pc.remoteDescription,n=null===(t=null===(e=this.connOptions)||void 0===e?void 0:e.autoSubscribe)||void 0===t||t,a=new Array;this.participants.forEach((e=>{e.tracks.forEach((e=>{e.isDesired!==n&&a.push(e.trackSid)}))})),this.engine.client.sendSyncState({answer:Kd({sdp:i.sdp,type:i.type}),offer:s?Kd({sdp:s.sdp,type:s.type}):void 0,subscription:{trackSids:a,subscribe:!n,participantTracks:[]},publishTracks:this.localParticipant.publishedTracksInfo(),dataChannels:this.localParticipant.dataChannelsInfo()})}updateSubscriptions(){for(const e of this.participants.values())for(const t of e.videoTracks.values())t.isSubscribed&&t instanceof Wd&&t.emitTrackUpdate()}setAndEmitConnectionState(e){return e!==this.state&&(this.state=e,this.emit(Vc.ConnectionStateChanged,this.state),!0)}emitWhenConnected(e){if(this.state===kh.Connected){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.emit(e,...i)}return!1}async simulateParticipants(e){var t,i;const s=Gr({audio:!0,video:!0,useRealTracks:!1},e.publish),n=Gr({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.name="simulated-room",this.localParticipant.updateInfo(kr.fromPartial({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(Vc.SignalConnected),this.emit(Vc.Connected),this.setAndEmitConnectionState(kh.Connected),s.video){const e=new wd(nd.Kind.Video,Tr.fromPartial({source:Ha.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Ja.AUDIO,name:"video-dummy"}),new ld(s.useRealTracks?(await navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Al(null!==(t=160*n.aspectRatios[0])&&void 0!==t?t:1,160,!0,!0)));this.localParticipant.addTrackPublication(e),this.localParticipant.emit($c.LocalTrackPublished,e)}if(s.audio){const e=new wd(nd.Kind.Audio,Tr.fromPartial({source:Ha.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Ja.AUDIO}),new cd(s.useRealTracks?(await navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Ol()));this.localParticipant.addTrackPublication(e),this.localParticipant.emit($c.LocalTrackPublished,e)}for(let e=0;e<n.count-1;e+=1){let t=kr.fromPartial({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:Xa.ACTIVE,tracks:[],joinedAt:Date.now()});const s=this.getOrCreateParticipant(t.identity,t);if(n.video){const a=Al(null!==(i=160*n.aspectRatios[e%n.aspectRatios.length])&&void 0!==i?i:1,160,!1,!0),r=Tr.fromPartial({source:Ha.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Ja.AUDIO});s.addSubscribedMediaTrack(a,r.sid,new MediaStream([a])),t.tracks=[...t.tracks,r]}if(n.audio){const e=Ol(),i=Tr.fromPartial({source:Ha.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Ja.AUDIO});s.addSubscribedMediaTrack(e,i.sid,new MediaStream([e])),t.tracks=[...t.tracks,i]}s.updateInfo(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 e!==Vc.ActiveSpeakersChanged&&ln.debug("room event ".concat(e),{event:e,args:i}),super.emit(e,...i)}}var Mh;!function(e){e[e.IDLE=0]="IDLE",e[e.RUNNING=1]="RUNNING",e[e.SKIPPED=2]="SKIPPED",e[e.SUCCESS=3]="SUCCESS",e[e.FAILED=4]="FAILED"}(Mh||(Mh={}));class Rh extends jl.EventEmitter{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.status=Mh.IDLE,this.logs=[],this.errorsAsWarnings=!1,this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Ph(i.roomOptions),this.connectOptions=i.connectOptions,i.errorsAsWarnings&&(this.errorsAsWarnings=i.errorsAsWarnings)}async run(e){if(this.status!==Mh.IDLE)throw Error("check is running already");this.setStatus(Mh.RUNNING),this.appendMessage("".concat(this.name," started."));try{await this.perform()}catch(e){e instanceof Error&&(this.errorsAsWarnings?this.appendWarning(e.message):this.appendError(e.message))}return await this.disconnect(),await new Promise((e=>setTimeout(e,500))),this.status!==Mh.SKIPPED&&this.setStatus(this.isSuccess()?Mh.SUCCESS:Mh.FAILED),e&&e(),this.getInfo()}isSuccess(){return!this.logs.some((e=>"error"===e.level))}async connect(){return this.room.state===kh.Connected||await this.room.connect(this.url,this.token),this.room}async disconnect(){this.room&&this.room.state!==kh.Disconnected&&(await this.room.disconnect(),await new Promise((e=>setTimeout(e,500))))}skip(){this.setStatus(Mh.SKIPPED)}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 null===this.room||void 0===e?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class _h extends t().PureComponent{constructor(e){super(e),this.state={videoRef:void 0,audioRef:void 0},this.handleVideoRefChange=this.handleVideoRefChange.bind(this),this.handleAudioRefChange=this.handleAudioRefChange.bind(this)}componentDidUpdate(e){this.state.videoRef&&!this.state.videoRef.srcObject&&this.props.cameraPub&&this.props.cameraPub.videoTrack&&this.props.cameraPub.videoTrack.attach(this.state.videoRef),this.state.audioRef&&!this.state.audioRef.srcObject&&this.props.micPub&&this.props.micPub.audioTrack&&this.props.micPub.audioTrack.attach(this.state.audioRef)}handleVideoRefChange(e){if(!e)return;this.setState({videoRef:e});const t=this.props.cameraPub;t&&t.isSubscribed&&!t.isMuted&&t.videoTrack&&t.videoTrack.attach(e)}handleAudioRefChange(e){if(!e)return;this.setState({audioRef:e});const t=this.props.micPub;t&&t.isSubscribed&&!t.isMuted&&this.state.audioTrack&&this.state.audioTrack.attach(e)}render(){let e="call-party carousel-item";this.props.isSpeaking&&(e+=" call-party-speaking");const i=this.props.micPub,s=this.props.cameraPub;return t().createElement("div",{className:e},t().createElement(t().Fragment,null,t().createElement("video",{ref:this.handleVideoRefChange}),t().createElement("audio",{ref:this.handleAudioRefChange}),i&&i.isMuted?t().createElement("i",{className:"material-icons muted"},"mic_off"):null,s&&s.isMuted?t().createElement(t().Fragment,null,t().createElement("div",{className:"avatar-box carousel-item"},t().createElement(Si.Z,{tinode:this.props.tinode,avatar:this.props.photo,topic:this.props.identity,title:this.props.name}))):null,t().createElement("div",{className:"caller-name inactive"},this.props.name)))}}class Nh extends t().Component{constructor(e){super(e),this.handlePrevClick=this.handlePrevClick.bind(this),this.handleNextClick=this.handleNextClick.bind(this),this.carouselRef=t().createRef(),this.contentRef=t().createRef(),this.prevRef=t().createRef(),this.nextRef=t().createRef()}handlePrevClick(){const e=this.carouselRef.current.offsetWidth;this.carouselRef.current.scrollBy(-(e+16),0),this.carouselRef.current.scrollLeft-e-16<=0&&(this.prevRef.current.style.display="none"),!this.contentRef.current.scrollWidth-e-16<=this.carouselRef.current.scrollLeft+e&&(this.nextRef.current.style.display="flex")}handleNextClick(){const e=this.carouselRef.current.offsetWidth;this.carouselRef.current.scrollBy(e+16,0),0!==this.carouselRef.current.scrollWidth&&(this.prevRef.current.style.display="flex"),this.contentRef.current.scrollWidth-e-16<=this.carouselRef.current.scrollLeft+e&&(this.nextRef.current.style.display="none")}render(){let e=[];return this.props.participants&&Object.entries(this.props.participants).forEach(((i,s)=>{let[n,a]=i;const r=a.participant,o=r.getTrack(nd.Source.Camera),c=r.getTrack(nd.Source.Microphone);e.push(t().createElement(_h,{tinode:this.props.tinode,isSpeaking:r.isSpeaking,cameraPub:o||null,micPub:c||null,name:a.name,identity:n,photo:a.photo,key:s}))})),t().createElement(t().Fragment,null,t().createElement("div",{id:"carousel-wrapper"},t().createElement("div",{id:"carousel",ref:this.carouselRef},t().createElement("div",{id:"carousel-content",ref:this.contentRef},e)),t().createElement("button",{id:"carousel-prev",ref:this.prevRef,onClick:this.handlePrevClick},t().createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24"},t().createElement("path",{fill:"none",d:"M0 0h24v24H0V0z"}),t().createElement("path",{d:"M15.61 7.41L14.2 6l-6 6 6 6 1.41-1.41L11.03 12l4.58-4.59z"}))),t().createElement("button",{id:"carousel-next",ref:this.nextRef,onClick:this.handleNextClick},t().createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24"},t().createElement("path",{fill:"none",d:"M0 0h24v24H0V0z"}),t().createElement("path",{d:"M10.02 6L8.61 7.41 13.19 12l-4.58 4.59L10.02 18l6-6-6-6z"})))))}}class Dh extends t().PureComponent{constructor(e){super(e),this.state={room:void 0,participants:{},activeSpeaker:void 0,previousOnInfo:void 0},this.isOutgoingCall=e.callState==Xi;const i=this.props.tinode.getTopic(this.props.topic);this.isBroadcast=i&&i.chan,this.localRef=t().createRef(),this.remoteRef=t().createRef(),this.onInfo=this.onInfo.bind(this),this.start=this.start.bind(this),this.stop=this.stop.bind(this),this.reportError=this.reportError.bind(this),this.handleCloseClick=this.handleCloseClick.bind(this),this.handleToggleCameraClick=this.handleToggleCameraClick.bind(this),this.handleToggleMicClick=this.handleToggleMicClick.bind(this),this.handleRemoteHangup=this.handleRemoteHangup.bind(this),this.handleTrackSubscribed=this.handleTrackSubscribed.bind(this),this.handleTrackUnsubscribed=this.handleTrackUnsubscribed.bind(this),this.handleActiveSpeakerChange=this.handleActiveSpeakerChange.bind(this),this.handleDisconnect=this.handleDisconnect.bind(this),this.handleLocalTrackUnpublished=this.handleLocalTrackUnpublished.bind(this),this.handleLocalTrackPublished=this.handleLocalTrackPublished.bind(this),this.handleParticipantConnected=this.handleParticipantConnected.bind(this),this.handleParticipantDisconnected=this.handleParticipantDisconnected.bind(this),this.handleData=this.handleData.bind(this),this.handleDevicesChanged=this.handleDevicesChanged.bind(this),this.startRoom=this.startRoom.bind(this),this.participants={}}componentDidMount(){const e=this.props.tinode.getTopic(this.props.topic);this.previousOnInfo=e.onInfo,e.onInfo=this.onInfo,this.start()}componentWillUnmount(){this.props.tinode.getTopic(this.props.topic).onInfo=this.previousOnInfo,this.stop()}onInfo(e){if("call"==e.what)switch(e.event){case"vc-token":const t=e.payload;this.setState({token:t.token}),this.startRoom(t.token);break;case"hang-up":this.handleRemoteHangup(e);break;default:console.warn("Unknown call event",e.event)}}handleParticipantConnected(e){if(e&&e instanceof Jd){e.on($c.TrackMuted,(t=>{console.log("track was muted",t.trackSid,e.identity),this.forceUpdate()})).on($c.TrackUnmuted,(t=>{console.log("track was unmuted",t.trackSid,e.identity),this.forceUpdate()})).on($c.IsSpeakingChanged,(e=>{this.forceUpdate()})).on($c.ConnectionQualityChanged,(e=>{this.forceUpdate()}));const t=this.props.tinode.getMeTopic().getContact(e.identity),i={name:t&&t.public&&t.public.fn?t.public.fn:e.identity,photo:(0,Ni.PD)(t&&t.public?t.public.photo:null),participant:e};this.participants[e.identity]=i,console.log("participant connected",this.participants),this.setState({participants:this.participants},(e=>{this.forceUpdate()}))}}handleParticipantDisconnected(e){console.log("Deleting participant ",e.identity),delete this.participants[e.identity],this.setState({participants:this.participants})}handleData(e,t){console.log("Data message ",e,t)}handleTrackSubscribed(e,t,i){i instanceof Jd&&this.remoteRef.current&&""==this.remoteRef.current.src&&!this.remoteRef.srcObject&&e.attach(this.remoteRef.current),this.forceUpdate()}handleTrackUnsubscribed(e,t,i){console.log("handleTrackUnsubscribed",e),e.detach(),this.forceUpdate()}handleLocalTrackPublished(e){console.log("Local track published",e);const t=e.track;if(t instanceof ld&&this.localRef.current){const e=this.localRef.current;t.attach(e),e.style.transform="scale(-1, 1)"}}handleLocalTrackUnpublished(e){const t=e.track;console.log("handleLocalTrackUnpublished",t),t.detach(),this.forceUpdate()}handleActiveSpeakerChange(e){console.log("handleActiveSpeakerChange",e),e.forEach((e=>{if(e.isSpeaking){console.log("Speaking participant ",e);const t=this.remoteRef.current,i=this.props.tinode.getMeTopic().getContact(e.identity),s=i&&i.public&&i.public.fn?i.public.fn:void 0;this.setState({activeSpeaker:s});const n=e.getTrack(nd.Source.Camera);n&&n.isSubscribed&&!n.isMuted&&n.videoTrack&&n.videoTrack.attach(t)}}))}handleDevicesChanged(){console.log("devices changed")}handleDisconnect(){console.log("disconnected from room"),this.handleCloseClick()}startRoom(e){const t={adaptiveStream:!0,dynacast:!0,publishDefaults:{simulcast:!0,videoSimulcastLayers:[Pd.h90,Pd.h216],videoCodec:"vp8"},videoCaptureDefaults:{resolution:Pd.h720.resolution}},i=new Ph(t);this.setState({room:i});const s=Date.now(),n=(this.props.tinode.getTopic(this.props.topic),this.isOutgoingCall||!this.isBroadcast);i.on(Vc.ParticipantConnected,this.handleParticipantConnected).on(Vc.ParticipantDisconnected,this.handleParticipantDisconnected).on(Vc.DataReceived,this.handleData).on(Vc.TrackSubscribed,this.handleTrackSubscribed).on(Vc.TrackUnsubscribed,this.handleTrackUnsubscribed).on(Vc.ActiveSpeakersChanged,this.handleActiveSpeakerChange).on(Vc.Disconnected,this.handleDisconnect).on(Vc.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(Vc.LocalTrackPublished,this.handleLocalTrackPublished).on(Vc.RoomMetadataChanged,(e=>{console.log("VC room new metadata ",e)})).on(Vc.MediaDevicesChanged,this.handleDevicesChanged).on(Vc.AudioPlaybackStatusChanged,(e=>{console.log("Audio playback status change: ",e)})).on(Vc.MediaDevicesError,(e=>{const t=jc.getFailure(e);this.reportError(t)})).on(Vc.ConnectionQualityChanged,((e,t)=>{const i=t?t.identity:"nil";console.log("Connection quality changed",i," -> ",e)})).on(Vc.SignalConnected,(e=>{const t=Date.now()-s;console.log(`signal connection established in ${t}ms`),n&&(i.localParticipant.enableCameraAndMicrophone(),console.log(`tracks published in ${Date.now()-s}ms`))}));const a=this.props.tinode.getServerParam("vcEndpoint",null);i.connect(a,e,{autoSubscribe:!0}).then((t=>{console.log("Connected to VC room",i.name,". Access token",e),i.participants.forEach((e=>{this.handleParticipantConnected(e)})),this.handleParticipantConnected(i.localParticipant)}))}start(){this.state.localStream?this.props.onError(this.props.intl.formatMessage(messages.already_in_call),"info"):this.isOutgoingCall?this.props.onCreateCall(this.props.topic,this.props.seq,this.props.callState,this.props.callAudioOnly).then((e=>{const t=e.params.token,i=e.params.seq;this.setState({callSeq:i,token:t}),this.startRoom(t)})):this.props.onJoin(this.props.topic,this.props.seq)}stop(){this.state.room&&this.state.room.disconnect()}reportError(e){this.props.onError(e.message,"err")}handleRemoteHangup(){this.handleCloseClick()}handleCloseClick(){this.stop(),this.props.onHangup(this.props.topic,this.props.seq)}handleToggleCameraClick(){if(!this.state.room)return;const e=this.state.room.localParticipant.isCameraEnabled;this.state.room.localParticipant.setCameraEnabled(!e).then((e=>this.forceUpdate())),this.forceUpdate()}handleToggleMicClick(){if(!this.state.room)return;const e=this.state.room.localParticipant.isMicrophoneEnabled;this.state.room.localParticipant.setMicrophoneEnabled(!e).then((e=>this.forceUpdate())),this.forceUpdate()}render(){const e=this.isOutgoingCall||!this.isBroadcast,i=!e||!this.state.room||!this.state.room.localParticipant,n=!i&&this.state.room.localParticipant.isMicrophoneEnabled?"mic":"mic_off",a=!i&&this.state.room.localParticipant.isCameraEnabled?"videocam":"videocam_off",r=this.state.activeSpeaker?this.state.activeSpeaker:(0,Di.Th)(this.props.title,mi.gD),o=this.remoteRef.current&&(this.remoteRef.current.src||this.remoteRef.current.srcObject);return t().createElement(t().Fragment,null,t().createElement("div",{id:"video-container"},!this.isBroadcast&&Object.keys(this.state.participants).length>0?t().createElement(Nh,{tinode:this.props.tinode,participants:this.state.participants}):null,t().createElement("div",{id:"video-container-panel"},e?t().createElement("div",{className:"call-party self",disabled:this.state.audioOnly},t().createElement("video",{ref:this.localRef,autoPlay:!0,muted:!0,playsInline:!0}),t().createElement("div",{className:"caller-name inactive"},t().createElement(s.FormattedMessage,{id:"calls_you_label",defaultMessage:[{type:0,value:"You"}]}))):null,t().createElement("div",{className:"call-party peer",disabled:!o},t().createElement("video",{ref:this.remoteRef,autoPlay:!0,playsInline:!0}),o?t().createElement(t().Fragment,null,t().createElement("div",{className:"caller-name inactive"},r)):t().createElement(t().Fragment,null,t().createElement("div",{className:"caller-card"},t().createElement("div",{className:"avatar-box"},t().createElement(Si.Z,{tinode:this.props.tinode,avatar:this.props.avatar,topic:this.props.topic,title:this.props.title})),t().createElement("div",{className:"caller-name"},r))))),t().createElement("div",{className:"controls"},t().createElement("button",{className:"danger",onClick:this.handleCloseClick},t().createElement("i",{className:"material-icons"},"call_end")),t().createElement("button",{className:"secondary",onClick:this.handleToggleCameraClick,disabled:i},t().createElement("i",{className:"material-icons"},a)),t().createElement("button",{className:"secondary",onClick:this.handleToggleMicClick,disabled:i},t().createElement("i",{className:"material-icons"},n)))))}}const Ih=(0,s.injectIntl)(Dh),Ah=(0,s.defineMessages)({unrecognized_video_format:{id:"unrecognized_video_format",defaultMessage:[{type:0,value:"Format of this video is not recognized"}]}});class Oh extends t().PureComponent{constructor(e){super(e),this.videoRef=t().createRef(),this.handleSendVideo=this.handleSendVideo.bind(this),this.handleKeyDown=this.handleKeyDown.bind(this)}componentDidMount(){document.addEventListener("keydown",this.handleKeyDown)}componentWillUnmount(){document.removeEventListener("keydown",this.handleKeyDown)}handleKeyDown(e){this.props.onSendMessage||(e.preventDefault(),"Escape"===e.key&&this.props.onClose())}handleSendVideo(e){this.props.onClose();const t={width:this.videoRef.current.videoWidth,height:this.videoRef.current.videoHeight,duration:1e3*this.videoRef.current.duration|0,mime:this.props.content.mime,name:this.props.content.filename};if(0==t.width||0==t.height)return void this.props.onError(this.props.intl.formatMessage(Ah.unrecognized_video_format),"err");const i=document.createElement("canvas");i.width=t.width,i.height=t.height;const s=i.getContext("2d");s.drawImage(this.videoRef.current,0,0,i.width,i.height),s.canvas.toBlob((i=>this.props.onSendMessage(e,this.props.content.blob,i,t)),"image/jpeg",.75)}render(){if(!this.props.content)return null;const e=this.props.content.width||"-",i=this.props.content.height||"-",n=this.props.onSendMessage?"nodownload":"",a=!this.props.onSendMessage;return t().createElement("div",{id:"image-preview"},t().createElement("div",{id:"image-preview-caption-panel"},t().createElement("span",null,this.props.content.filename),t().createElement("a",{href:"#",onClick:e=>{e.preventDefault(),this.props.onClose()}},t().createElement("i",{className:"material-icons gray"},"close"))),t().createElement("div",{id:"image-preview-container"},t().createElement("video",{className:"image-preview",controls:!0,controlsList:n,disablePictureInPicture:!0,ref:this.videoRef,autoPlay:a,src:this.props.tinode.authorizeURL(this.props.content.url),poster:this.props.content.preview,alt:this.props.content.filename})),this.props.onSendMessage?t().createElement(Hs,{messagePrompt:"add_image_caption",acceptBlank:!0,tinode:this.props.tinode,reply:this.props.reply,onCancelReply:this.props.onCancelReply,onSendMessage:this.handleSendVideo,onError:this.props.onError}):t().createElement("div",{id:"image-preview-footer"},t().createElement("div",null,t().createElement("div",null,t().createElement("b",null,t().createElement(s.FormattedMessage,{id:"label_file_name",defaultMessage:[{type:0,value:"File name:"}]}))),t().createElement("div",null,t().createElement("span",{title:this.props.content.filename},this.props.content.filename))),t().createElement("div",null,t().createElement("div",null,t().createElement("b",null,t().createElement(s.FormattedMessage,{id:"label_content_type",defaultMessage:[{type:0,value:"Content type:"}]}))),t().createElement("div",null,this.props.content.type)),t().createElement("div",null,t().createElement("div",null,t().createElement("b",null,t().createElement(s.FormattedMessage,{id:"label_size",defaultMessage:[{type:0,value:"Size:"}]}))),t().createElement("div",null,e," × ",i," px; ",(0,ki.FK)(this.props.content.size)))))}}const Uh=(0,s.injectIntl)(Oh);var xh=r(5030);const Lh=(0,s.defineMessages)({online_now:{id:"online_now",defaultMessage:[{type:0,value:"online now"}]},last_seen:{id:"last_seen_timestamp",defaultMessage:[{type:0,value:"Last seen"}]},not_found:{id:"title_not_found",defaultMessage:[{type:0,value:"Not found"}]},channel:{id:"channel",defaultMessage:[{type:0,value:"channel"}]},file_attachment_too_large:{id:"file_attachment_too_large",defaultMessage:[{type:0,value:"The file size "},{type:1,value:"size"},{type:0,value:" exceeds the "},{type:1,value:"limit"},{type:0,value:" limit."}]},invalid_content:{id:"invalid_content",defaultMessage:[{type:0,value:"invalid content"}]},editing_message:{id:"editing_message",defaultMessage:[{type:0,value:"Editing"}]},drag_file:{id:"drag_file",defaultMessage:[{type:0,value:"Drag file here"}]}});function Fh(e){if(e){const t=e.getExcessive()||"";return e.isJoiner("given")&&(t.includes("R")||t.includes("W"))}return!1}function Bh(e){if(e){const t=e.getMissing()||"";return e.isJoiner("want")&&(t.includes("R")||t.includes("W"))}return!1}function qh(e){return e==Xi||e==Yi}class jh extends t().Component{constructor(e){super(e),this.state=jh.getDerivedStateFromProps(e,{}),this.componentSetup=this.componentSetup.bind(this),this.leave=this.leave.bind(this),this.sendMessage=this.sendMessage.bind(this),this.retrySend=this.retrySend.bind(this),this.sendImageAttachment=this.sendImageAttachment.bind(this),this.sendVideoAttachment=this.sendVideoAttachment.bind(this),this.sendFileAttachment=this.sendFileAttachment.bind(this),this.sendAudioAttachment=this.sendAudioAttachment.bind(this),this.sendKeyPress=this.sendKeyPress.bind(this),this.subscribe=this.subscribe.bind(this),this.handleScrollReference=this.handleScrollReference.bind(this),this.mountDnDEvents=this.mountDnDEvents.bind(this),this.handleScrollEvent=this.handleScrollEvent.bind(this),this.handleDescChange=this.handleDescChange.bind(this),this.handleSubsUpdated=this.handleSubsUpdated.bind(this),this.handleMessageUpdate=this.handleMessageUpdate.bind(this),this.handleAuxUpdate=this.handleAuxUpdate.bind(this),this.handleAllMessagesReceived=this.handleAllMessagesReceived.bind(this),this.handleInfoReceipt=this.handleInfoReceipt.bind(this),this.handleExpandMedia=this.handleExpandMedia.bind(this),this.handleClosePreview=this.handleClosePreview.bind(this),this.handleFormResponse=this.handleFormResponse.bind(this),this.handleContextClick=this.handleContextClick.bind(this),this.handleShowMessageContextMenu=this.handleShowMessageContextMenu.bind(this),this.handleNewChatAcceptance=this.handleNewChatAcceptance.bind(this),this.handleEnablePeer=this.handleEnablePeer.bind(this),this.handleAttachFile=this.handleAttachFile.bind(this),this.handleAttachImageOrVideo=this.handleAttachImageOrVideo.bind(this),this.handleCancelUpload=this.handleCancelUpload.bind(this),this.postReadNotification=this.postReadNotification.bind(this),this.clearNotificationQueue=this.clearNotificationQueue.bind(this),this.goToLatestMessage=this.goToLatestMessage.bind(this),this.handleFileDrop=this.handleFileDrop.bind(this),this.handlePickReply=this.handlePickReply.bind(this),this.handleEditMessage=this.handleEditMessage.bind(this),this.handleCancelReply=this.handleCancelReply.bind(this),this.handleQuoteClick=this.handleQuoteClick.bind(this),this.handleUnpinMessage=this.handleUnpinMessage.bind(this),this.handleCallHangup=this.handleCallHangup.bind(this),this.isDragEnabled=this.isDragEnabled.bind(this),this.handleDragStart=this.handleDragStart.bind(this),this.handleDragIn=this.handleDragIn.bind(this),this.handleDragOut=this.handleDragOut.bind(this),this.handleDrag=this.handleDrag.bind(this),this.handleDrop=this.handleDrop.bind(this),this.chatMessageRefs=[],this.getOrCreateMessageRef=this.getOrCreateMessageRef.bind(this),this.getVisibleMessageRange=this.getVisibleMessageRange.bind(this),this.dragCounter=0,this.dndRef=null,this.readNotificationQueue=[],this.readNotificationTimer=null,this.keyPressTimer=null}getOrCreateMessageRef(e){if(this.chatMessageRefs[e])return this.chatMessageRefs[e];const i=t().createRef();return this.chatMessageRefs[e]=i,i}getVisibleMessageRange(e){let t=Number.MAX_SAFE_INTEGER,i=-1;return this.chatMessageRefs.forEach(((s,n)=>{if(s.current){const{top:a,bottom:r,height:o}=s.current.getBoundingClientRect();(a<=e.top?e.top-a<=o:r-e.bottom<=o)&&(t=Math.min(t,n),i=Math.max(i,n))}})),i>=t?{min:t,max:i}:{min:0,max:0}}componentDidMount(){this.messagesScroller&&this.messagesScroller.addEventListener("scroll",this.handleScrollEvent),this.mountDnDEvents(this.dndRef),this.componentSetup({},{})}componentWillUnmount(){this.messagesScroller&&this.messagesScroller.removeEventListener("scroll",this.handleScrollEvent),this.clearNotificationQueue(),this.dndRef&&(this.dndRef.removeEventListener("dragstart",this.handleDragStart),this.dndRef.removeEventListener("dragenter",this.handleDragIn),this.dndRef.removeEventListener("dragleave",this.handleDragOut),this.dndRef.removeEventListener("dragover",this.handleDrag),this.dndRef.removeEventListener("drop",this.handleDrop))}componentDidUpdate(e,t){!this.messagesScroller||t.topic==this.state.topic&&t.maxSeqId==this.state.maxSeqId&&t.minSeqId==this.state.minSeqId||this.state.scrollPosition<100&&(this.messagesScroller.scrollTop=this.messagesScroller.scrollHeight-this.state.scrollPosition-this.messagesScroller.offsetHeight),this.props.applicationVisible?this.postReadNotification(0):this.clearNotificationQueue(),this.componentSetup(e,t)}componentSetup(e,t){const i=this.props.tinode?this.props.tinode.getTopic(this.state.topic):void 0;if(this.state.topic!=t.topic&&(t.topic&&!ui.Tinode.isNewGroupTopicName(t.topic)&&(this.leave(t.topic),t.rtcPanel&&this.handleCallHangup(t.topic,e.callSeq)),i&&(i.onData=this.handleMessageUpdate,i.onAllMessagesReceived=this.handleAllMessagesReceived,i.onInfo=this.handleInfoReceipt,i.onMetaDesc=this.handleDescChange,i.onSubsUpdated=this.handleSubsUpdated,i.onPres=this.handleSubsUpdated,i.onAuxUpdated=this.handleAuxUpdate)),i)if(this.state.topic!=t.topic||this.props.myUserId&&!e.myUserId){const e=this.props.newTopicParams&&this.props.newTopicParams._topicName==this.props.topic;i.isP2PType()&&e&&!mi.FX?i.getMeta(i.startMetaQuery().withDesc().build()):this.props.myUserId&&this.subscribe(i)}else i.isSubscribed()&&this.state.isReader&&!t.isReader&&i.getMeta(i.startMetaQuery().withLaterData().build())}static getDerivedStateFromProps(e,t){let i={};if(e.topic)if(e.topic!=t.topic){const s=e.tinode.getTopic(e.topic);if(i={topic:e.topic,deleted:s._deleted,docPreview:null,imagePreview:null,imagePostview:null,videoPreview:null,videoPostview:null,rtcPanel:null,typingIndicator:!1,scrollPosition:0,fetchingMessages:!1,showGoToLastButton:!1,contentToEdit:null,dragging:!1,selectedPin:0},e.forwardMessage?i.reply={content:e.forwardMessage.preview,seq:null}:i.reply=null,s){const n=[];e.connected&&s.subscribers((t=>{t.online&&t.user!=e.myUserId&&n.push(t)})),Object.assign(i,{onlineSubs:n}),s.public?Object.assign(i,{title:s.public.fn,avatar:(0,Ni.PD)(s.public.photo)}):Object.assign(i,{title:"",avatar:null});const a=s.p2pPeerDesc();a?Object.assign(i,{peerMessagingDisabled:Bh(a.acs)}):t.peerMessagingDisabled&&Object.assign(i,{peerMessagingDisabled:!1}),Object.assign(i,{minSeqId:s.minMsgSeq(),maxSeqId:s.maxMsgSeq(),latestClearId:s.maxClearId(),channel:s.isChannelType(),pins:(s.aux("pins")||[]).slice()}),e.callTopic==s.name&&qh(e.callState)&&(i.rtcPanel=e.callTopic)}else Object.assign(i,{minSeqId:-1,maxSeqId:-1,latestClearId:-1,onlineSubs:[],title:"",avatar:null,peerMessagingDisabled:!1,channel:!1,pins:[]})}else e.callTopic==t.topic&&!t.rtcPanel&&qh(e.callState)&&(i.rtcPanel=e.callTopic);else i={minSeqId:-1,maxSeqId:-1,latestClearId:-1,onlineSubs:[],topic:null,title:"",avatar:null,isVerified:!1,isStaff:!1,isDangerous:!1,deleted:!1,docPreview:null,imagePreview:null,imagePostview:null,videoPreview:null,videoPostview:null,rtcPanel:null,typingIndicator:!1,scrollPosition:0,fetchingMessages:!1,peerMessagingDisabled:!1,channel:!1,reply:null,contentToEdit:null,showGoToLastButton:!1,dragging:!1,pins:[],selectedPin:0};return e.acs?(e.acs.isWriter()!=t.isWriter&&(i.isWriter=!t.isWriter),e.acs.isReader()!=t.isReader&&(i.isReader=!t.isReader),e.acs.isAdmin()!=t.isAdmin&&(i.isAdmin=!t.isAdmin),!e.acs.isReader("given")!=t.readingBlocked&&(i.readingBlocked=!t.readingBlocked),e.acs.isSharer()!=t.isSharer&&(i.isSharer=!t.isSharer)):(t.isWriter&&(i.isWriter=!1),t.isReader&&(i.isReader=!1),t.isAdmin&&(i.isAdmin=!1),t.readingBlocked||(t.readingBlocked=!0),t.isSharer&&(i.isSharer=!1)),Fh(e.acs)==!t.unconformed&&(i.unconfirmed=!t.unconformed),!e.connected&&t.onlineSubs&&t.onlineSubs.length>0&&(i.onlineSubs=[]),i}subscribe(e){if(e.isSubscribed()||!this.props.ready)return;const t=this.props.newTopicParams&&this.props.newTopicParams._topicName==this.props.topic;let i=e.startMetaQuery().withLaterDesc().withLaterSub().withAux();(this.state.isReader||t)&&(i=i.withLaterData(mi.Hm),this.state.isReader&&(i=i.withLaterDel()),this.setState({fetchingMessages:!0}));const s=t?this.props.newTopicParams:void 0;e.subscribe(i.build(),s).then((t=>{if(303==t.code)return void xh.Z.navigateTo(xh.Z.setUrlTopic("",t.params.topic));this.state.topic!=t.topic&&this.setState({topic:t.topic}),this.state.deleted&&this.setState({deleted:!1}),this.props.onNewTopicCreated(this.props.topic,t.topic);let i=[];e.queuedMessages((t=>{t._sending||(t._fatal||t.head&&t.head.webrtc?i.push(t.seq):e.isSubscribed()&&this.retrySend(t))})),i.length>0&&e.delMessagesList(i,!0)})).catch((e=>{console.error("Failed subscription to",this.state.topic,e),this.props.onError(e.message,"err");const t=jh.getDerivedStateFromProps({},{});t.title=this.props.intl.formatMessage(Lh.not_found),this.setState(t)}))}leave(e){if(!e||!this.props.tinode.isTopicCached(e))return;const t=this.props.tinode.getTopic(e);t&&t.isSubscribed()&&t.leave(!1).catch((e=>{})).finally((e=>{this.setState({fetchingMessages:!1}),t.onData=void 0,t.onAllMessagesReceived=void 0,t.onInfo=void 0,t.onMetaDesc=void 0,t.onSubsUpdated=void 0,t.onPres=void 0,t.onAuxUpdated=void 0}))}handleScrollReference(e){e&&(e.addEventListener("scroll",this.handleScrollEvent),this.messagesScroller=e,this.messagesScroller.scrollTop=this.messagesScroller.scrollHeight-this.state.scrollPosition-this.messagesScroller.offsetHeight)}handleScrollEvent(e){const t=e.target.scrollHeight-e.target.scrollTop-e.target.offsetHeight;if(this.setState({scrollPosition:t,showGoToLastButton:t>100&&t<this.state.scrollPosition}),!this.state.fetchingMessages&&e.target.scrollTop<=40){const t=this.props.tinode.getTopic(this.state.topic);if(t&&t.isSubscribed()){const{min:i,max:s}=this.getVisibleMessageRange(e.target.getBoundingClientRect()),n=t.msgHasMoreMessages(i,s,!1);n.length>0&&this.setState({fetchingMessages:!0},(e=>{t.getMessagesPage(mi.Hm,n,i,s).catch((e=>this.props.onError(e.message,"err"))).finally((e=>this.setState({fetchingMessages:!1})))}))}}}mountDnDEvents(e){e&&(e.addEventListener("dragstart",this.handleDragStart),e.addEventListener("dragenter",this.handleDragIn),e.addEventListener("dragleave",this.handleDragOut),e.addEventListener("dragover",this.handleDrag),e.addEventListener("drop",this.handleDrop),this.dndRef=e)}goToLatestMessage(){this.setState({scrollPosition:0}),this.messagesScroller&&(this.messagesScroller.scrollTop=this.messagesScroller.scrollHeight-this.messagesScroller.offsetHeight)}handleDescChange(e){e.public?this.setState({title:e.public.fn,avatar:(0,Ni.PD)(e.public.photo)}):this.setState({title:"",avatar:null}),e.acs&&this.setState({isWriter:e.acs.isWriter(),isReader:e.acs.isReader(),isAdmin:e.acs.isAdmin(),readingBlocked:!e.acs.isReader("given"),unconfirmed:Fh(e.acs)})}postReadNotification(e){if(!this.props.applicationVisible)return;this.readNotificationTimer||(this.readNotificationTimer=setInterval((e=>{if(0==this.readNotificationQueue.length)return clearInterval(this.readNotificationTimer),void(this.readNotificationTimer=null);let t=-1;for(;this.readNotificationQueue.length>0;){const e=this.readNotificationQueue[0];if(e.topicName!=this.state.topic){this.readNotificationQueue.shift();continue}const i=new Date;if(!(e.sendAt<=i))break;this.readNotificationQueue.shift(),t=Math.max(t,e.seq)}if(t>=0){const e=this.props.tinode.getTopic(this.state.topic);e&&e.noteRead(t)}}),300));const t=new Date;this.readNotificationQueue.push({topicName:this.state.topic,seq:e,sendAt:t.setMilliseconds(t.getMilliseconds()+mi.l8)})}clearNotificationQueue(){this.readNotificationQueue=[],this.readNotificationTimer&&(clearInterval(this.readNotificationTimer),this.readNotificationTimer=null)}handleSubsUpdated(){if(this.state.topic){const e=[],t=this.props.tinode.getTopic(this.state.topic);t.subscribers((t=>{t.online&&t.user!=this.props.myUserId&&e.push(t)}));const i={onlineSubs:e},s=t.p2pPeerDesc();s?Object.assign(i,{peerMessagingDisabled:Bh(s.acs)}):this.state.peerMessagingDisabled&&Object.assign(i,{peerMessagingDisabled:!1}),this.setState(i)}}handleMessageUpdate(e){if(!this.state.topic)return;const t=this.props.tinode.getTopic(this.state.topic);if(!e)return void this.setState({latestClearId:t.maxClearId()});clearTimeout(this.keyPressTimer),this.setState({maxSeqId:t.maxMsgSeq(),minSeqId:t.minMsgSeq(),typingIndicator:!1},(i=>{t.isNewMessage(e.seq)?this.state.scrollPosition>100?this.setState({showGoToLastButton:!0}):this.goToLatestMessage():this.messagesScroller&&(this.messagesScroller.scrollTop=this.messagesScroller.scrollHeight-this.state.scrollPosition-this.messagesScroller.offsetHeight)}));t.msgStatus(e,!0)>=ui.Tinode.MESSAGE_STATUS_SENT&&e.from!=this.props.myUserId&&this.postReadNotification(e.seq)}handleAllMessagesReceived(e){this.setState({fetchingMessages:!1}),e>0&&this.postReadNotification(0);this.props.tinode.getTopic(this.state.topic).getPinnedMessages()}handleAuxUpdate(e){const t=(e.pins||[]).slice();let i=this.state.selectedPin;t.length>this.state.pins.length?i=0:i>=t.length&&(i=Math.max(0,t.length-1)),this.setState({pins:t,selectedPin:i})}handleInfoReceipt(e){switch(e.what){case"kp":clearTimeout(this.keyPressTimer),this.keyPressTimer=setTimeout((e=>this.setState({typingIndicator:!1})),mi.mc+1e3),this.state.typingIndicator||this.setState({typingIndicator:!0});break;case"read":case"recv":this.forceUpdate();break;default:console.info("Other change in topic: ",e.what)}}handleExpandMedia(e){e&&(e.video?this.setState({videoPostview:e}):this.setState({imagePostview:e}))}handleClosePreview(){this.state.imagePreview&&this.state.imagePreview.url&&URL.revokeObjectURL(this.state.imagePreview.url),this.state.videoPreview&&this.state.videoPreview.url&&URL.revokeObjectURL(this.state.videoPreview.url),this.setState({imagePostview:null,imagePreview:null,docPreview:null,videoPreview:null,videoPostview:null})}handleFormResponse(e,t,i){if("pub"==e)this.sendMessage(ui.Drafty.attachJSON(ui.Drafty.parse(t),i));else if("url"==e){const e=new URL(i.ref),t=e.searchParams;for(let e in i.resp)i.resp.hasOwnProperty(e)&&t.set(e,i.resp[e]);["name","seq"].forEach((e=>{i[e]&&t.set(e,i[e])})),t.set("uid",this.props.myUserId),t.set("topic",this.state.topic),e.search=t,window.open(e,"_blank")}else console.info("Unknown action in form",e)}handleContextClick(e){e.preventDefault(),e.stopPropagation(),this.props.showContextMenu({topicName:this.state.topic,y:e.pageY,x:e.pageX})}handleShowMessageContextMenu(e,t){"chan"==e.userFrom&&(e.userFrom=this.state.topic,e.userName=this.state.title),e.topicName=this.state.topic;const i=t||[],s=this.props.tinode.getTopic(e.topicName);if(s){s.isChannelType()||i.push("message_delete");const e=s.getAccessMode();e&&e.isDeleter()&&i.push("message_delete_hard")}this.props.showContextMenu(e,i)}handleNewChatAcceptance(e){this.props.onNewChat(this.state.topic,e)}handleEnablePeer(e){e.preventDefault(),this.props.onChangePermissions(this.state.topic,mi.RK,this.state.topic)}sendKeyPress(e){const t=this.props.tinode.getTopic(this.state.topic);t.isSubscribed()&&(e?t.noteRecording(!0):t.noteKeyPress())}sendMessage(e,t,i){let s;if(this.props.forwardMessage)e=this.props.forwardMessage.msg,s=this.props.forwardMessage.head,this.handleCancelReply();else if(this.state.reply){if(this.state.reply.editing){if(e==this.state.contentToEdit)return void this.handleCancelReply();s={replace:":"+this.state.reply.seq}}else this.state.reply.content&&(s={reply:""+this.state.reply.seq},"string"==typeof e&&(e=ui.Drafty.parse(e)),e=ui.Drafty.append(ui.Drafty.sanitizeEntities(this.state.reply.content),e));this.handleCancelReply()}this.props.sendMessage(e,t,i,s)}retrySend(e){this.props.sendMessage(e.content,void 0,void 0,e.head).then((t=>{this.props.tinode.getTopic(this.state.topic).delMessagesList([e.seq],!0)}))}sendFileAttachment(e){const t=.75*this.props.tinode.getServerParam("maxMessageSize",mi.kd)-1024|0;if(e.size>t){const t=this.props.tinode.getLargeFileHelper();if(!t)return void this.props.onError(this.props.intl.formatMessage(Lh.cannot_initiate_upload));const i=t.upload(e),s=ui.Drafty.attachFile(null,{mime:e.type,filename:e.name,size:e.size,urlPromise:i});this.sendMessage(s,i,t)}else(0,Ni.sT)(e).then((t=>this.sendMessage(ui.Drafty.attachFile(null,{mime:t.mime,data:t.bits,filename:t.name,size:e.size})))).catch((e=>this.props.onError(e.message,"err")))}handleAttachFile(e){const t=this.props.tinode.getServerParam("maxFileUploadSize",mi.GQ);e.size>t?this.props.onError(this.props.intl.formatMessage(Lh.file_attachment_too_large,{size:(0,ki.FK)(e.size),limit:(0,ki.FK)(t)}),"err"):this.setState({docPreview:{file:e,name:e.name,size:e.size,type:e.type}})}handleCallHangup(e,t){this.props.onVideoCallClosed(),this.setState({rtcPanel:null}),this.props.onCallHangup(e,t)}sendImageAttachment(e,t){const i=this.state.imagePreview.mime,s=this.state.imagePreview.width,n=this.state.imagePreview.height,a=this.state.imagePreview.filename,r=.75*this.props.tinode.getServerParam("maxMessageSize",mi.kd)-1024|0;if(t.size>r){const r=this.props.tinode.getLargeFileHelper();if(!r)return void this.props.onError(this.props.intl.formatMessage(Lh.cannot_initiate_upload));const o=r.upload(t);(0,Ni.EA)(t,mi.H2,mi.H2,-1,!1).then((e=>(0,Ni.w8)(e.blob))).then((c=>{let l=ui.Drafty.insertImage(null,0,{mime:i,_tempPreview:c.bits,bits:c.bits,width:s,height:n,filename:a,size:t.size,urlPromise:o});e&&(l=ui.Drafty.appendLineBreak(l),l=ui.Drafty.append(l,ui.Drafty.parse(e))),this.sendMessage(l,o,r)})).catch((e=>this.props.onError(e,"err")))}else(0,Ni.w8)(t).then((i=>{let r=ui.Drafty.insertImage(null,0,{mime:i.mime,bits:i.bits,width:s,height:n,filename:a,size:t.size});e&&(r=ui.Drafty.appendLineBreak(r),r=ui.Drafty.append(r,ui.Drafty.parse(e))),this.sendMessage(r)}))}sendVideoAttachment(e,t,i,s){const n=s.width,a=s.height,r=.75*this.props.tinode.getServerParam("maxMessageSize",mi.kd)-1024|0,o=[];let c;if(t.size+i.size>r){if(c=this.props.tinode.getLargeFileHelper(),!c)return void this.props.onError(this.props.intl.formatMessage(Lh.cannot_initiate_upload));o[0]=t.size>.675*r?c.upload(t):null,o[1]=i.size>.275*r?c.upload(i):null}if(0==o.length)return void Promise.all([(0,Ni.w8)(t),(0,Ni.w8)(i)]).then((i=>{const[r,o]=i;let c=ui.Drafty.insertVideo(null,0,{mime:r.mime,bits:r.bits,preview:o.bits,premime:o.mime,width:n,height:a,duration:s.duration,filename:s.name,size:t.size});e&&(c=ui.Drafty.appendLineBreak(c),c=ui.Drafty.append(c,ui.Drafty.parse(e))),this.sendMessage(c)}));const l=Promise.all(o),d=[];d[0]=o[0]?null:(0,Ni.w8)(t),d[1]=o[1]?null:(0,Ni.EA)(i,mi.yW,mi.yW,-1,!1).then((e=>(0,Ni.w8)(e.blob))),d[2]=(0,Ni.EA)(i,mi.ly,mi.ly,-1,!1).then((e=>(0,Ni.w8)(e.blob))),Promise.all(d).then((i=>{const[r,o,d]=i;let h=ui.Drafty.insertVideo(null,0,{mime:s.mime,bits:r?r.bits:null,_tempPreview:d.bits,preview:o?o.bits:d.bits,premime:o?o.mime:d.mime,width:n,height:a,duration:s.duration,filename:s.name,size:t.size,urlPromise:l});e&&(h=ui.Drafty.appendLineBreak(h),h=ui.Drafty.append(h,ui.Drafty.parse(e))),this.sendMessage(h,l,c)})).catch((e=>this.props.onError(e.message,"err")))}handleAttachImageOrVideo(e){const t=this.props.tinode.getServerParam("maxFileUploadSize",mi.GQ);e.type.startsWith("video/")?this.setState({videoPreview:{url:URL.createObjectURL(e),blob:e,filename:e.name,size:e.size,mime:e.type}}):(0,Ni.EA)(e,mi.yW,mi.yW,t,!1).then((e=>{this.setState({imagePreview:{url:URL.createObjectURL(e.blob),blob:e.blob,filename:e.name,width:e.width,height:e.height,size:e.blob.size,mime:e.mime}})})).catch((e=>{this.props.onError(e.message,"err")}))}handleFileDrop(e){if(!e||0==e.length)return;const t=e[0];t.type&&t.type.startsWith("image/")?this.handleAttachImageOrVideo(t):this.handleAttachFile(t)}sendAudioAttachment(e,t,i){fetch(e).then((e=>e.blob())).then((e=>{const s=.75*this.props.tinode.getServerParam("maxMessageSize",mi.kd)-1024;if(e.size>s){const s=this.props.tinode.getLargeFileHelper();if(!s)return void this.props.onError(this.props.intl.formatMessage(Lh.cannot_initiate_upload));const n=s.upload(e),a=ui.Drafty.appendAudio(null,{mime:e.type,size:e.size,duration:i,preview:t,urlPromise:n});this.sendMessage(a,n,s)}else(0,Ni.w8)(e).then((s=>{this.sendMessage(ui.Drafty.appendAudio(null,{mime:s.mime,bits:s.bits,size:e.size,duration:i,preview:t}))}))})).catch((e=>{this.props.onError(e.message,"err")}))}handleCancelUpload(e,t){const i=this.props.tinode.getTopic(this.state.topic).findMessage(e);i&&(i._cancelled=!0),t.cancel()}handlePickReply(e,t,i,s){e&&t?(t="string"==typeof t?ui.Drafty.init(t):t,t=ui.Drafty.isValid(t)?ui.Drafty.replyContent(t,mi.cl):ui.Drafty.append(ui.Drafty.init("⚠ "),ui.Drafty.wrapInto(this.props.intl.formatMessage(Lh.invalid_content),"EM")),this.setState({reply:{content:ui.Drafty.quote(s,i,t),seq:e}}),this.props.onCancelForwardMessage()):this.setState({reply:null})}handleEditMessage(e,t){if(!e||!t)return void this.setState({reply:null});t="string"==typeof t?ui.Drafty.init(t):t;const i=ui.Drafty.toMarkdown(t);t=ui.Drafty.isValid(t)?ui.Drafty.replyContent(t,mi.nT):ui.Drafty.append(ui.Drafty.init("⚠ "),ui.Drafty.wrapInto(this.props.intl.formatMessage(Lh.invalid_content),"EM")),this.setState({reply:{content:ui.Drafty.quote(this.props.intl.formatMessage(Lh.editing_message),null,t),seq:e,editing:!0},contentToEdit:i}),this.props.onCancelForwardMessage()}handleCancelReply(){this.setState({reply:null,contentToEdit:null}),this.props.onCancelForwardMessage()}handleQuoteClick(e){const t=this.getOrCreateMessageRef(e);t&&t.current?(t.current.scrollIntoView({block:"center",behavior:"smooth"}),t.current.classList.add("flash"),setTimeout((e=>{t.current.classList.remove("flash")}),1e3)):console.error("Unresolved message ref",e)}handleUnpinMessage(e){this.props.tinode.getTopic(this.state.topic).pinMessage(e,!1)}isDragEnabled(){return this.state.isWriter&&!this.state.unconfirmed&&!this.props.forwardMessage&&!this.state.peerMessagingDisabled}handleDragStart(e){e.preventDefault(),e.stopPropagation(),e.dataTransfer.clearData()}handleDragIn(e){e.preventDefault(),e.stopPropagation(),this.dragCounter++,e.dataTransfer.items&&e.dataTransfer.items.length>0&&this.setState({dragging:!0})}handleDragOut(e){e.preventDefault(),e.stopPropagation(),this.dragCounter--,this.dragCounter<=0&&this.setState({dragging:!1})}handleDrag(e){e.preventDefault(),e.stopPropagation()}handleDrop(e){e.preventDefault(),e.stopPropagation(),this.setState({dragging:!1}),this.isDragEnabled()&&e.dataTransfer.files&&e.dataTransfer.files.length>0&&(this.handleFileDrop(e.dataTransfer.files),this.dragCounter=0)}render(){const{formatMessage:e}=this.props.intl;let i;if(this.state.topic){let n;if(this.state.imagePreview)n=t().createElement(Zs,{content:this.state.imagePreview,tinode:this.props.tinode,reply:this.state.reply,onCancelReply:this.handleCancelReply,onClose:this.handleClosePreview,onSendMessage:this.sendImageAttachment});else if(this.state.videoPreview)n=t().createElement(Uh,{content:this.state.videoPreview,tinode:this.props.tinode,reply:this.state.reply,onError:this.props.onError,onCancelReply:this.handleCancelReply,onClose:this.handleClosePreview,onSendMessage:this.sendVideoAttachment});else if(this.state.imagePostview)n=t().createElement(Zs,{content:this.state.imagePostview,onClose:this.handleClosePreview});else if(this.state.videoPostview)n=t().createElement(Uh,{content:this.state.videoPostview,tinode:this.props.tinode,onError:this.props.onError,onClose:this.handleClosePreview});else if(this.state.docPreview)n=t().createElement(Gs,{content:this.state.docPreview,tinode:this.props.tinode,reply:this.state.reply,onCancelReply:this.handleCancelReply,onClose:this.handleClosePreview,onSendMessage:this.sendFileAttachment});else if(this.state.rtcPanel)n=ui.Tinode.isP2PTopicName(this.state.rtcPanel)?t().createElement(Os,{topic:this.state.topic,seq:this.props.callSeq,callState:this.props.callState,callAudioOnly:this.props.callAudioOnly,tinode:this.props.tinode,title:this.state.title,avatar:this.state.avatar||!0,onError:this.props.onError,onHangup:this.handleCallHangup,onInvite:this.props.onCallInvite,onSendOffer:this.props.onCallSendOffer,onIceCandidate:this.props.onCallIceCandidate,onSendAnswer:this.props.onCallSendAnswer}):t().createElement(Ih,{topic:this.state.topic,seq:this.props.callSeq,callState:this.props.callState,callAudioOnly:this.props.callAudioOnly,tinode:this.props.tinode,title:this.state.title,avatar:this.state.avatar||!0,myUid:this.props.myUserId,onError:this.props.onError,onHangup:this.handleCallHangup,onCreateCall:this.props.onCallInvite,onJoin:this.props.onVCJoin});else{const i=this.props.tinode.getTopic(this.state.topic),a=i.isChannelType(),r=i.isGroupType()&&!a,o=[];i.trusted&&(i.trusted.verified&&o.push({icon:"verified",color:"badge-inv"}),i.trusted.staff&&o.push({icon:"staff",color:"badge-inv"}),i.trusted.danger&&o.push({icon:"dangerous",color:"badge-inv"}));const c=[];this.state.pins.forEach((e=>c.push(i.latestMsgVersion(e)||i.findMessage(e))));const l=[];let d=null,h=null,u=null;i.messages(((e,s,n,a)=>{let o=n?n.from||"chan":null,c="single",p=e.from||"chan";p==d?c=p==o?"middle":"last":p==o&&(c="first"),d=p;const m=!(p==this.props.myUserId),g=i.msgStatus(e,!0);let f,v,b=p;const y=i.userDesc(p);y&&y.public&&(f=y.public.fn,v=(0,Ni.PD)(y.public.photo)),u=r?"chat-box group":"chat-box";const S=this.getOrCreateMessageRef(e.seq);let w=e.head?parseInt(e.head.reply):null;if(w&&!isNaN(w)||(w=null),e.hi)l.push(t().createElement(Ys,{deleted:!0,key:e.seq}));else{const i=new Date(e.ts);h&&h.toDateString()==i.toDateString()||(l.push(t().createElement(Ys,{date:(0,ki.EZ)(e.ts),locale:this.props.intl.locale,key:"date-"+e.seq})),h=i),l.push(t().createElement(Vs,{tinode:this.props.tinode,topic:this.state.topic,content:e.content,mimeType:e.head&&e.head.mime,replyToSeq:w,edited:e.head&&!e.head.webrtc&&e.head.replace,timestamp:e.ts,response:m,seq:e.seq,isGroup:r,isChan:this.state.channel,userFrom:b,userName:f,userAvatar:v,sequence:c,received:g,uploader:e._uploader,userIsWriter:this.state.isWriter,userIsAdmin:this.state.isAdmin,pinned:this.state.pins.includes(e.seq),viewportWidth:this.props.viewportWidth,showContextMenu:this.handleShowMessageContextMenu,onExpandMedia:this.handleExpandMedia,onFormResponse:this.handleFormResponse,onCancelUpload:this.handleCancelUpload,pickReply:this.handlePickReply,editMessage:this.handleEditMessage,onQuoteClick:this.handleQuoteClick,onAcceptCall:this.props.onAcceptCall,onError:this.props.onError,ref:S,key:e.seq}))}}));let p=null;if(a)p=e(Lh.channel);else{const t=this.props.tinode.getMeTopic().getContact(this.state.topic);t&&ui.Tinode.isP2PTopicName(t.topic)&&(t.online?p=e(Lh.online_now):t.seen&&(p=e(Lh.last_seen)+": "+(0,ki.pz)(t.seen.when,this.props.intl.locale)))}const m=this.state.avatar||!0,g=this.state.deleted?null:this.props.online?"online"+(this.state.typingIndicator?" typing":""):"offline",f="panel-title"+(this.state.deleted?" deleted":"");let v=t().createElement(t().Fragment,null,t().createElement("div",{id:"messages-container"},t().createElement("button",{className:"action-button"+(this.state.showGoToLastButton?"":" hidden"),onClick:this.goToLatestMessage},t().createElement("i",{className:"material-icons"},"arrow_downward")),t().createElement("div",{id:"messages-panel",ref:this.handleScrollReference},t().createElement("ul",{id:"scroller",className:u},l)),this.state.isReader?null:t().createElement("div",{id:"write-only-background"},this.state.readingBlocked?t().createElement("div",{id:"write-only-note"},t().createElement(s.FormattedMessage,{id:"messages_not_readable",defaultMessage:[{type:0,value:"no access to messages"}]})):null)),this.state.peerMessagingDisabled&&!this.state.unconfirmed?t().createElement("div",{id:"peer-messaging-disabled-note"},t().createElement("i",{className:"material-icons secondary"},"block")," ",t().createElement(s.FormattedMessage,{id:"peers_messaging_disabled",defaultMessage:[{type:0,value:"Peer's messaging is disabled."}]})," ",t().createElement("a",{href:"#",onClick:this.handleEnablePeer},t().createElement(s.FormattedMessage,{id:"enable_peers_messaging",defaultMessage:[{type:0,value:"Enable"}]})),"."):null,this.state.unconfirmed?t().createElement(Ks,{onAction:this.handleNewChatAcceptance}):t().createElement(Hs,{tinode:this.props.tinode,topicName:this.state.topic,noInput:!!this.props.forwardMessage,disabled:!this.state.isWriter||this.state.deleted,reply:this.state.reply,initMessage:this.state.contentToEdit,onKeyPress:this.sendKeyPress,onRecordingProgress:this.sendKeyPress,onSendMessage:this.sendMessage,onAttachFile:this.props.forwardMessage?null:this.handleAttachFile,onAttachImage:this.props.forwardMessage?null:this.handleAttachImageOrVideo,onAttachAudio:this.props.forwardMessage?null:this.sendAudioAttachment,onError:this.props.onError,onQuoteClick:this.handleQuoteClick,onCancelReply:this.handleCancelReply}));n=t().createElement(t().Fragment,null,t().createElement("div",{id:"topic-caption-panel",className:"caption-panel"},this.props.displayMobile?t().createElement("a",{href:"#",id:"hide-message-view",onClick:e=>{e.preventDefault(),this.props.onHideMessagesView()}},t().createElement("i",{className:"material-icons"},"arrow_back")):null,t().createElement("div",{className:"avatar-box"},t().createElement(Si.Z,{tinode:this.props.tinode,avatar:m,topic:this.state.topic,title:this.state.title,deleted:this.state.deleted}),a?null:t().createElement("span",{className:g})),t().createElement("div",{id:"topic-title-group"},t().createElement("div",{id:"topic-title",className:f},this.state.title||t().createElement("i",null,t().createElement(s.FormattedMessage,{id:"unnamed_topic",defaultMessage:[{type:0,value:"Unnamed"}]})),t().createElement(yi,{badges:o})),t().createElement("div",{id:"topic-last-seen"},p)),t().createElement("div",{style:{marginLeft:"auto"}}),this.props.displayMobile?null:t().createElement(tn,{tinode:this.props.tinode,messages:c,selected:this.state.selectedPin,isAdmin:this.state.isAdmin,setSelected:e=>this.setState({selectedPin:e}),onSelected:this.handleQuoteClick,onCancel:this.handleUnpinMessage}),r?t().createElement(zs,{tinode:this.props.tinode,subscribers:this.state.onlineSubs}):null,t().createElement("div",null,t().createElement("a",{href:"#",onClick:this.handleContextClick},t().createElement("i",{className:"material-icons"},"more_vert")))),this.props.displayMobile?t().createElement(t().Fragment,null,t().createElement(tn,{tinode:this.props.tinode,messages:c,selected:this.state.selectedPin,isAdmin:this.state.isAdmin,setSelected:e=>this.setState({selectedPin:e}),onSelected:this.handleQuoteClick,onCancel:this.handleUnpinMessage}),t().createElement(rs,{level:this.props.errorLevel,text:this.props.errorText,onClearError:this.props.onError})):null,t().createElement(Qs.Z,{show:this.state.fetchingMessages}),v,this.state.dragging&&this.isDragEnabled()?t().createElement("div",{className:"drag-n-drop"},e(Lh.drag_file)):null)}i=t().createElement("div",{id:"topic-view",ref:this.mountDnDEvents},n)}else i=t().createElement(Xs,{serverVersion:this.props.serverVersion,serverAddress:this.props.serverAddress});return i}}const Vh=(0,s.injectIntl)(jh);class $h extends t().PureComponent{render(){return t().createElement("a",{href:"#",onClick:e=>{e.preventDefault(),this.props.onBack()}},t().createElement("i",{className:"material-icons"},"arrow_back"))}}class Wh extends t().PureComponent{render(){return t().createElement("div",null,t().createElement("a",{href:"#",onClick:e=>{e.preventDefault(),this.props.onNewTopic()}},t().createElement("i",{className:"material-icons"},"chat"))," ",t().createElement("a",{href:"#",onClick:e=>{e.preventDefault(),this.props.onSettings()}},t().createElement("i",{className:"material-icons"},"settings")))}}class Jh extends t().PureComponent{render(){return t().createElement("div",null,t().createElement("a",{href:"#",onClick:e=>{e.preventDefault(),this.props.onSignUp()}},t().createElement("i",{className:"material-icons"},"person_add"))," ",t().createElement("a",{href:"#",onClick:e=>{e.preventDefault(),this.props.onSettings()}},t().createElement("i",{className:"material-icons"},"settings")))}}class Hh extends t().PureComponent{render(){const e=[];this.props.trustedBadges&&this.props.trustedBadges.forEach((t=>{e.push({icon:t,color:"badge-inv"})}));let i=null;return this.props.tinode&&(i=this.props.tinode.authorizeURL((0,Di.Fv)(this.props.avatar,"image"))),t().createElement("div",{id:"side-caption-panel",className:"caption-panel"},this.props.onCancel?t().createElement($h,{onBack:this.props.onCancel}):null,i?t().createElement("div",{id:"self-avatar",className:"avatar-box"},t().createElement(Si.Z,{tinode:this.props.tinode,avatar:i,topic:this.props.myUserId,title:this.props.title})):null,t().createElement("div",{id:"sidepanel-title",className:"panel-title"},this.props.title,t().createElement(yi,{badges:e})),"login"===this.props.state?t().createElement(Jh,{onSignUp:this.props.onSignUp,onSettings:this.props.onSettings}):"contacts"===this.props.state?t().createElement(Wh,{onNewTopic:this.props.onNewTopic,onSettings:this.props.onSettings}):null)}}const Gh=(0,s.defineMessages)({archived_contacts_title:{id:"archived_contacts",defaultMessage:[{type:0,value:"Archived contacts ("},{type:1,value:"count"},{type:0,value:")"}]}});class zh extends t().Component{constructor(e){super(e),this.handleAction=this.handleAction.bind(this),this.state=zh.deriveStateFromProps(e)}static deriveStateFromProps(e){const t=[];let i=0,s=0;return e.chatList.forEach((n=>{const a=n.acs&&!n.acs.isJoiner();a&&e.blocked&&t.push(n),a||e.blocked||(n.private&&n.private.arch?e.archive?t.push(n):s++:e.archive||(t.push(n),i+=n.unread>0?1:0))})),t.sort(((e,t)=>(t.touched||0)-(e.touched||0))),s>0&&t.push({action:"archive",title:Gh.archived_contacts_title,values:{count:s}}),{contactList:t,unreadThreads:i}}componentDidUpdate(e,t){if(e.chatList!=this.props.chatList||e.archive!=this.props.archive||e.blocked!=this.props.blocked){const e=zh.deriveStateFromProps(this.props);this.setState(e),e.unreadThreads!=t.unreadThreads&&(0,Di.J_)(e.unreadThreads)}}handleAction(e){this.props.onShowArchive()}render(){return t().createElement(s.FormattedMessage,{id:"contacts_not_found",defaultMessage:[{type:0,value:"You have no chats"},{type:0,value:"<br/>"},{type:0,value:"¯∖_(ツ)_/¯"}]},(e=>t().createElement(zi,{tinode:this.props.tinode,connected:this.props.connected,contacts:this.state.contactList,emptyListMessage:e,topicSelected:this.props.topicSelected,myUserId:this.props.myUserId,showOnline:!0,showUnread:!0,onTopicSelected:this.props.onTopicSelected,showContextMenu:this.props.showContextMenu,onAction:this.handleAction})))}}class Zh extends t().PureComponent{constructor(e){super(e),this.handleCheckboxClick=this.handleCheckboxClick.bind(this)}handleCheckboxClick(e,t){"sound"==e?this.props.onToggleMessageSounds(t):"alert"==e?this.props.onTogglePushNotifications(t):"incognito"==e&&this.props.onToggleIncognitoMode(t)}render(){return t().createElement("div",{className:"scrollable-panel"},t().createElement("div",{className:"panel-form-row"},t().createElement("label",{htmlFor:"message-sound"},t().createElement(s.FormattedMessage,{id:"label_message_sound",defaultMessage:[{type:0,value:"Message sound:"}]})),t().createElement(ns.Z,{name:"sound",id:"message-sound",checked:this.props.messageSounds,onChange:this.handleCheckboxClick})),t().createElement("div",{className:"panel-form-row"},t().createElement("label",{htmlFor:"desktop-alerts"},this.props.desktopAlertsEnabled?t().createElement(s.FormattedMessage,{id:"label_push_notifications",defaultMessage:[{type:0,value:"Notification alerts:"}]}):t().createElement(s.FormattedMessage,{id:"label_push_notifications_disabled",defaultMessage:[{type:0,value:"Notification alerts (requires HTTPS):"}]})),t().createElement(ns.Z,{name:"alert",id:"desktop-alerts",checked:this.props.desktopAlerts,onChange:this.props.desktopAlertsEnabled?this.handleCheckboxClick:null})),t().createElement("div",{className:"panel-form-row"},t().createElement("label",{htmlFor:"incognito-mode"},t().createElement(s.FormattedMessage,{id:"label_incognito_mode",defaultMessage:[{type:0,value:"Incognito mode:"}]})),t().createElement(ns.Z,{name:"incognito",id:"incognito-mode",checked:this.props.incognitoMode,onChange:this.handleCheckboxClick})))}}const Kh=(0,s.defineMessages)({delete_account:{id:"delete_account",defaultMessage:[{type:0,value:"Delete account"}]},delete_account_warning:{id:"delete_account_warning",defaultMessage:[{type:0,value:"Are you sure you want to delete your account? It cannot be undone."}]}});class Qh extends t().Component{constructor(e){super(e);const t=this.props.tinode.getMeTopic();let i=0;t.contacts((e=>{e.acs&&!e.acs.isJoiner()&&i++}));const s=t.getDefaultAccess();this.state={auth:s?s.auth:null,anon:s?s.anon:null,showPermissionEditorFor:void 0,blockedCount:i},this.handlePasswordUpdate=this.handlePasswordUpdate.bind(this),this.handleLaunchPermissionsEditor=this.handleLaunchPermissionsEditor.bind(this),this.handleHidePermissionsEditor=this.handleHidePermissionsEditor.bind(this),this.handlePermissionsChanged=this.handlePermissionsChanged.bind(this),this.handleDeleteAccount=this.handleDeleteAccount.bind(this)}handlePasswordUpdate(e){this.setState({password:e}),this.props.onUpdatePassword(e)}handleLaunchPermissionsEditor(e){this.setState({showPermissionEditorFor:e,editedPermissions:this.state[e]})}handleHidePermissionsEditor(){this.setState({showPermissionEditorFor:void 0})}handlePermissionsChanged(e){let t={};t[this.state.showPermissionEditorFor]=e,this.props.onUpdateAccountDesc("me",void 0,void 0,t);let i={showPermissionEditorFor:void 0};i[this.state.showPermissionEditorFor]=e,this.setState(i)}handleDeleteAccount(e){e.preventDefault();const{formatMessage:t}=this.props.intl;this.props.onShowAlert(t(Kh.delete_account),t(Kh.delete_account_warning),(e=>this.props.onDeleteAccount()),null,!0,null)}render(){return t().createElement(t().Fragment,null,this.state.showPermissionEditorFor?t().createElement(ms,{mode:this.state.editedPermissions,skip:"O",onSubmit:this.handlePermissionsChanged,onCancel:this.handleHidePermissionsEditor}):t().createElement("div",{className:"scrollable-panel"},t().createElement("div",{className:"panel-form-column"},t().createElement("label",{className:"small"},t().createElement(s.FormattedMessage,{id:"label_password",defaultMessage:[{type:0,value:"Password"}]})),t().createElement("div",null,t().createElement(s.FormattedMessage,{id:"password_unchanged_prompt",defaultMessage:[{type:0,value:"Unchanged"}]},(e=>t().createElement(vs,{placeholder:e,type:"password",onFinished:this.handlePasswordUpdate}))))),t().createElement("div",{className:"hr"}),t().createElement("div",{className:"panel-form-column"},t().createElement("a",{href:"#",className:"danger flat-button",onClick:e=>{e.preventDefault(),this.props.onLogout()}},t().createElement("i",{className:"material-icons"},"exit_to_app"),"  ",t().createElement(s.FormattedMessage,{id:"button_logout",defaultMessage:[{type:0,value:"Logout"}]})),t().createElement("a",{href:"#",className:"danger flat-button",onClick:e=>{this.handleDeleteAccount(e)}},t().createElement("i",{className:"material-icons"},"delete"),"  ",t().createElement(s.FormattedMessage,{id:"button_delete_account",defaultMessage:[{type:0,value:"Delete account"}]}))),t().createElement("div",{className:"hr"}),t().createElement("div",{className:"panel-form-column"},t().createElement("div",null,t().createElement("label",{className:"small"},t().createElement(s.FormattedMessage,{id:"label_default_access_mode",defaultMessage:[{type:0,value:"Default access mode:"}]}))),t().createElement("div",{className:"quoted"},t().createElement("div",null,"Auth: ",t().createElement("tt",{className:"clickable",onClick:this.handleLaunchPermissionsEditor.bind(this,"auth")},this.state.auth)),t().createElement("div",null,"Anon: ",t().createElement("tt",{className:"clickable",onClick:this.handleLaunchPermissionsEditor.bind(this,"anon")},this.state.anon)))),this.state.blockedCount>0?t().createElement(t().Fragment,null,t().createElement("div",{className:"hr"}),t().createElement("div",{className:"panel-form-row"},t().createElement("i",{className:"material-icons"},"block")," ",t().createElement("a",{href:"#",className:"gray",onClick:e=>{e.preventDefault(),this.props.onShowBlocked()}},t().createElement(s.FormattedMessage,{id:"blocked_contacts_link",defaultMessage:[{type:0,value:"Blocked contacts ("},{type:1,value:"count"},{type:0,value:")"}],values:{count:this.state.blockedCount}})))):null))}}const Xh=(0,s.injectIntl)(Qh);class Yh extends t().PureComponent{render(){return t().createElement("div",{className:"scrollable-panel"},t().createElement("div",{className:"panel-form-column"},t().createElement("a",{href:mi.li,className:"flat-button",target:"_blank"},t().createElement("i",{className:"material-icons"},"email"),"  ",t().createElement(s.FormattedMessage,{id:"link_contact_us",defaultMessage:[{type:0,value:"Contact Us"}]})),t().createElement("a",{href:mi.S9,className:"flat-button",target:"_blank"},t().createElement("i",{className:"material-icons"},"description"),"  ",t().createElement(s.FormattedMessage,{id:"link_terms_of_service",defaultMessage:[{type:0,value:"Terms of Service"}]})),t().createElement("a",{href:mi.NW,className:"flat-button",target:"_blank"},t().createElement("i",{className:"material-icons"},"policy"),"  ",t().createElement(s.FormattedMessage,{id:"link_privacy_policy",defaultMessage:[{type:0,value:"Privacy Policy"}]}))),t().createElement("div",{className:"hr"}),t().createElement("div",{className:"panel-form-column"},t().createElement("div",{className:"panel-form-row"},t().createElement("label",{className:"small"},t().createElement(s.FormattedMessage,{id:"label_client",defaultMessage:[{type:0,value:"Client:"}]})),mi.iC),t().createElement("div",{className:"panel-form-row"},t().createElement("label",{className:"small"},t().createElement(s.FormattedMessage,{id:"label_sdk",defaultMessage:[{type:0,value:"SDK:"}]})),ui.Tinode.getLibrary()),t().createElement("div",{className:"panel-form-row"},t().createElement("label",{className:"small"},t().createElement(s.FormattedMessage,{id:"label_server",defaultMessage:[{type:0,value:"Server:"}]})),this.props.serverVersion),t().createElement("div",{className:"panel-form-row"},t().createElement("label",{className:"small"},t().createElement(s.FormattedMessage,{id:"label_server_address",defaultMessage:[{type:0,value:"Server address:"}]})),this.props.serverAddress)))}}class eu extends t().Component{constructor(e){super(e),this.state={login:e.login,password:"",hostName:e.serverAddress,saveToken:e.persist},this.handleLoginChange=this.handleLoginChange.bind(this),this.handlePasswordChange=this.handlePasswordChange.bind(this),this.handleToggleSaveToken=this.handleToggleSaveToken.bind(this),this.handleSubmit=this.handleSubmit.bind(this)}handleLoginChange(e){this.setState({login:e.target.value})}handlePasswordChange(e){this.setState({password:e.target.value})}handleToggleSaveToken(){this.props.onPersistenceChange(!this.state.saveToken),this.setState({saveToken:!this.state.saveToken})}handleSubmit(e){e.preventDefault(),this.props.onLogin(this.state.login.trim(),this.state.password.trim())}render(){let e="primary";return this.props.disabled&&(e+=" disabled"),t().createElement("form",{id:"login-form",onSubmit:this.handleSubmit},t().createElement(s.FormattedMessage,{id:"login_prompt",defaultMessage:[{type:0,value:"Login"}]},(e=>t().createElement("input",{type:"text",id:"inputLogin",placeholder:e,autoComplete:"username",autoCorrect:"off",autoCapitalize:"none",value:this.state.login,onChange:this.handleLoginChange,required:!0,autoFocus:!0}))),t().createElement(s.FormattedMessage,{id:"password_prompt",defaultMessage:[{type:0,value:"Password"}]},(e=>t().createElement(fs.Z,{type:"password",id:"inputPassword",placeholder:e,autoComplete:"current-password",value:this.state.password,onChange:this.handlePasswordChange,required:!0}))),t().createElement("div",{className:"panel-form-row"},t().createElement(ns.Z,{id:"save-token",name:"save-token",checked:this.state.saveToken,onChange:this.handleToggleSaveToken}),t().createElement("label",{htmlFor:"save-token"}," ",t().createElement(s.FormattedMessage,{id:"stay_logged_in",defaultMessage:[{type:0,value:"Stay logged in"}]})),t().createElement("a",{href:"#reset"},t().createElement(s.FormattedMessage,{id:"forgot_password_link",defaultMessage:[{type:0,value:"Forgot password?"}]}))),t().createElement("div",{className:"dialog-buttons"},t().createElement("button",{className:e,type:"submit"},t().createElement(s.FormattedMessage,{id:"button_sign_in",defaultMessage:[{type:0,value:"Sign in"}]}))))}}const tu=(0,s.defineMessages)({invalid_id:{id:"error_invalid_id",defaultMessage:[{type:0,value:"Invalid ID"}]}});class iu extends t().PureComponent{constructor(e){super(e),this.state={groupId:""},this.handleChange=this.handleChange.bind(this),this.handleKeyPress=this.handleKeyPress.bind(this),this.handleSubmit=this.handleSubmit.bind(this)}handleChange(e){this.setState({groupId:e.target.value})}handleKeyPress(e){"Enter"===e.key&&this.handleSubmit(e)}handleSubmit(e){if(e.preventDefault(),this.state.groupId){const e=this.state.groupId.trim(),t=e.substr(0,3);e.length>3&&["usr","grp","chn"].includes(t)?this.props.onSubmit(e):this.props.onError(this.props.intl.formatMessage(tu.invalid_id),"err")}}render(){return t().createElement("div",{className:"panel-form"},t().createElement("div",{className:"panel-form-row"},t().createElement(s.FormattedMessage,{id:"group_user_id_prompt",defaultMessage:[{type:0,value:"Group or User ID"}]},(e=>t().createElement("input",{type:"text",placeholder:e,value:this.state.groupId,onChange:this.handleChange,onKeyPress:this.handleKeyPress,required:!0,autoFocus:!0})))),t().createElement("div",{className:"dialog-buttons"},t().createElement("button",{className:"primary",onClick:this.handleSubmit},t().createElement(s.FormattedMessage,{id:"button_subscribe",defaultMessage:[{type:0,value:"Subscribe"}]}))))}}const su=(0,s.injectIntl)(iu);class nu extends t().PureComponent{constructor(e){super(e),this.fullName=t().createRef(),this.state={fullName:"",private:"",description:"",imageUrl:null,tags:[],isChannel:!1,newAvatar:null,newAvatarMime:null},this.handleFieldEdit=this.handleFieldEdit.bind(this),this.handleImageChanged=this.handleImageChanged.bind(this),this.handleAvatarCropped=this.handleAvatarCropped.bind(this),this.handleAvatarCropCancel=this.handleAvatarCropCancel.bind(this),this.uploadAvatar=this.uploadAvatar.bind(this),this.handleTagsChanged=this.handleTagsChanged.bind(this),this.handleChannelToggle=this.handleChannelToggle.bind(this),this.handleSubmit=this.handleSubmit.bind(this)}componentDidMount(){}handleFieldEdit(e,t){this.setState({[e]:t.target.value||""})}handleImageChanged(e,t){this.setState({newAvatar:t,newAvatarMime:e})}handleAvatarCropped(e,t,i,s){const n=t?URL.createObjectURL(t):null;this.setState({imageUrl:n,newAvatar:null,newAvatarMime:null}),t&&this.uploadAvatar(e,t,i,s)}handleAvatarCropCancel(){this.setState({newAvatar:null,newAvatarMime:null})}uploadAvatar(e,t,i,s){const n=e=>{let{mime:t,blob:i}=e;if(i.size>mi.uv){this.props.tinode.getLargeFileHelper().upload(i).then((e=>this.setState({imageUrl:e}))).catch((e=>this.props.onError(e.message,"err")))}else(0,Ni.w8)(i).then((e=>this.setState({imageUrl:(0,Ni.PD)({data:e.bits,type:t})})))};i>mi.IX||s>mi.IX||i!=s?(0,Ni.EA)(t,mi.IX,mi.IX,mi.GQ,!0).then((e=>n(e))).catch((e=>this.props.onError(e.message,"err"))):n({mime:e,blob:t,width:i,height:s})}handleTagsChanged(e){this.setState({tags:e})}handleChannelToggle(){this.setState({isChannel:!this.state.isChannel})}handleSubmit(e){e.preventDefault();const t=this.state.fullName.trim().substring(0,mi.S8),i=this.state.private.trim().substring(0,mi.S8),s=this.state.description.trim().substring(0,mi.EI);t&&this.props.onSubmit(t,s,this.state.imageUrl,i,this.state.tags,this.state.isChannel)}render(){if(this.state.newAvatar)return t().createElement(gs.Z,{avatar:this.state.newAvatar,mime:this.state.newAvatarMime,onSubmit:this.handleAvatarCropped,onCancel:this.handleAvatarCropCancel,onError:this.props.onError});let e="primary";return this.props.disabled&&(e+=" disabled"),t().createElement("form",{className:"panel-form",onSubmit:this.handleSubmit},t().createElement("div",{className:"panel-form-column"},t().createElement("center",null,t().createElement(ss.Z,{tinode:this.props.tinode,avatar:this.state.imageUrl,onError:this.props.onError,onImageUpdated:this.handleImageChanged})),t().createElement("div",{className:"group"},t().createElement("label",{className:"small",htmlFor:"new-topic-fn"},t().createElement(s.FormattedMessage,{id:"label_topic_name",defaultMessage:[{type:0,value:"Name"}]})),t().createElement(s.FormattedMessage,{id:"topic_name_editing_placeholder",defaultMessage:[{type:0,value:"Freeform name of the group"}]},(e=>t().createElement("input",{type:"text",id:"new-topic-fn",placeholder:e,ref:this.fullName,value:this.state.fullName,onChange:this.handleFieldEdit.bind(this,"fullName"),autoFocus:!0,required:!0,tabIndex:0})))),t().createElement("div",{className:"group"},t().createElement("label",{className:"small",htmlFor:"new-topic-priv"},t().createElement(s.FormattedMessage,{id:"label_private",defaultMessage:[{type:0,value:"Private comment"}]})),t().createElement(s.FormattedMessage,{id:"private_editing_placeholder",defaultMessage:[{type:0,value:"Visible to you only"}]},(e=>t().createElement("input",{type:"text",id:"new-topic-priv",placeholder:e,value:this.state.private,onChange:this.handleFieldEdit.bind(this,"private"),tabIndex:1})))),t().createElement("div",{className:"group"},t().createElement("label",{className:"small",htmlFor:"new-topic-desc"},t().createElement(s.FormattedMessage,{id:"label_description",defaultMessage:[{type:0,value:"Description"}]})),t().createElement(s.FormattedMessage,{id:"description_editing_placeholder",defaultMessage:[{type:0,value:"Description (optional)"}]},(e=>t().createElement("input",{type:"text",id:"new-topic-desc",placeholder:e,value:this.state.description,onChange:this.handleFieldEdit.bind(this,"description"),tabIndex:2}))))),t().createElement("div",{className:"panel-form-row"},t().createElement(ns.Z,{checked:this.state.isChannel,tabIndex:3,onChange:this.handleChannelToggle})," ",t().createElement("label",{onClick:this.handleChannelToggle},t().createElement(s.FormattedMessage,{id:"channel_prompt",defaultMessage:[{type:0,value:"This is a channel"}]}))),t().createElement(s.FormattedMessage,{id:"title_tag_manager",defaultMessage:[{type:0,value:"Tags (search & discovery)"}]},(e=>t().createElement(bs,{tinode:this.props.tinode,tags:this.state.tags,activated:!0,onTagsChanged:this.handleTagsChanged,tabIndex:4,title:e}))),t().createElement("div",{className:"dialog-buttons"},t().createElement("button",{className:e},t().createElement(s.FormattedMessage,{id:"button_create",defaultMessage:[{type:0,value:"Create"}]}))))}}const au=(0,s.defineMessages)({search_for_contacts:{id:"search_for_contacts",defaultMessage:[{type:0,value:"Use search to find contacts"}]},search_no_results:{id:"search_no_results",defaultMessage:[{type:0,value:"Search returned no results"}]},search_placeholder:{id:"search_placeholder",defaultMessage:[{type:0,value:"List like alice@example.com, +17025550003..."}]}});class ru extends t().Component{constructor(e){super(e),this.state={tabSelected:"find",searchQuery:null},this.handleTabClick=this.handleTabClick.bind(this),this.handleSearchContacts=this.handleSearchContacts.bind(this),this.handleSearchResultSelected=this.handleSearchResultSelected.bind(this),this.handleNewGroupSubmit=this.handleNewGroupSubmit.bind(this),this.handleGroupByID=this.handleGroupByID.bind(this)}componentDidMount(){this.props.onInitFind()}handleTabClick(e){e.preventDefault(),xh.Z.navigateTo(xh.Z.addUrlParam(window.location.hash,"tab",e.currentTarget.dataset.id)),this.setState({tabSelected:e.currentTarget.dataset.id})}handleSearchContacts(e){this.props.onSearchContacts(e),this.setState({searchQuery:ui.Tinode.isNullValue(e)?null:e})}handleSearchResultSelected(e){"find"==this.state.tabSelected&&(xh.Z.navigateTo(xh.Z.removeUrlParam(window.location.hash,"tab")),this.props.onCreateTopic(e))}handleNewGroupSubmit(e,t,i,s,n,a){xh.Z.navigateTo(xh.Z.removeUrlParam(window.location.hash,"tab")),this.props.onCreateTopic(void 0,{public:(0,Di.n$)(e,i,null,t),private:s,tags:n},a)}handleGroupByID(e){xh.Z.navigateTo(xh.Z.removeUrlParam(window.location.hash,"tab")),this.props.onCreateTopic(e)}render(){const{formatMessage:e}=this.props.intl,i=e(this.state.searchQuery?au.search_no_results:au.search_for_contacts),n=e(au.search_placeholder);return t().createElement("div",{className:"flex-column"},t().createElement("ul",{className:"tabbar"},t().createElement("li",{className:"find"===this.state.tabSelected?"active":null},t().createElement("a",{href:"#","data-id":"find",onClick:this.handleTabClick},t().createElement(s.FormattedMessage,{id:"tabtitle_find_user",defaultMessage:[{type:0,value:"find"}]}))),t().createElement("li",{className:"grp"===this.state.tabSelected?"active":null},t().createElement("a",{href:"#","data-id":"grp",onClick:this.handleTabClick},t().createElement(s.FormattedMessage,{id:"tabtitle_new_group",defaultMessage:[{type:0,value:"new group"}]}))),t().createElement("li",{className:"byid"===this.state.tabSelected?"active":null},t().createElement("a",{href:"#","data-id":"byid",onClick:this.handleTabClick},t().createElement(s.FormattedMessage,{id:"tabtitle_group_by_id",defaultMessage:[{type:0,value:"by id"}]})))),"grp"===this.state.tabSelected?t().createElement(nu,{tinode:this.props.tinode,onSubmit:this.handleNewGroupSubmit,onError:this.props.onError}):"byid"===this.state.tabSelected?t().createElement(su,{onSubmit:this.handleGroupByID,onError:this.props.onError}):t().createElement("div",{className:"flex-column"},t().createElement(Zi,{placeholder:n,onSearchContacts:this.handleSearchContacts}),t().createElement(zi,{tinode:this.props.tinode,contacts:this.props.searchResults,myUserId:this.props.myUserId,emptyListMessage:i,showOnline:!1,showUnread:!1,showContextMenu:!1,onTopicSelected:this.handleSearchResultSelected})))}}const ou=(0,s.injectIntl)(ru);class cu extends t().PureComponent{constructor(e){super(e),this.state={hostName:e.serverAddress,changed:!1},this.handleHostNameChange=this.handleHostNameChange.bind(this),this.handleEditingFinished=this.handleEditingFinished.bind(this),this.handleKeyDown=this.handleKeyDown.bind(this)}handleHostNameChange(e){this.setState({hostName:e.target.value,changed:!0})}handleEditingFinished(){this.state.changed&&(this.setState({changed:!1}),this.props.onServerAddressChange(this.state.hostName.trim()))}handleKeyDown(e){"Enter"==e.key&&this.handleEditingFinished()}render(){const e=[];for(let i in mi.Rc){let s=mi.Rc[i];e.push(t().createElement("option",{key:s,value:s}))}return t().createElement("div",{className:"panel-form-row"},t().createElement("input",{type:"search",id:"host-name",placeholder:this.props.hostName,list:"known-hosts",className:"quoted",value:this.state.hostName,onChange:this.handleHostNameChange,onBlur:this.handleEditingFinished,onKeyDown:this.handleKeyDown,required:!0}),t().createElement("datalist",{id:"known-hosts"},e))}}class lu extends t().PureComponent{constructor(e){super(e),this.state={transport:e.transport||"def",serverAddress:e.serverAddress,secureConnection:e.secureConnection},this.handleSubmit=this.handleSubmit.bind(this),this.handleTransportSelected=this.handleTransportSelected.bind(this),this.handleServerAddressChange=this.handleServerAddressChange.bind(this),this.handleToggleSecure=this.handleToggleSecure.bind(this)}handleSubmit(e){e.preventDefault(),this.props.onUpdate({transport:this.state.transport,serverAddress:this.state.serverAddress,secureConnection:this.state.secureConnection})}handleTransportSelected(e){this.setState({transport:e.currentTarget.value})}handleServerAddressChange(e){this.setState({serverAddress:e})}handleToggleSecure(e){this.setState({secureConnection:!this.state.secureConnection})}render(){const e={def:"default",ws:"websocket",lp:"long polling"},i=[];return["def","ws","lp"].forEach((s=>{const n="transport-"+s,a=e[s];i.push(t().createElement("li",{key:s},t().createElement("input",{type:"radio",id:n,name:"transport-select",value:s,checked:this.state.transport===s,onChange:this.handleTransportSelected}),t().createElement("label",{htmlFor:n},a)))})),t().createElement("form",{id:"settings-form",className:"panel-form",onSubmit:this.handleSubmit},t().createElement("div",{className:"panel-form-row"},t().createElement("label",{className:"small"},t().createElement(s.FormattedMessage,{id:"label_server_to_use",defaultMessage:[{type:0,value:"Server to use:"}]}))),t().createElement(cu,{serverAddress:this.state.serverAddress,onServerAddressChange:this.handleServerAddressChange}),t().createElement("div",{className:"panel-form-row"},t().createElement(ns.Z,{id:"secure-connection",name:"secure-connection",checked:this.state.secureConnection,className:"quoted",onChange:this.handleToggleSecure}),t().createElement("label",{htmlFor:"secure-connection"},t().createElement(s.FormattedMessage,{id:"label_use_secure_connection",defaultMessage:[{type:0,value:"Use secure connection"}]}))),t().createElement("div",{className:"panel-form-row"},t().createElement("label",{className:"small"},t().createElement(s.FormattedMessage,{id:"label_wire_transport",defaultMessage:[{type:0,value:"Wire transport:"}]}))),t().createElement("div",{className:"panel-form-row"},t().createElement("ul",{className:"quoted"},i)),t().createElement("div",{className:"dialog-buttons"},t().createElement("button",{type:"submit",className:"primary"},t().createElement(s.FormattedMessage,{id:"button_update",defaultMessage:[{type:0,value:"Update"}]}))))}}const du=(0,s.defineMessages)({phone:{id:"phone_dative",defaultMessage:[{type:0,value:"phone"}]},email:{id:"email_dative",defaultMessage:[{type:0,value:"email"}]}});class hu extends t().PureComponent{constructor(e){super(e),this.state={code:e.credCode||"",codeReceived:e.credCode},this.handleCodeChange=this.handleCodeChange.bind(this),this.handleKeyPress=this.handleKeyPress.bind(this),this.handleSubmit=this.handleSubmit.bind(this),this.handleCancel=this.handleCancel.bind(this)}static getDerivedStateFromProps(e,t){return e.credCode!=t.codeReceived?{code:e.credCode||"",codeReceived:e.credCode}:t}componentDidMount(){this.props.credCode&&this.props.onSubmit(this.props.credMethod,this.props.credCode,this.props.credToken)}componentDidUpdate(e,t){this.state.codeReceived&&this.state.code&&this.state.code!=t.code&&this.props.onSubmit(this.props.credMethod,this.state.code,this.props.credToken)}handleCodeChange(e){this.setState({code:e.target.value.replace(/[^\d]/g,"")})}handleKeyPress(e){"Enter"===e.key?this.handleSubmit(e):"Escape"==e.key&&this.handleCancel(e)}handleSubmit(e){e.preventDefault(),this.state.code&&this.state.code.trim()&&this.props.onSubmit(this.props.credMethod,this.state.code.trim(),this.props.credToken)}handleCancel(e){e.preventDefault(),this.props.onCancel()}render(){const{formatMessage:e}=this.props.intl,i={email:e(du.email),tel:e(du.phone)}[this.props.credMethod]||this.props.credMethod;return t().createElement("div",{className:"panel-form"},t().createElement("div",{className:"panel-form-row"},t().createElement("label",{className:"small gray",htmlFor:"enter-confirmation-code"},t().createElement(s.FormattedMessage,{id:"enter_confirmation_code_prompt",defaultMessage:[{type:0,value:"Confirmation code"}],values:{method:i}}))),t().createElement("div",{className:"panel-form-row"},t().createElement(s.FormattedMessage,{id:"numeric_confirmation_code_prompt",defaultMessage:[{type:0,value:"Numbers only"}]},(e=>t().createElement("input",{type:"text",id:"enter-confirmation-code",placeholder:e,value:this.state.code,onChange:this.handleCodeChange,onKeyDown:this.handleKeyPress,required:!0})))),t().createElement("div",{className:"dialog-buttons"},t().createElement("button",{className:"secondary",onClick:this.handleCancel},t().createElement(s.FormattedMessage,{id:"button_cancel",defaultMessage:[{type:0,value:"Cancel"}]})),t().createElement("button",{className:"primary",onClick:this.handleSubmit},t().createElement(s.FormattedMessage,{id:"button_confirm",defaultMessage:[{type:0,value:"Confirm"}]}))))}}const uu=(0,s.injectIntl)(hu),pu=t().lazy((e=>Promise.all([r.e(501),r.e(365)]).then(r.bind(r,1365)))),mu=t().lazy((e=>Promise.all([r.e(501),r.e(327)]).then(r.bind(r,327)))),gu=t().lazy((e=>Promise.all([r.e(501),r.e(311)]).then(r.bind(r,1311)))),fu=(0,s.defineMessages)({login:{id:"sidepanel_title_login",defaultMessage:[{type:0,value:"Sign In"}]},register:{id:"sidepanel_title_register",defaultMessage:[{type:0,value:"Create Account"}]},settings:{id:"sidepanel_title_settings",defaultMessage:[{type:0,value:"Settings"}]},edit:{id:"sidepanel_title_account_settings",defaultMessage:[{type:0,value:"Account Settings"}]},general:{id:"panel_title_general",defaultMessage:[{type:0,value:"General"}]},security:{id:"panel_title_security",defaultMessage:[{type:0,value:"Security"}]},crop:{id:"panel_title_crop",defaultMessage:[{type:0,value:"Drag to Adjust"}]},notif:{id:"sidepanel_title_acc_notifications",defaultMessage:[{type:0,value:"Notifications"}]},support:{id:"sidepanel_title_acc_support",defaultMessage:[{type:0,value:"Support"}]},newtpk:{id:"sidepanel_title_newtpk",defaultMessage:[{type:0,value:"Start New Chat"}]},cred:{id:"sidepanel_title_cred",defaultMessage:[{type:0,value:"Confirm Credentials"}]},reset:{id:"sidepanel_title_reset",defaultMessage:[{type:0,value:"Reset Password"}]},archive:{id:"sidepanel_title_archive",defaultMessage:[{type:0,value:"Archived Chats"}]},blocked:{id:"sidepanel_title_blocked",defaultMessage:[{type:0,value:"Blocked Chats"}]}});class vu extends t().PureComponent{constructor(e){super(e),this.handleNewTopic=this.handleNewTopic.bind(this)}handleNewTopic(){this.props.onNavigate("newtpk")}render(){const{formatMessage:i}=this.props.intl,n=this.props.state||(this.props.myUserId?"contacts":"login");let a,r,o,c;return"contacts"==n?(a=this.props.title,r=!this.props.avatar||this.props.avatar,o=this.props.trustedBadges):(a=i(fu[n]),r=!1,o=null),-1==["login","contacts"].indexOf(n)&&(c=this.props.onCancel),t().createElement("div",{id:"sidepanel"},t().createElement(Hh,{state:n,title:a,avatar:r,tinode:this.props.tinode,trustedBadges:o,myUserId:this.props.myUserId,onSignUp:this.props.onSignUp,onSettings:this.props.onSettings,onNewTopic:this.handleNewTopic,onCancel:c}),t().createElement(rs,{level:this.props.errorLevel,text:this.props.errorText,action:this.props.errorAction,actionText:this.props.errorActionText,onClearError:this.props.onError}),t().createElement(Qs.Z,{show:this.props.loadSpinnerVisible}),"login"===n?t().createElement(eu,{login:this.props.login,disabled:this.props.loginDisabled,persist:this.props.persist,onLogin:this.props.onLoginRequest,onPersistenceChange:this.props.onPersistenceChange}):"register"===n?t().createElement(e.Suspense,{fallback:t().createElement("div",{className:"panel-form-row"},t().createElement(s.FormattedMessage,{id:"loading_note",defaultMessage:[{type:0,value:"Loading..."}]}))},t().createElement(mu,{tinode:this.props.tinode,reqCredMethod:this.props.reqCredMethod,onShowCountrySelector:this.props.onShowCountrySelector,onCreateAccount:this.props.onCreateAccount,onCancel:this.props.onCancel,onError:this.props.onError})):"settings"===n?t().createElement(lu,{transport:this.props.transport,serverAddress:this.props.serverAddress,secureConnection:this.props.secureConnection,onCancel:this.props.onCancel,onUpdate:this.props.onGlobalSettings}):"edit"===n?t().createElement(e.Suspense,{fallback:t().createElement("div",{className:"panel-form-row"},t().createElement(s.FormattedMessage,{id:"loading_note",defaultMessage:[{type:0,value:"Loading..."}]}))},t().createElement(pu,{tinode:this.props.tinode,myUserId:this.props.myUserId,trustedBadges:this.props.trustedBadges,reqCredMethod:this.props.reqCredMethod,onShowCountrySelector:this.props.onShowCountrySelector,onNavigate:this.props.onNavigate,onCredAdd:this.props.onCredAdd,onCredDelete:this.props.onCredDelete,onCredConfirm:this.props.onCredConfirm,onError:this.props.onError})):"general"===n||"crop"===n?t().createElement(Ss,{topic:"me",tinode:this.props.tinode,myUserId:this.props.myUserId,reqCredMethod:this.props.reqCredMethod,onUpdateTopicDesc:this.props.onUpdateAccountDesc,onUpdateTagsRequest:this.props.onUpdateAccountTags,onError:this.props.onError}):"notif"===n?t().createElement(Zh,{messageSounds:this.props.messageSounds,desktopAlerts:this.props.desktopAlerts,desktopAlertsEnabled:this.props.desktopAlertsEnabled,incognitoMode:this.props.incognitoMode,onTogglePushNotifications:this.props.onTogglePushNotifications,onToggleMessageSounds:this.props.onToggleMessageSounds,onToggleIncognitoMode:this.props.onToggleIncognitoMode}):"security"===n?t().createElement(Xh,{tinode:this.props.tinode,onUpdateAccountDesc:this.props.onUpdateAccountDesc,onUpdatePassword:this.props.onUpdatePassword,onLogout:this.props.onLogout,onDeleteAccount:this.props.onDeleteAccount,onShowAlert:this.props.onShowAlert,onShowBlocked:this.props.onShowBlocked}):"support"===n?t().createElement(Yh,{serverAddress:this.props.serverAddress,serverVersion:this.props.serverVersion}):"contacts"===n||"archive"==n||"blocked"==n?t().createElement(zh,{tinode:this.props.tinode,myUserId:this.props.myUserId,connected:this.props.connected,topicSelected:this.props.topicSelected,archive:"archive"==n,blocked:"blocked"==n,chatList:this.props.chatList,showContextMenu:this.props.showContextMenu,onTopicSelected:this.props.onTopicSelected,onShowArchive:this.props.onShowArchive}):"newtpk"===n?t().createElement(ou,{tinode:this.props.tinode,searchResults:this.props.searchResults,onInitFind:this.props.onInitFind,onSearchContacts:this.props.onSearchContacts,onCreateTopic:this.props.onCreateTopic,onError:this.props.onError}):"cred"===n?t().createElement(uu,{credCode:this.props.credCode,credMethod:this.props.credMethod,credToken:this.props.credToken,onSubmit:this.props.onValidateCredentials,onCancel:this.props.onCancel}):"reset"===n?t().createElement(e.Suspense,{fallback:t().createElement("div",{className:"panel-form-row"},t().createElement(s.FormattedMessage,{id:"loading_note",defaultMessage:[{type:0,value:"Loading..."}]}))},t().createElement(gu,{tinode:this.props.tinode,reqCredMethod:this.props.reqCredMethod,onShowCountrySelector:this.props.onShowCountrySelector,onRequest:this.props.onPasswordResetRequest,onReset:this.props.onResetPassword,onCancel:this.props.onCancel,onError:this.props.onError})):null)}}const bu=(0,s.injectIntl)(vu);var yu=r(3119);function Su(){let e=mi.Mv;return"object"==typeof window.location&&("file:"==window.location.protocol||"localhost"==window.location.hostname?e=mi.Rc.local:window.location.hostname&&(e=window.location.hostname+(window.location.port?":"+window.location.port:""))),e}function wu(){return"object"==typeof window.location&&"https:"==window.location.protocol}var Cu=r(320);const ku=t().lazy((e=>r.e(290).then(r.bind(r,1290)))),Eu=new Audio("audio/msg.m4a"),Tu=(0,s.defineMessages)({reconnect_countdown:{id:"reconnect_countdown",defaultMessage:[{type:0,value:"Disconnected. Reconnecting in "},{type:1,value:"seconds"},{type:0,value:"…"}]},reconnect_now:{id:"reconnect_now",defaultMessage:[{type:0,value:"Try now"}]},push_init_failed:{id:"push_init_failed",defaultMessage:[{type:0,value:"Failed to initialize push notifications"}]},invalid_security_token:{id:"invalid_security_token",defaultMessage:[{type:0,value:"Invalid security token"}]},no_connection:{id:"no_connection",defaultMessage:[{type:0,value:"No connection"}]},code_doesnot_match:{id:"code_doesnot_match",defaultMessage:[{type:0,value:"Code does not match"}]},menu_item_info:{id:"menu_item_info",defaultMessage:[{type:0,value:"Info"}]},menu_item_audio_call:{id:"menu_item_audio_call",defaultMessage:[{type:0,value:"Call"}]},menu_item_video_call:{id:"menu_item_video_call",defaultMessage:[{type:0,value:"Video call"}]},cred_confirmed_successfully:{id:"cred_confirmed_successfully",defaultMessage:[{type:0,value:"Confirmed successfully"}]}});class Pu extends t().Component{constructor(e){super(e),this.selfRef=t().createRef(),this.state=this.getBlankState(),this.handleResize=this.handleResize.bind(this),this.handleHashRoute=this.handleHashRoute.bind(this),this.handleOnline=this.handleOnline.bind(this),this.checkForAppUpdate=this.checkForAppUpdate.bind(this),this.handleVisibilityEvent=this.handleVisibilityEvent.bind(this),this.handleError=this.handleError.bind(this),this.handleLoginRequest=this.handleLoginRequest.bind(this),this.handlePersistenceChange=this.handlePersistenceChange.bind(this),this.handleConnected=this.handleConnected.bind(this),this.handleAutoreconnectIteration=this.handleAutoreconnectIteration.bind(this),this.doLogin=this.doLogin.bind(this),this.handleLoginSuccessful=this.handleLoginSuccessful.bind(this),this.handleDisconnect=this.handleDisconnect.bind(this),this.tnMeMetaDesc=this.tnMeMetaDesc.bind(this),this.tnMeContactUpdate=this.tnMeContactUpdate.bind(this),this.tnMeSubsUpdated=this.tnMeSubsUpdated.bind(this),this.resetContactList=this.resetContactList.bind(this),this.tnInitFind=this.tnInitFind.bind(this),this.tnFndSubsUpdated=this.tnFndSubsUpdated.bind(this),this.handleSearchContacts=this.handleSearchContacts.bind(this),this.handleTopicSelected=this.handleTopicSelected.bind(this),this.handleHideMessagesView=this.handleHideMessagesView.bind(this),this.handleSendMessage=this.handleSendMessage.bind(this),this.handleNewChatInvitation=this.handleNewChatInvitation.bind(this),this.handleNewAccount=this.handleNewAccount.bind(this),this.handleNewAccountRequest=this.handleNewAccountRequest.bind(this),this.handleUpdatePasswordRequest=this.handleUpdatePasswordRequest.bind(this),this.handleUpdateAccountTagsRequest=this.handleUpdateAccountTagsRequest.bind(this),this.handleToggleIncognitoMode=this.handleToggleIncognitoMode.bind(this),this.handleSettings=this.handleSettings.bind(this),this.handleGlobalSettings=this.handleGlobalSettings.bind(this),this.handleShowArchive=this.handleShowArchive.bind(this),this.handleShowBlocked=this.handleShowBlocked.bind(this),this.handleToggleMessageSounds=this.handleToggleMessageSounds.bind(this),this.handleCredAdd=this.handleCredAdd.bind(this),this.handleCredDelete=this.handleCredDelete.bind(this),this.handleCredConfirm=this.handleCredConfirm.bind(this),this.initFCMessaging=this.initFCMessaging.bind(this),this.toggleFCMToken=this.toggleFCMToken.bind(this),this.handlePushMessage=this.handlePushMessage.bind(this),this.handleSidepanelCancel=this.handleSidepanelCancel.bind(this),this.handleStartTopicRequest=this.handleStartTopicRequest.bind(this),this.handleNewTopicCreated=this.handleNewTopicCreated.bind(this),this.handleTopicUpdateRequest=this.handleTopicUpdateRequest.bind(this),this.handleUnarchive=this.handleUnarchive.bind(this),this.handleChangePermissions=this.handleChangePermissions.bind(this),this.handleTagsUpdateRequest=this.handleTagsUpdateRequest.bind(this),this.handleLogout=this.handleLogout.bind(this),this.handleDeleteAccount=this.handleDeleteAccount.bind(this),this.handleDeleteTopicRequest=this.handleDeleteTopicRequest.bind(this),this.handleDeleteMessagesRequest=this.handleDeleteMessagesRequest.bind(this),this.handleLeaveUnsubRequest=this.handleLeaveUnsubRequest.bind(this),this.handleBlockTopicRequest=this.handleBlockTopicRequest.bind(this),this.handleReportTopic=this.handleReportTopic.bind(this),this.handleShowContextMenu=this.handleShowContextMenu.bind(this),this.defaultTopicContextMenu=this.defaultTopicContextMenu.bind(this),this.handleHideContextMenu=this.handleHideContextMenu.bind(this),this.handleShowAlert=this.handleShowAlert.bind(this),this.handleShowInfoView=this.handleShowInfoView.bind(this),this.handleMemberUpdateRequest=this.handleMemberUpdateRequest.bind(this),this.handleValidateCredentialsRequest=this.handleValidateCredentialsRequest.bind(this),this.handlePasswordResetRequest=this.handlePasswordResetRequest.bind(this),this.handleResetPassword=this.handleResetPassword.bind(this),this.handleContextMenuAction=this.handleContextMenuAction.bind(this),this.handleShowCountrySelector=this.handleShowCountrySelector.bind(this),this.handleShowForwardDialog=this.handleShowForwardDialog.bind(this),this.handleHideForwardDialog=this.handleHideForwardDialog.bind(this),this.handleStartVideoCall=this.handleStartVideoCall.bind(this),this.handleStartAudioCall=this.handleStartAudioCall.bind(this),this.handleInfoMessage=this.handleInfoMessage.bind(this),this.handleDataMessage=this.handleDataMessage.bind(this),this.handleCallClose=this.handleCallClose.bind(this),this.handleCallInvite=this.handleCallInvite.bind(this),this.handleCallRinging=this.handleCallRinging.bind(this),this.handleCallHangup=this.handleCallHangup.bind(this),this.handleCallSendOffer=this.handleCallSendOffer.bind(this),this.handleCallIceCandidate=this.handleCallIceCandidate.bind(this),this.handleCallSendAnswer=this.handleCallSendAnswer.bind(this),this.handleVCCallJoin=this.handleVCCallJoin.bind(this),this.handleCallAccept=this.handleCallAccept.bind(this),this.sendMessageToTopic=this.sendMessageToTopic.bind(this),this.callTimeoutTimer=null}getBlankState(){const e=Cu.Z.getObject("settings")||{},t=!!Cu.Z.getObject("keep-logged-in");return{connected:!1,ready:!1,autoLogin:!1,transport:e.transport||null,serverAddress:e.serverAddress||Su(),secureConnection:void 0===e.secureConnection?wu():e.secureConnection,serverVersion:"no connection",messageSounds:!e.messageSoundsOff,incognitoMode:!1,desktopAlerts:t&&!!e.desktopAlerts,desktopAlertsEnabled:(wu()||"object"==typeof window.location&&"localhost"==window.location.hostname)&&void 0!==de&&"undefined"!=typeof navigator&&"undefined"!=typeof FIREBASE_INIT,firebaseToken:t?Cu.Z.getObject("firebase-token"):null,applicationVisible:!document.hidden,errorText:"",errorLevel:null,errorAction:void 0,errorActionText:null,sidePanelSelected:"login",sidePanelTitle:null,sidePanelAvatar:null,myTrustedBadges:[],loadSpinnerVisible:!1,login:"",password:"",persist:t,myUserId:null,liveConnection:navigator.onLine,topicSelected:"",topicSelectedOnline:!1,topicSelectedAcs:null,newTopicParams:null,loginDisabled:!1,displayMobile:window.innerWidth<=mi.yl,infoPanel:void 0,mobilePanel:"sidepanel",callTopic:void 0,callState:0,callAudioOnly:void 0,callShouldStart:!1,contextMenuVisible:!1,contextMenuBounds:null,contextMenuClickAt:null,contextMenuParams:null,contextMenuItems:[],forwardDialogVisible:!1,forwardMessage:null,alertVisible:!1,alertParams:{},chatList:[],searchResults:[],searchableContacts:[],reqCredMethod:void 0,credMethod:void 0,credCode:void 0,credToken:void 0,requestedTopic:void 0}}componentDidMount(){if(window.addEventListener("resize",this.handleResize),this.handleOnlineOn=e=>{this.handleOnline(!0)},window.addEventListener("online",this.handleOnlineOn),this.handleOnlineOff=e=>{this.handleOnline(!1)},window.addEventListener("offline",this.handleOnlineOff),window.addEventListener("hashchange",this.handleHashRoute),"function"==typeof BroadcastChannel){new BroadcastChannel("tinode-sw").addEventListener("message",this.handlePushMessage)}else console.warn("Your browser does not support BroadcastChannel. Some features will not be available");document.addEventListener("visibilitychange",this.handleVisibilityEvent),this.setState({viewportWidth:document.documentElement.clientWidth,viewportHeight:document.documentElement.clientHeight}),new Promise(((e,t)=>{this.tinode=Pu.tnSetup(this.state.serverAddress,wu(),this.state.transport,this.props.intl.locale,this.state.persist,e),this.tinode.onConnect=this.handleConnected,this.tinode.onDisconnect=this.handleDisconnect,this.tinode.onAutoreconnectIteration=this.handleAutoreconnectIteration,this.tinode.onInfoMessage=this.handleInfoMessage,this.tinode.onDataMessage=this.handleDataMessage})).then((e=>{this.state.desktopAlertsEnabled&&this.initFCMessaging().catch((e=>{})),this.resetContactList();const t=this.state.persist?Cu.Z.getObject("auth-token"):void 0;t&&(this.setState({autoLogin:!0}),t.expires=new Date(t.expires),this.tinode.setAuthToken(t),this.tinode.connect().catch((e=>{this.handleError(e.message,"err")}))),this.readTimer=null,this.readTimerCallback=null;const i=xh.Z.parseUrlHash(window.location.hash);if(["cred","reset","register"].includes(i.path[0]))this.handleHashRoute();else{this.setState({requestedTopic:i.path[1]});const e=i.params&&i.params.cred_done?xh.Z.addUrlParam("","cred_done",i.params.cred_done):"";xh.Z.navigateTo(e)}}))}componentWillUnmount(){window.removeEventListener("resize",this.handleResize),window.removeEventListener("hashchange",this.handleHashRoute),window.removeEventListener("online",this.handleOnlineOn),window.removeEventListener("offline",this.handleOnlineOff),document.removeEventListener("visibilitychange",this.handleVisibilityEvent)}static tnSetup(e,t,i,s,n,a){const r=new ui.Tinode({appName:mi.iC,host:e,apiKey:mi.$h,transport:i,secure:t,persist:n},a);return r.setHumanLanguage(s),r.enableLogging(mi.JG,!0),r}handlePushMessage(e){this.tinode.oobNotification(e.data||{})}initFCMessaging(){const{formatMessage:e,locale:t}=this.props.intl,i=(t,i)=>{console.error(t,i),this.handleError(e(Tu.push_init_failed),"err"),this.setState({firebaseToken:null}),Cu.Z.updateObject("settings",{desktopAlerts:!1})};try{return this.fcm=ci(de(FIREBASE_INIT,mi.iC)),navigator.serviceWorker.getRegistration("/service-worker.js").then((e=>e||navigator.serviceWorker.register("/service-worker.js").then((e=>(this.checkForAppUpdate(e),e))))).then((e=>((e.active||e.installing).postMessage(JSON.stringify({locale:t,version:yu.l})),Pu.requestFCMToken(this.fcm,e)))).then((e=>{const t=Cu.Z.getObject("keep-logged-in");e!=this.state.firebaseToken&&(this.tinode.setDeviceToken(e),t&&Cu.Z.setObject("firebase-token",e)),this.setState({firebaseToken:e,desktopAlerts:!0}),t&&Cu.Z.updateObject("settings",{desktopAlerts:!0}),hi(this.fcm,(e=>{this.handlePushMessage(e)}))})).catch((e=>{throw i(e),e}))}catch(e){return i(e),Promise.reject(e)}}static requestFCMToken(e,t){return li(e,{serviceWorkerRegistration:t,vapidKey:FIREBASE_INIT.messagingVapidKey}).then((t=>{if(t)return t;if("undefined"!=typeof Notification)return Notification.requestPermission().then((t=>{if("granted"===t)return li(e,{serviceWorkerRegistration:reg,vapidKey:FIREBASE_INIT.messagingVapidKey}).then((e=>{if(e)return e;throw new Error("Failed to initialize notifications")}));throw new Error("No permission to send notifications: "+t)}));throw new Error("Notifications are not supported")}))}handleResize(){const e=document.documentElement.clientWidth<=mi.yl;this.setState({viewportWidth:document.documentElement.clientWidth,viewportHeight:document.documentElement.clientHeight}),this.state.displayMobile!=e&&this.setState({displayMobile:e})}checkForAppUpdate(e){e.onupdatefound=i=>{const n=e.installing;n.onstatechange=e=>{if("installed"==n.state&&navigator.serviceWorker.controller){const e=t().createElement(t().Fragment,null,t().createElement(s.FormattedMessage,{id:"update_available",defaultMessage:[{type:0,value:"Update available."}]})," ",t().createElement("a",{href:""},t().createElement(s.FormattedMessage,{id:"reload_update",defaultMessage:[{type:0,value:"Reload"}]})),".");this.handleError(e,"info")}}}}handleHashRoute(){const e=xh.Z.parseUrlHash(window.location.hash),t={infoPanel:e.params.info,newTopicTabSelected:e.params.tab};if(e.path&&e.path.length>0){["register","settings","edit","notif","security","support","general","crop","cred","reset","newtpk","archive","blocked","contacts",""].includes(e.path[0])?t.sidePanelSelected=e.path[0]:console.warn("Unknown sidepanel view",e.path[0]);let i=e.path[1]||null;i!=this.state.topicSelected&&(ui.Tinode.topicType(i)?t.mobilePanel="topic-view":(i=null,t.mobilePanel="sidepanel"),Object.assign(t,{topicSelected:i,topicSelectedAcs:this.tinode.getTopicAccessMode(i)}))}else Object.assign(t,{sidePanelSelected:"",topicSelected:null});e.params.method&&(t.credMethod=e.params.method),e.params.code&&(t.credCode=e.params.code),e.params.token&&(t.credToken=e.params.token),e.params.cred_done&&Object.assign(t,Pu.stateForError(this.props.intl.formatMessage(Tu.cred_confirmed_successfully),"info")),this.setState(t)}handleOnline(e){e?(this.handleError(),clearInterval(this.reconnectCountdown),this.tinode.reconnect()):this.handleError(this.props.intl.formatMessage(Tu.no_connection),"warn"),this.setState({liveConnection:e})}handleVisibilityEvent(){this.setState({applicationVisible:!document.hidden})}static stateForError(e,t,i,s){return{errorText:e,errorLevel:t,errorAction:i,errorActionText:s,callShouldStart:!1}}handleError(e,t,i,s){this.setState(Pu.stateForError(e,t,i,s))}handleLoginRequest(e,t){this.setState({loginDisabled:!0,login:e,password:t,loadSpinnerVisible:!0,autoLogin:!0}),this.handleError("",null),this.tinode.isConnected()?this.doLogin(e,t,null,{meth:this.state.credMethod,resp:this.state.credCode}):this.tinode.connect().catch((e=>{this.setState({loginDisabled:!1,autoLogin:!1,loadSpinnerVisible:!1}),this.handleError(e.message,"err")})),this.state.desktopAlertsEnabled&&!this.state.firebaseToken&&this.initFCMessaging()}handlePersistenceChange(e){e?this.tinode.initStorage().then((e=>{Cu.Z.setObject("keep-logged-in",!0),this.setState({persist:!0})})):this.tinode.clearStorage().then((e=>{Cu.Z.setObject("keep-logged-in",!1),this.setState({persist:!1})}))}handleConnected(){clearInterval(this.reconnectCountdown),this.handleError();const e=this.tinode.getServerInfo();this.setState({serverVersion:e.ver+" "+(e.build?e.build:"none"),reqCredMethod:((e.reqCred||{}).auth||[])[0]||"email"}),this.state.autoLogin&&this.doLogin(this.state.login,this.state.password,null,{meth:this.state.credMethod,resp:this.state.credCode})}handleAutoreconnectIteration(e,t){if(clearInterval(this.reconnectCountdown),e<0)return void this.handleError();if(t)return void t.then((e=>{this.handleError()})).catch((e=>{this.handleError(e.message,"err")}));const{formatMessage:i}=this.props.intl;let s=e/1e3;s|=s,this.reconnectCountdown=setInterval((e=>{if(s<-10)return clearInterval(this.reconnectCountdown),void this.tinode.reconnect();const t=s>99?(0,ki.nH)(s):s;this.handleError(i(Tu.reconnect_countdown,{seconds:t}),"warn",(e=>{clearInterval(this.reconnectCountdown),this.tinode.reconnect()}),i(Tu.reconnect_now)),s-=1}),1e3)}handleDisconnect(e){this.setState({connected:!1,ready:!1,topicSelectedOnline:!1,errorText:e&&e.message?e.message:"Disconnected",errorLevel:e&&e.message?"err":"warn",loginDisabled:!1,contextMenuVisible:!1,forwardDialogVisible:!1,serverVersion:"no connection"})}doLogin(e,t,i,s){if(this.tinode.isAuthenticated())return void xh.Z.navigateTo("");let n=i||(this.tinode.getAuthToken()||{}).token;if(!(e&&t||n))return xh.Z.navigateTo(""),void this.setState({loginDisabled:!1});s=ui.Tinode.credential(s);let a,r=this.tinode.isConnected()?Promise.resolve():this.tinode.connect();e&&t?(n=null,this.setState({password:null}),a=r.then((i=>this.tinode.loginBasic(e,t,s)))):a=r.then((e=>this.tinode.loginToken(n,s))),a.then((e=>{e.code>=300&&"validate credentials"===e.text?(this.setState({loadSpinnerVisible:!1}),s&&this.handleError(this.props.intl.formatMessage(Tu.code_doesnot_match),"warn"),Pu.navigateToCredentialsView(e.params)):this.handleLoginSuccessful()})).catch((e=>{const t=e.code>=500;this.setState({loginDisabled:!1,credMethod:void 0,credCode:void 0,loadSpinnerVisible:!1,autoLogin:t}),this.handleError(e.message,"err"),console.warn("Login failed",e),t||(n&&this.handleLogout(),xh.Z.navigateTo(""))}))}static navigateToCredentialsView(e){const t=xh.Z.parseUrlHash(window.location.hash);t.path[0]="cred",t.params.method=e.cred[0],t.params.token=e.token,t.params.code=e.code,xh.Z.navigateTo(xh.Z.composeUrlHash(t.path,t.params))}handleLoginSuccessful(){this.handleError(),Cu.Z.getObject("keep-logged-in")&&Cu.Z.setObject("auth-token",this.tinode.getAuthToken());const e=this.state.requestedTopic,t=this.tinode.getMeTopic();t.onMetaDesc=this.tnMeMetaDesc,t.onContactUpdate=this.tnMeContactUpdate,t.onSubsUpdated=this.tnMeSubsUpdated,this.setState({connected:!0,credMethod:void 0,credCode:void 0,credToken:void 0,myUserId:this.tinode.getCurrentUserID(),autoLogin:!0,requestedTopic:void 0}),t.subscribe(t.startMetaQuery().withLaterSub().withDesc().withTags().withCred().build()).catch((e=>{this.tinode.disconnect(),localStorage.removeItem("auth-token"),this.handleError(e.message,"err"),xh.Z.navigateTo("")})).finally((e=>{this.setState({loadSpinnerVisible:!1})}));let i=xh.Z.setUrlSidePanel(window.location.hash,"contacts");e&&(i=xh.Z.setUrlTopic(i,e)),xh.Z.navigateTo(i)}tnMeMetaDesc(e){if(e){if(e.public&&this.setState({sidePanelTitle:e.public.fn,sidePanelAvatar:(0,Ni.PD)(e.public.photo)}),e.trusted){const t=[];for(const[i,s]of Object.entries(e.trusted))s&&t.push(i);this.setState({myTrustedBadges:t})}e.acs&&this.setState({incognitoMode:!e.acs.isPresencer()})}}tnMeContactUpdate(e,t){if("on"==e||"off"==e)this.resetContactList(),this.state.topicSelected==t.topic&&this.setState({topicSelectedOnline:"on"==e});else if("read"==e)this.resetContactList();else if("msg"==e&&t){const e=this.tinode.getTopic(t.topic),i=e&&e.isArchived();t.unread>0&&this.state.messageSounds&&!i&&(document.hidden||this.state.topicSelected!=t.topic)&&Eu.play().catch((e=>{})),this.resetContactList()}else"recv"==e||("gone"==e||"unsub"==e?(this.state.topicSelected==t.topic&&this.handleTopicSelected(null),this.resetContactList()):"acs"==e?this.state.topicSelected==t.topic&&this.setState({topicSelectedAcs:t.acs}):"del"==e||"upd"==e||"call"==e||console.info("Unsupported (yet) presence update:",e,"in",(t||{}).topic))}tnMeSubsUpdated(e){this.resetContactList()}static prepareSearchableContacts(e,t){const i={};for(const t of e)ui.Tinode.isP2PTopicName(t.topic)&&(i[t.topic]={user:t.topic,updated:t.updated,public:t.public,private:t.private,acs:t.acs});for(const e of t)i[e.user]||(i[e.user]=e);return Object.values(i)}resetContactList(){const e={chatList:[]};this.state.ready||(e.ready=!0),this.tinode.getMeTopic().contacts((t=>{t.topic||t.user||(t.topic=t.name),e.chatList.push(t),this.state.topicSelected==t.topic&&(e.topicSelectedOnline=t.online,e.topicSelectedAcs=t.acs)}));const t=new Date(0);e.chatList.sort(((e,i)=>(e.touched||t).getTime()-(i.touched||t).getTime())),e.searchableContacts=Pu.prepareSearchableContacts(e.chatList,this.state.searchResults),this.setState(e)}tnInitFind(){const e=this.tinode.getFndTopic();e.onSubsUpdated=this.tnFndSubsUpdated,e.isSubscribed()?this.tnFndSubsUpdated():e.subscribe(e.startMetaQuery().withSub().build()).catch((e=>{this.handleError(e.message,"err")}))}tnFndSubsUpdated(){const e=[];this.tinode.getFndTopic().contacts((t=>{e.push(t)})),this.setState({searchResults:e,searchableContacts:Pu.prepareSearchableContacts(this.state.chatList,e)})}handleSearchContacts(e){const t=this.tinode.getFndTopic();t.setMeta({desc:{public:e}}).then((e=>t.getMeta(t.startMetaQuery().withSub().build()))).catch((e=>this.handleError(e.message,"err")))}handleTopicSelected(e){this.state.newTopicParams&&this.state.newTopicParams._topicName!=e&&this.setState({newTopicParams:null}),e?(this.setState({errorText:"",errorLevel:null,mobilePanel:"topic-view",infoPanel:void 0}),this.state.topicSelected!=e&&(this.setState({topicSelectedOnline:this.tinode.isTopicOnline(e),topicSelectedAcs:this.tinode.getTopicAccessMode(e),forwardMessage:null}),xh.Z.navigateTo(xh.Z.setUrlTopic("",e)))):(this.setState({topicSelected:null,errorText:"",errorLevel:null,mobilePanel:"sidepanel",topicSelectedOnline:!1,topicSelectedAcs:null,infoPanel:void 0,forwardMessage:null}),xh.Z.navigateTo(xh.Z.setUrlTopic("",null)))}handleHideMessagesView(){this.setState({mobilePanel:"sidepanel"}),xh.Z.navigateTo(xh.Z.setUrlTopic(window.location.hash,null))}handleSendMessage(e,t,i,s){const n=this.tinode.getTopic(this.state.topicSelected);return this.sendMessageToTopic(n,e,t,i,s)}sendMessageToTopic(e,t,i,s,n){(t=e.createMessage(t,!1))._uploader=s,n&&(t.head=Object.assign(t.head||{},n));const a=[];if(i&&a.push(i),!e.isSubscribed()){const i=e.subscribe().then((i=>{let s=[];e.queuedMessages((i=>{i._sending||i.seq==t.seq||(i.head&&i.head.webrtc?s.push(i.seq):e.isSubscribed()&&e.publishMessage(i))})),s.length>0&&e.delMessagesList(s,!0)}));a.push(i)}return e.publishDraft(t,Promise.all(a)).then((t=>(e.isArchived()&&e.archive(!1),t))).catch((e=>this.handleError(e.message,"err")))}handleNewChatInvitation(e,t){const i=this.tinode.getTopic(e);let s=null;switch(t){case"accept":const n=i.getAccessMode().getGiven();s=i.setMeta({sub:{mode:n}}),i.isP2PType()&&(s=s.then((t=>i.setMeta({sub:{user:e,mode:n}}))));break;case"delete":s=i.delTopic(!0);break;case"block":const a=i.getAccessMode().updateWant("-JP").getWant();s=i.setMeta({sub:{mode:a}}).then((e=>this.handleTopicSelected(null)));break;default:console.warn("Unknown invitation action",'"'+t+'""')}null!=s&&s.catch((e=>this.handleError(e.message,"err")))}handleNewAccount(){this.handleError(),xh.Z.navigateTo(xh.Z.setUrlSidePanel(window.location.hash,"register"))}handleNewAccountRequest(e,t,i,s,n){this.handleError(),this.tinode.connect(this.state.serverAddress).then((a=>{let r;return i&&i.photo&&i.photo.ref&&(r=[i.photo.ref]),this.tinode.createAccountBasic(e,t,{public:i,tags:n,cred:ui.Tinode.credential(s),attachments:r})})).then((e=>{e.code>=300&&"validate credentials"==e.text?Pu.navigateToCredentialsView(e.params):this.handleLoginSuccessful(this)})).catch((e=>{this.handleError(e.message,"err")}))}handleToggleIncognitoMode(e){this.setState({incognitoMode:null});const t=this.tinode.getMeTopic(),i=t.getAccessMode().updateWant(e?"-P":"+P").getWant();t.setMeta({sub:{mode:i}}).catch((t=>{this.setState({incognitoMode:!e}),this.handleError(t.message,"err")}))}handleUpdateAccountTagsRequest(e,t){this.tinode.getMeTopic().setMeta({tags:t}).catch((e=>this.handleError(e.message,"err")))}handleSettings(){this.handleError(),xh.Z.navigateTo(xh.Z.setUrlSidePanel(window.location.hash,this.state.myUserId?"edit":"settings"))}handleGlobalSettings(e){const t=e.serverAddress||this.state.serverAddress,i=e.transport||this.state.transport,s=void 0===e.secureConnection?this.state.secureConnection:e.secureConnection;this.tinode&&(this.tinode.clearStorage(),this.tinode.onDisconnect=void 0,this.tinode.disconnect()),this.tinode=Pu.tnSetup(t,s,i,this.props.intl.locale,Cu.Z.getObject("keep-logged-in")),this.tinode.onConnect=this.handleConnected,this.tinode.onDisconnect=this.handleDisconnect,this.tinode.onAutoreconnectIteration=this.handleAutoreconnectIteration,this.tinode.onInfoMessage=this.handleInfoMessage,this.tinode.onDataMessage=this.handleDataMessage,this.setState({serverAddress:t,transport:i,secureConnection:s}),Cu.Z.setObject("settings",{serverAddress:t,transport:i,secureConnection:s}),xh.Z.navigateTo(xh.Z.setUrlSidePanel(window.location.hash,""))}handleShowArchive(){xh.Z.navigateTo(xh.Z.setUrlSidePanel(window.location.hash,this.state.myUserId?"archive":""))}handleShowBlocked(){xh.Z.navigateTo(xh.Z.setUrlSidePanel(window.location.hash,this.state.myUserId?"blocked":""))}toggleFCMToken(e){e?(this.setState({desktopAlerts:null}),this.state.firebaseToken?(this.setState({desktopAlerts:!0}),Cu.Z.getObject("keep-logged-in")&&Cu.Z.updateObject("settings",{desktopAlerts:!0})):this.initFCMessaging()):this.state.firebaseToken&&this.fcm?di(this.fcm).catch((e=>{console.error("Unable to delete token.",e)})).finally((e=>{Cu.Z.updateObject("settings",{desktopAlerts:!1}),localStorage.removeItem("firebase-token"),this.setState({desktopAlerts:!1,firebaseToken:null}),this.tinode.setDeviceToken(null)})):(this.setState({desktopAlerts:!1,firebaseToken:null}),Cu.Z.updateObject("settings",{desktopAlerts:!1}))}handleToggleMessageSounds(e){this.setState({messageSounds:e}),Cu.Z.updateObject("settings",{messageSoundsOff:!e})}handleCredAdd(e,t){this.tinode.getMeTopic().setMeta({cred:{meth:e,val:t}}).catch((e=>this.handleError(e.message,"err")))}handleCredDelete(e,t){this.tinode.getMeTopic().delCredential(e,t).catch((e=>this.handleError(e.message,"err")))}handleCredConfirm(e,t){Pu.navigateToCredentialsView({cred:[e],code:t})}handleSidepanelCancel(){const e=xh.Z.parseUrlHash(window.location.hash);let t="";["security","support","general","notif"].includes(e.path[0])?t="edit":"crop"==e.path[0]?t="general":"blocked"==e.path[0]?t="security":this.state.myUserId&&(t="contacts"),e.path[0]=t,e.params&&(delete e.params.code,delete e.params.method,delete e.params.tab,delete e.params.scheme,delete e.params.token),xh.Z.navigateTo(xh.Z.composeUrlHash(e.path,e.params)),this.setState({errorText:"",errorLevel:null})}basicNavigator(e){xh.Z.navigateTo(xh.Z.setUrlSidePanel(window.location.hash,e))}infoNavigator(e){xh.Z.navigateTo(xh.Z.setUrlInfoPanel(window.location.hash,e))}handleStartTopicRequest(e,t,i){if(e&&this.tinode.isTopicCached(e))return void this.handleTopicSelected(e);const s={};ui.Tinode.isP2PTopicName(e)?(s.sub={mode:mi.RK},s.desc={defacs:{auth:mi.RK}}):(e=e||this.tinode.newGroupTopicName(i),t&&(s.desc={public:t.public,private:{comment:t.private}},s.tags=t.tags)),s._topicName=e,this.setState({newTopicParams:s},(t=>{this.handleTopicSelected(e)}))}handleNewTopicCreated(e,t){let i={};this.state.callShouldStart&&(i={callState:Yi,callShouldStart:!1}),this.state.topicSelected==e&&e!=t&&(i.topicSelected=t),this.setState(i,(e=>{xh.Z.navigateTo(xh.Z.setUrlTopic("",t))}))}handleTopicUpdateRequest(e,t,i,s){this.handleError();const n=this.tinode.getTopic(e);if(n){const e={};let a;t&&(t.photo&&(t.photo.ref&&t.photo.ref!=ui.Tinode.DEL_CHAR?a=[t.photo.ref]:t.photo.data&&t.photo.data!=ui.Tinode.DEL_CHAR||(t.photo=ui.Tinode.DEL_CHAR)),e.public=t),"string"==typeof i&&(e.private=i===ui.Tinode.DEL_CHAR?ui.Tinode.DEL_CHAR:{comment:i}),s&&(e.defacs=s),n.setMeta({desc:e,attachments:a}).catch((e=>this.handleError(e.message,"err")))}}handleUnarchive(e){const t=this.tinode.getTopic(e);t&&t.archive(!1).catch((e=>this.handleError(e.message,"err")))}handleUpdatePasswordRequest(e){this.handleError(),e&&this.tinode.updateAccountBasic(null,this.tinode.getCurrentLogin(),e).catch((e=>this.handleError(e.message,"err")))}handleChangePermissions(e,t,i){const s=this.tinode.getTopic(e);if(s){const e=s.getAccessMode();i?(e.updateGiven(t),t=e.getGiven()):(e.updateWant(t),t=e.getWant()),s.setMeta({sub:{user:i,mode:t}}).catch((e=>this.handleError(e.message,"err")))}}handleTagsUpdateRequest(e,t){const i=this.tinode.getTopic(e);i&&i.setMeta({tags:t}).catch((e=>this.handleError(e.message,"err")))}handleLogout(){let e;(0,Di.J_)(0),localStorage.removeItem("auth-token"),localStorage.removeItem("firebase-token"),localStorage.removeItem("settings"),this.state.firebaseToken&&di(this.fcm),clearInterval(this.reconnectCountdown),this.tinode?(e=this.tinode.clearStorage(),this.tinode.onDisconnect=void 0,this.tinode.disconnect()):e=Promose.resolve(),this.setState(this.getBlankState()),e.then((e=>{this.tinode=Pu.tnSetup(this.state.serverAddress,wu(),this.state.transport,this.props.intl.locale,Cu.Z.getObject("keep-logged-in"),(e=>{this.tinode.onConnect=this.handleConnected,this.tinode.onDisconnect=this.handleDisconnect,this.tinode.onAutoreconnectIteration=this.handleAutoreconnectIteration,this.tinode.onInfoMessage=this.handleInfoMessage,this.tinode.onDataMessage=this.handleDataMessage,xh.Z.navigateTo("")}))}))}handleDeleteAccount(){this.tinode.delCurrentUser(!0).then((e=>{this.handleLogout()}))}handleDeleteTopicRequest(e){const t=this.tinode.getTopic(e);t&&t.delTopic(!0).then((e=>{xh.Z.navigateTo(xh.Z.setUrlTopic(window.location.hash,""))})).catch((e=>{this.handleError(e.message,"err")}))}handleDeleteMessagesRequest(e){const t=this.tinode.getTopic(e);t&&t.delMessagesAll(!0).catch((e=>this.handleError(e.message,"err")))}handleLeaveUnsubRequest(e){const t=this.tinode.getTopic(e);t&&t.leave(!0).then((e=>{xh.Z.navigateTo(xh.Z.setUrlTopic(window.location.hash,""))})).catch((e=>{this.handleError(e.message,"err")}))}handleBlockTopicRequest(e){const t=this.tinode.getTopic(e);t&&t.updateMode(null,"-JP").then((e=>{xh.Z.navigateTo(xh.Z.setUrlTopic(window.location.hash,""))})).catch((e=>this.handleError(e.message,"err")))}handleReportTopic(e){const t=this.tinode.getTopic(e);t&&(this.tinode.report("report",e),t.updateMode(null,"-JP").then((e=>{xh.Z.navigateTo(xh.Z.setUrlTopic(window.location.hash,""))})).catch((e=>this.handleError(e.message,"err"))))}handleShowContextMenu(e,t){this.setState({contextMenuVisible:!0,contextMenuClickAt:{x:e.x,y:e.y},contextMenuParams:e,contextMenuItems:t||this.defaultTopicContextMenu(e.topicName),contextMenuBounds:this.selfRef.current.getBoundingClientRect()})}handleShowForwardDialog(e){"newtpk"==this.state.sidePanelSelected&&this.handleSidepanelCancel();const t="➦ "+e.userName,i="string"==typeof e.content?ui.Drafty.init(e.content):ui.Drafty.forwardedContent(e.content),s=ui.Drafty.preview(i,mi.vX,!0),n=ui.Drafty.append(ui.Drafty.appendLineBreak(ui.Drafty.mention(t,e.userFrom)),i),a=ui.Drafty.quote(t,e.userFrom,s),r={forwarded:e.topicName+":"+e.seq};this.setState({forwardDialogVisible:!0,forwardMessage:{head:r,msg:n,preview:a}})}defaultTopicContextMenu(e){const t=this.tinode.getTopic(e);if(t._deleted)return["topic_delete"];let i=!1,s=!1,n=!1,a=!1,r=!1,o=!1,c=!1,l=!1;if(t){a=t.isSubscribed(),o=t.isArchived();const e=t.getAccessMode();e&&(i=e.isMuted(),s=!e.isJoiner(),n=!e.isJoiner("want"),r=e.isDeleter(),l=e.isWriter())}c=l&&!!this.tinode.getServerParam("iceServers");const d=!!this.tinode.getServerParam("vcEndpoint");return[a?{title:this.props.intl.formatMessage(Tu.menu_item_info),handler:this.handleShowInfoView}:null,a&&ui.Tinode.isP2PTopicName(e)&&c?{title:this.props.intl.formatMessage(Tu.menu_item_audio_call),handler:this.handleStartAudioCall}:null,a&&c?{title:this.props.intl.formatMessage(Tu.menu_item_video_call),disabled:ui.Tinode.isGroupTopicName(e)&&!d,handler:this.handleStartVideoCall}:null,a?"messages_clear":null,a&&r?"messages_clear_hard":null,i?s?null:"topic_unmute":"topic_mute",n?"topic_unblock":"topic_block",o?"topic_restore":"topic_archive","topic_delete"]}handleHideContextMenu(){this.setState({contextMenuVisible:!1,contextMenuClickAt:null,contextMenuParams:null,contextMenuBounds:null})}handleHideForwardDialog(e){this.setState({forwardDialogVisible:!1,forwardMessage:e?this.state.forwardMessage:null})}handleContextMenuAction(e,t,i){"topic_archive"==e?t&&i.topicName&&i.topicName==this.state.topicSelected&&t.then((e=>{this.handleTopicSelected(null)})):"menu_item_forward"==e&&this.handleShowForwardDialog(i)}handleShowAlert(e,t,i,s,n,a){this.setState({alertVisible:!0,alertParams:{title:e,content:t,onConfirm:i,confirm:s,onReject:n,reject:a}})}handleShowInfoView(){xh.Z.navigateTo(xh.Z.addUrlParam(window.location.hash,"info","info")),this.setState({infoPanel:"info"})}handleMemberUpdateRequest(e,t,i){if(!e)return;const s=this.tinode.getTopic(e);s&&(t&&t.length>0&&t.forEach((e=>{s.invite(e,null).catch((e=>this.handleError(e.message,"err")))})),i&&i.length>0&&i.forEach((e=>{s.delSubscription(e).catch((e=>this.handleError(e.message,"err")))})))}handleValidateCredentialsRequest(e,t,i){this.tinode.isAuthenticated()?this.tinode.getMeTopic().setMeta({cred:{meth:e,resp:t}}).then((e=>xh.Z.navigateTo(xh.Z.setUrlSidePanel(window.location.hash,"contacts")))).catch((e=>this.handleError(e.message,"err"))):(this.setState({credMethod:e,credCode:t,credToken:i}),this.doLogin(null,null,i,{meth:e,resp:t}))}handlePasswordResetRequest(e,t){return this.tinode.connect().then((i=>this.tinode.requestResetAuthSecret("basic",e,t))).catch((e=>{this.handleError(e.message,"err")}))}handleResetPassword(e,t){const i=(0,Ni.DC)(t.secret);i&&t.scheme?this.tinode.connect().then((s=>this.tinode.updateAccountBasic(null,null,e,{scheme:t.scheme,secret:i}))).then((e=>xh.Z.navigateTo(""))).catch((e=>{this.handleError(e.message,"err")})):this.handleError(this.props.intl.formatMessage(Tu.invalid_security_token),"err")}handleShowCountrySelector(i,n,a){this.handleShowAlert("Select country",t().createElement(e.Suspense,{fallback:t().createElement("div",null,t().createElement(s.FormattedMessage,{id:"loading_note",defaultMessage:[{type:0,value:"Loading..."}]}))},t().createElement(ku,{selected:i,onSubmit:(e,t)=>{this.setState({alertVisible:!1}),a(e,t)}})),null,null,(e=>{}),"Cancel")}handleStartVideoCall(){this.setState({callTopic:this.state.topicSelected,callState:Xi,callAudioOnly:!1})}handleStartAudioCall(){this.setState({callTopic:this.state.topicSelected,callState:Xi,callAudioOnly:!0})}handleCallInvite(e,t,i,s){switch(i){case Xi:const i={webrtc:es,aonly:!!s},n=ui.Drafty.videoCall(s);return ui.Tinode.isGroupTopicName(e)&&(i.vc=!0),this.handleSendMessage(n,void 0,void 0,i).then((e=>e.code<200||e.code>=300||!e.params||!e.params.seq?(this.handleCallClose(),e):(this.setState({callSeq:e.params.seq}),e)));case Yi:const a=this.tinode.getTopic(e);if(!a)return;a.videoCall("accept",t)}}handleCallRinging(e,t){const i=this.tinode.getTopic(e);i&&i.videoCall("ringing",t)}handleCallHangup(e,t){const i=this.tinode.getTopic(e);i&&i.videoCall("hang-up",t)}handleCallSendOffer(e,t,i){const s=this.tinode.getTopic(e);s&&s.videoCall("offer",t,i)}handleCallIceCandidate(e,t,i){const s=this.tinode.getTopic(e);s&&s.videoCall("ice-candidate",t,i)}handleCallSendAnswer(e,t,i){const s=this.tinode.getTopic(e);s&&s.videoCall("answer",t,i)}handleVCCallJoin(e,t){const i=this.tinode.getTopic(e);i&&i.videoCall("vc-join",t)}handleCallClose(){this.callTimeoutTimer&&clearTimeout(this.callTimeoutTimer),this.setState({callTopic:void 0,callState:0,callAudioOnly:void 0})}handleCallAccept(e,t,i){const s=this.tinode.getTopic(e);if(s)if(s.isSubscribed()){this.handleTopicSelected(t?e:this.state.callTopic);const s={callState:Yi};t&&(s.callTopic=e,s.callSeq=i),this.setState(s)}else this.setState({callShouldStart:!0},(e=>this.handleTopicSelected(this.state.callTopic)))}handleInfoMessage(e){if("call"==e.what)switch(e.event){case"accept":if(ui.Tinode.isMeTopicName(e.topic)&&this.tinode.isMe(e.from))return void this.setState({callTopic:null,callState:0,callSeq:null,callAudioOnly:void 0});e.topic==this.state.callTopic&&this.setState({callState:Yi});break;case"hang-up":this.handleCallClose()}}handleDataMessage(e){if(e.head&&e.head.webrtc&&e.head.webrtc==es&&ui.Tinode.isP2PTopicName(e.topic)){const t=this.tinode.getTopic(e.topic);if(t){const i=t.latestMsgVersion(e.seq)||e;i.head&&i.head.webrtc&&i.head.webrtc==es&&e.from!=this.state.myUserId&&(0==this.state.callState?this.setState({callTopic:e.topic,callState:2,callSeq:e.seq,callAudioOnly:!!i.head.aonly}):this.handleCallHangup(e.topic,e.seq))}else console.warn("Received vc data message from unknown topic",e.topic)}}render(){return t().createElement("div",{id:"app-container",ref:this.selfRef},this.state.contextMenuVisible?t().createElement(vi,{tinode:this.tinode,bounds:this.state.contextMenuBounds,clickAt:this.state.contextMenuClickAt,params:this.state.contextMenuParams,items:this.state.contextMenuItems,hide:this.handleHideContextMenu,onShowAlert:this.handleShowAlert,onAction:this.handleContextMenuAction,onTopicRemoved:e=>{e==this.state.topicSelected&&this.handleTopicSelected(null)},onError:this.handleError}):null,this.state.forwardDialogVisible?t().createElement(Ki,{tinode:this.tinode,contacts:this.state.chatList,topicSelected:this.state.topicSelected,myUserId:this.state.myUserId,hide:this.handleHideForwardDialog,onInitFind:this.tnInitFind,searchResults:this.state.searchResults,onSearchContacts:this.handleSearchContacts,onTopicSelected:this.handleStartTopicRequest}):null,this.state.callTopic&&2==this.state.callState?t().createElement(is,{tinode:this.tinode,topic:this.state.callTopic,seq:this.state.callSeq,callState:this.state.callState,audioOnly:this.state.callAudioOnly,onClose:this.handleCallClose,onRinging:this.handleCallRinging,onAcceptCall:this.handleCallAccept,onReject:this.handleCallHangup}):null,this.state.alertVisible?t().createElement(pi,{title:this.state.alertParams.title,content:this.state.alertParams.content,onReject:this.state.alertParams.onReject?e=>this.setState({alertVisible:!1}):null,reject:this.state.alertParams.reject,onConfirm:this.state.alertParams.onConfirm?e=>{this.setState({alertVisible:!1}),this.state.alertParams.onConfirm()}:null,confirm:this.state.alertParams.confirm}):null,this.state.displayMobile&&"sidepanel"!=this.state.mobilePanel?null:t().createElement(bu,{tinode:this.tinode,connected:this.state.connected,displayMobile:this.state.displayMobile,state:this.state.sidePanelSelected,title:this.state.sidePanelTitle,avatar:this.state.sidePanelAvatar,trustedBadges:this.state.myTrustedBadges,login:this.state.login,persist:this.state.persist,myUserId:this.state.myUserId,loginDisabled:this.state.loginDisabled,loadSpinnerVisible:this.state.loadSpinnerVisible,errorText:this.state.errorText,errorLevel:this.state.errorLevel,errorAction:this.state.errorAction,errorActionText:this.state.errorActionText,topicSelected:this.state.topicSelected,chatList:this.state.chatList,credMethod:this.state.credMethod,credCode:this.state.credCode,credToken:this.state.credToken,transport:this.state.transport,messageSounds:this.state.messageSounds,desktopAlerts:this.state.desktopAlerts,desktopAlertsEnabled:this.state.desktopAlertsEnabled,incognitoMode:this.state.incognitoMode,serverAddress:this.state.serverAddress,secureConnection:this.state.secureConnection,serverVersion:this.state.serverVersion,reqCredMethod:this.state.reqCredMethod,onGlobalSettings:this.handleGlobalSettings,onSignUp:this.handleNewAccount,onSettings:this.handleSettings,onNavigate:this.basicNavigator,onLoginRequest:this.handleLoginRequest,onPersistenceChange:this.handlePersistenceChange,onCreateAccount:this.handleNewAccountRequest,onUpdateAccountDesc:this.handleTopicUpdateRequest,onUpdatePassword:this.handleUpdatePasswordRequest,onUpdateAccountTags:this.handleUpdateAccountTagsRequest,onTogglePushNotifications:this.toggleFCMToken,onToggleMessageSounds:this.handleToggleMessageSounds,onToggleIncognitoMode:this.handleToggleIncognitoMode,onCredAdd:this.handleCredAdd,onCredDelete:this.handleCredDelete,onCredConfirm:this.handleCredConfirm,onTopicSelected:this.handleTopicSelected,onCreateTopic:this.handleStartTopicRequest,onLogout:this.handleLogout,onDeleteAccount:this.handleDeleteAccount,onShowAlert:this.handleShowAlert,onCancel:this.handleSidepanelCancel,onError:this.handleError,onValidateCredentials:this.handleValidateCredentialsRequest,onPasswordResetRequest:this.handlePasswordResetRequest,onResetPassword:this.handleResetPassword,onShowArchive:this.handleShowArchive,onShowBlocked:this.handleShowBlocked,onShowCountrySelector:this.handleShowCountrySelector,onInitFind:this.tnInitFind,searchResults:this.state.searchResults,onSearchContacts:this.handleSearchContacts,showContextMenu:this.handleShowContextMenu}),!this.state.displayMobile||"topic-view"==this.state.mobilePanel&&!this.state.infoPanel?t().createElement(Vh,{tinode:this.tinode,connected:this.state.connected,ready:this.state.ready,online:this.state.topicSelectedOnline,acs:this.state.topicSelectedAcs,displayMobile:this.state.displayMobile,viewportWidth:this.state.viewportWidth,viewportHeight:this.state.viewportHeight,topic:this.state.topicSelected,myUserId:this.state.myUserId,myUserName:this.state.sidePanelTitle,serverVersion:this.state.serverVersion,serverAddress:this.state.serverAddress,applicationVisible:this.state.applicationVisible,forwardMessage:this.state.forwardMessage,onCancelForwardMessage:this.handleHideForwardDialog,callTopic:this.state.callTopic,callSeq:this.state.callSeq,callState:this.state.callState,callAudioOnly:this.state.callAudioOnly,onCallHangup:this.handleCallHangup,onAcceptCall:this.handleCallAccept,onCallInvite:this.handleCallInvite,onCallSendOffer:this.handleCallSendOffer,onCallIceCandidate:this.handleCallIceCandidate,onCallSendAnswer:this.handleCallSendAnswer,onVCJoin:this.handleVCCallJoin,errorText:this.state.errorText,errorLevel:this.state.errorLevel,errorAction:this.state.errorAction,errorActionText:this.state.errorActionText,newTopicParams:this.state.newTopicParams,onHideMessagesView:this.handleHideMessagesView,onError:this.handleError,onNewTopicCreated:this.handleNewTopicCreated,showContextMenu:this.handleShowContextMenu,onChangePermissions:this.handleChangePermissions,onNewChat:this.handleNewChatInvitation,sendMessage:this.handleSendMessage,onVideoCallClosed:this.handleCallClose}):null,this.state.infoPanel?t().createElement(Ps,{tinode:this.tinode,connected:this.state.connected,displayMobile:this.state.displayMobile,topic:this.state.topicSelected,searchableContacts:this.state.searchableContacts,myUserId:this.state.myUserId,panel:this.state.infoPanel,errorText:this.state.errorText,errorLevel:this.state.errorLevel,errorAction:this.state.errorAction,errorActionText:this.state.errorActionText,onNavigate:this.infoNavigator,onTopicDescUpdateRequest:this.handleTopicUpdateRequest,onShowAlert:this.handleShowAlert,onChangePermissions:this.handleChangePermissions,onMemberUpdateRequest:this.handleMemberUpdateRequest,onDeleteTopic:this.handleDeleteTopicRequest,onDeleteMessages:this.handleDeleteMessagesRequest,onLeaveTopic:this.handleLeaveUnsubRequest,onBlockTopic:this.handleBlockTopicRequest,onReportTopic:this.handleReportTopic,onAddMember:this.handleManageGroupMembers,onTopicTagsUpdateRequest:this.handleTagsUpdateRequest,onTopicUnArchive:this.handleUnarchive,onInitFind:this.tnInitFind,onError:this.handleError,showContextMenu:this.handleShowContextMenu}):null)}}const Mu=(0,s.injectIntl)(Pu);if("undefined"!=typeof FIREBASE_INIT&&FIREBASE_INIT&&FIREBASE_INIT.measurementId){const xu=document.getElementsByTagName("head")[0];let Lu=document.createElement("script");function Fu(){dataLayer.push(arguments)}Lu.src="https://www.googletagmanager.com/gtag/js?id="+FIREBASE_INIT.measurementId,Lu.async=!0,xu.prepend(Lu),window.dataLayer=window.dataLayer||[],Fu("js",new Date),Fu("config",FIREBASE_INIT.measurementId)}const Ru={de:e=>r.e(92).then(r.t.bind(r,6092,19)),en:e=>r.e(514).then(r.t.bind(r,4514,19)),es:e=>r.e(932).then(r.t.bind(r,9932,19)),fr:e=>r.e(107).then(r.t.bind(r,107,19)),ko:e=>r.e(898).then(r.t.bind(r,898,19)),ro:e=>r.e(817).then(r.t.bind(r,4817,19)),ru:e=>r.e(734).then(r.t.bind(r,3734,19)),zh:e=>r.e(700).then(r.t.bind(r,5700,19)),"zh-TW":e=>r.e(226).then(r.t.bind(r,5226,19))},{params:_u}=xh.Z.parseUrlHash(window.location.hash),Nu=_u&&_u.hl||navigator.languages&&navigator.languages[0]||navigator.language||navigator.userLanguage||"en",Du=Nu.replace("_","-"),Iu=Du.split("-")[0].toLowerCase(),Au=Ru[Du]?Nu:Ru[Iu]?Iu:"en";document.getElementsByTagName("html")[0].setAttribute("lang",Au);const Ou=(0,i.s)(document.getElementById("mountPoint"));Ru[Au]().then((e=>Ou.render(t().createElement(s.IntlProvider,{locale:Nu,messages:e,textComponent:t().Fragment},t().createElement(Mu,null)))))})()})();
//# sourceMappingURL=index.prod.js.map