Files
im_webapp/umd/index.prod.js
T
2023-06-10 12:14:59 -07:00

2 lines
683 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:()=>E,H2:()=>T,Hm:()=>C,IX:()=>v,JG:()=>o,Mv:()=>r,NW:()=>j,RK:()=>p,Rc:()=>a,S8:()=>_,S9:()=>q,VL:()=>d,Zd:()=>R,Zf:()=>F,cG:()=>h,cl:()=>O,dm:()=>N,gD:()=>I,iC:()=>s,kd:()=>k,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:()=>w,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,C=24,k=262144,E=1<<23,w=1024,T=64,P=96,M=36,R=48,N=4,_=60,D=360,I=20,A=80,O=30,U=84,x=48,L=2e3,F=6e5,B="mailto:support@tinode.co",j="https://tinode.co/privacy.html",q="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(6)}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-rc2"},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 C(e){return e&&e._delegate?e._delegate:e}class k{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 E="[DEFAULT]";class w{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:E})}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=E){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=E){return this.instances.has(e)}getOptions(e=E){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===E?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=E){return this.component?this.component.multipleInstances?e:E: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 w(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},N=M.INFO,_={[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=_[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 j={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 q(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(J(this),t),$(U.get(this))}:function(...t){return $(e.apply(J(this),t))}:function(t,...i){const s=e.call(J(this),t,...i);return L.set(s,t.sort?t.sort():[t]),$(s)}}function V(e){return"function"==typeof e?q(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,j):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 J=e=>B.get(e);const W=["get","getKey","getAll","getAllKeys","count"],H=["put","add","delete","clear"],G=new Map;function Z(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(G.get(t))return G.get(t);const i=t.replace(/FromIndex$/,""),s=t!==i,n=H.includes(i);if(!(i in(s?IDBIndex:IDBObjectStore).prototype)||!n&&!W.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 G.set(t,a),a}j=(e=>({...e,get:(t,i,s)=>Z(t,i)||e.get(t,i,s),has:(t,i)=>!!Z(t,i)||e.has(t,i)}))(j);class z{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 K="@firebase/app",Q="0.9.12",Y=new class{constructor(e){this.name=e,this._logLevel=N,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"),X="[DEFAULT]",ee={[K]:"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"},te=new Map,ie=new Map;function se(e,t){try{e.container.addComponent(t)}catch(i){Y.debug(`Component ${t.name} failed to register with FirebaseApp ${e.name}`,i)}}function ne(e){const t=e.name;if(ie.has(t))return Y.debug(`There were multiple attempts to register component ${t}.`),!1;ie.set(t,e);for(const t of te.values())se(t,e);return!0}function ae(e,t){const i=e.container.getProvider("heartbeat").getImmediate({optional:!0});return i&&i.triggerHeartbeat(),e.container.getProvider(t)}const re=new v("app","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call initializeApp() first","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 oe{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 k("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 re.create("app-deleted",{appName:this._name})}}function ce(e,t={}){let i=e;if("object"!=typeof t){t={name:t}}const s=Object.assign({name:X,automaticDataCollectionEnabled:!1},t),n=s.name;if("string"!=typeof n||!n)throw re.create("bad-app-name",{appName:String(n)});if(i||(i=u()),!i)throw re.create("no-options");const a=te.get(n);if(a){if(y(i,a.options)&&y(s,a.config))return a;throw re.create("duplicate-app",{appName:n})}const r=new T(n);for(const e of ie.values())r.addComponent(e);const o=new oe(i,s,r);return te.set(n,o),o}function le(e,t,i){var s;let n=null!==(s=ee[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 Y.warn(e.join(" "))}ne(new k(`${n}-version`,(()=>({library:n,version:t})),"VERSION"))}const de="firebase-heartbeat-database",he=1,ue="firebase-heartbeat-store";let pe=null;function me(){return pe||(pe=function(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),e)})),i&&r.addEventListener("blocked",(e=>i(e.oldVersion,e.newVersion,e))),o.then((e=>{a&&e.addEventListener("close",(()=>a())),n&&e.addEventListener("versionchange",(e=>n(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),o}(de,he,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(ue)}}).catch((e=>{throw re.create("idb-open",{originalErrorMessage:e.message})}))),pe}async function ge(e,t){try{const i=(await me()).transaction(ue,"readwrite"),s=i.objectStore(ue);await s.put(t,fe(e)),await i.done}catch(e){if(e instanceof f)Y.warn(e.message);else{const t=re.create("idb-set",{originalErrorMessage:null==e?void 0:e.message});Y.warn(t.message)}}}function fe(e){return`${e.name}!${e.options.appId}`}class ve{constructor(e){this.container=e,this._heartbeatsCache=null;const t=this.container.getProvider("app").getImmediate();this._storage=new ye(t),this._heartbeatsCachePromise=this._storage.read().then((e=>(this._heartbeatsCache=e,e)))}async triggerHeartbeat(){const e=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),t=be();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=be(),{heartbeatsToSend:t,unsentEntries:i}=function(e,t=1024){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),Se(i)>t){e.dates.pop();break}}else if(i.push({agent:n.agent,dates:[n.date]}),Se(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 be(){return(new Date).toISOString().substring(0,10)}class ye{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{const t=await me();return await t.transaction(ue).objectStore(ue).get(fe(e))}catch(e){if(e instanceof f)Y.warn(e.message);else{const t=re.create("idb-get",{originalErrorMessage:null==e?void 0:e.message});Y.warn(t.message)}}}(this.app)||{heartbeats:[]}}return{heartbeats:[]}}async overwrite(e){var t;if(await this._canUseIndexedDBPromise){const i=await this.read();return ge(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 ge(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:i.lastSentHeartbeatDate,heartbeats:[...i.heartbeats,...e.heartbeats]})}}}function Se(e){return c(JSON.stringify({version:2,heartbeats:e})).length}var Ce;Ce="",ne(new k("platform-logger",(e=>new z(e)),"PRIVATE")),ne(new k("heartbeat",(e=>new ve(e)),"PRIVATE")),le(K,Q,Ce),le(K,Q,"esm2017"),le("fire-js","");le("firebase","9.22.2","app");const ke=(e,t)=>t.some((t=>e instanceof t));let Ee,we;const Te=new WeakMap,Pe=new WeakMap,Me=new WeakMap,Re=new WeakMap,Ne=new WeakMap;let _e={get(e,t,i){if(e instanceof IDBTransaction){if("done"===t)return Pe.get(e);if("objectStoreNames"===t)return e.objectStoreNames||Me.get(e);if("store"===t)return i.objectStoreNames[1]?void 0:i.objectStore(i.objectStoreNames[0])}return Ae(e[t])},set:(e,t,i)=>(e[t]=i,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function De(e){return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(we||(we=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(Oe(this),t),Ae(Te.get(this))}:function(...t){return Ae(e.apply(Oe(this),t))}:function(t,...i){const s=e.call(Oe(this),t,...i);return Me.set(s,t.sort?t.sort():[t]),Ae(s)}}function Ie(e){return"function"==typeof e?De(e):(e instanceof IDBTransaction&&function(e){if(Pe.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)}));Pe.set(e,t)}(e),ke(e,Ee||(Ee=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,_e):e)}function Ae(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(Ae(e.result)),s()},a=()=>{i(e.error),s()};e.addEventListener("success",n),e.addEventListener("error",a)}));return t.then((t=>{t instanceof IDBCursor&&Te.set(t,e)})).catch((()=>{})),Ne.set(t,e),t}(e);if(Re.has(e))return Re.get(e);const t=Ie(e);return t!==e&&(Re.set(e,t),Ne.set(t,e)),t}const Oe=e=>Ne.get(e);const Ue=["get","getKey","getAll","getAllKeys","count"],xe=["put","add","delete","clear"],Le=new Map;function Fe(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(Le.get(t))return Le.get(t);const i=t.replace(/FromIndex$/,""),s=t!==i,n=xe.includes(i);if(!(i in(s?IDBIndex:IDBObjectStore).prototype)||!n&&!Ue.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 Le.set(t,a),a}!function(e){_e=e(_e)}((e=>({...e,get:(t,i,s)=>Fe(t,i)||e.get(t,i,s),has:(t,i)=>!!Fe(t,i)||e.has(t,i)})));const Be="@firebase/installations",je="0.6.4",qe=1e4,Ve=`w:${je}`,$e="FIS_v2",Je="https://firebaseinstallations.googleapis.com/v1",We=36e5,He=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 Ge(e){return e instanceof f&&e.code.includes("request-failed")}function Ze({projectId:e}){return`${Je}/projects/${e}/installations`}function ze(e){return{token:e.token,requestStatus:2,expiresIn:(t=e.expiresIn,Number(t.replace("s","000"))),creationTime:Date.now()};var t}async function Ke(e,t){const i=(await t.json()).error;return He.create("request-failed",{requestName:e,serverCode:i.code,serverMessage:i.message,serverStatus:i.status})}function Qe({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function Ye(e,{refreshToken:t}){const i=Qe(e);return i.append("Authorization",function(e){return`${$e} ${e}`}(t)),i}async function Xe(e){const t=await e();return t.status>=500&&t.status<600?e():t}function et(e){return new Promise((t=>{setTimeout(t,e)}))}const tt=/^[cdef][\w-]{21}$/,it="";function st(){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 tt.test(t)?t:it}catch(e){return it}}function nt(e){return`${e.appName}!${e.appId}`}const at=new Map;function rt(e,t){const i=nt(e);ot(i,t),function(e,t){const i=lt();i&&i.postMessage({key:e,fid:t});dt()}(i,t)}function ot(e,t){const i=at.get(e);if(i)for(const e of i)e(t)}let ct=null;function lt(){return!ct&&"BroadcastChannel"in self&&(ct=new BroadcastChannel("[Firebase] FID Change"),ct.onmessage=e=>{ot(e.data.key,e.data.fid)}),ct}function dt(){0===at.size&&ct&&(ct.close(),ct=null)}const ht="firebase-installations-database",ut=1,pt="firebase-installations-store";let mt=null;function gt(){return mt||(mt=function(e,t,{blocked:i,upgrade:s,blocking:n,terminated:a}={}){const r=indexedDB.open(e,t),o=Ae(r);return s&&r.addEventListener("upgradeneeded",(e=>{s(Ae(r.result),e.oldVersion,e.newVersion,Ae(r.transaction))})),i&&r.addEventListener("blocked",(()=>i())),o.then((e=>{a&&e.addEventListener("close",(()=>a())),n&&e.addEventListener("versionchange",(()=>n()))})).catch((()=>{})),o}(ht,ut,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(pt)}})),mt}async function ft(e,t){const i=nt(e),s=(await gt()).transaction(pt,"readwrite"),n=s.objectStore(pt),a=await n.get(i);return await n.put(t,i),await s.done,a&&a.fid===t.fid||rt(e,t.fid),t}async function vt(e){const t=nt(e),i=(await gt()).transaction(pt,"readwrite");await i.objectStore(pt).delete(t),await i.done}async function bt(e,t){const i=nt(e),s=(await gt()).transaction(pt,"readwrite"),n=s.objectStore(pt),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||rt(e,r.fid),r}async function yt(e){let t;const i=await bt(e.appConfig,(i=>{const s=function(e){const t=e||{fid:st(),registrationStatus:0};return kt(t)}(i),n=function(e,t){if(0===t.registrationStatus){if(!navigator.onLine){return{installationEntry:t,registrationPromise:Promise.reject(He.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=Ze(e),n=Qe(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:Ve},o={method:"POST",headers:n,body:JSON.stringify(r)},c=await Xe((()=>fetch(s,o)));if(c.ok){const e=await c.json();return{fid:e.fid||i,registrationStatus:2,refreshToken:e.refreshToken,authToken:ze(e.authToken)}}throw await Ke("Create Installation",c)}(e,t);return ft(e.appConfig,i)}catch(i){throw Ge(i)&&409===i.customData.serverCode?await vt(e.appConfig):await ft(e.appConfig,{fid:t.fid,registrationStatus:0}),i}}(e,i);return{installationEntry:i,registrationPromise:s}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:St(e)}:{installationEntry:t}}(e,s);return t=n.registrationPromise,n.installationEntry}));return i.fid===it?{installationEntry:await t}:{installationEntry:i,registrationPromise:t}}async function St(e){let t=await Ct(e.appConfig);for(;1===t.registrationStatus;)await et(100),t=await Ct(e.appConfig);if(0===t.registrationStatus){const{installationEntry:t,registrationPromise:i}=await yt(e);return i||t}return t}function Ct(e){return bt(e,(e=>{if(!e)throw He.create("installation-not-found");return kt(e)}))}function kt(e){return 1===(t=e).registrationStatus&&t.registrationTime+qe<Date.now()?{fid:e.fid,registrationStatus:0}:e;var t}async function Et({appConfig:e,heartbeatServiceProvider:t},i){const s=function(e,{fid:t}){return`${Ze(e)}/${t}/authTokens:generate`}(e,i),n=Ye(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:Ve,appId:e.appId}},o={method:"POST",headers:n,body:JSON.stringify(r)},c=await Xe((()=>fetch(s,o)));if(c.ok){return ze(await c.json())}throw await Ke("Generate Auth Token",c)}async function wt(e,t=!1){let i;const s=await bt(e.appConfig,(s=>{if(!Pt(s))throw He.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+We}(e)}(n))return s;if(1===n.requestStatus)return i=async function(e,t){let i=await Tt(e.appConfig);for(;1===i.authToken.requestStatus;)await et(100),i=await Tt(e.appConfig);const s=i.authToken;return 0===s.requestStatus?wt(e,t):s}(e,t),s;{if(!navigator.onLine)throw He.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 Et(e,t),s=Object.assign(Object.assign({},t),{authToken:i});return await ft(e.appConfig,s),i}catch(i){if(!Ge(i)||401!==i.customData.serverCode&&404!==i.customData.serverCode){const i=Object.assign(Object.assign({},t),{authToken:{requestStatus:0}});await ft(e.appConfig,i)}else await vt(e.appConfig);throw i}}(e,t),t}}));return i?await i:s.authToken}function Tt(e){return bt(e,(e=>{if(!Pt(e))throw He.create("not-registered");const t=e.authToken;return 1===(i=t).requestStatus&&i.requestTime+qe<Date.now()?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e;var i}))}function Pt(e){return void 0!==e&&2===e.registrationStatus}async function Mt(e,t=!1){const i=e;await async function(e){const{registrationPromise:t}=await yt(e);t&&await t}(i);return(await wt(i,t)).token}function Rt(e){return He.create("missing-app-config-values",{valueName:e})}const Nt="installations",_t=e=>{const t=ae(e.getProvider("app").getImmediate(),Nt).getImmediate();return{getId:()=>async function(e){const t=e,{installationEntry:i,registrationPromise:s}=await yt(t);return s?s.catch(console.error):wt(t).catch(console.error),i.fid}(t),getToken:e=>Mt(t,e)}};ne(new k(Nt,(e=>{const t=e.getProvider("app").getImmediate(),i=function(e){if(!e||!e.options)throw Rt("App Configuration");if(!e.name)throw Rt("App Name");const t=["projectId","apiKey","appId"];for(const i of t)if(!e.options[i])throw Rt(i);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t);return{app:t,appConfig:i,heartbeatServiceProvider:ae(t,"heartbeat"),_delete:()=>Promise.resolve()}}),"PUBLIC")),ne(new k("installations-internal",_t,"PRIVATE")),le(Be,je),le(Be,je,"esm2017");const Dt=(e,t)=>t.some((t=>e instanceof t));let It,At;const Ot=new WeakMap,Ut=new WeakMap,xt=new WeakMap,Lt=new WeakMap,Ft=new WeakMap;let Bt={get(e,t,i){if(e instanceof IDBTransaction){if("done"===t)return Ut.get(e);if("objectStoreNames"===t)return e.objectStoreNames||xt.get(e);if("store"===t)return i.objectStoreNames[1]?void 0:i.objectStore(i.objectStoreNames[0])}return Vt(e[t])},set:(e,t,i)=>(e[t]=i,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function jt(e){return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(At||(At=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply($t(this),t),Vt(Ot.get(this))}:function(...t){return Vt(e.apply($t(this),t))}:function(t,...i){const s=e.call($t(this),t,...i);return xt.set(s,t.sort?t.sort():[t]),Vt(s)}}function qt(e){return"function"==typeof e?jt(e):(e instanceof IDBTransaction&&function(e){if(Ut.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)}));Ut.set(e,t)}(e),Dt(e,It||(It=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,Bt):e)}function Vt(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(Vt(e.result)),s()},a=()=>{i(e.error),s()};e.addEventListener("success",n),e.addEventListener("error",a)}));return t.then((t=>{t instanceof IDBCursor&&Ot.set(t,e)})).catch((()=>{})),Ft.set(t,e),t}(e);if(Lt.has(e))return Lt.get(e);const t=qt(e);return t!==e&&(Lt.set(e,t),Ft.set(t,e)),t}const $t=e=>Ft.get(e);function Jt(e,t,{blocked:i,upgrade:s,blocking:n,terminated:a}={}){const r=indexedDB.open(e,t),o=Vt(r);return s&&r.addEventListener("upgradeneeded",(e=>{s(Vt(r.result),e.oldVersion,e.newVersion,Vt(r.transaction))})),i&&r.addEventListener("blocked",(()=>i())),o.then((e=>{a&&e.addEventListener("close",(()=>a())),n&&e.addEventListener("versionchange",(()=>n()))})).catch((()=>{})),o}function Wt(e,{blocked:t}={}){const i=indexedDB.deleteDatabase(e);return t&&i.addEventListener("blocked",(()=>t())),Vt(i).then((()=>{}))}const Ht=["get","getKey","getAll","getAllKeys","count"],Gt=["put","add","delete","clear"],Zt=new Map;function zt(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(Zt.get(t))return Zt.get(t);const i=t.replace(/FromIndex$/,""),s=t!==i,n=Gt.includes(i);if(!(i in(s?IDBIndex:IDBObjectStore).prototype)||!n&&!Ht.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 Zt.set(t,a),a}!function(e){Bt=e(Bt)}((e=>({...e,get:(t,i,s)=>zt(t,i)||e.get(t,i,s),has:(t,i)=>!!zt(t,i)||e.has(t,i)})));const Kt="/firebase-messaging-sw.js",Qt="/firebase-cloud-messaging-push-scope",Yt="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4",Xt="https://fcmregistrations.googleapis.com/v1",ei="google.c.a.c_id",ti="google.c.a.c_l",ii="google.c.a.ts";var si,ni;function ai(e){const t=new Uint8Array(e);return btoa(String.fromCharCode(...t)).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function ri(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"}(si||(si={})),function(e){e.PUSH_RECEIVED="push-received",e.NOTIFICATION_CLICKED="notification-clicked"}(ni||(ni={}));const oi="fcm_token_details_db",ci=5,li="fcm_token_object_Store";const di="firebase-messaging-database",hi=1,ui="firebase-messaging-store";let pi=null;function mi(){return pi||(pi=Jt(di,hi,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(ui)}})),pi}async function gi(e){const t=vi(e),i=await mi(),s=await i.transaction(ui).objectStore(ui).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(oi))return null}let t=null;return(await Jt(oi,ci,{upgrade:async(i,s,n,a)=>{var r;if(s<2)return;if(!i.objectStoreNames.contains(li))return;const o=a.objectStore(li),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:ai(e.vapidKey)}}}else if(3===s){const e=c;t={token:e.fcmToken,createTime:e.createTime,subscriptionOptions:{auth:ai(e.auth),p256dh:ai(e.p256dh),endpoint:e.endpoint,swScope:e.swScope,vapidKey:ai(e.vapidKey)}}}else if(4===s){const e=c;t={token:e.fcmToken,createTime:e.createTime,subscriptionOptions:{auth:ai(e.auth),p256dh:ai(e.p256dh),endpoint:e.endpoint,swScope:e.swScope,vapidKey:ai(e.vapidKey)}}}}})).close(),await Wt(oi),await Wt("fcm_vapid_details_db"),await Wt("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 fi(e,t),t}}async function fi(e,t){const i=vi(e),s=(await mi()).transaction(ui,"readwrite");return await s.objectStore(ui).put(t,i),await s.done,t}function vi({appConfig:e}){return e.appId}const bi=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 yi(e,t){const i={method:"DELETE",headers:await Ci(e)};try{const s=await fetch(`${Si(e.appConfig)}/${t}`,i),n=await s.json();if(n.error){const e=n.error.message;throw bi.create("token-unsubscribe-failed",{errorInfo:e})}}catch(e){throw bi.create("token-unsubscribe-failed",{errorInfo:null==e?void 0:e.toString()})}}function Si({projectId:e}){return`${Xt}/projects/${e}/registrations`}async function Ci({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 ki({p256dh:e,auth:t,endpoint:i,vapidKey:s}){const n={web:{endpoint:i,auth:t,p256dh:e}};return s!==Yt&&(n.web.applicationPubKey=s),n}const Ei=6048e5;async function wi(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:ri(t)})}(e.swRegistration,e.vapidKey),i={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:t.endpoint,auth:ai(t.getKey("auth")),p256dh:ai(t.getKey("p256dh"))},s=await gi(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+Ei?async function(e,t){try{const i=await async function(e,t){const i=await Ci(e),s=ki(t.subscriptionOptions),n={method:"PATCH",headers:i,body:JSON.stringify(s)};let a;try{const i=await fetch(`${Si(e.appConfig)}/${t.token}`,n);a=await i.json()}catch(e){throw bi.create("token-update-failed",{errorInfo:null==e?void 0:e.toString()})}if(a.error){const e=a.error.message;throw bi.create("token-update-failed",{errorInfo:e})}if(!a.token)throw bi.create("token-update-no-token");return a.token}(e.firebaseDependencies,t),s=Object.assign(Object.assign({},t),{token:i,createTime:Date.now()});return await fi(e.firebaseDependencies,s),i}catch(t){throw await Ti(e),t}}(e,{token:s.token,createTime:Date.now(),subscriptionOptions:i}):s.token;try{await yi(e.firebaseDependencies,s.token)}catch(e){console.warn(e)}return Pi(e.firebaseDependencies,i)}return Pi(e.firebaseDependencies,i)}async function Ti(e){const t=await gi(e.firebaseDependencies);t&&(await yi(e.firebaseDependencies,t.token),await async function(e){const t=vi(e),i=(await mi()).transaction(ui,"readwrite");await i.objectStore(ui).delete(t),await i.done}(e.firebaseDependencies));const i=await e.swRegistration.pushManager.getSubscription();return!i||i.unsubscribe()}async function Pi(e,t){const i=await async function(e,t){const i=await Ci(e),s=ki(t),n={method:"POST",headers:i,body:JSON.stringify(s)};let a;try{const t=await fetch(Si(e.appConfig),n);a=await t.json()}catch(e){throw bi.create("token-subscribe-failed",{errorInfo:null==e?void 0:e.toString()})}if(a.error){const e=a.error.message;throw bi.create("token-subscribe-failed",{errorInfo:e})}if(!a.token)throw bi.create("token-subscribe-no-token");return a.token}(e,t),s={token:i,createTime:Date.now(),subscriptionOptions:t};return await fi(e,s),s.token}function Mi(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 Ri(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 Ni(e){return bi.create("missing-app-config-values",{valueName:e})}Ri("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),Ri("AzSCbw63g1R0nCw85jG8","Iaya3yLKwmgvh7cF0q4");class _i{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 Ni("App Configuration Object");if(!e.name)throw Ni("App Name");const t=["projectId","apiKey","appId","messagingSenderId"],{options:i}=e;for(const e of t)if(!i[e])throw Ni(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 Di(e){try{e.swRegistration=await navigator.serviceWorker.register(Kt,{scope:Qt}),e.swRegistration.update().catch((()=>{}))}catch(e){throw bi.create("failed-service-worker-registration",{browserErrorMessage:null==e?void 0:e.message})}}async function Ii(e,t){if(!navigator)throw bi.create("only-available-in-window");if("default"===Notification.permission&&await Notification.requestPermission(),"granted"!==Notification.permission)throw bi.create("permission-blocked");return await async function(e,t){t?e.vapidKey=t:e.vapidKey||(e.vapidKey=Yt)}(e,null==t?void 0:t.vapidKey),await async function(e,t){if(t||e.swRegistration||await Di(e),t||!e.swRegistration){if(!(t instanceof ServiceWorkerRegistration))throw bi.create("invalid-sw-registration");e.swRegistration=t}}(e,null==t?void 0:t.serviceWorkerRegistration),wi(e)}async function Ai(e,t,i){const s=function(e){switch(e){case ni.NOTIFICATION_CLICKED:return"notification_open";case ni.PUSH_RECEIVED:return"notification_foreground";default:throw new Error}}(t);(await e.firebaseDependencies.analyticsProvider.get()).logEvent(s,{message_id:i[ei],message_name:i[ti],message_time:i[ii],message_device_time:Math.floor(Date.now()/1e3)})}async function Oi(e,t){const i=t.data;if(!i.isFirebaseMessaging)return;e.onMessageHandler&&i.messageType===ni.PUSH_RECEIVED&&("function"==typeof e.onMessageHandler?e.onMessageHandler(Mi(i)):e.onMessageHandler.next(Mi(i)));const s=i.data;var n;"object"==typeof(n=s)&&n&&ei in n&&"1"===s["google.c.a.e"]&&await Ai(e,i.messageType,s)}const Ui="@firebase/messaging",xi="0.12.4",Li=e=>{const t=e.getProvider("messaging").getImmediate();return{getToken:e=>Ii(t,e)}};async function Fi(){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 Bi(e=function(e=X){const t=te.get(e);if(!t&&e===X&&u())return ce();if(!t)throw re.create("no-app",{appName:e});return t}()){return Fi().then((e=>{if(!e)throw bi.create("unsupported-browser")}),(e=>{throw bi.create("indexed-db-unsupported")})),ae(C(e),"messaging").getImmediate()}async function ji(e,t){return Ii(e=C(e),t)}function qi(e){return async function(e){if(!navigator)throw bi.create("only-available-in-window");return e.swRegistration||await Di(e),Ti(e)}(e=C(e))}function Vi(e,t){return function(e,t){if(!navigator)throw bi.create("only-available-in-window");return e.onMessageHandler=t,()=>{e.onMessageHandler=null}}(e=C(e),t)}ne(new k("messaging",(e=>{const t=new _i(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return navigator.serviceWorker.addEventListener("message",(e=>Oi(t,e))),t}),"PUBLIC")),ne(new k("messaging-internal",Li,"PRIVATE")),le(Ui,xi),le(Ui,xi,"esm2017");var $i=r(2506);class Ji 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 Wi=r(8962);const Hi=(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 Gi 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(Hi.info),handler:null},messages_clear:{id:"messages_clear",title:i(Hi.clear_messages),handler:(t,s)=>e.onShowAlert(i(Hi.clear_messages),i(Hi.clear_messages_warning),(e=>{this.deleteMessages(!0,!1,t,s)}),null,!0,null)},messages_clear_hard:{id:"messages_clear_hard",title:i(Hi.clear_for_all),handler:(t,s)=>e.onShowAlert(i(Hi.clear_for_all),i(Hi.delete_messages_warning),(e=>this.deleteMessages(!0,!0,t,s)),null,!0,null)},message_delete:{id:"message_delete",title:i(Hi.delete),handler:(e,t)=>this.deleteMessages(!1,!1,e,t)},message_delete_hard:{id:"message_delete_hard",title:i(Hi.delete_for_all),handler:(e,t)=>this.deleteMessages(!1,!0,e,t)},menu_item_send_retry:{id:"menu_item_send_retry",title:i(Hi.send_retry),handler:(e,t)=>this.retryMessage(e,t)},menu_item_reply:{id:"menu_item_reply",title:i(Hi.reply),handler:(e,t)=>this.replyToMessage(e,t)},menu_item_forward:{id:"menu_item_forward",title:i(Hi.forward),handler:e=>{}},menu_item_edit:{id:"menu_item_edit",title:i(Hi.edit),handler:(e,t)=>this.editMessage(e,t)},menu_item_pin:{id:"menu_item_pin",title:i(Hi.pin_message),handler:(e,t)=>this.pinMessage(!0,e,t)},menu_item_unpin:{id:"menu_item_unpin",title:i(Hi.unpin_message),handler:(e,t)=>this.pinMessage(!1,e,t)},topic_unmute:{id:"topic_unmute",title:i(Hi.unmute),handler:this.topicPermissionSetter.bind(this,"+P")},topic_mute:{id:"topic_mute",title:i(Hi.mute),handler:this.topicPermissionSetter.bind(this,"-P")},topic_unblock:{id:"topic_unblock",title:i(Hi.unblock),handler:this.topicPermissionSetter.bind(this,"+JP")},topic_block:{id:"topic_block",title:i(Hi.block),handler:(t,s)=>e.onShowAlert(i(Hi.block),i(Hi.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(Hi.topic_delete),handler:(t,s)=>e.onShowAlert(i(Hi.topic_delete),i(Hi.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(Hi.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(Hi.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(Hi.edit_permissions),handler:null},member_delete:{id:"member_delete",title:i(Hi.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(Hi.mute),handler:this.topicPermissionSetter.bind(this,"-P")},member_unmute:{id:"member_unmute",title:i(Hi.unmute),handler:this.topicPermissionSetter.bind(this,"+P")},member_block:{id:"member_block",title:i(Hi.block),handler:this.topicPermissionSetter.bind(this,"-JP")},member_unblock:{id:"member_unblock",title:i(Hi.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*Wi.o6,n=Wi.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 Zi=(0,s.injectIntl)(Gi),zi={muted:"notifications_off",banned:"block",staff:"verified_user"};class Ki 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},zi[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 Qi=r(1887);class Yi extends t().PureComponent{render(){return this.props.count>0?t().createElement("span",{className:"unread"},this.props.count>9?"9+":this.props.count):null}}var Xi=r(4861),es=r(3905);class ts 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,es.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 is 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,es.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 ss 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,es.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 ns 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 as 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 rs 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(as,{progress:this.props.progress,onCancel:this.props.onCancelUpload})))}}var os=r(8405),cs=r(3740);const ls=(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 ds(e,i,s,n,a){if(a.includes("QQ"))return fs.call(this,e,i,s,n);if(!e)return s;let r=$i.Drafty.tagName(e),o=$i.Drafty.attrValue(e,i)||{};switch(o.key=n,e){case"AU":o.src&&(o.src=this.authorizeURL((0,cs.Fv)(o.src,"audio")),o.duration=i.duration>0?0|i.duration:void 0,o.preview=i.preview,o.loading="lazy"),r=Xi.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=hs.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,es.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=ts,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=us.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(ls.drafty_unknown))]),s=[t().createElement("i",{key:"x0",className:"material-icons gray"},"extension")," "].concat(e)}}return r?t().createElement(r,o,s):s}function hs(e,t,i){if(!t)return i.src="img/broken_image.png",i.style={width:Wi.$_+"px",height:Wi.$_+"px"},e;i.className="inline-image";const s=(0,os.rS)(t.width,t.height,this.viewportWidth>0?Math.min(this.viewportWidth-6.5*Wi.o6,34.5*Wi.o6):34.5*Wi.o6,24*Wi.o6,!1)||{dstWidth:Wi.sA,dstHeight:Wi.sA};return i.style={width:s.dstWidth+"px",height:s.dstHeight+"px",minWidth:s.dstWidth+"px",minHeight:s.dstHeight+"px"},$i.Drafty.isProcessing(t)?e=rs:(i.src=this.authorizeURL((0,cs.Fv)(i.src,"image")),i.alt=t.name,i.src?(Math.max(t.width||0,t.height||0)>Wi.$_&&(i.onClick=this.onImagePreview,i.className+=" image-clickable"),i.loading="lazy"):i.src=null),e}function us(e,t,i){if(!t)return i.src="img/broken_video.png",i.style={width:Wi.$_+"px",height:Wi.$_+"px"},e;i.className="inline-image";const s=(0,os.rS)(t.width,t.height,this.viewportWidth>0?Math.min(this.viewportWidth-6.5*Wi.o6,34.5*Wi.o6):34.5*Wi.o6,24*Wi.o6,!1)||{dstWidth:Wi.wO,dstHeight:Wi.wO};return i.style={width:s.dstWidth+"px",height:s.dstHeight+"px",minWidth:s.dstWidth+"px",minHeight:s.dstHeight+"px"},$i.Drafty.isProcessing(t)?e=rs:(i.src=this.authorizeURL((0,cs.Fv)(i.src,"image")),i.alt=t.name,(t.ref||t.val)&&(i.onClick=this.onVideoPreview,i.loading="lazy"),e=ss),e}function ps(e,i,s,n){if(!e)return s;let a=$i.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,es.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(ls.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(ls.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(ls.drafty_attachment)];break;case"VC":a=is,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(ls.drafty_video)];break;default:a||(a=t().Fragment,s=[t().createElement("i",{key:"x0",className:"material-icons gray"},"extension")," ",this.formatMessage(ls.drafty_unknown)])}return a?t().createElement(a,r,s):s}function ms(e,t){return e.style={width:Wi.$_+"px",height:Wi.$_+"px",maxWidth:Wi.$_+"px",maxHeight:Wi.$_+"px"},e.className="inline-image",e.alt=this.formatMessage(ls.drafty_image),e.src=t&&e.src||"img/broken_image.png",e.title=e.alt,e}function gs(e,t){const i=(0,os.rS)(t.width,t.height,Wi.Zd,Wi.$_);return e.style={width:i.width+"px",height:i.height+"px",maxWidth:Wi.Zd+"px",maxHeight:Wi.$_+"px"},e.className="inline-image",e.alt=this.formatMessage(ls.drafty_video),e.title=e.alt,e.src=t&&e.src||"img/broken_video.png",e}function fs(e,i,s,n){if(["BR","EX","IM","MN","VD"].includes(e)){let a=$i.Drafty.tagName(e),r=$i.Drafty.attrValue(e,i)||{};switch(r.key=n,e){case"BR":s=null;break;case"IM":r=ms.call(this,r,i),s=[t().createElement("img",r,null)," ",r.alt],a=t().Fragment,r={key:n};break;case"VD":r=gs.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,es.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,es.TX)(e,16)||this.formatMessage(ls.drafty_attachment)]}return t().createElement(a,r,s)}return ps.call(this,e,i,s,n)}function vs(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,os.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,cs.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,os.EA)(e,t?Wi.Zd:Wi.$_,Wi.$_,-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,os.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=Wi.$_,e.height=Wi.$_,t}))}function bs(e,i,s,n,a){if("IM"==e||"VD"==e){const a="IM"==e?ms.call(this,{key:n},i):gs.call(this,{key:n},i);let r;try{r=(0,cs.Oi)(vs.call(this,i,"VD"==e))}catch(e){console.warn("Failed to quote image:",e.message),r=(0,cs.Oi)(e)}return a.whenDone=r,s=[t().createElement(ns,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=$i.Drafty.attrValue("QQ",i)||{};return e.key=n,e.className="reply-quote",t().createElement($i.Drafty.tagName("QQ"),e,s)}return fs.call(this,e,i,s,n)}class ys 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:$i.Drafty.isValid(this.props.preview)?o=t().createElement(t().Fragment,null,$i.Drafty.format(this.props.preview,ps,{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,cs.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(Qi.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(Ki,{badges:r}),this.props.deleted?null:t().createElement(Yi,{count:this.props.unread})),this.props.showMode?t().createElement("span",null,t().createElement(Ki,{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 Ss=(0,s.injectIntl)(ys);class Cs 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 ks=(0,s.injectIntl)(Cs),Es=(0,s.defineMessages)({badge_you:{id:"badge_you",defaultMessage:[{type:0,value:"you"}]},badge_owner:{id:"badge_owner",defaultMessage:[{type:0,value:"owner"}]}});class ws 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(ks,{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=$i.Tinode.isChannelTopicName(r),c=!o&&$i.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(Es.badge_you),color:"green"}),a.acs&&a.acs.isOwner()&&d.push({name:e(Es.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,Wi.rV):$i.Drafty.preview(e.content,Wi.rV)))}s.push(t().createElement(Ss,{tinode:this.props.tinode,title:a.public?a.public.fn:null,avatar:(0,os.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 Ts=(0,s.injectIntl)(ws);class Ps 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($i.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:$i.Tinode.DEL_CHAR)}handleClear(e){e.preventDefault(),this.state.edited&&this.props.onSearchContacts($i.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 Ms 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:$i.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(Ps,{placeholder:e,onSearchContacts:this.handleSearchContacts}))),t().createElement(s.FormattedMessage,{id:"search_no_results",defaultMessage:[{type:0,value:"Search returned no results"}]},(i=>t().createElement(Ts,{tinode:this.props.tinode,contacts:e,myUserId:this.props.myUserId,emptyListMessage:i,showOnline:!1,showUnread:!1,showContextMenu:!1,onTopicSelected:this.handleContactSelected})))))}}var Rs=r(955);const Ns="started",_s=new Audio("audio/call-in.m4a");class Ds 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&&(_s.play().catch((e=>{})),this.ringTimer=setInterval((e=>{_s.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),_s.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,cs.Th)(e.public?e.public.fn:void 0,Wi.S8),avatar:(0,os.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(Qi.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,cs.Th)(this.state.fullName,Wi.gD),t().createElement(Rs.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 Is=r(7432),As=r(2323);class Os extends t().PureComponent{render(){return t().createElement("a",{href:"#",onClick:e=>{e.preventDefault(),this.props.onCancel()}},t().createElement("i",{className:"material-icons"},"close"))}}class Us 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(Os,{onCancel:this.hide})))}}class xs 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(Qi.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 Ls extends t().Component{constructor(e){super(e),this.state=Ls.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:Ls.sortChips(e.chips,e.staticMembers),chipIndex:Ls.indexChips(e.chips)}}componentDidUpdate(e,t){e.chips==this.props.chips&&e.staticMembers==this.props.staticMembers&&e.prompt==this.props.prompt||this.setState(Ls.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(xs,{tinode:this.props.tinode,onCancel:this.handleChipCancel,avatar:(0,os.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 Fs=(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 Bs extends t().Component{constructor(e){super(e),this.state={members:e.members,index:Bs.indexMembers(e.members),staticMembers:Bs.staticMembers(e.members,e.keepInitialMembers,e.requiredMember),contactFilter:"",noContactsMessage:e.intl.formatMessage(Fs.no_contacts),selectedContacts:Bs.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=Bs.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=Bs.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(Fs.contacts_not_found_short,{query:e}):t(Fs.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(Ls,{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(Ts,{tinode:this.props.tinode,contacts:this.props.contacts,myUserId:this.props.myUserId,topicSelected:this.state.selectedContacts,filter:this.state.contactFilter,filterFunc:Bs.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 js=(0,s.injectIntl)(Bs),qs=(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 Vs 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(qs.joiner,{val:"J"}),R:e(qs.reader,{val:"R"}),W:e(qs.writer,{val:"W"}),P:e(qs.preser,{val:"P"}),A:e(qs.approver,{val:"A"}),S:e(qs.sharer,{val:"S"}),D:e(qs.deleter,{val:"D"}),O:e(qs.owner,{val:"O"})};let a=this.props.skip||"",r=this.state.mode,o=(this.props.compare||"").replace("N",""),c=[];for(let e=0;e<8;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(As.Z,{name:s,checked:r.indexOf(s)>=0,onChange:this.handleChange}):t().createElement(As.Z,{name:s,checked:r.indexOf(s)>=0})),this.props.compare?t().createElement("td",{className:"checkbox"},t().createElement(As.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(Ss,{tinode:this.props.tinode,item:this.props.item,title:this.props.userTitle,small:!0,avatar:(0,os.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 $s=(0,s.injectIntl)(Vs);var Js=r(9875),Ws=r(195);class Hs 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=Ws.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 Gs 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,cs.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",Wi.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",Wi.VL),i=this.props.tinode.getServerParam("maxTagLength",Wi.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(Ls,{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 Zs extends t().Component{constructor(e){super(e);const t=this.props.tinode.getTopic(this.props.topic),i=t.getAccessMode();this.state={isMe:$i.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,os.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,Wi.S8))&&this.state.fullName!==e&&(this.setState({fullName:e}),this.props.onUpdateTopicDesc(this.props.topic,(0,cs.n$)(e,null)))}handlePrivateUpdate(e){e=e.trim().substring(0,Wi.S8),this.state.private!==e&&(this.setState({private:e}),this.props.onUpdateTopicDesc(this.props.topic,null,e||$i.Tinode.DEL_CHAR))}handleDescriptionUpdate(e){(e=e.trim().substring(0,Wi.EI))&&(this.setState({description:e}),this.props.onUpdateTopicDesc(this.props.topic,(0,cs.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,cs.n$)(null,$i.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>Wi.uv){this.props.tinode.getLargeFileHelper().upload(i).then((e=>this.props.onUpdateTopicDesc(this.props.topic,(0,cs.n$)(null,e)))).catch((e=>this.props.onError(e.message,"err")))}else(0,os.w8)(i).then((e=>{const i=(0,os.PD)({data:e.bits,type:t});this.setState({source:i}),this.props.onUpdateTopicDesc(this.props.topic,(0,cs.n$)(null,i))}))};i>Wi.IX||s>Wi.IX||i!=s?(0,os.EA)(t,Wi.IX,Wi.IX,Wi.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,cs.h6)(this.state.tags.slice(0),e.slice(0))||this.props.onUpdateTags(e)}render(){if(this.state.newAvatar)return t().createElement(Js.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(Is.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(Hs,{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(Hs,{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(Hs,{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(Hs,{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(Gs,{tinode:this.props.tinode,title:e,activated:!1,tags:this.state.tags,onSubmit:this.handleTagsUpdated})))):null)}}class zs 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,cs.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(Zs,{tinode:this.props.tinode,topic:this.props.topic,onUpdateTopicDesc:this.props.onUpdateTopicDesc,onUpdateTags:this.handleTagsUpdated,onError:this.props.onError}))}}const Ks=(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 Qs 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(Ks.topic_delete),t(Ks.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?Ks.delete_messages:Ks.clear_messages),t(this.props.deleter?Ks.delete_messages_warning:Ks.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(Ks.leave_chat),t(Ks.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(Ks.block_contact),t(Ks.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(Ks.report_chat),t(Ks.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?Ks.delete_messages:Ks.clear_messages)),this.props.owner?t().createElement("a",{href:"#",className:"danger flat-button",onClick:this.handleDeleteTopic},t().createElement("i",{className:"material-icons"},"delete"),"  ",e(Ks.topic_delete)):t().createElement("a",{href:"#",className:"danger flat-button",onClick:this.handleLeave},t().createElement("i",{className:"material-icons"},"exit_to_app"),"  ",e(Ks.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(Ks.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(Ks.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(Ks.other_user),":  ",t().createElement("tt",{className:"clickable",onClick:e=>{e.preventDefault(),this.props.onLaunchPermissionsEditor("given")}},this.props.modeGiven2))))))}}const Ys=(0,s.injectIntl)(Qs),Xs=(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 en 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=Wi.xt,i.modeWant2=Wi.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,cs.Th)(e.public&&e.public.fn,Wi.S8),description:(0,cs.Th)(e.public&&e.public.note,Wi.EI),avatar:(0,os.PD)(e.public?e.public.photo:null),trustedBadges:n,private:(0,cs.Th)(e.private&&e.private.comment,Wi.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,cs.n$)(null,t||$i.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=$i.AccessMode.encode($i.AccessMode.diff("ASDO",this.state.modeGiven)),this.state.channel&&(a+="W")),r=i(Xs.perm_want),o=i(Xs.perm_given);break;case"given":s=this.state.modeGiven2,n=this.state.modeWant2,a=this.state.groupTopic?this.state.owner?"":"O":"ASDO",r=i(Xs.perm_given),o=i(Xs.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(Xs.perm_given),o=i(Xs.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(Xs.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?Xs["perm_"+e[0]]:Xs[i])||Xs.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(Os,{onCancel:this.handleBackNavigate}))),this.props.displayMobile?t().createElement(Us,{level:this.props.errorLevel,text:this.props.errorText,onClearError:this.props.onError}):null,"members"==i?t().createElement(js,{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($s,{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(zs,{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(Ys,{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(Is.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(Rs.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(As.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(As.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(Ts,{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 tn=(0,s.injectIntl)(en),sn=new Audio("audio/call-out.m4a");sn.loop=!0;const nn=new Audio("audio/call-end.m4a");nn.loop=!0;const an=new Audio("audio/dialing.m4a"),rn="video:muted",on="video:unmuted",cn=(0,s.defineMessages)({already_in_call:{id:"already_in_call",defaultMessage:[{type:0,value:"You already in an ongoing call!"}]}});class ln 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=1==e.callState,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,1!=this.props.callState&&3!=this.props.callState||!this.localRef.current||this.start()}componentWillUnmount(){this.props.tinode.getTopic(this.props.topic).onInfo=this.previousOnInfo,this.stop()}handleVideoCallAccepted(e){sn.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":sn.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(cn.already_in_call),"info"):3!=this.props.callState?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,an.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,3,this.props.callAudioOnly)}stop(){nn.pause(),nn.currentTime=0,sn.pause(),sn.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 rn:this.setState({remoteVideoLive:!1},(e=>{this.remoteRef.current.srcObject=this.state.remoteStream}));break;case on:this.setState({remoteVideoLive:!0},(e=>{this.remoteRef.current.srcObject=this.state.remoteStream}))}}handleDataChannelOpen(e){this.state.audioOnly||e.target.send(on)}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}),sn.pause(),sn.currentTime=0,nn.loop=!0,nn.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(rn),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(on)})).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,cs.Th)(this.props.title,Wi.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(Qi.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 dn=(0,s.injectIntl)(ln);class hn 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,es.FK)(this.props.size),")"):null;this.props.uploading||this.state.downloader||!(0,cs.Xc)(this.props.downloadUrl)?(i=(0,cs.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(as,{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 un=(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 pn extends t().PureComponent{render(){const{formatMessage:e}=this.props.intl;let i;i=this.props.received<=$i.Tinode.MESSAGE_STATUS_SENDING?e(un.message_sending):this.props.received==$i.Tinode.MESSAGE_STATUS_FAILED||this.props.received==$i.Tinode.MESSAGE_STATUS_FATAL?e(un.message_sending_failed):this.props.timestamp.toLocaleTimeString(this.props.intl.locale,{timeStyle:"short"});const s=(0,cs.es)(this.props.received),n=s?t().createElement("i",{className:"material-icons small "+s.color},s.name):null,a=this.props.edited?e(un.message_edited_marker):null;return t().createElement("span",{className:"timestamp"},i,a," ",n)}}const mn=(0,s.injectIntl)(pn);function gn(){return gn=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},gn.apply(this,arguments)}class fn 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,cs.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==$i.Tinode.MESSAGE_STATUS_FAILED&&t.push("menu_item_send_retry"),this.props.received>$i.Tinode.MESSAGE_STATUS_FATAL){if(this.props.userIsWriter&&(t.push("menu_item_reply"),!this.props.response)){let e=!1;$i.Drafty.entities(this.props.content,((t,i,s)=>(e=["AU","EX","FM","IM","VC","VD"].includes(s),e))),e||$i.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==$i.Drafty.getContentType()&&$i.Drafty.isValid(r)){$i.Drafty.attachments(r,((e,i)=>{"application/json"!=e.mime&&o.push(t().createElement(hn,{tinode:this.props.tinode,downloadUrl:$i.Drafty.getDownloadUrl(e),filename:e.name,uploading:$i.Drafty.isProcessing(e),mimetype:e.mime,size:$i.Drafty.getEntitySize(e),progress:this.state.progress,onCancelUpload:this.handleCancelUpload,onError:this.props.onError,key:i}))}),this);const e=$i.Drafty.format(r,ds,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(Qi.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(mn,{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 vn=(0,s.injectIntl)(fn),bn=t().forwardRef(((e,i)=>t().createElement(vn,gn({innerRef:i},e)))),yn=t().lazy((e=>Promise.all([r.e(246),r.e(252)]).then(r.bind(r,252)))),Sn=(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 Cn 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?$i.Drafty.format(this.props.reply.content,bs,{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,os.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>Wi.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(Sn.messaging_disabled):this.props.messagePrompt?i(Sn[this.props.messagePrompt]):i(Sn.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(Sn.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(Sn.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(yn,{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(Sn.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(Sn.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 kn=(0,s.injectIntl)(Cn);class En 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,es.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,es.FK)(this.props.content.size)))),t().createElement(kn,{noInput:!0,tinode:this.props.tinode,reply:this.props.reply,onCancelReply:this.props.onCancelReply,onSendMessage:this.handleSendDoc,onError:this.props.onError})):null}}class wn extends t().Component{constructor(e){super(e)}render(){const e=[],i=(this.props.subscribers||[]).length,n=Math.min(Wi.dm,i);return(this.props.subscribers||[]).some((i=>(e.push(t().createElement("div",{className:"avatar-box",key:i.user},t().createElement(Qi.Z,{tinode:this.props.tinode,topic:i.user,avatar:(0,os.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 Tn 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,os.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/Wi.o6/1.5|0)-2,12),a=(0,es.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(kn,{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,es.FK)(this.props.content.size)))))}}class Pn 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 Mn=r(7646);class Rn extends t().PureComponent{render(){const e=Wi.iC+" ("+$i.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 Nn 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 _n 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?$i.Drafty.format(i.content,ps,{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 Dn=(0,s.injectIntl)(_n);function In(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 An="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function On(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Un,xn={exports:{}};Un=xn,function(e,t){Un.exports?Un.exports=t():e.log=t()}(An,(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}));var Ln,Fn=xn.exports;!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"}(Ln||(Ln={}));const Bn=Fn.getLogger("livekit");Bn.setLevel(Ln.info);var jn=Vn,qn=null;try{qn=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(Pp){}function Vn(e,t,i){this.low=0|e,this.high=0|t,this.unsigned=!!i}function $n(e){return!0===(e&&e.__isLong__)}Vn.prototype.__isLong__,Object.defineProperty(Vn.prototype,"__isLong__",{value:!0}),Vn.isLong=$n;var Jn={},Wn={};function Hn(e,t){var i,s,n;return t?(n=0<=(e>>>=0)&&e<256)&&(s=Wn[e])?s:(i=Zn(e,(0|e)<0?-1:0,!0),n&&(Wn[e]=i),i):(n=-128<=(e|=0)&&e<128)&&(s=Jn[e])?s:(i=Zn(e,e<0?-1:0,!1),n&&(Jn[e]=i),i)}function Gn(e,t){if(isNaN(e))return t?sa:ia;if(t){if(e<0)return sa;if(e>=Xn)return ca}else{if(e<=-ea)return la;if(e+1>=ea)return oa}return e<0?Gn(-e,t).neg():Zn(e%Yn|0,e/Yn|0,t)}function Zn(e,t,i){return new Vn(e,t,i)}Vn.fromInt=Hn,Vn.fromNumber=Gn,Vn.fromBits=Zn;var zn=Math.pow;function Kn(e,t,i){if(0===e.length)throw Error("empty string");if("NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return ia;if("number"==typeof t?(i=t,t=!1):t=!!t,(i=i||10)<2||36<i)throw RangeError("radix");var s;if((s=e.indexOf("-"))>0)throw Error("interior hyphen");if(0===s)return Kn(e.substring(1),t,i).neg();for(var n=Gn(zn(i,8)),a=ia,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=Gn(zn(i,o));a=a.mul(l).add(Gn(c))}else a=(a=a.mul(n)).add(Gn(c))}return a.unsigned=t,a}function Qn(e,t){return"number"==typeof e?Gn(e,t):"string"==typeof e?Kn(e,t):Zn(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}Vn.fromString=Kn,Vn.fromValue=Qn;var Yn=4294967296,Xn=Yn*Yn,ea=Xn/2,ta=Hn(1<<24),ia=Hn(0);Vn.ZERO=ia;var sa=Hn(0,!0);Vn.UZERO=sa;var na=Hn(1);Vn.ONE=na;var aa=Hn(1,!0);Vn.UONE=aa;var ra=Hn(-1);Vn.NEG_ONE=ra;var oa=Zn(-1,2147483647,!1);Vn.MAX_VALUE=oa;var ca=Zn(-1,-1,!0);Vn.MAX_UNSIGNED_VALUE=ca;var la=Zn(0,-2147483648,!1);Vn.MIN_VALUE=la;var da=Vn.prototype;da.toInt=function(){return this.unsigned?this.low>>>0:this.low},da.toNumber=function(){return this.unsigned?(this.high>>>0)*Yn+(this.low>>>0):this.high*Yn+(this.low>>>0)},da.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(la)){var t=Gn(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=Gn(zn(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}},da.getHighBits=function(){return this.high},da.getHighBitsUnsigned=function(){return this.high>>>0},da.getLowBits=function(){return this.low},da.getLowBitsUnsigned=function(){return this.low>>>0},da.getNumBitsAbs=function(){if(this.isNegative())return this.eq(la)?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},da.isZero=function(){return 0===this.high&&0===this.low},da.eqz=da.isZero,da.isNegative=function(){return!this.unsigned&&this.high<0},da.isPositive=function(){return this.unsigned||this.high>=0},da.isOdd=function(){return 1==(1&this.low)},da.isEven=function(){return 0==(1&this.low)},da.equals=function(e){return $n(e)||(e=Qn(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&(this.high===e.high&&this.low===e.low)},da.eq=da.equals,da.notEquals=function(e){return!this.eq(e)},da.neq=da.notEquals,da.ne=da.notEquals,da.lessThan=function(e){return this.comp(e)<0},da.lt=da.lessThan,da.lessThanOrEqual=function(e){return this.comp(e)<=0},da.lte=da.lessThanOrEqual,da.le=da.lessThanOrEqual,da.greaterThan=function(e){return this.comp(e)>0},da.gt=da.greaterThan,da.greaterThanOrEqual=function(e){return this.comp(e)>=0},da.gte=da.greaterThanOrEqual,da.ge=da.greaterThanOrEqual,da.compare=function(e){if($n(e)||(e=Qn(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},da.comp=da.compare,da.negate=function(){return!this.unsigned&&this.eq(la)?la:this.not().add(na)},da.neg=da.negate,da.add=function(e){$n(e)||(e=Qn(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,Zn((d&=65535)<<16|(h&=65535),(c&=65535)<<16|(l&=65535),this.unsigned)},da.subtract=function(e){return $n(e)||(e=Qn(e)),this.add(e.neg())},da.sub=da.subtract,da.multiply=function(e){if(this.isZero())return ia;if($n(e)||(e=Qn(e)),qn)return Zn(qn.mul(this.low,this.high,e.low,e.high),qn.get_high(),this.unsigned);if(e.isZero())return ia;if(this.eq(la))return e.isOdd()?la:ia;if(e.eq(la))return this.isOdd()?la:ia;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(ta)&&e.lt(ta))return Gn(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,Zn((h&=65535)<<16|(u&=65535),(l&=65535)<<16|(d&=65535),this.unsigned)},da.mul=da.multiply,da.divide=function(e){if($n(e)||(e=Qn(e)),e.isZero())throw Error("division by zero");var t,i,s;if(qn)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?Zn((this.unsigned?qn.div_u:qn.div_s)(this.low,this.high,e.low,e.high),qn.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?sa:ia;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return sa;if(e.gt(this.shru(1)))return aa;s=sa}else{if(this.eq(la))return e.eq(na)||e.eq(ra)?la:e.eq(la)?na:(t=this.shr(1).div(e).shl(1)).eq(ia)?e.isNegative()?na:ra:(i=this.sub(e.mul(t)),s=t.add(i.div(e)));if(e.eq(la))return this.unsigned?sa:ia;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=ia}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:zn(2,n-48),r=Gn(t),o=r.mul(e);o.isNegative()||o.gt(i);)o=(r=Gn(t-=a,this.unsigned)).mul(e);r.isZero()&&(r=na),s=s.add(r),i=i.sub(o)}return s},da.div=da.divide,da.modulo=function(e){return $n(e)||(e=Qn(e)),qn?Zn((this.unsigned?qn.rem_u:qn.rem_s)(this.low,this.high,e.low,e.high),qn.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},da.mod=da.modulo,da.rem=da.modulo,da.not=function(){return Zn(~this.low,~this.high,this.unsigned)},da.and=function(e){return $n(e)||(e=Qn(e)),Zn(this.low&e.low,this.high&e.high,this.unsigned)},da.or=function(e){return $n(e)||(e=Qn(e)),Zn(this.low|e.low,this.high|e.high,this.unsigned)},da.xor=function(e){return $n(e)||(e=Qn(e)),Zn(this.low^e.low,this.high^e.high,this.unsigned)},da.shiftLeft=function(e){return $n(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?Zn(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):Zn(0,this.low<<e-32,this.unsigned)},da.shl=da.shiftLeft,da.shiftRight=function(e){return $n(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?Zn(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):Zn(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},da.shr=da.shiftRight,da.shiftRightUnsigned=function(e){if($n(e)&&(e=e.toInt()),0===(e&=63))return this;var t=this.high;return e<32?Zn(this.low>>>e|t<<32-e,t>>>e,this.unsigned):Zn(32===e?t:t>>>e-32,0,this.unsigned)},da.shru=da.shiftRightUnsigned,da.shr_u=da.shiftRightUnsigned,da.toSigned=function(){return this.unsigned?Zn(this.low,this.high,!1):this},da.toUnsigned=function(){return this.unsigned?this:Zn(this.low,this.high,!0)},da.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},da.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]},da.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]},Vn.fromBytes=function(e,t,i){return i?Vn.fromBytesLE(e,t):Vn.fromBytesBE(e,t)},Vn.fromBytesLE=function(e,t){return new Vn(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},Vn.fromBytesBE=function(e,t){return new Vn(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};var ha,ua,pa=On(jn),ma={},ga={};var fa,va,ba,ya,Sa,Ca,ka,Ea={};var wa,Ta,Pa,Ma,Ra,Na,_a={};function Da(){return Na||(Na=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:function(){return e},set:void 0,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),t}t.asPromise=(ua||(ua=1,ha=function(e,t){for(var i=new Array(arguments.length-1),s=0,n=2,a=!0;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))}}))}),ha),t.base64=(fa||(fa=1,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)}}(Ea)),Ea),t.EventEmitter=function(){if(ba)return va;function e(){this._listeners={}}return ba=1,va=e,e.prototype.on=function(e,t,i){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:i||this}),this},e.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},e.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},va}(),t.float=function(){if(Sa)return ya;function e(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 a(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 r(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=a.bind(null,t),e.writeFloatBE=a.bind(null,i),e.readFloatLE=r.bind(null,s),e.readFloatBE=r.bind(null,n)}(),"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 a(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 r(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=a.bind(null,t,0,4),e.writeDoubleBE=a.bind(null,i,4,0),e.readDoubleLE=r.bind(null,s,0,4),e.readDoubleBE=r.bind(null,n,4,0)}(),e}function t(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 i(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 s(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function n(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}return Sa=1,ya=e(e)}(),t.inquire=ka?Ca:(ka=1,Ca=function(e){return null}),t.utf8=(wa||(wa=1,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}}(_a)),_a),t.pool=Pa?Ta:(Pa=1,Ta=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}}),t.LongBits=function(){if(Ra)return Ma;Ra=1,Ma=t;var e=Da();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},Ma}(),t.isNode=Boolean(void 0!==An&&An&&An.process&&An.process.versions&&An.process.versions.node),t.global=t.isNode&&An||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||An,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}}(ga)),ga}var Ia,Aa=qa,Oa=Da(),Ua=Oa.LongBits,xa=Oa.base64,La=Oa.utf8;function Fa(e,t,i){this.fn=e,this.len=t,this.next=void 0,this.val=i}function Ba(){}function ja(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function qa(){this.len=0,this.head=new Fa(Ba,0,0),this.tail=this.head,this.states=null}var Va=function(){return Oa.Buffer?function(){return(qa.create=function(){return new Ia})()}:function(){return new qa}};function $a(e,t,i){t[i]=255&e}function Ja(e,t){this.len=e,this.next=void 0,this.val=t}function Wa(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 Ha(e,t,i){t[i]=255&e,t[i+1]=e>>>8&255,t[i+2]=e>>>16&255,t[i+3]=e>>>24}qa.create=Va(),qa.alloc=function(e){return new Oa.Array(e)},Oa.Array!==Array&&(qa.alloc=Oa.pool(qa.alloc,Oa.Array.prototype.subarray)),qa.prototype._push=function(e,t,i){return this.tail=this.tail.next=new Fa(e,t,i),this.len+=t,this},Ja.prototype=Object.create(Fa.prototype),Ja.prototype.fn=function(e,t,i){for(;e>127;)t[i++]=127&e|128,e>>>=7;t[i]=e},qa.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new Ja((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},qa.prototype.int32=function(e){return e<0?this._push(Wa,10,Ua.fromNumber(e)):this.uint32(e)},qa.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},qa.prototype.uint64=function(e){var t=Ua.from(e);return this._push(Wa,t.length(),t)},qa.prototype.int64=qa.prototype.uint64,qa.prototype.sint64=function(e){var t=Ua.from(e).zzEncode();return this._push(Wa,t.length(),t)},qa.prototype.bool=function(e){return this._push($a,1,e?1:0)},qa.prototype.fixed32=function(e){return this._push(Ha,4,e>>>0)},qa.prototype.sfixed32=qa.prototype.fixed32,qa.prototype.fixed64=function(e){var t=Ua.from(e);return this._push(Ha,4,t.lo)._push(Ha,4,t.hi)},qa.prototype.sfixed64=qa.prototype.fixed64,qa.prototype.float=function(e){return this._push(Oa.float.writeFloatLE,4,e)},qa.prototype.double=function(e){return this._push(Oa.float.writeDoubleLE,8,e)};var Ga=Oa.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]};qa.prototype.bytes=function(e){var t=e.length>>>0;if(!t)return this._push($a,1,0);if(Oa.isString(e)){var i=qa.alloc(t=xa.length(e));xa.decode(e,i,0),e=i}return this.uint32(t)._push(Ga,t,e)},qa.prototype.string=function(e){var t=La.length(e);return t?this.uint32(t)._push(La.write,t,e):this._push($a,1,0)},qa.prototype.fork=function(){return this.states=new ja(this),this.head=this.tail=new Fa(Ba,0,0),this.len=0,this},qa.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 Fa(Ba,0,0),this.len=0),this},qa.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},qa.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},qa._configure=function(e){Ia=e,qa.create=Va(),Ia._configure()};var Za=Qa,za=Aa;(Qa.prototype=Object.create(za.prototype)).constructor=Qa;var Ka=Da();function Qa(){za.call(this)}function Ya(e,t,i){e.length<40?Ka.utf8.write(e,t,i):t.utf8Write?t.utf8Write(e,i):t.write(e,i)}Qa._configure=function(){Qa.alloc=Ka._Buffer_allocUnsafe,Qa.writeBytesBuffer=Ka.Buffer&&Ka.Buffer.prototype instanceof Uint8Array&&"set"===Ka.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++]}},Qa.prototype.bytes=function(e){Ka.isString(e)&&(e=Ka._Buffer_from(e,"base64"));var t=e.length>>>0;return this.uint32(t),t&&this._push(Qa.writeBytesBuffer,t,e),this},Qa.prototype.string=function(e){var t=Ka.Buffer.byteLength(e);return this.uint32(t),t&&this._push(Ya,t,e),this},Qa._configure();var Xa,er=ar,tr=Da(),ir=tr.LongBits,sr=tr.utf8;function nr(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function ar(e){this.buf=e,this.pos=0,this.len=e.length}var rr,or="undefined"!=typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new ar(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new ar(e);throw Error("illegal buffer")},cr=function(){return tr.Buffer?function(e){return(ar.create=function(e){return tr.Buffer.isBuffer(e)?new Xa(e):or(e)})(e)}:or};function lr(){var e=new ir(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw nr(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 nr(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 dr(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function hr(){if(this.pos+8>this.len)throw nr(this,8);return new ir(dr(this.buf,this.pos+=4),dr(this.buf,this.pos+=4))}ar.create=cr(),ar.prototype._slice=tr.Array.prototype.subarray||tr.Array.prototype.slice,ar.prototype.uint32=(rr=4294967295,function(){if(rr=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return rr;if(rr=(rr|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return rr;if(rr=(rr|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return rr;if(rr=(rr|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return rr;if(rr=(rr|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return rr;if((this.pos+=5)>this.len)throw this.pos=this.len,nr(this,10);return rr}),ar.prototype.int32=function(){return 0|this.uint32()},ar.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)|0},ar.prototype.bool=function(){return 0!==this.uint32()},ar.prototype.fixed32=function(){if(this.pos+4>this.len)throw nr(this,4);return dr(this.buf,this.pos+=4)},ar.prototype.sfixed32=function(){if(this.pos+4>this.len)throw nr(this,4);return 0|dr(this.buf,this.pos+=4)},ar.prototype.float=function(){if(this.pos+4>this.len)throw nr(this,4);var e=tr.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},ar.prototype.double=function(){if(this.pos+8>this.len)throw nr(this,4);var e=tr.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},ar.prototype.bytes=function(){var e=this.uint32(),t=this.pos,i=this.pos+e;if(i>this.len)throw nr(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)},ar.prototype.string=function(){var e=this.bytes();return sr.read(e,0,e.length)},ar.prototype.skip=function(e){if("number"==typeof e){if(this.pos+e>this.len)throw nr(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw nr(this)}while(128&this.buf[this.pos++]);return this},ar.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},ar._configure=function(e){Xa=e,ar.create=cr(),Xa._configure();var t=tr.Long?"toLong":"toNumber";tr.merge(ar.prototype,{int64:function(){return lr.call(this)[t](!1)},uint64:function(){return lr.call(this)[t](!0)},sint64:function(){return lr.call(this).zzDecode()[t](!1)},fixed64:function(){return hr.call(this)[t](!0)},sfixed64:function(){return hr.call(this)[t](!1)}})};var ur=gr,pr=er;(gr.prototype=Object.create(pr.prototype)).constructor=gr;var mr=Da();function gr(e){pr.call(this,e)}gr._configure=function(){mr.Buffer&&(gr.prototype._slice=mr.Buffer.prototype.slice)},gr.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))},gr._configure();var fr={},vr=yr,br=Da();function yr(e,t,i){if("function"!=typeof e)throw TypeError("rpcImpl must be a function");br.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=Boolean(t),this.responseDelimited=Boolean(i)}(yr.prototype=Object.create(br.EventEmitter.prototype)).constructor=yr,yr.prototype.rpcCall=function e(t,i,s,n,a){if(!n)throw TypeError("request must be specified");var r=this;if(!a)return br.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)},yr.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this},fr.Service=vr;var Sr={};!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=Aa,t.BufferWriter=Za,t.Reader=er,t.BufferReader=ur,t.util=Da(),t.rpc=fr,t.roots=Sr,t.configure=i,i()}(ma);var Cr,kr,Er,wr,Tr,Pr,Mr,Rr,Nr,_r,Dr,Ir,Ar,Or,Ur,xr=On(ma);function Lr(e){switch(e){case 0:case"AUDIO":return Er.AUDIO;case 1:case"VIDEO":return Er.VIDEO;case 2:case"DATA":return Er.DATA;default:return Er.UNRECOGNIZED}}function Fr(e){switch(e){case Er.AUDIO:return"AUDIO";case Er.VIDEO:return"VIDEO";case Er.DATA:return"DATA";case Er.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function Br(e){switch(e){case 0:case"UNKNOWN":return wr.UNKNOWN;case 1:case"CAMERA":return wr.CAMERA;case 2:case"MICROPHONE":return wr.MICROPHONE;case 3:case"SCREEN_SHARE":return wr.SCREEN_SHARE;case 4:case"SCREEN_SHARE_AUDIO":return wr.SCREEN_SHARE_AUDIO;default:return wr.UNRECOGNIZED}}function jr(e){switch(e){case wr.UNKNOWN:return"UNKNOWN";case wr.CAMERA:return"CAMERA";case wr.MICROPHONE:return"MICROPHONE";case wr.SCREEN_SHARE:return"SCREEN_SHARE";case wr.SCREEN_SHARE_AUDIO:return"SCREEN_SHARE_AUDIO";case wr.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function qr(e){switch(e){case 0:case"LOW":return Tr.LOW;case 1:case"MEDIUM":return Tr.MEDIUM;case 2:case"HIGH":return Tr.HIGH;case 3:case"OFF":return Tr.OFF;default:return Tr.UNRECOGNIZED}}function Vr(e){switch(e){case Tr.LOW:return"LOW";case Tr.MEDIUM:return"MEDIUM";case Tr.HIGH:return"HIGH";case Tr.OFF:return"OFF";case Tr.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function $r(e){switch(e){case 0:case"POOR":return Pr.POOR;case 1:case"GOOD":return Pr.GOOD;case 2:case"EXCELLENT":return Pr.EXCELLENT;default:return Pr.UNRECOGNIZED}}function Jr(e){switch(e){case 0:case"UNSET":return Mr.UNSET;case 1:case"DISABLED":return Mr.DISABLED;case 2:case"ENABLED":return Mr.ENABLED;default:return Mr.UNRECOGNIZED}}function Wr(e){switch(e){case Mr.UNSET:return"UNSET";case Mr.DISABLED:return"DISABLED";case Mr.ENABLED:return"ENABLED";case Mr.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function Hr(e){switch(e){case 0:case"UNKNOWN_REASON":return Rr.UNKNOWN_REASON;case 1:case"CLIENT_INITIATED":return Rr.CLIENT_INITIATED;case 2:case"DUPLICATE_IDENTITY":return Rr.DUPLICATE_IDENTITY;case 3:case"SERVER_SHUTDOWN":return Rr.SERVER_SHUTDOWN;case 4:case"PARTICIPANT_REMOVED":return Rr.PARTICIPANT_REMOVED;case 5:case"ROOM_DELETED":return Rr.ROOM_DELETED;case 6:case"STATE_MISMATCH":return Rr.STATE_MISMATCH;case 7:case"JOIN_FAILURE":return Rr.JOIN_FAILURE;default:return Rr.UNRECOGNIZED}}function Gr(e){switch(e){case 0:case"SE_UNKOWN":return _r.SE_UNKOWN;case 1:case"SE_CODEC_UNSUPPORTED":return _r.SE_CODEC_UNSUPPORTED;case 2:case"SE_TRACK_NOTFOUND":return _r.SE_TRACK_NOTFOUND;default:return _r.UNRECOGNIZED}}function Zr(e){switch(e){case 0:case"JOINING":return Dr.JOINING;case 1:case"JOINED":return Dr.JOINED;case 2:case"ACTIVE":return Dr.ACTIVE;case 3:case"DISCONNECTED":return Dr.DISCONNECTED;default:return Dr.UNRECOGNIZED}}function zr(e){switch(e){case 0:case"NONE":return Ir.NONE;case 1:case"GCM":return Ir.GCM;case 2:case"CUSTOM":return Ir.CUSTOM;default:return Ir.UNRECOGNIZED}}function Kr(e){switch(e){case Ir.NONE:return"NONE";case Ir.GCM:return"GCM";case Ir.CUSTOM:return"CUSTOM";case Ir.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function Qr(e){switch(e){case 0:case"RELIABLE":return Ar.RELIABLE;case 1:case"LOSSY":return Ar.LOSSY;default:return Ar.UNRECOGNIZED}}function Yr(e){switch(e){case 0:case"Standard":return Or.Standard;case 1:case"Cloud":return Or.Cloud;default:return Or.UNRECOGNIZED}}function Xr(e){switch(e){case 0:case"UNKNOWN":return Ur.UNKNOWN;case 1:case"JS":return Ur.JS;case 2:case"SWIFT":return Ur.SWIFT;case 3:case"ANDROID":return Ur.ANDROID;case 4:case"FLUTTER":return Ur.FLUTTER;case 5:case"GO":return Ur.GO;case 6:case"UNITY":return Ur.UNITY;case 7:case"REACT_NATIVE":return Ur.REACT_NATIVE;case 8:case"RUST":return Ur.RUST;default:return Ur.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"})(),xr.util.Long!==pa&&(xr.util.Long=pa,xr.configure()),function(e){e[e.DEFAULT_AC=0]="DEFAULT_AC",e[e.OPUS=1]="OPUS",e[e.AAC=2]="AAC",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Cr||(Cr={})),function(e){e[e.DEFAULT_VC=0]="DEFAULT_VC",e[e.H264_BASELINE=1]="H264_BASELINE",e[e.H264_MAIN=2]="H264_MAIN",e[e.H264_HIGH=3]="H264_HIGH",e[e.VP8=4]="VP8",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(kr||(kr={})),function(e){e[e.AUDIO=0]="AUDIO",e[e.VIDEO=1]="VIDEO",e[e.DATA=2]="DATA",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Er||(Er={})),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"}(wr||(wr={})),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"}(Tr||(Tr={})),function(e){e[e.POOR=0]="POOR",e[e.GOOD=1]="GOOD",e[e.EXCELLENT=2]="EXCELLENT",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Pr||(Pr={})),function(e){e[e.UNSET=0]="UNSET",e[e.DISABLED=1]="DISABLED",e[e.ENABLED=2]="ENABLED",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Mr||(Mr={})),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"}(Rr||(Rr={})),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"}(Nr||(Nr={})),function(e){e[e.SE_UNKOWN=0]="SE_UNKOWN",e[e.SE_CODEC_UNSUPPORTED=1]="SE_CODEC_UNSUPPORTED",e[e.SE_TRACK_NOTFOUND=2]="SE_TRACK_NOTFOUND",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(_r||(_r={})),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"}(Dr||(Dr={})),function(e){e[e.NONE=0]="NONE",e[e.GCM=1]="GCM",e[e.CUSTOM=2]="CUSTOM",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Ir||(Ir={})),function(e){e[e.RELIABLE=0]="RELIABLE",e[e.LOSSY=1]="LOSSY",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Ar||(Ar={})),function(e){e[e.Standard=0]="Standard",e[e.Cloud=1]="Cloud",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Or||(Or={})),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.REACT_NATIVE=7]="REACT_NATIVE",e[e.RUST=8]="RUST",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Ur||(Ur={}));const eo={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.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)to.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.numPublishers&&t.uint32(88).uint32(e.numPublishers),!0===e.activeRecording&&t.uint32(80).bool(e.activeRecording),t},decode(e,t){const i=e instanceof xr.Reader?e:xr.Reader.create(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,numPublishers:0,activeRecording:!1};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;n.sid=i.string();continue;case 2:if(18!==e)break;n.name=i.string();continue;case 3:if(24!==e)break;n.emptyTimeout=i.uint32();continue;case 4:if(32!==e)break;n.maxParticipants=i.uint32();continue;case 5:if(40!==e)break;n.creationTime=Co(i.int64());continue;case 6:if(50!==e)break;n.turnPassword=i.string();continue;case 7:if(58!==e)break;n.enabledCodecs.push(to.decode(i,i.uint32()));continue;case 8:if(66!==e)break;n.metadata=i.string();continue;case 9:if(72!==e)break;n.numParticipants=i.uint32();continue;case 11:if(88!==e)break;n.numPublishers=i.uint32();continue;case 10:if(80!==e)break;n.activeRecording=i.bool();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({sid:ko(e.sid)?String(e.sid):"",name:ko(e.name)?String(e.name):"",emptyTimeout:ko(e.emptyTimeout)?Number(e.emptyTimeout):0,maxParticipants:ko(e.maxParticipants)?Number(e.maxParticipants):0,creationTime:ko(e.creationTime)?Number(e.creationTime):0,turnPassword:ko(e.turnPassword)?String(e.turnPassword):"",enabledCodecs:Array.isArray(null==e?void 0:e.enabledCodecs)?e.enabledCodecs.map((e=>to.fromJSON(e))):[],metadata:ko(e.metadata)?String(e.metadata):"",numParticipants:ko(e.numParticipants)?Number(e.numParticipants):0,numPublishers:ko(e.numPublishers)?Number(e.numPublishers):0,activeRecording:!!ko(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?to.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.numPublishers&&(t.numPublishers=Math.round(e.numPublishers)),void 0!==e.activeRecording&&(t.activeRecording=e.activeRecording),t},create:e=>eo.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,s,n,a,r,o,c,l,d,h;const u={sid:"",name:"",emptyTimeout:0,maxParticipants:0,creationTime:0,turnPassword:"",enabledCodecs:[],metadata:"",numParticipants:0,numPublishers:0,activeRecording:!1};return u.sid=null!==(t=e.sid)&&void 0!==t?t:"",u.name=null!==(i=e.name)&&void 0!==i?i:"",u.emptyTimeout=null!==(s=e.emptyTimeout)&&void 0!==s?s:0,u.maxParticipants=null!==(n=e.maxParticipants)&&void 0!==n?n:0,u.creationTime=null!==(a=e.creationTime)&&void 0!==a?a:0,u.turnPassword=null!==(r=e.turnPassword)&&void 0!==r?r:"",u.enabledCodecs=(null===(o=e.enabledCodecs)||void 0===o?void 0:o.map((e=>to.fromPartial(e))))||[],u.metadata=null!==(c=e.metadata)&&void 0!==c?c:"",u.numParticipants=null!==(l=e.numParticipants)&&void 0!==l?l:0,u.numPublishers=null!==(d=e.numPublishers)&&void 0!==d?d:0,u.activeRecording=null!==(h=e.activeRecording)&&void 0!==h&&h,u}};const to={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.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 xr.Reader?e:xr.Reader.create(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:if(10!==e)break;n.mime=i.string();continue;case 2:if(18!==e)break;n.fmtpLine=i.string();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({mime:ko(e.mime)?String(e.mime):"",fmtpLine:ko(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=>to.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 io={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.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),!0===e.canUpdateMetadata&&t.uint32(80).bool(e.canUpdateMetadata),t},decode(e,t){const i=e instanceof xr.Reader?e:xr.Reader.create(e);let s=void 0===t?i.len:i.pos+t;const n={canSubscribe:!1,canPublish:!1,canPublishData:!1,canPublishSources:[],hidden:!1,recorder:!1,canUpdateMetadata:!1};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:if(8!==e)break;n.canSubscribe=i.bool();continue;case 2:if(16!==e)break;n.canPublish=i.bool();continue;case 3:if(24!==e)break;n.canPublishData=i.bool();continue;case 9:if(72===e){n.canPublishSources.push(i.int32());continue}if(74===e){const e=i.uint32()+i.pos;for(;i.pos<e;)n.canPublishSources.push(i.int32());continue}break;case 7:if(56!==e)break;n.hidden=i.bool();continue;case 8:if(64!==e)break;n.recorder=i.bool();continue;case 10:if(80!==e)break;n.canUpdateMetadata=i.bool();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({canSubscribe:!!ko(e.canSubscribe)&&Boolean(e.canSubscribe),canPublish:!!ko(e.canPublish)&&Boolean(e.canPublish),canPublishData:!!ko(e.canPublishData)&&Boolean(e.canPublishData),canPublishSources:Array.isArray(null==e?void 0:e.canPublishSources)?e.canPublishSources.map((e=>Br(e))):[],hidden:!!ko(e.hidden)&&Boolean(e.hidden),recorder:!!ko(e.recorder)&&Boolean(e.recorder),canUpdateMetadata:!!ko(e.canUpdateMetadata)&&Boolean(e.canUpdateMetadata)}),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=>jr(e))):t.canPublishSources=[],void 0!==e.hidden&&(t.hidden=e.hidden),void 0!==e.recorder&&(t.recorder=e.recorder),void 0!==e.canUpdateMetadata&&(t.canUpdateMetadata=e.canUpdateMetadata),t},create:e=>io.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,s,n,a,r,o;const c={canSubscribe:!1,canPublish:!1,canPublishData:!1,canPublishSources:[],hidden:!1,recorder:!1,canUpdateMetadata:!1};return c.canSubscribe=null!==(t=e.canSubscribe)&&void 0!==t&&t,c.canPublish=null!==(i=e.canPublish)&&void 0!==i&&i,c.canPublishData=null!==(s=e.canPublishData)&&void 0!==s&&s,c.canPublishSources=(null===(n=e.canPublishSources)||void 0===n?void 0:n.map((e=>e)))||[],c.hidden=null!==(a=e.hidden)&&void 0!==a&&a,c.recorder=null!==(r=e.recorder)&&void 0!==r&&r,c.canUpdateMetadata=null!==(o=e.canUpdateMetadata)&&void 0!==o&&o,c}};const so={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.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)ao.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&&io.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 xr.Reader?e:xr.Reader.create(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:if(10!==e)break;n.sid=i.string();continue;case 2:if(18!==e)break;n.identity=i.string();continue;case 3:if(24!==e)break;n.state=i.int32();continue;case 4:if(34!==e)break;n.tracks.push(ao.decode(i,i.uint32()));continue;case 5:if(42!==e)break;n.metadata=i.string();continue;case 6:if(48!==e)break;n.joinedAt=Co(i.int64());continue;case 9:if(74!==e)break;n.name=i.string();continue;case 10:if(80!==e)break;n.version=i.uint32();continue;case 11:if(90!==e)break;n.permission=io.decode(i,i.uint32());continue;case 12:if(98!==e)break;n.region=i.string();continue;case 13:if(104!==e)break;n.isPublisher=i.bool();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({sid:ko(e.sid)?String(e.sid):"",identity:ko(e.identity)?String(e.identity):"",state:ko(e.state)?Zr(e.state):0,tracks:Array.isArray(null==e?void 0:e.tracks)?e.tracks.map((e=>ao.fromJSON(e))):[],metadata:ko(e.metadata)?String(e.metadata):"",joinedAt:ko(e.joinedAt)?Number(e.joinedAt):0,name:ko(e.name)?String(e.name):"",version:ko(e.version)?Number(e.version):0,permission:ko(e.permission)?io.fromJSON(e.permission):void 0,region:ko(e.region)?String(e.region):"",isPublisher:!!ko(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 Dr.JOINING:return"JOINING";case Dr.JOINED:return"JOINED";case Dr.ACTIVE:return"ACTIVE";case Dr.DISCONNECTED:return"DISCONNECTED";case Dr.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.state)),e.tracks?t.tracks=e.tracks.map((e=>e?ao.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?io.toJSON(e.permission):void 0),void 0!==e.region&&(t.region=e.region),void 0!==e.isPublisher&&(t.isPublisher=e.isPublisher),t},create:e=>so.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=>ao.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?io.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 no={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.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)ro.encode(i,t.uint32(34).fork()).ldelim();return t},decode(e,t){const i=e instanceof xr.Reader?e:xr.Reader.create(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:if(10!==e)break;n.mimeType=i.string();continue;case 2:if(18!==e)break;n.mid=i.string();continue;case 3:if(26!==e)break;n.cid=i.string();continue;case 4:if(34!==e)break;n.layers.push(ro.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({mimeType:ko(e.mimeType)?String(e.mimeType):"",mid:ko(e.mid)?String(e.mid):"",cid:ko(e.cid)?String(e.cid):"",layers:Array.isArray(null==e?void 0:e.layers)?e.layers.map((e=>ro.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?ro.toJSON(e):void 0)):t.layers=[],t},create:e=>no.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=>ro.fromPartial(e))))||[],a}};const ao={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.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)ro.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)no.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 xr.Reader?e:xr.Reader.create(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:if(10!==e)break;n.sid=i.string();continue;case 2:if(16!==e)break;n.type=i.int32();continue;case 3:if(26!==e)break;n.name=i.string();continue;case 4:if(32!==e)break;n.muted=i.bool();continue;case 5:if(40!==e)break;n.width=i.uint32();continue;case 6:if(48!==e)break;n.height=i.uint32();continue;case 7:if(56!==e)break;n.simulcast=i.bool();continue;case 8:if(64!==e)break;n.disableDtx=i.bool();continue;case 9:if(72!==e)break;n.source=i.int32();continue;case 10:if(82!==e)break;n.layers.push(ro.decode(i,i.uint32()));continue;case 11:if(90!==e)break;n.mimeType=i.string();continue;case 12:if(98!==e)break;n.mid=i.string();continue;case 13:if(106!==e)break;n.codecs.push(no.decode(i,i.uint32()));continue;case 14:if(112!==e)break;n.stereo=i.bool();continue;case 15:if(120!==e)break;n.disableRed=i.bool();continue;case 16:if(128!==e)break;n.encryption=i.int32();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({sid:ko(e.sid)?String(e.sid):"",type:ko(e.type)?Lr(e.type):0,name:ko(e.name)?String(e.name):"",muted:!!ko(e.muted)&&Boolean(e.muted),width:ko(e.width)?Number(e.width):0,height:ko(e.height)?Number(e.height):0,simulcast:!!ko(e.simulcast)&&Boolean(e.simulcast),disableDtx:!!ko(e.disableDtx)&&Boolean(e.disableDtx),source:ko(e.source)?Br(e.source):0,layers:Array.isArray(null==e?void 0:e.layers)?e.layers.map((e=>ro.fromJSON(e))):[],mimeType:ko(e.mimeType)?String(e.mimeType):"",mid:ko(e.mid)?String(e.mid):"",codecs:Array.isArray(null==e?void 0:e.codecs)?e.codecs.map((e=>no.fromJSON(e))):[],stereo:!!ko(e.stereo)&&Boolean(e.stereo),disableRed:!!ko(e.disableRed)&&Boolean(e.disableRed),encryption:ko(e.encryption)?zr(e.encryption):0}),toJSON(e){const t={};return void 0!==e.sid&&(t.sid=e.sid),void 0!==e.type&&(t.type=Fr(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=jr(e.source)),e.layers?t.layers=e.layers.map((e=>e?ro.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?no.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=Kr(e.encryption)),t},create:e=>ao.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=>ro.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=>no.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 ro={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.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 xr.Reader?e:xr.Reader.create(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:if(8!==e)break;n.quality=i.int32();continue;case 2:if(16!==e)break;n.width=i.uint32();continue;case 3:if(24!==e)break;n.height=i.uint32();continue;case 4:if(32!==e)break;n.bitrate=i.uint32();continue;case 5:if(40!==e)break;n.ssrc=i.uint32();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({quality:ko(e.quality)?qr(e.quality):0,width:ko(e.width)?Number(e.width):0,height:ko(e.height)?Number(e.height):0,bitrate:ko(e.bitrate)?Number(e.bitrate):0,ssrc:ko(e.ssrc)?Number(e.ssrc):0}),toJSON(e){const t={};return void 0!==e.quality&&(t.quality=Vr(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=>ro.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 oo={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.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":uo.encode(e.value.user,t.uint32(18).fork()).ldelim();break;case"speaker":co.encode(e.value.speaker,t.uint32(26).fork()).ldelim()}return t},decode(e,t){const i=e instanceof xr.Reader?e:xr.Reader.create(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:if(8!==e)break;n.kind=i.int32();continue;case 2:if(18!==e)break;n.value={$case:"user",user:uo.decode(i,i.uint32())};continue;case 3:if(26!==e)break;n.value={$case:"speaker",speaker:co.decode(i,i.uint32())};continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({kind:ko(e.kind)?Qr(e.kind):0,value:ko(e.user)?{$case:"user",user:uo.fromJSON(e.user)}:ko(e.speaker)?{$case:"speaker",speaker:co.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 Ar.RELIABLE:return"RELIABLE";case Ar.LOSSY:return"LOSSY";case Ar.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)?uo.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)?co.toJSON(null===(r=e.value)||void 0===r?void 0:r.speaker):void 0),o},create:e=>oo.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:uo.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:co.fromPartial(e.value.speaker)}),c}};const co={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.Writer.create();for(const i of e.speakers)lo.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof xr.Reader?e:xr.Reader.create(e);let s=void 0===t?i.len:i.pos+t;const n={speakers:[]};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;n.speakers.push(lo.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({speakers:Array.isArray(null==e?void 0:e.speakers)?e.speakers.map((e=>lo.fromJSON(e))):[]}),toJSON(e){const t={};return e.speakers?t.speakers=e.speakers.map((e=>e?lo.toJSON(e):void 0)):t.speakers=[],t},create:e=>co.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=>lo.fromPartial(e))))||[],i}};const lo={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.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 xr.Reader?e:xr.Reader.create(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:if(10!==e)break;n.sid=i.string();continue;case 2:if(21!==e)break;n.level=i.float();continue;case 3:if(24!==e)break;n.active=i.bool();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({sid:ko(e.sid)?String(e.sid):"",level:ko(e.level)?Number(e.level):0,active:!!ko(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=>lo.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 ho(){return{participantSid:"",payload:new Uint8Array,destinationSids:[],topic:void 0}}const uo={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.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 xr.Reader?e:xr.Reader.create(e);let s=void 0===t?i.len:i.pos+t;const n=ho();for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;n.participantSid=i.string();continue;case 2:if(18!==e)break;n.payload=i.bytes();continue;case 3:if(26!==e)break;n.destinationSids.push(i.string());continue;case 4:if(34!==e)break;n.topic=i.string();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({participantSid:ko(e.participantSid)?String(e.participantSid):"",payload:ko(e.payload)?So(e.payload):new Uint8Array,destinationSids:Array.isArray(null==e?void 0:e.destinationSids)?e.destinationSids.map((e=>String(e))):[],topic:ko(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(yo.Buffer)return yo.Buffer.from(e).toString("base64");{const t=[];return e.forEach((e=>{t.push(String.fromCharCode(e))})),yo.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=>uo.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,s,n;const a=ho();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 po={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.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 xr.Reader?e:xr.Reader.create(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:if(10!==e)break;n.participantSid=i.string();continue;case 2:if(18!==e)break;n.trackSids.push(i.string());continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({participantSid:ko(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=>po.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 mo={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.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 xr.Reader?e:xr.Reader.create(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:if(8!==e)break;n.edition=i.int32();continue;case 2:if(18!==e)break;n.version=i.string();continue;case 3:if(24!==e)break;n.protocol=i.int32();continue;case 4:if(34!==e)break;n.region=i.string();continue;case 5:if(42!==e)break;n.nodeId=i.string();continue;case 6:if(50!==e)break;n.debugInfo=i.string();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({edition:ko(e.edition)?Yr(e.edition):0,version:ko(e.version)?String(e.version):"",protocol:ko(e.protocol)?Number(e.protocol):0,region:ko(e.region)?String(e.region):"",nodeId:ko(e.nodeId)?String(e.nodeId):"",debugInfo:ko(e.debugInfo)?String(e.debugInfo):""}),toJSON(e){const t={};return void 0!==e.edition&&(t.edition=function(e){switch(e){case Or.Standard:return"Standard";case Or.Cloud:return"Cloud";case Or.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=>mo.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 go={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.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 xr.Reader?e:xr.Reader.create(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:if(8!==e)break;n.sdk=i.int32();continue;case 2:if(18!==e)break;n.version=i.string();continue;case 3:if(24!==e)break;n.protocol=i.int32();continue;case 4:if(34!==e)break;n.os=i.string();continue;case 5:if(42!==e)break;n.osVersion=i.string();continue;case 6:if(50!==e)break;n.deviceModel=i.string();continue;case 7:if(58!==e)break;n.browser=i.string();continue;case 8:if(66!==e)break;n.browserVersion=i.string();continue;case 9:if(74!==e)break;n.address=i.string();continue;case 10:if(82!==e)break;n.network=i.string();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({sdk:ko(e.sdk)?Xr(e.sdk):0,version:ko(e.version)?String(e.version):"",protocol:ko(e.protocol)?Number(e.protocol):0,os:ko(e.os)?String(e.os):"",osVersion:ko(e.osVersion)?String(e.osVersion):"",deviceModel:ko(e.deviceModel)?String(e.deviceModel):"",browser:ko(e.browser)?String(e.browser):"",browserVersion:ko(e.browserVersion)?String(e.browserVersion):"",address:ko(e.address)?String(e.address):"",network:ko(e.network)?String(e.network):""}),toJSON(e){const t={};return void 0!==e.sdk&&(t.sdk=function(e){switch(e){case Ur.UNKNOWN:return"UNKNOWN";case Ur.JS:return"JS";case Ur.SWIFT:return"SWIFT";case Ur.ANDROID:return"ANDROID";case Ur.FLUTTER:return"FLUTTER";case Ur.GO:return"GO";case Ur.UNITY:return"UNITY";case Ur.REACT_NATIVE:return"REACT_NATIVE";case Ur.RUST:return"RUST";case Ur.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=>go.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 fo={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.Writer.create();return void 0!==e.video&&vo.encode(e.video,t.uint32(10).fork()).ldelim(),void 0!==e.screen&&vo.encode(e.screen,t.uint32(18).fork()).ldelim(),0!==e.resumeConnection&&t.uint32(24).int32(e.resumeConnection),void 0!==e.disabledCodecs&&bo.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 xr.Reader?e:xr.Reader.create(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:if(10!==e)break;n.video=vo.decode(i,i.uint32());continue;case 2:if(18!==e)break;n.screen=vo.decode(i,i.uint32());continue;case 3:if(24!==e)break;n.resumeConnection=i.int32();continue;case 4:if(34!==e)break;n.disabledCodecs=bo.decode(i,i.uint32());continue;case 5:if(40!==e)break;n.forceRelay=i.int32();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({video:ko(e.video)?vo.fromJSON(e.video):void 0,screen:ko(e.screen)?vo.fromJSON(e.screen):void 0,resumeConnection:ko(e.resumeConnection)?Jr(e.resumeConnection):0,disabledCodecs:ko(e.disabledCodecs)?bo.fromJSON(e.disabledCodecs):void 0,forceRelay:ko(e.forceRelay)?Jr(e.forceRelay):0}),toJSON(e){const t={};return void 0!==e.video&&(t.video=e.video?vo.toJSON(e.video):void 0),void 0!==e.screen&&(t.screen=e.screen?vo.toJSON(e.screen):void 0),void 0!==e.resumeConnection&&(t.resumeConnection=Wr(e.resumeConnection)),void 0!==e.disabledCodecs&&(t.disabledCodecs=e.disabledCodecs?bo.toJSON(e.disabledCodecs):void 0),void 0!==e.forceRelay&&(t.forceRelay=Wr(e.forceRelay)),t},create:e=>fo.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?vo.fromPartial(e.video):void 0,s.screen=void 0!==e.screen&&null!==e.screen?vo.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?bo.fromPartial(e.disabledCodecs):void 0,s.forceRelay=null!==(i=e.forceRelay)&&void 0!==i?i:0,s}};const vo={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.Writer.create();return 0!==e.hardwareEncoder&&t.uint32(8).int32(e.hardwareEncoder),t},decode(e,t){const i=e instanceof xr.Reader?e:xr.Reader.create(e);let s=void 0===t?i.len:i.pos+t;const n={hardwareEncoder:0};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:if(8!==e)break;n.hardwareEncoder=i.int32();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({hardwareEncoder:ko(e.hardwareEncoder)?Jr(e.hardwareEncoder):0}),toJSON(e){const t={};return void 0!==e.hardwareEncoder&&(t.hardwareEncoder=Wr(e.hardwareEncoder)),t},create:e=>vo.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 bo={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.Writer.create();for(const i of e.codecs)to.encode(i,t.uint32(10).fork()).ldelim();for(const i of e.publish)to.encode(i,t.uint32(18).fork()).ldelim();return t},decode(e,t){const i=e instanceof xr.Reader?e:xr.Reader.create(e);let s=void 0===t?i.len:i.pos+t;const n={codecs:[],publish:[]};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;n.codecs.push(to.decode(i,i.uint32()));continue;case 2:if(18!==e)break;n.publish.push(to.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({codecs:Array.isArray(null==e?void 0:e.codecs)?e.codecs.map((e=>to.fromJSON(e))):[],publish:Array.isArray(null==e?void 0:e.publish)?e.publish.map((e=>to.fromJSON(e))):[]}),toJSON(e){const t={};return e.codecs?t.codecs=e.codecs.map((e=>e?to.toJSON(e):void 0)):t.codecs=[],e.publish?t.publish=e.publish.map((e=>e?to.toJSON(e):void 0)):t.publish=[],t},create:e=>bo.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const s={codecs:[],publish:[]};return s.codecs=(null===(t=e.codecs)||void 0===t?void 0:t.map((e=>to.fromPartial(e))))||[],s.publish=(null===(i=e.publish)||void 0===i?void 0:i.map((e=>to.fromPartial(e))))||[],s}};var yo=(()=>{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 So(e){if(yo.Buffer)return Uint8Array.from(yo.Buffer.from(e,"base64"));{const t=yo.atob(e),i=new Uint8Array(t.length);for(let e=0;e<t.length;++e)i[e]=t.charCodeAt(e);return i}}function Co(e){if(e.gt(Number.MAX_SAFE_INTEGER))throw new yo.Error("Value is larger than Number.MAX_SAFE_INTEGER");return e.toNumber()}function ko(e){return null!=e}xr.util.Long!==pa&&(xr.util.Long=pa,xr.configure());const Eo=7e3,wo=[0,300,1200,2700,4800,Eo,Eo,Eo,Eo,Eo];function To(e,t,i,s){return new(i||(i=Promise))((function(n,a){function r(e){try{c(s.next(e))}catch(e){a(e)}}function o(e){try{c(s.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):function(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(r,o)}c((s=s.apply(e,t||[])).next())}))}function Po(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],s=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&s>=e.length&&(e=void 0),{value:e&&e[s++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Mo(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,i=e[Symbol.asyncIterator];return i?i.call(e):(e=Po(e),t={},s("next"),s("throw"),s("return"),t[Symbol.asyncIterator]=function(){return this},t);function s(i){t[i]=e[i]&&function(t){return new Promise((function(s,n){(function(e,t,i,s){Promise.resolve(s).then((function(t){e({value:t,done:i})}),t)})(s,n,(t=e[i](t)).done,t.value)}))}}}var Ro,No={exports:{}},_o="object"==typeof Reflect?Reflect:null,Do=_o&&"function"==typeof _o.apply?_o.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};Ro=_o&&"function"==typeof _o.ownKeys?_o.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var Io=Number.isNaN||function(e){return e!=e};function Ao(){Ao.init.call(this)}No.exports=Ao,No.exports.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))}$o(e,t,a,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&$o(e,"error",t,i)}(e,n,{once:!0})}))},Ao.EventEmitter=Ao,Ao.prototype._events=void 0,Ao.prototype._eventsCount=0,Ao.prototype._maxListeners=void 0;var Oo=10;function Uo(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function xo(e){return void 0===e._maxListeners?Ao.defaultMaxListeners:e._maxListeners}function Lo(e,t,i,s){var n,a,r,o;if(Uo(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=xo(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 Fo(){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 Bo(e,t,i){var s={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},n=Fo.bind(s);return n.listener=i,s.wrapFn=n,n}function jo(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):Vo(n,n.length)}function qo(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 Vo(e,t){for(var i=new Array(t),s=0;s<t;++s)i[s]=e[s];return i}function $o(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(Ao,"defaultMaxListeners",{enumerable:!0,get:function(){return Oo},set:function(e){if("number"!=typeof e||e<0||Io(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");Oo=e}}),Ao.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},Ao.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||Io(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},Ao.prototype.getMaxListeners=function(){return xo(this)},Ao.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)Do(o,this,t);else{var c=o.length,l=Vo(o,c);for(i=0;i<c;++i)Do(l[i],this,t)}return!0},Ao.prototype.addListener=function(e,t){return Lo(this,e,t,!1)},Ao.prototype.on=Ao.prototype.addListener,Ao.prototype.prependListener=function(e,t){return Lo(this,e,t,!0)},Ao.prototype.once=function(e,t){return Uo(t),this.on(e,Bo(this,e,t)),this},Ao.prototype.prependOnceListener=function(e,t){return Uo(t),this.prependListener(e,Bo(this,e,t)),this},Ao.prototype.removeListener=function(e,t){var i,s,n,a,r;if(Uo(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},Ao.prototype.off=Ao.prototype.removeListener,Ao.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},Ao.prototype.listeners=function(e){return jo(this,e,!0)},Ao.prototype.rawListeners=function(e){return jo(this,e,!1)},Ao.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):qo.call(e,t)},Ao.prototype.listenerCount=qo,Ao.prototype.eventNames=function(){return this._eventsCount>0?Ro(this._events):[]};var Jo=No.exports;let Wo=!0,Ho=!0;function Go(e,t,i){const s=e.match(t);return s&&s.length>=i&&parseInt(s[i],10)}function Zo(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 zo(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Wo=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function Ko(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Ho=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function Qo(){if("object"==typeof window){if(Wo)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function Yo(e,t){Ho&&console.warn(e+" is deprecated, please use "+t+" instead.")}function Xo(e){return"[object Object]"===Object.prototype.toString.call(e)}function ec(e){return Xo(e)?Object.keys(e).reduce((function(t,i){const s=Xo(e[i]),n=s?ec(e[i]):e[i],a=s&&!Object.keys(n).length;return void 0===n||a?t:Object.assign(t,{[i]:n})}),{}):e}function tc(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((s=>{s.endsWith("Id")?tc(e,e.get(t[s]),i):s.endsWith("Ids")&&t[s].forEach((t=>{tc(e,e.get(t),i)}))})))}function ic(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&&tc(e,i,n)}))})),n}const sc=Qo;function nc(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),sc("chrome: "+JSON.stringify(e)),n(e)}))}e.video=s(e.video)}return sc("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 ac(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function rc(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 Zo(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function oc(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 cc(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 lc(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=>ic(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}),Zo(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>ic(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 dc(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 hc(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return dc(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 uc(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 pc(e,t){Zo(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var mc=Object.freeze({__proto__:null,fixNegotiationNeeded:pc,shimAddTrackRemoveTrack:hc,shimAddTrackRemoveTrackWithNative:dc,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:oc,shimGetStats:cc,shimGetUserMedia:nc,shimMediaStream:ac,shimOnTrack:rc,shimPeerConnection:uc,shimSenderReceiverGetStats:lc});function gc(e,t){const i=e&&e.navigator,s=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,s){Yo("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 fc(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 vc(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 bc(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 yc(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}),Zo(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Sc(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){Yo("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function Cc(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function kc(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.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,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return s})}function Ec(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 wc(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 Tc(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 Pc=Object.freeze({__proto__:null,shimAddTransceiver:kc,shimCreateAnswer:Tc,shimCreateOffer:wc,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:Ec,shimGetUserMedia:gc,shimOnTrack:fc,shimPeerConnection:vc,shimRTCDataChannel:Cc,shimReceiverGetStats:yc,shimRemoveStream:Sc,shimSenderGetStats:bc});function Mc(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 Rc(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 Nc(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 _c(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(Dc(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,s){t.mediaDevices.getUserMedia(e).then(i,s)}.bind(t))}function Dc(e){return e&&void 0!==e.video?Object.assign({},e,{video:ec(e.video)}):e}function Ic(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];void 0===s.urls&&s.url?(Yo("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 Ac(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 Oc(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 Uc(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var xc=Object.freeze({__proto__:null,shimAudioContext:Uc,shimCallbacksAPI:Nc,shimConstraints:Dc,shimCreateOfferLegacy:Oc,shimGetUserMedia:_c,shimLocalStreamsAPI:Mc,shimRTCIceServerUrls:Ic,shimRemoteStreamsAPI:Rc,shimTrackEventTransceiver:Ac}),Lc={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};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.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(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.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const s=e.substring(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.substring(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.substring(7,t),10)},s=e.indexOf(":",t);return s>-1?(i.attribute=e.substring(t+1,s),i.value=e.substring(s+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(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.substring(6)},t.parseFingerprint=function(e){const t=e.substring(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.substring(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.substring(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.substring(12),password:n.substring(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(" ");i.profile=s[2];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())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))}));const n=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{n.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let s="";s+="m="+e+" ",s+=i.codecs.length>0?"9":"0",s+=" "+(i.profile||"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.substring(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].substring(7),10):0===d[0].indexOf("b=AS:")?1e3*parseInt(d[0].substring(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].substring(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].substring(19),10)),isNaN(n)&&(n=65536);const a=t.matchPrefix(e,"a=sctp-port:");if(a.length>0)return{port:parseInt(a[0].substring(12),10),protocol:i.fmt,maxMessageSize:n};const r=t.matchPrefix(e,"a=sctpmap:");if(r.length>0){const e=r[0].substring(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,22)},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].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(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].substring(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}(Lc);var Fc=Lc.exports,Bc=On(Fc),jc=In({__proto__:null,default:Bc},[Fc]);function qc(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.substring(2)),e.candidate&&e.candidate.length){const i=new t(e),s=Bc.parseCandidate(e.candidate);for(const e in s)e in i||Object.defineProperty(i,e,{value:s[e]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,Zo(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function Vc(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||Zo(e,"icecandidate",(e=>{if(e.candidate){const t=Bc.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function $c(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=Bc.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=Bc.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=Bc.matchPrefix(e.sdp,"a=max-message-size:");return n.length>0?s=parseInt(n[0].substring(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 Jc(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},Zo(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function Wc(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 Hc(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 Gc(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 Zc(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 zc,Kc,Qc,Yc=Object.freeze({__proto__:null,removeExtmapAllowMixed:Hc,shimAddIceCandidateNullOrEmpty:Gc,shimConnectionState:Wc,shimMaxMessageSize:$c,shimParameterlessSetLocalDescription:Zc,shimRTCIceCandidate:qc,shimRTCIceCandidateRelayProtocol:Vc,shimSendThrowTypeError:Jc});function Xc(e){switch(e){case 0:case"PUBLISHER":return zc.PUBLISHER;case 1:case"SUBSCRIBER":return zc.SUBSCRIBER;default:return zc.UNRECOGNIZED}}function el(e){switch(e){case zc.PUBLISHER:return"PUBLISHER";case zc.SUBSCRIBER:return"SUBSCRIBER";case zc.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function tl(e){switch(e){case 0:case"ACTIVE":return Kc.ACTIVE;case 1:case"PAUSED":return Kc.PAUSED;default:return Kc.UNRECOGNIZED}}function il(e){switch(e){case 0:case"UDP":return Qc.UDP;case 1:case"TCP":return Qc.TCP;case 2:case"TLS":return Qc.TLS;default:return Qc.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=Qo,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=Go(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=Go(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=Go(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),n={browserDetails:s,commonShim:Yc,extractVersion:Go,disableLog:zo,disableWarnings:Ko,sdp:jc};switch(s.browser){case"chrome":if(!mc||!uc||!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=mc,Gc(e,s),Zc(e),nc(e,s),ac(e),uc(e,s),rc(e),hc(e,s),oc(e),cc(e),lc(e),pc(e,s),qc(e),Vc(e),Wc(e),$c(e,s),Jc(e),Hc(e,s);break;case"firefox":if(!Pc||!vc||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),n;i("adapter.js shimming firefox."),n.browserShim=Pc,Gc(e,s),Zc(e),gc(e,s),vc(e,s),fc(e),Sc(e),bc(e),yc(e),Cc(e),kc(e),Ec(e),wc(e),Tc(e),qc(e),Wc(e),$c(e,s),Jc(e);break;case"safari":if(!xc||!t.shimSafari)return i("Safari shim is not included in this adapter release."),n;i("adapter.js shimming safari."),n.browserShim=xc,Gc(e,s),Zc(e),Ic(e),Oc(e),Nc(e),Mc(e),Rc(e),Ac(e),_c(e),Uc(e),qc(e),Vc(e),$c(e,s),Jc(e),Hc(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"}(zc||(zc={})),function(e){e[e.ACTIVE=0]="ACTIVE",e[e.PAUSED=1]="PAUSED",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Kc||(Kc={})),function(e){e[e.UDP=0]="UDP",e[e.TCP=1]="TCP",e[e.TLS=2]="TLS",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Qc||(Qc={}));const sl={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.Writer.create();var i;switch(null===(i=e.message)||void 0===i?void 0:i.$case){case"offer":ml.encode(e.message.offer,t.uint32(10).fork()).ldelim();break;case"answer":ml.encode(e.message.answer,t.uint32(18).fork()).ldelim();break;case"trickle":ol.encode(e.message.trickle,t.uint32(26).fork()).ldelim();break;case"addTrack":rl.encode(e.message.addTrack,t.uint32(34).fork()).ldelim();break;case"mute":cl.encode(e.message.mute,t.uint32(42).fork()).ldelim();break;case"subscription":fl.encode(e.message.subscription,t.uint32(50).fork()).ldelim();break;case"trackSetting":vl.encode(e.message.trackSetting,t.uint32(58).fork()).ldelim();break;case"leave":bl.encode(e.message.leave,t.uint32(66).fork()).ldelim();break;case"updateLayers":yl.encode(e.message.updateLayers,t.uint32(82).fork()).ldelim();break;case"subscriptionPermission":Il.encode(e.message.subscriptionPermission,t.uint32(90).fork()).ldelim();break;case"syncState":Ol.encode(e.message.syncState,t.uint32(98).fork()).ldelim();break;case"simulate":xl.encode(e.message.simulate,t.uint32(106).fork()).ldelim();break;case"ping":t.uint32(112).int64(e.message.ping);break;case"updateMetadata":Sl.encode(e.message.updateMetadata,t.uint32(122).fork()).ldelim();break;case"pingReq":Ll.encode(e.message.pingReq,t.uint32(130).fork()).ldelim()}return t},decode(e,t){const i=e instanceof xr.Reader?e:xr.Reader.create(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:if(10!==e)break;n.message={$case:"offer",offer:ml.decode(i,i.uint32())};continue;case 2:if(18!==e)break;n.message={$case:"answer",answer:ml.decode(i,i.uint32())};continue;case 3:if(26!==e)break;n.message={$case:"trickle",trickle:ol.decode(i,i.uint32())};continue;case 4:if(34!==e)break;n.message={$case:"addTrack",addTrack:rl.decode(i,i.uint32())};continue;case 5:if(42!==e)break;n.message={$case:"mute",mute:cl.decode(i,i.uint32())};continue;case 6:if(50!==e)break;n.message={$case:"subscription",subscription:fl.decode(i,i.uint32())};continue;case 7:if(58!==e)break;n.message={$case:"trackSetting",trackSetting:vl.decode(i,i.uint32())};continue;case 8:if(66!==e)break;n.message={$case:"leave",leave:bl.decode(i,i.uint32())};continue;case 10:if(82!==e)break;n.message={$case:"updateLayers",updateLayers:yl.decode(i,i.uint32())};continue;case 11:if(90!==e)break;n.message={$case:"subscriptionPermission",subscriptionPermission:Il.decode(i,i.uint32())};continue;case 12:if(98!==e)break;n.message={$case:"syncState",syncState:Ol.decode(i,i.uint32())};continue;case 13:if(106!==e)break;n.message={$case:"simulate",simulate:xl.decode(i,i.uint32())};continue;case 14:if(112!==e)break;n.message={$case:"ping",ping:$l(i.int64())};continue;case 15:if(122!==e)break;n.message={$case:"updateMetadata",updateMetadata:Sl.decode(i,i.uint32())};continue;case 16:if(130!==e)break;n.message={$case:"pingReq",pingReq:Ll.decode(i,i.uint32())};continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({message:Jl(e.offer)?{$case:"offer",offer:ml.fromJSON(e.offer)}:Jl(e.answer)?{$case:"answer",answer:ml.fromJSON(e.answer)}:Jl(e.trickle)?{$case:"trickle",trickle:ol.fromJSON(e.trickle)}:Jl(e.addTrack)?{$case:"addTrack",addTrack:rl.fromJSON(e.addTrack)}:Jl(e.mute)?{$case:"mute",mute:cl.fromJSON(e.mute)}:Jl(e.subscription)?{$case:"subscription",subscription:fl.fromJSON(e.subscription)}:Jl(e.trackSetting)?{$case:"trackSetting",trackSetting:vl.fromJSON(e.trackSetting)}:Jl(e.leave)?{$case:"leave",leave:bl.fromJSON(e.leave)}:Jl(e.updateLayers)?{$case:"updateLayers",updateLayers:yl.fromJSON(e.updateLayers)}:Jl(e.subscriptionPermission)?{$case:"subscriptionPermission",subscriptionPermission:Il.fromJSON(e.subscriptionPermission)}:Jl(e.syncState)?{$case:"syncState",syncState:Ol.fromJSON(e.syncState)}:Jl(e.simulate)?{$case:"simulate",simulate:xl.fromJSON(e.simulate)}:Jl(e.ping)?{$case:"ping",ping:Number(e.ping)}:Jl(e.updateMetadata)?{$case:"updateMetadata",updateMetadata:Sl.fromJSON(e.updateMetadata)}:Jl(e.pingReq)?{$case:"pingReq",pingReq:Ll.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,C,k,E,w,T,P,M,R,N,_,D,I,A,O,U,x,L,F,B,j,q,V,$,J;const W={};return"offer"===(null===(t=e.message)||void 0===t?void 0:t.$case)&&(W.offer=(null===(i=e.message)||void 0===i?void 0:i.offer)?ml.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)&&(W.answer=(null===(a=e.message)||void 0===a?void 0:a.answer)?ml.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)&&(W.trickle=(null===(c=e.message)||void 0===c?void 0:c.trickle)?ol.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)&&(W.addTrack=(null===(h=e.message)||void 0===h?void 0:h.addTrack)?rl.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)&&(W.mute=(null===(m=e.message)||void 0===m?void 0:m.mute)?cl.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)&&(W.subscription=(null===(v=e.message)||void 0===v?void 0:v.subscription)?fl.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)&&(W.trackSetting=(null===(S=e.message)||void 0===S?void 0:S.trackSetting)?vl.toJSON(null===(C=e.message)||void 0===C?void 0:C.trackSetting):void 0),"leave"===(null===(k=e.message)||void 0===k?void 0:k.$case)&&(W.leave=(null===(E=e.message)||void 0===E?void 0:E.leave)?bl.toJSON(null===(w=e.message)||void 0===w?void 0:w.leave):void 0),"updateLayers"===(null===(T=e.message)||void 0===T?void 0:T.$case)&&(W.updateLayers=(null===(P=e.message)||void 0===P?void 0:P.updateLayers)?yl.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)&&(W.subscriptionPermission=(null===(N=e.message)||void 0===N?void 0:N.subscriptionPermission)?Il.toJSON(null===(_=e.message)||void 0===_?void 0:_.subscriptionPermission):void 0),"syncState"===(null===(D=e.message)||void 0===D?void 0:D.$case)&&(W.syncState=(null===(I=e.message)||void 0===I?void 0:I.syncState)?Ol.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)&&(W.simulate=(null===(U=e.message)||void 0===U?void 0:U.simulate)?xl.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)&&(W.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)&&(W.updateMetadata=(null===(j=e.message)||void 0===j?void 0:j.updateMetadata)?Sl.toJSON(null===(q=e.message)||void 0===q?void 0:q.updateMetadata):void 0),"pingReq"===(null===(V=e.message)||void 0===V?void 0:V.$case)&&(W.pingReq=(null===($=e.message)||void 0===$?void 0:$.pingReq)?Ll.toJSON(null===(J=e.message)||void 0===J?void 0:J.pingReq):void 0),W},create:e=>sl.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,C,k,E,w,T,P,M,R,N,_,D,I,A,O,U,x,L,F,B,j,q,V,$,J,W;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:ml.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:ml.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:ol.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:rl.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:cl.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:fl.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===(C=e.message)||void 0===C?void 0:C.trackSetting)&&(H.message={$case:"trackSetting",trackSetting:vl.fromPartial(e.message.trackSetting)}),"leave"===(null===(k=e.message)||void 0===k?void 0:k.$case)&&void 0!==(null===(E=e.message)||void 0===E?void 0:E.leave)&&null!==(null===(w=e.message)||void 0===w?void 0:w.leave)&&(H.message={$case:"leave",leave:bl.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:yl.fromPartial(e.message.updateLayers)}),"subscriptionPermission"===(null===(R=e.message)||void 0===R?void 0:R.$case)&&void 0!==(null===(N=e.message)||void 0===N?void 0:N.subscriptionPermission)&&null!==(null===(_=e.message)||void 0===_?void 0:_.subscriptionPermission)&&(H.message={$case:"subscriptionPermission",subscriptionPermission:Il.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:Ol.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:xl.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===(j=e.message)||void 0===j?void 0:j.$case)&&void 0!==(null===(q=e.message)||void 0===q?void 0:q.updateMetadata)&&null!==(null===(V=e.message)||void 0===V?void 0:V.updateMetadata)&&(H.message={$case:"updateMetadata",updateMetadata:Sl.fromPartial(e.message.updateMetadata)}),"pingReq"===(null===($=e.message)||void 0===$?void 0:$.$case)&&void 0!==(null===(J=e.message)||void 0===J?void 0:J.pingReq)&&null!==(null===(W=e.message)||void 0===W?void 0:W.pingReq)&&(H.message={$case:"pingReq",pingReq:Ll.fromPartial(e.message.pingReq)}),H}};const nl={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.Writer.create();var i;switch(null===(i=e.message)||void 0===i?void 0:i.$case){case"join":dl.encode(e.message.join,t.uint32(10).fork()).ldelim();break;case"answer":ml.encode(e.message.answer,t.uint32(18).fork()).ldelim();break;case"offer":ml.encode(e.message.offer,t.uint32(26).fork()).ldelim();break;case"trickle":ol.encode(e.message.trickle,t.uint32(34).fork()).ldelim();break;case"update":gl.encode(e.message.update,t.uint32(42).fork()).ldelim();break;case"trackPublished":ul.encode(e.message.trackPublished,t.uint32(50).fork()).ldelim();break;case"leave":bl.encode(e.message.leave,t.uint32(66).fork()).ldelim();break;case"mute":cl.encode(e.message.mute,t.uint32(74).fork()).ldelim();break;case"speakersChanged":kl.encode(e.message.speakersChanged,t.uint32(82).fork()).ldelim();break;case"roomUpdate":El.encode(e.message.roomUpdate,t.uint32(90).fork()).ldelim();break;case"connectionQuality":Tl.encode(e.message.connectionQuality,t.uint32(98).fork()).ldelim();break;case"streamStateUpdate":Ml.encode(e.message.streamStateUpdate,t.uint32(106).fork()).ldelim();break;case"subscribedQualityUpdate":_l.encode(e.message.subscribedQualityUpdate,t.uint32(114).fork()).ldelim();break;case"subscriptionPermissionUpdate":Al.encode(e.message.subscriptionPermissionUpdate,t.uint32(122).fork()).ldelim();break;case"refreshToken":t.uint32(130).string(e.message.refreshToken);break;case"trackUnpublished":pl.encode(e.message.trackUnpublished,t.uint32(138).fork()).ldelim();break;case"pong":t.uint32(144).int64(e.message.pong);break;case"reconnect":hl.encode(e.message.reconnect,t.uint32(154).fork()).ldelim();break;case"pongResp":Fl.encode(e.message.pongResp,t.uint32(162).fork()).ldelim();break;case"subscriptionResponse":Bl.encode(e.message.subscriptionResponse,t.uint32(170).fork()).ldelim()}return t},decode(e,t){const i=e instanceof xr.Reader?e:xr.Reader.create(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:if(10!==e)break;n.message={$case:"join",join:dl.decode(i,i.uint32())};continue;case 2:if(18!==e)break;n.message={$case:"answer",answer:ml.decode(i,i.uint32())};continue;case 3:if(26!==e)break;n.message={$case:"offer",offer:ml.decode(i,i.uint32())};continue;case 4:if(34!==e)break;n.message={$case:"trickle",trickle:ol.decode(i,i.uint32())};continue;case 5:if(42!==e)break;n.message={$case:"update",update:gl.decode(i,i.uint32())};continue;case 6:if(50!==e)break;n.message={$case:"trackPublished",trackPublished:ul.decode(i,i.uint32())};continue;case 8:if(66!==e)break;n.message={$case:"leave",leave:bl.decode(i,i.uint32())};continue;case 9:if(74!==e)break;n.message={$case:"mute",mute:cl.decode(i,i.uint32())};continue;case 10:if(82!==e)break;n.message={$case:"speakersChanged",speakersChanged:kl.decode(i,i.uint32())};continue;case 11:if(90!==e)break;n.message={$case:"roomUpdate",roomUpdate:El.decode(i,i.uint32())};continue;case 12:if(98!==e)break;n.message={$case:"connectionQuality",connectionQuality:Tl.decode(i,i.uint32())};continue;case 13:if(106!==e)break;n.message={$case:"streamStateUpdate",streamStateUpdate:Ml.decode(i,i.uint32())};continue;case 14:if(114!==e)break;n.message={$case:"subscribedQualityUpdate",subscribedQualityUpdate:_l.decode(i,i.uint32())};continue;case 15:if(122!==e)break;n.message={$case:"subscriptionPermissionUpdate",subscriptionPermissionUpdate:Al.decode(i,i.uint32())};continue;case 16:if(130!==e)break;n.message={$case:"refreshToken",refreshToken:i.string()};continue;case 17:if(138!==e)break;n.message={$case:"trackUnpublished",trackUnpublished:pl.decode(i,i.uint32())};continue;case 18:if(144!==e)break;n.message={$case:"pong",pong:$l(i.int64())};continue;case 19:if(154!==e)break;n.message={$case:"reconnect",reconnect:hl.decode(i,i.uint32())};continue;case 20:if(162!==e)break;n.message={$case:"pongResp",pongResp:Fl.decode(i,i.uint32())};continue;case 21:if(170!==e)break;n.message={$case:"subscriptionResponse",subscriptionResponse:Bl.decode(i,i.uint32())};continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({message:Jl(e.join)?{$case:"join",join:dl.fromJSON(e.join)}:Jl(e.answer)?{$case:"answer",answer:ml.fromJSON(e.answer)}:Jl(e.offer)?{$case:"offer",offer:ml.fromJSON(e.offer)}:Jl(e.trickle)?{$case:"trickle",trickle:ol.fromJSON(e.trickle)}:Jl(e.update)?{$case:"update",update:gl.fromJSON(e.update)}:Jl(e.trackPublished)?{$case:"trackPublished",trackPublished:ul.fromJSON(e.trackPublished)}:Jl(e.leave)?{$case:"leave",leave:bl.fromJSON(e.leave)}:Jl(e.mute)?{$case:"mute",mute:cl.fromJSON(e.mute)}:Jl(e.speakersChanged)?{$case:"speakersChanged",speakersChanged:kl.fromJSON(e.speakersChanged)}:Jl(e.roomUpdate)?{$case:"roomUpdate",roomUpdate:El.fromJSON(e.roomUpdate)}:Jl(e.connectionQuality)?{$case:"connectionQuality",connectionQuality:Tl.fromJSON(e.connectionQuality)}:Jl(e.streamStateUpdate)?{$case:"streamStateUpdate",streamStateUpdate:Ml.fromJSON(e.streamStateUpdate)}:Jl(e.subscribedQualityUpdate)?{$case:"subscribedQualityUpdate",subscribedQualityUpdate:_l.fromJSON(e.subscribedQualityUpdate)}:Jl(e.subscriptionPermissionUpdate)?{$case:"subscriptionPermissionUpdate",subscriptionPermissionUpdate:Al.fromJSON(e.subscriptionPermissionUpdate)}:Jl(e.refreshToken)?{$case:"refreshToken",refreshToken:String(e.refreshToken)}:Jl(e.trackUnpublished)?{$case:"trackUnpublished",trackUnpublished:pl.fromJSON(e.trackUnpublished)}:Jl(e.pong)?{$case:"pong",pong:Number(e.pong)}:Jl(e.reconnect)?{$case:"reconnect",reconnect:hl.fromJSON(e.reconnect)}:Jl(e.pongResp)?{$case:"pongResp",pongResp:Fl.fromJSON(e.pongResp)}:Jl(e.subscriptionResponse)?{$case:"subscriptionResponse",subscriptionResponse:Bl.fromJSON(e.subscriptionResponse)}: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,C,k,E,w,T,P,M,R,N,_,D,I,A,O,U,x,L,F,B,j,q,V,$,J,W,H,G,Z,z,K,Q,Y,X,ee,te,ie,se,ne;const ae={};return"join"===(null===(t=e.message)||void 0===t?void 0:t.$case)&&(ae.join=(null===(i=e.message)||void 0===i?void 0:i.join)?dl.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)&&(ae.answer=(null===(a=e.message)||void 0===a?void 0:a.answer)?ml.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)&&(ae.offer=(null===(c=e.message)||void 0===c?void 0:c.offer)?ml.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)&&(ae.trickle=(null===(h=e.message)||void 0===h?void 0:h.trickle)?ol.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)&&(ae.update=(null===(m=e.message)||void 0===m?void 0:m.update)?gl.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)&&(ae.trackPublished=(null===(v=e.message)||void 0===v?void 0:v.trackPublished)?ul.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)&&(ae.leave=(null===(S=e.message)||void 0===S?void 0:S.leave)?bl.toJSON(null===(C=e.message)||void 0===C?void 0:C.leave):void 0),"mute"===(null===(k=e.message)||void 0===k?void 0:k.$case)&&(ae.mute=(null===(E=e.message)||void 0===E?void 0:E.mute)?cl.toJSON(null===(w=e.message)||void 0===w?void 0:w.mute):void 0),"speakersChanged"===(null===(T=e.message)||void 0===T?void 0:T.$case)&&(ae.speakersChanged=(null===(P=e.message)||void 0===P?void 0:P.speakersChanged)?kl.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)&&(ae.roomUpdate=(null===(N=e.message)||void 0===N?void 0:N.roomUpdate)?El.toJSON(null===(_=e.message)||void 0===_?void 0:_.roomUpdate):void 0),"connectionQuality"===(null===(D=e.message)||void 0===D?void 0:D.$case)&&(ae.connectionQuality=(null===(I=e.message)||void 0===I?void 0:I.connectionQuality)?Tl.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)&&(ae.streamStateUpdate=(null===(U=e.message)||void 0===U?void 0:U.streamStateUpdate)?Ml.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)&&(ae.subscribedQualityUpdate=(null===(F=e.message)||void 0===F?void 0:F.subscribedQualityUpdate)?_l.toJSON(null===(B=e.message)||void 0===B?void 0:B.subscribedQualityUpdate):void 0),"subscriptionPermissionUpdate"===(null===(j=e.message)||void 0===j?void 0:j.$case)&&(ae.subscriptionPermissionUpdate=(null===(q=e.message)||void 0===q?void 0:q.subscriptionPermissionUpdate)?Al.toJSON(null===(V=e.message)||void 0===V?void 0:V.subscriptionPermissionUpdate):void 0),"refreshToken"===(null===($=e.message)||void 0===$?void 0:$.$case)&&(ae.refreshToken=null===(J=e.message)||void 0===J?void 0:J.refreshToken),"trackUnpublished"===(null===(W=e.message)||void 0===W?void 0:W.$case)&&(ae.trackUnpublished=(null===(H=e.message)||void 0===H?void 0:H.trackUnpublished)?pl.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)&&(ae.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)&&(ae.reconnect=(null===(Q=e.message)||void 0===Q?void 0:Q.reconnect)?hl.toJSON(null===(Y=e.message)||void 0===Y?void 0:Y.reconnect):void 0),"pongResp"===(null===(X=e.message)||void 0===X?void 0:X.$case)&&(ae.pongResp=(null===(ee=e.message)||void 0===ee?void 0:ee.pongResp)?Fl.toJSON(null===(te=e.message)||void 0===te?void 0:te.pongResp):void 0),"subscriptionResponse"===(null===(ie=e.message)||void 0===ie?void 0:ie.$case)&&(ae.subscriptionResponse=(null===(se=e.message)||void 0===se?void 0:se.subscriptionResponse)?Bl.toJSON(null===(ne=e.message)||void 0===ne?void 0:ne.subscriptionResponse):void 0),ae},create:e=>nl.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,C,k,E,w,T,P,M,R,N,_,D,I,A,O,U,x,L,F,B,j,q,V,$,J,W,H,G,Z,z,K,Q,Y,X,ee,te,ie,se,ne,ae,re;const oe={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)&&(oe.message={$case:"join",join:dl.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)&&(oe.message={$case:"answer",answer:ml.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)&&(oe.message={$case:"offer",offer:ml.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)&&(oe.message={$case:"trickle",trickle:ol.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)&&(oe.message={$case:"update",update:gl.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)&&(oe.message={$case:"trackPublished",trackPublished:ul.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===(C=e.message)||void 0===C?void 0:C.leave)&&(oe.message={$case:"leave",leave:bl.fromPartial(e.message.leave)}),"mute"===(null===(k=e.message)||void 0===k?void 0:k.$case)&&void 0!==(null===(E=e.message)||void 0===E?void 0:E.mute)&&null!==(null===(w=e.message)||void 0===w?void 0:w.mute)&&(oe.message={$case:"mute",mute:cl.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)&&(oe.message={$case:"speakersChanged",speakersChanged:kl.fromPartial(e.message.speakersChanged)}),"roomUpdate"===(null===(R=e.message)||void 0===R?void 0:R.$case)&&void 0!==(null===(N=e.message)||void 0===N?void 0:N.roomUpdate)&&null!==(null===(_=e.message)||void 0===_?void 0:_.roomUpdate)&&(oe.message={$case:"roomUpdate",roomUpdate:El.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)&&(oe.message={$case:"connectionQuality",connectionQuality:Tl.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)&&(oe.message={$case:"streamStateUpdate",streamStateUpdate:Ml.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)&&(oe.message={$case:"subscribedQualityUpdate",subscribedQualityUpdate:_l.fromPartial(e.message.subscribedQualityUpdate)}),"subscriptionPermissionUpdate"===(null===(j=e.message)||void 0===j?void 0:j.$case)&&void 0!==(null===(q=e.message)||void 0===q?void 0:q.subscriptionPermissionUpdate)&&null!==(null===(V=e.message)||void 0===V?void 0:V.subscriptionPermissionUpdate)&&(oe.message={$case:"subscriptionPermissionUpdate",subscriptionPermissionUpdate:Al.fromPartial(e.message.subscriptionPermissionUpdate)}),"refreshToken"===(null===($=e.message)||void 0===$?void 0:$.$case)&&void 0!==(null===(J=e.message)||void 0===J?void 0:J.refreshToken)&&null!==(null===(W=e.message)||void 0===W?void 0:W.refreshToken)&&(oe.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)&&(oe.message={$case:"trackUnpublished",trackUnpublished:pl.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)&&(oe.message={$case:"pong",pong:e.message.pong}),"reconnect"===(null===(Y=e.message)||void 0===Y?void 0:Y.$case)&&void 0!==(null===(X=e.message)||void 0===X?void 0:X.reconnect)&&null!==(null===(ee=e.message)||void 0===ee?void 0:ee.reconnect)&&(oe.message={$case:"reconnect",reconnect:hl.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)&&(oe.message={$case:"pongResp",pongResp:Fl.fromPartial(e.message.pongResp)}),"subscriptionResponse"===(null===(ne=e.message)||void 0===ne?void 0:ne.$case)&&void 0!==(null===(ae=e.message)||void 0===ae?void 0:ae.subscriptionResponse)&&null!==(null===(re=e.message)||void 0===re?void 0:re.subscriptionResponse)&&(oe.message={$case:"subscriptionResponse",subscriptionResponse:Bl.fromPartial(e.message.subscriptionResponse)}),oe}};const al={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.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 xr.Reader?e:xr.Reader.create(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:if(10!==e)break;n.codec=i.string();continue;case 2:if(18!==e)break;n.cid=i.string();continue;case 3:if(24!==e)break;n.enableSimulcastLayers=i.bool();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({codec:Jl(e.codec)?String(e.codec):"",cid:Jl(e.cid)?String(e.cid):"",enableSimulcastLayers:!!Jl(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=>al.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 rl={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.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)ro.encode(i,t.uint32(74).fork()).ldelim();for(const i of e.simulcastCodecs)al.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 xr.Reader?e:xr.Reader.create(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:if(10!==e)break;n.cid=i.string();continue;case 2:if(18!==e)break;n.name=i.string();continue;case 3:if(24!==e)break;n.type=i.int32();continue;case 4:if(32!==e)break;n.width=i.uint32();continue;case 5:if(40!==e)break;n.height=i.uint32();continue;case 6:if(48!==e)break;n.muted=i.bool();continue;case 7:if(56!==e)break;n.disableDtx=i.bool();continue;case 8:if(64!==e)break;n.source=i.int32();continue;case 9:if(74!==e)break;n.layers.push(ro.decode(i,i.uint32()));continue;case 10:if(82!==e)break;n.simulcastCodecs.push(al.decode(i,i.uint32()));continue;case 11:if(90!==e)break;n.sid=i.string();continue;case 12:if(96!==e)break;n.stereo=i.bool();continue;case 13:if(104!==e)break;n.disableRed=i.bool();continue;case 14:if(112!==e)break;n.encryption=i.int32();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({cid:Jl(e.cid)?String(e.cid):"",name:Jl(e.name)?String(e.name):"",type:Jl(e.type)?Lr(e.type):0,width:Jl(e.width)?Number(e.width):0,height:Jl(e.height)?Number(e.height):0,muted:!!Jl(e.muted)&&Boolean(e.muted),disableDtx:!!Jl(e.disableDtx)&&Boolean(e.disableDtx),source:Jl(e.source)?Br(e.source):0,layers:Array.isArray(null==e?void 0:e.layers)?e.layers.map((e=>ro.fromJSON(e))):[],simulcastCodecs:Array.isArray(null==e?void 0:e.simulcastCodecs)?e.simulcastCodecs.map((e=>al.fromJSON(e))):[],sid:Jl(e.sid)?String(e.sid):"",stereo:!!Jl(e.stereo)&&Boolean(e.stereo),disableRed:!!Jl(e.disableRed)&&Boolean(e.disableRed),encryption:Jl(e.encryption)?zr(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=Fr(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=jr(e.source)),e.layers?t.layers=e.layers.map((e=>e?ro.toJSON(e):void 0)):t.layers=[],e.simulcastCodecs?t.simulcastCodecs=e.simulcastCodecs.map((e=>e?al.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=Kr(e.encryption)),t},create:e=>rl.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=>ro.fromPartial(e))))||[],g.simulcastCodecs=(null===(d=e.simulcastCodecs)||void 0===d?void 0:d.map((e=>al.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 ol={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.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 xr.Reader?e:xr.Reader.create(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:if(10!==e)break;n.candidateInit=i.string();continue;case 2:if(16!==e)break;n.target=i.int32();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({candidateInit:Jl(e.candidateInit)?String(e.candidateInit):"",target:Jl(e.target)?Xc(e.target):0}),toJSON(e){const t={};return void 0!==e.candidateInit&&(t.candidateInit=e.candidateInit),void 0!==e.target&&(t.target=el(e.target)),t},create:e=>ol.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 cl={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.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 xr.Reader?e:xr.Reader.create(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:if(10!==e)break;n.sid=i.string();continue;case 2:if(16!==e)break;n.muted=i.bool();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({sid:Jl(e.sid)?String(e.sid):"",muted:!!Jl(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=>cl.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}};function ll(){return{room:void 0,participant:void 0,otherParticipants:[],serverVersion:"",iceServers:[],subscriberPrimary:!1,alternativeUrl:"",clientConfiguration:void 0,serverRegion:"",pingTimeout:0,pingInterval:0,serverInfo:void 0,sifTrailer:new Uint8Array}}const dl={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.Writer.create();void 0!==e.room&&eo.encode(e.room,t.uint32(10).fork()).ldelim(),void 0!==e.participant&&so.encode(e.participant,t.uint32(18).fork()).ldelim();for(const i of e.otherParticipants)so.encode(i,t.uint32(26).fork()).ldelim();""!==e.serverVersion&&t.uint32(34).string(e.serverVersion);for(const i of e.iceServers)Cl.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&&fo.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&&mo.encode(e.serverInfo,t.uint32(98).fork()).ldelim(),0!==e.sifTrailer.length&&t.uint32(106).bytes(e.sifTrailer),t},decode(e,t){const i=e instanceof xr.Reader?e:xr.Reader.create(e);let s=void 0===t?i.len:i.pos+t;const n=ll();for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;n.room=eo.decode(i,i.uint32());continue;case 2:if(18!==e)break;n.participant=so.decode(i,i.uint32());continue;case 3:if(26!==e)break;n.otherParticipants.push(so.decode(i,i.uint32()));continue;case 4:if(34!==e)break;n.serverVersion=i.string();continue;case 5:if(42!==e)break;n.iceServers.push(Cl.decode(i,i.uint32()));continue;case 6:if(48!==e)break;n.subscriberPrimary=i.bool();continue;case 7:if(58!==e)break;n.alternativeUrl=i.string();continue;case 8:if(66!==e)break;n.clientConfiguration=fo.decode(i,i.uint32());continue;case 9:if(74!==e)break;n.serverRegion=i.string();continue;case 10:if(80!==e)break;n.pingTimeout=i.int32();continue;case 11:if(88!==e)break;n.pingInterval=i.int32();continue;case 12:if(98!==e)break;n.serverInfo=mo.decode(i,i.uint32());continue;case 13:if(106!==e)break;n.sifTrailer=i.bytes();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({room:Jl(e.room)?eo.fromJSON(e.room):void 0,participant:Jl(e.participant)?so.fromJSON(e.participant):void 0,otherParticipants:Array.isArray(null==e?void 0:e.otherParticipants)?e.otherParticipants.map((e=>so.fromJSON(e))):[],serverVersion:Jl(e.serverVersion)?String(e.serverVersion):"",iceServers:Array.isArray(null==e?void 0:e.iceServers)?e.iceServers.map((e=>Cl.fromJSON(e))):[],subscriberPrimary:!!Jl(e.subscriberPrimary)&&Boolean(e.subscriberPrimary),alternativeUrl:Jl(e.alternativeUrl)?String(e.alternativeUrl):"",clientConfiguration:Jl(e.clientConfiguration)?fo.fromJSON(e.clientConfiguration):void 0,serverRegion:Jl(e.serverRegion)?String(e.serverRegion):"",pingTimeout:Jl(e.pingTimeout)?Number(e.pingTimeout):0,pingInterval:Jl(e.pingInterval)?Number(e.pingInterval):0,serverInfo:Jl(e.serverInfo)?mo.fromJSON(e.serverInfo):void 0,sifTrailer:Jl(e.sifTrailer)?Vl(e.sifTrailer):new Uint8Array}),toJSON(e){const t={};return void 0!==e.room&&(t.room=e.room?eo.toJSON(e.room):void 0),void 0!==e.participant&&(t.participant=e.participant?so.toJSON(e.participant):void 0),e.otherParticipants?t.otherParticipants=e.otherParticipants.map((e=>e?so.toJSON(e):void 0)):t.otherParticipants=[],void 0!==e.serverVersion&&(t.serverVersion=e.serverVersion),e.iceServers?t.iceServers=e.iceServers.map((e=>e?Cl.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?fo.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?mo.toJSON(e.serverInfo):void 0),void 0!==e.sifTrailer&&(t.sifTrailer=function(e){if(ql.Buffer)return ql.Buffer.from(e).toString("base64");{const t=[];return e.forEach((e=>{t.push(String.fromCharCode(e))})),ql.btoa(t.join(""))}}(void 0!==e.sifTrailer?e.sifTrailer:new Uint8Array)),t},create:e=>dl.fromPartial(null!=e?e:{}),fromPartial(e){var t,i,s,n,a,r,o,c,l;const d=ll();return d.room=void 0!==e.room&&null!==e.room?eo.fromPartial(e.room):void 0,d.participant=void 0!==e.participant&&null!==e.participant?so.fromPartial(e.participant):void 0,d.otherParticipants=(null===(t=e.otherParticipants)||void 0===t?void 0:t.map((e=>so.fromPartial(e))))||[],d.serverVersion=null!==(i=e.serverVersion)&&void 0!==i?i:"",d.iceServers=(null===(s=e.iceServers)||void 0===s?void 0:s.map((e=>Cl.fromPartial(e))))||[],d.subscriberPrimary=null!==(n=e.subscriberPrimary)&&void 0!==n&&n,d.alternativeUrl=null!==(a=e.alternativeUrl)&&void 0!==a?a:"",d.clientConfiguration=void 0!==e.clientConfiguration&&null!==e.clientConfiguration?fo.fromPartial(e.clientConfiguration):void 0,d.serverRegion=null!==(r=e.serverRegion)&&void 0!==r?r:"",d.pingTimeout=null!==(o=e.pingTimeout)&&void 0!==o?o:0,d.pingInterval=null!==(c=e.pingInterval)&&void 0!==c?c:0,d.serverInfo=void 0!==e.serverInfo&&null!==e.serverInfo?mo.fromPartial(e.serverInfo):void 0,d.sifTrailer=null!==(l=e.sifTrailer)&&void 0!==l?l:new Uint8Array,d}};const hl={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.Writer.create();for(const i of e.iceServers)Cl.encode(i,t.uint32(10).fork()).ldelim();return void 0!==e.clientConfiguration&&fo.encode(e.clientConfiguration,t.uint32(18).fork()).ldelim(),t},decode(e,t){const i=e instanceof xr.Reader?e:xr.Reader.create(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:if(10!==e)break;n.iceServers.push(Cl.decode(i,i.uint32()));continue;case 2:if(18!==e)break;n.clientConfiguration=fo.decode(i,i.uint32());continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({iceServers:Array.isArray(null==e?void 0:e.iceServers)?e.iceServers.map((e=>Cl.fromJSON(e))):[],clientConfiguration:Jl(e.clientConfiguration)?fo.fromJSON(e.clientConfiguration):void 0}),toJSON(e){const t={};return e.iceServers?t.iceServers=e.iceServers.map((e=>e?Cl.toJSON(e):void 0)):t.iceServers=[],void 0!==e.clientConfiguration&&(t.clientConfiguration=e.clientConfiguration?fo.toJSON(e.clientConfiguration):void 0),t},create:e=>hl.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=>Cl.fromPartial(e))))||[],i.clientConfiguration=void 0!==e.clientConfiguration&&null!==e.clientConfiguration?fo.fromPartial(e.clientConfiguration):void 0,i}};const ul={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.Writer.create();return""!==e.cid&&t.uint32(10).string(e.cid),void 0!==e.track&&ao.encode(e.track,t.uint32(18).fork()).ldelim(),t},decode(e,t){const i=e instanceof xr.Reader?e:xr.Reader.create(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:if(10!==e)break;n.cid=i.string();continue;case 2:if(18!==e)break;n.track=ao.decode(i,i.uint32());continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({cid:Jl(e.cid)?String(e.cid):"",track:Jl(e.track)?ao.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?ao.toJSON(e.track):void 0),t},create:e=>ul.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?ao.fromPartial(e.track):void 0,i}};const pl={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.Writer.create();return""!==e.trackSid&&t.uint32(10).string(e.trackSid),t},decode(e,t){const i=e instanceof xr.Reader?e:xr.Reader.create(e);let s=void 0===t?i.len:i.pos+t;const n={trackSid:""};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;n.trackSid=i.string();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({trackSid:Jl(e.trackSid)?String(e.trackSid):""}),toJSON(e){const t={};return void 0!==e.trackSid&&(t.trackSid=e.trackSid),t},create:e=>pl.fromPartial(null!=e?e:{}),fromPartial(e){var t;const i={trackSid:""};return i.trackSid=null!==(t=e.trackSid)&&void 0!==t?t:"",i}};const ml={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.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 xr.Reader?e:xr.Reader.create(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:if(10!==e)break;n.type=i.string();continue;case 2:if(18!==e)break;n.sdp=i.string();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({type:Jl(e.type)?String(e.type):"",sdp:Jl(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=>ml.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 gl={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.Writer.create();for(const i of e.participants)so.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof xr.Reader?e:xr.Reader.create(e);let s=void 0===t?i.len:i.pos+t;const n={participants:[]};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;n.participants.push(so.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({participants:Array.isArray(null==e?void 0:e.participants)?e.participants.map((e=>so.fromJSON(e))):[]}),toJSON(e){const t={};return e.participants?t.participants=e.participants.map((e=>e?so.toJSON(e):void 0)):t.participants=[],t},create:e=>gl.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=>so.fromPartial(e))))||[],i}};const fl={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.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)po.encode(i,t.uint32(26).fork()).ldelim();return t},decode(e,t){const i=e instanceof xr.Reader?e:xr.Reader.create(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:if(10!==e)break;n.trackSids.push(i.string());continue;case 2:if(16!==e)break;n.subscribe=i.bool();continue;case 3:if(26!==e)break;n.participantTracks.push(po.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({trackSids:Array.isArray(null==e?void 0:e.trackSids)?e.trackSids.map((e=>String(e))):[],subscribe:!!Jl(e.subscribe)&&Boolean(e.subscribe),participantTracks:Array.isArray(null==e?void 0:e.participantTracks)?e.participantTracks.map((e=>po.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?po.toJSON(e):void 0)):t.participantTracks=[],t},create:e=>fl.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=>po.fromPartial(e))))||[],n}};const vl={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.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 xr.Reader?e:xr.Reader.create(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:if(10!==e)break;n.trackSids.push(i.string());continue;case 3:if(24!==e)break;n.disabled=i.bool();continue;case 4:if(32!==e)break;n.quality=i.int32();continue;case 5:if(40!==e)break;n.width=i.uint32();continue;case 6:if(48!==e)break;n.height=i.uint32();continue;case 7:if(56!==e)break;n.fps=i.uint32();continue;case 8:if(64!==e)break;n.priority=i.uint32();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({trackSids:Array.isArray(null==e?void 0:e.trackSids)?e.trackSids.map((e=>String(e))):[],disabled:!!Jl(e.disabled)&&Boolean(e.disabled),quality:Jl(e.quality)?qr(e.quality):0,width:Jl(e.width)?Number(e.width):0,height:Jl(e.height)?Number(e.height):0,fps:Jl(e.fps)?Number(e.fps):0,priority:Jl(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=Vr(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=>vl.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 bl={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.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 xr.Reader?e:xr.Reader.create(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:if(8!==e)break;n.canReconnect=i.bool();continue;case 2:if(16!==e)break;n.reason=i.int32();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({canReconnect:!!Jl(e.canReconnect)&&Boolean(e.canReconnect),reason:Jl(e.reason)?Hr(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 Rr.UNKNOWN_REASON:return"UNKNOWN_REASON";case Rr.CLIENT_INITIATED:return"CLIENT_INITIATED";case Rr.DUPLICATE_IDENTITY:return"DUPLICATE_IDENTITY";case Rr.SERVER_SHUTDOWN:return"SERVER_SHUTDOWN";case Rr.PARTICIPANT_REMOVED:return"PARTICIPANT_REMOVED";case Rr.ROOM_DELETED:return"ROOM_DELETED";case Rr.STATE_MISMATCH:return"STATE_MISMATCH";case Rr.JOIN_FAILURE:return"JOIN_FAILURE";case Rr.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.reason)),t},create:e=>bl.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 yl={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.Writer.create();""!==e.trackSid&&t.uint32(10).string(e.trackSid);for(const i of e.layers)ro.encode(i,t.uint32(18).fork()).ldelim();return t},decode(e,t){const i=e instanceof xr.Reader?e:xr.Reader.create(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:if(10!==e)break;n.trackSid=i.string();continue;case 2:if(18!==e)break;n.layers.push(ro.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({trackSid:Jl(e.trackSid)?String(e.trackSid):"",layers:Array.isArray(null==e?void 0:e.layers)?e.layers.map((e=>ro.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.trackSid&&(t.trackSid=e.trackSid),e.layers?t.layers=e.layers.map((e=>e?ro.toJSON(e):void 0)):t.layers=[],t},create:e=>yl.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=>ro.fromPartial(e))))||[],s}};const Sl={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.Writer.create();return""!==e.metadata&&t.uint32(10).string(e.metadata),""!==e.name&&t.uint32(18).string(e.name),t},decode(e,t){const i=e instanceof xr.Reader?e:xr.Reader.create(e);let s=void 0===t?i.len:i.pos+t;const n={metadata:"",name:""};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;n.metadata=i.string();continue;case 2:if(18!==e)break;n.name=i.string();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({metadata:Jl(e.metadata)?String(e.metadata):"",name:Jl(e.name)?String(e.name):""}),toJSON(e){const t={};return void 0!==e.metadata&&(t.metadata=e.metadata),void 0!==e.name&&(t.name=e.name),t},create:e=>Sl.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const s={metadata:"",name:""};return s.metadata=null!==(t=e.metadata)&&void 0!==t?t:"",s.name=null!==(i=e.name)&&void 0!==i?i:"",s}};const Cl={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.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 xr.Reader?e:xr.Reader.create(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:if(10!==e)break;n.urls.push(i.string());continue;case 2:if(18!==e)break;n.username=i.string();continue;case 3:if(26!==e)break;n.credential=i.string();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({urls:Array.isArray(null==e?void 0:e.urls)?e.urls.map((e=>String(e))):[],username:Jl(e.username)?String(e.username):"",credential:Jl(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=>Cl.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 kl={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.Writer.create();for(const i of e.speakers)lo.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof xr.Reader?e:xr.Reader.create(e);let s=void 0===t?i.len:i.pos+t;const n={speakers:[]};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;n.speakers.push(lo.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({speakers:Array.isArray(null==e?void 0:e.speakers)?e.speakers.map((e=>lo.fromJSON(e))):[]}),toJSON(e){const t={};return e.speakers?t.speakers=e.speakers.map((e=>e?lo.toJSON(e):void 0)):t.speakers=[],t},create:e=>kl.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=>lo.fromPartial(e))))||[],i}};const El={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.Writer.create();return void 0!==e.room&&eo.encode(e.room,t.uint32(10).fork()).ldelim(),t},decode(e,t){const i=e instanceof xr.Reader?e:xr.Reader.create(e);let s=void 0===t?i.len:i.pos+t;const n={room:void 0};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;n.room=eo.decode(i,i.uint32());continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({room:Jl(e.room)?eo.fromJSON(e.room):void 0}),toJSON(e){const t={};return void 0!==e.room&&(t.room=e.room?eo.toJSON(e.room):void 0),t},create:e=>El.fromPartial(null!=e?e:{}),fromPartial(e){const t={room:void 0};return t.room=void 0!==e.room&&null!==e.room?eo.fromPartial(e.room):void 0,t}};const wl={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.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 xr.Reader?e:xr.Reader.create(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:if(10!==e)break;n.participantSid=i.string();continue;case 2:if(16!==e)break;n.quality=i.int32();continue;case 3:if(29!==e)break;n.score=i.float();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({participantSid:Jl(e.participantSid)?String(e.participantSid):"",quality:Jl(e.quality)?$r(e.quality):0,score:Jl(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 Pr.POOR:return"POOR";case Pr.GOOD:return"GOOD";case Pr.EXCELLENT:return"EXCELLENT";case Pr.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.quality)),void 0!==e.score&&(t.score=e.score),t},create:e=>wl.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 Tl={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.Writer.create();for(const i of e.updates)wl.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof xr.Reader?e:xr.Reader.create(e);let s=void 0===t?i.len:i.pos+t;const n={updates:[]};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;n.updates.push(wl.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({updates:Array.isArray(null==e?void 0:e.updates)?e.updates.map((e=>wl.fromJSON(e))):[]}),toJSON(e){const t={};return e.updates?t.updates=e.updates.map((e=>e?wl.toJSON(e):void 0)):t.updates=[],t},create:e=>Tl.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=>wl.fromPartial(e))))||[],i}};const Pl={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.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 xr.Reader?e:xr.Reader.create(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:if(10!==e)break;n.participantSid=i.string();continue;case 2:if(18!==e)break;n.trackSid=i.string();continue;case 3:if(24!==e)break;n.state=i.int32();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({participantSid:Jl(e.participantSid)?String(e.participantSid):"",trackSid:Jl(e.trackSid)?String(e.trackSid):"",state:Jl(e.state)?tl(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 Kc.ACTIVE:return"ACTIVE";case Kc.PAUSED:return"PAUSED";case Kc.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.state)),t},create:e=>Pl.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 Ml={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.Writer.create();for(const i of e.streamStates)Pl.encode(i,t.uint32(10).fork()).ldelim();return t},decode(e,t){const i=e instanceof xr.Reader?e:xr.Reader.create(e);let s=void 0===t?i.len:i.pos+t;const n={streamStates:[]};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;n.streamStates.push(Pl.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({streamStates:Array.isArray(null==e?void 0:e.streamStates)?e.streamStates.map((e=>Pl.fromJSON(e))):[]}),toJSON(e){const t={};return e.streamStates?t.streamStates=e.streamStates.map((e=>e?Pl.toJSON(e):void 0)):t.streamStates=[],t},create:e=>Ml.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=>Pl.fromPartial(e))))||[],i}};const Rl={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.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 xr.Reader?e:xr.Reader.create(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:if(8!==e)break;n.quality=i.int32();continue;case 2:if(16!==e)break;n.enabled=i.bool();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({quality:Jl(e.quality)?qr(e.quality):0,enabled:!!Jl(e.enabled)&&Boolean(e.enabled)}),toJSON(e){const t={};return void 0!==e.quality&&(t.quality=Vr(e.quality)),void 0!==e.enabled&&(t.enabled=e.enabled),t},create:e=>Rl.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 Nl={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.Writer.create();""!==e.codec&&t.uint32(10).string(e.codec);for(const i of e.qualities)Rl.encode(i,t.uint32(18).fork()).ldelim();return t},decode(e,t){const i=e instanceof xr.Reader?e:xr.Reader.create(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:if(10!==e)break;n.codec=i.string();continue;case 2:if(18!==e)break;n.qualities.push(Rl.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({codec:Jl(e.codec)?String(e.codec):"",qualities:Array.isArray(null==e?void 0:e.qualities)?e.qualities.map((e=>Rl.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.codec&&(t.codec=e.codec),e.qualities?t.qualities=e.qualities.map((e=>e?Rl.toJSON(e):void 0)):t.qualities=[],t},create:e=>Nl.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=>Rl.fromPartial(e))))||[],s}};const _l={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.Writer.create();""!==e.trackSid&&t.uint32(10).string(e.trackSid);for(const i of e.subscribedQualities)Rl.encode(i,t.uint32(18).fork()).ldelim();for(const i of e.subscribedCodecs)Nl.encode(i,t.uint32(26).fork()).ldelim();return t},decode(e,t){const i=e instanceof xr.Reader?e:xr.Reader.create(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:if(10!==e)break;n.trackSid=i.string();continue;case 2:if(18!==e)break;n.subscribedQualities.push(Rl.decode(i,i.uint32()));continue;case 3:if(26!==e)break;n.subscribedCodecs.push(Nl.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({trackSid:Jl(e.trackSid)?String(e.trackSid):"",subscribedQualities:Array.isArray(null==e?void 0:e.subscribedQualities)?e.subscribedQualities.map((e=>Rl.fromJSON(e))):[],subscribedCodecs:Array.isArray(null==e?void 0:e.subscribedCodecs)?e.subscribedCodecs.map((e=>Nl.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.trackSid&&(t.trackSid=e.trackSid),e.subscribedQualities?t.subscribedQualities=e.subscribedQualities.map((e=>e?Rl.toJSON(e):void 0)):t.subscribedQualities=[],e.subscribedCodecs?t.subscribedCodecs=e.subscribedCodecs.map((e=>e?Nl.toJSON(e):void 0)):t.subscribedCodecs=[],t},create:e=>_l.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=>Rl.fromPartial(e))))||[],n.subscribedCodecs=(null===(s=e.subscribedCodecs)||void 0===s?void 0:s.map((e=>Nl.fromPartial(e))))||[],n}};const Dl={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.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 xr.Reader?e:xr.Reader.create(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:if(10!==e)break;n.participantSid=i.string();continue;case 2:if(16!==e)break;n.allTracks=i.bool();continue;case 3:if(26!==e)break;n.trackSids.push(i.string());continue;case 4:if(34!==e)break;n.participantIdentity=i.string();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({participantSid:Jl(e.participantSid)?String(e.participantSid):"",allTracks:!!Jl(e.allTracks)&&Boolean(e.allTracks),trackSids:Array.isArray(null==e?void 0:e.trackSids)?e.trackSids.map((e=>String(e))):[],participantIdentity:Jl(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=>Dl.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 Il={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.Writer.create();!0===e.allParticipants&&t.uint32(8).bool(e.allParticipants);for(const i of e.trackPermissions)Dl.encode(i,t.uint32(18).fork()).ldelim();return t},decode(e,t){const i=e instanceof xr.Reader?e:xr.Reader.create(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:if(8!==e)break;n.allParticipants=i.bool();continue;case 2:if(18!==e)break;n.trackPermissions.push(Dl.decode(i,i.uint32()));continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({allParticipants:!!Jl(e.allParticipants)&&Boolean(e.allParticipants),trackPermissions:Array.isArray(null==e?void 0:e.trackPermissions)?e.trackPermissions.map((e=>Dl.fromJSON(e))):[]}),toJSON(e){const t={};return void 0!==e.allParticipants&&(t.allParticipants=e.allParticipants),e.trackPermissions?t.trackPermissions=e.trackPermissions.map((e=>e?Dl.toJSON(e):void 0)):t.trackPermissions=[],t},create:e=>Il.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=>Dl.fromPartial(e))))||[],s}};const Al={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.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 xr.Reader?e:xr.Reader.create(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:if(10!==e)break;n.participantSid=i.string();continue;case 2:if(18!==e)break;n.trackSid=i.string();continue;case 3:if(24!==e)break;n.allowed=i.bool();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({participantSid:Jl(e.participantSid)?String(e.participantSid):"",trackSid:Jl(e.trackSid)?String(e.trackSid):"",allowed:!!Jl(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=>Al.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 Ol={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.Writer.create();void 0!==e.answer&&ml.encode(e.answer,t.uint32(10).fork()).ldelim(),void 0!==e.subscription&&fl.encode(e.subscription,t.uint32(18).fork()).ldelim();for(const i of e.publishTracks)ul.encode(i,t.uint32(26).fork()).ldelim();for(const i of e.dataChannels)Ul.encode(i,t.uint32(34).fork()).ldelim();return void 0!==e.offer&&ml.encode(e.offer,t.uint32(42).fork()).ldelim(),t},decode(e,t){const i=e instanceof xr.Reader?e:xr.Reader.create(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:if(10!==e)break;n.answer=ml.decode(i,i.uint32());continue;case 2:if(18!==e)break;n.subscription=fl.decode(i,i.uint32());continue;case 3:if(26!==e)break;n.publishTracks.push(ul.decode(i,i.uint32()));continue;case 4:if(34!==e)break;n.dataChannels.push(Ul.decode(i,i.uint32()));continue;case 5:if(42!==e)break;n.offer=ml.decode(i,i.uint32());continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({answer:Jl(e.answer)?ml.fromJSON(e.answer):void 0,subscription:Jl(e.subscription)?fl.fromJSON(e.subscription):void 0,publishTracks:Array.isArray(null==e?void 0:e.publishTracks)?e.publishTracks.map((e=>ul.fromJSON(e))):[],dataChannels:Array.isArray(null==e?void 0:e.dataChannels)?e.dataChannels.map((e=>Ul.fromJSON(e))):[],offer:Jl(e.offer)?ml.fromJSON(e.offer):void 0}),toJSON(e){const t={};return void 0!==e.answer&&(t.answer=e.answer?ml.toJSON(e.answer):void 0),void 0!==e.subscription&&(t.subscription=e.subscription?fl.toJSON(e.subscription):void 0),e.publishTracks?t.publishTracks=e.publishTracks.map((e=>e?ul.toJSON(e):void 0)):t.publishTracks=[],e.dataChannels?t.dataChannels=e.dataChannels.map((e=>e?Ul.toJSON(e):void 0)):t.dataChannels=[],void 0!==e.offer&&(t.offer=e.offer?ml.toJSON(e.offer):void 0),t},create:e=>Ol.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?ml.fromPartial(e.answer):void 0,s.subscription=void 0!==e.subscription&&null!==e.subscription?fl.fromPartial(e.subscription):void 0,s.publishTracks=(null===(t=e.publishTracks)||void 0===t?void 0:t.map((e=>ul.fromPartial(e))))||[],s.dataChannels=(null===(i=e.dataChannels)||void 0===i?void 0:i.map((e=>Ul.fromPartial(e))))||[],s.offer=void 0!==e.offer&&null!==e.offer?ml.fromPartial(e.offer):void 0,s}};const Ul={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.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 xr.Reader?e:xr.Reader.create(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:if(10!==e)break;n.label=i.string();continue;case 2:if(16!==e)break;n.id=i.uint32();continue;case 3:if(24!==e)break;n.target=i.int32();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({label:Jl(e.label)?String(e.label):"",id:Jl(e.id)?Number(e.id):0,target:Jl(e.target)?Xc(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=el(e.target)),t},create:e=>Ul.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 xl={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.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);break;case"subscriberBandwidth":t.uint32(48).int64(e.scenario.subscriberBandwidth)}return t},decode(e,t){const i=e instanceof xr.Reader?e:xr.Reader.create(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:if(8!==e)break;n.scenario={$case:"speakerUpdate",speakerUpdate:i.int32()};continue;case 2:if(16!==e)break;n.scenario={$case:"nodeFailure",nodeFailure:i.bool()};continue;case 3:if(24!==e)break;n.scenario={$case:"migration",migration:i.bool()};continue;case 4:if(32!==e)break;n.scenario={$case:"serverLeave",serverLeave:i.bool()};continue;case 5:if(40!==e)break;n.scenario={$case:"switchCandidateProtocol",switchCandidateProtocol:i.int32()};continue;case 6:if(48!==e)break;n.scenario={$case:"subscriberBandwidth",subscriberBandwidth:$l(i.int64())};continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({scenario:Jl(e.speakerUpdate)?{$case:"speakerUpdate",speakerUpdate:Number(e.speakerUpdate)}:Jl(e.nodeFailure)?{$case:"nodeFailure",nodeFailure:Boolean(e.nodeFailure)}:Jl(e.migration)?{$case:"migration",migration:Boolean(e.migration)}:Jl(e.serverLeave)?{$case:"serverLeave",serverLeave:Boolean(e.serverLeave)}:Jl(e.switchCandidateProtocol)?{$case:"switchCandidateProtocol",switchCandidateProtocol:il(e.switchCandidateProtocol)}:Jl(e.subscriberBandwidth)?{$case:"subscriberBandwidth",subscriberBandwidth:Number(e.subscriberBandwidth)}:void 0}),toJSON(e){var t,i,s,n,a,r,o,c,l,d,h,u,p;const m={};return"speakerUpdate"===(null===(t=e.scenario)||void 0===t?void 0:t.$case)&&(m.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)&&(m.nodeFailure=null===(n=e.scenario)||void 0===n?void 0:n.nodeFailure),"migration"===(null===(a=e.scenario)||void 0===a?void 0:a.$case)&&(m.migration=null===(r=e.scenario)||void 0===r?void 0:r.migration),"serverLeave"===(null===(o=e.scenario)||void 0===o?void 0:o.$case)&&(m.serverLeave=null===(c=e.scenario)||void 0===c?void 0:c.serverLeave),"switchCandidateProtocol"===(null===(l=e.scenario)||void 0===l?void 0:l.$case)&&(m.switchCandidateProtocol=void 0!==(null===(d=e.scenario)||void 0===d?void 0:d.switchCandidateProtocol)?function(e){switch(e){case Qc.UDP:return"UDP";case Qc.TCP:return"TCP";case Qc.TLS:return"TLS";case Qc.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(null===(h=e.scenario)||void 0===h?void 0:h.switchCandidateProtocol):void 0),"subscriberBandwidth"===(null===(u=e.scenario)||void 0===u?void 0:u.$case)&&(m.subscriberBandwidth=Math.round(null===(p=e.scenario)||void 0===p?void 0:p.subscriberBandwidth)),m},create:e=>xl.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;const y={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)&&(y.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)&&(y.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)&&(y.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)&&(y.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)&&(y.scenario={$case:"switchCandidateProtocol",switchCandidateProtocol:e.scenario.switchCandidateProtocol}),"subscriberBandwidth"===(null===(f=e.scenario)||void 0===f?void 0:f.$case)&&void 0!==(null===(v=e.scenario)||void 0===v?void 0:v.subscriberBandwidth)&&null!==(null===(b=e.scenario)||void 0===b?void 0:b.subscriberBandwidth)&&(y.scenario={$case:"subscriberBandwidth",subscriberBandwidth:e.scenario.subscriberBandwidth}),y}};const Ll={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.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 xr.Reader?e:xr.Reader.create(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:if(8!==e)break;n.timestamp=$l(i.int64());continue;case 2:if(16!==e)break;n.rtt=$l(i.int64());continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({timestamp:Jl(e.timestamp)?Number(e.timestamp):0,rtt:Jl(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=>Ll.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 Fl={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.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 xr.Reader?e:xr.Reader.create(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:if(8!==e)break;n.lastPingTimestamp=$l(i.int64());continue;case 2:if(16!==e)break;n.timestamp=$l(i.int64());continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({lastPingTimestamp:Jl(e.lastPingTimestamp)?Number(e.lastPingTimestamp):0,timestamp:Jl(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=>Fl.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}};const Bl={encode(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xr.Writer.create();return""!==e.trackSid&&t.uint32(10).string(e.trackSid),0!==e.err&&t.uint32(16).int32(e.err),t},decode(e,t){const i=e instanceof xr.Reader?e:xr.Reader.create(e);let s=void 0===t?i.len:i.pos+t;const n={trackSid:"",err:0};for(;i.pos<s;){const e=i.uint32();switch(e>>>3){case 1:if(10!==e)break;n.trackSid=i.string();continue;case 2:if(16!==e)break;n.err=i.int32();continue}if(4==(7&e)||0===e)break;i.skipType(7&e)}return n},fromJSON:e=>({trackSid:Jl(e.trackSid)?String(e.trackSid):"",err:Jl(e.err)?Gr(e.err):0}),toJSON(e){const t={};return void 0!==e.trackSid&&(t.trackSid=e.trackSid),void 0!==e.err&&(t.err=function(e){switch(e){case _r.SE_UNKOWN:return"SE_UNKOWN";case _r.SE_CODEC_UNSUPPORTED:return"SE_CODEC_UNSUPPORTED";case _r.SE_TRACK_NOTFOUND:return"SE_TRACK_NOTFOUND";case _r.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.err)),t},create:e=>Bl.fromPartial(null!=e?e:{}),fromPartial(e){var t,i;const s={trackSid:"",err:0};return s.trackSid=null!==(t=e.trackSid)&&void 0!==t?t:"",s.err=null!==(i=e.err)&&void 0!==i?i:0,s}};var jl,ql=(()=>{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 Vl(e){if(ql.Buffer)return Uint8Array.from(ql.Buffer.from(e,"base64"));{const t=ql.atob(e),i=new Uint8Array(t.length);for(let e=0;e<t.length;++e)i[e]=t.charCodeAt(e);return i}}function $l(e){if(e.gt(Number.MAX_SAFE_INTEGER))throw new ql.Error("Value is larger than Number.MAX_SAFE_INTEGER");return e.toNumber()}function Jl(e){return null!=e}xr.util.Long!==pa&&(xr.util.Long=pa,xr.configure());class Wl extends Error{constructor(e,t){super(t||"an error has occured"),this.code=e}}class Hl extends Wl{constructor(e,t,i){super(1,e),this.status=i,this.reason=t}}class Gl extends Wl{constructor(e){super(21,null!=e?e:"device is unsupported")}}class Zl extends Wl{constructor(e){super(20,null!=e?e:"track is invalid")}}class zl extends Wl{constructor(e){super(10,null!=e?e:"unsupported server")}}class Kl extends Wl{constructor(e){super(12,null!=e?e:"unexpected connection state")}}class Ql extends Wl{constructor(e){super(13,null!=e?e:"unable to negotiate")}}!function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"}(jl||(jl={})),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}}(jl||(jl={}));class Yl{}Yl.setTimeout=function(){return setTimeout(...arguments)},Yl.setInterval=function(){return setInterval(...arguments)},Yl.clearTimeout=function(){return clearTimeout(...arguments)},Yl.clearInterval=function(){return clearInterval(...arguments)};const Xl=/version\/(\d+(\.?_?\d+)+)/i;let ed;function td(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(void 0===e&&"undefined"==typeof navigator)return;const i=(null!=e?e:navigator.userAgent).toLowerCase();if(void 0===ed||t){const e=id.find((e=>{let{test:t}=e;return t.test(i)}));ed=null==e?void 0:e.describe(i)}return ed}const id=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:sd(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:sd(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:sd(Xl,e)})}];function sd(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;const s=t.match(e);return s&&s.length>=i&&s[i]||""}function nd(e,t,i){const s=Object.assign({},e);return!0===s.audio&&(s.audio={}),!0===s.video&&(s.video={}),s.audio&&ad(s.audio,t),s.video&&ad(s.video,i),s}function ad(e,t){return Object.keys(t).forEach((i=>{void 0===e[i]&&(e[i]=t[i])})),e}function rd(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)ad(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 od(){const e="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(e)return new e({latencyHint:"interactive"})}const cd="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function ld(e){return To(this,void 0,void 0,(function*(){return new Promise((t=>setTimeout(t,e)))}))}function dd(){return"addTransceiver"in RTCPeerConnection.prototype}function hd(){return"addTrack"in RTCPeerConnection.prototype}function ud(e){return"av1"===e||"vp9"===e}function pd(e){return!!document&&(e||(e=document.createElement("audio")),"setSinkId"in e)}const md={Chrome:"100",Safari:"15",Firefox:"100"};function gd(){var e;return"Firefox"===(null===(e=td())||void 0===e?void 0:e.name)}function fd(){var e;return"Safari"===(null===(e=td())||void 0===e?void 0:e.name)}function vd(){return!!bd()&&/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent)}function bd(){return"undefined"!=typeof document}function yd(){return"ReactNative"==navigator.product}function Sd(e){return e.hostname.endsWith(".livekit.cloud")}function Cd(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function kd(){if(!yd())return;let e=Cd();return e?e.platform:void 0}function Ed(){if(bd())return window.devicePixelRatio;if(yd()){let e=Cd();if(e)return e.devicePixelRatio}return 1}function wd(e,t){const i=e.split("."),s=t.split("."),n=Math.min(i.length,s.length);for(let e=0;e<n;++e){const t=parseInt(i[e],10),a=parseInt(s[e],10);if(t>a)return 1;if(t<a)return-1;if(e===n-1&&t===a)return 0}return""===e&&""!==t?-1:""===t?1:i.length==s.length?0:i.length<s.length?-1:1}function Td(e){for(const t of e)t.target.handleResize(t)}function Pd(e){for(const t of e)t.target.handleVisibilityChanged(t)}let Md=null;const Rd=()=>(Md||(Md=new ResizeObserver(Td)),Md);let Nd=null;const _d=()=>(Nd||(Nd=new IntersectionObserver(Pd,{root:null,rootMargin:"0px"})),Nd);let Dd;function Id(){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 Ad(){if(!Dd){const e=new AudioContext,t=e.createOscillator(),i=e.createMediaStreamDestination();if(t.connect(i),t.start(),[Dd]=i.stream.getAudioTracks(),!Dd)throw Error("Could not get empty media stream audio track");Dd.enabled=!1}return Dd}class Od{constructor(e,t){this.onFinally=t,this.promise=new Promise(((t,i)=>To(this,void 0,void 0,(function*(){this.resolve=t,this.reject=i,e&&(yield e(t,i))})))).finally((()=>{var e;return null===(e=this.onFinally)||void 0===e?void 0:e.call(this)}))}}class Ud{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}}var xd;!function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(xd||(xd={}));class Ld{constructor(){this.pendingTasks=new Map,this.taskMutex=new Ud,this.nextTaskIndex=0}run(e){return To(this,void 0,void 0,(function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:xd.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=xd.RUNNING,yield e()}finally{t.status=xd.COMPLETED,this.pendingTasks.delete(t.id),i()}}))}flush(){return To(this,void 0,void 0,(function*(){return this.run((()=>To(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}}const Fd=["syncState","trickle","offer","answer","simulate","leave"];class Bd{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 Ld,this.queuedRequests=[],this.closingLock=new Ud}join(e,t,i,s){return To(this,void 0,void 0,(function*(){this.isConnected=!1,this.options=i;return yield this.connect(e,t,i,s)}))}reconnect(e,t,i,s){return To(this,void 0,void 0,(function*(){if(!this.options)return void Bn.warn("attempted to reconnect without signal options being set, ignoring");this.isReconnecting=!0,this.clearPingInterval();return yield this.connect(e,t,Object.assign(Object.assign({},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",yd()?"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,function(){var e;const t=go.fromPartial({sdk:Ur.JS,protocol:9,version:"1.10.0"});return yd()&&(t.os=null!==(e=kd())&&void 0!==e?e:""),t}(),i);return new Promise(((t,a)=>To(this,void 0,void 0,(function*(){const r=()=>To(this,void 0,void 0,(function*(){this.close(),a(new Hl("room connection has been cancelled (signal)"))}));(null==s?void 0:s.aborted)&&r(),null==s||s.addEventListener("abort",r),Bn.debug("connecting to ".concat(e+n)),this.ws&&(yield this.close()),this.ws=new WebSocket(e+n),this.ws.binaryType="arraybuffer",this.ws.onerror=t=>To(this,void 0,void 0,(function*(){if(this.isConnected)this.handleWSError(t);else try{const t=yield fetch("http".concat(e.substring(2),"/validate").concat(n));if(t.status.toFixed(0).startsWith("4")){const e=yield t.text();a(new Hl(e,0,t.status))}else a(new Hl("Internal error",2,t.status))}catch(e){a(new Hl("server was not reachable",1))}})),this.ws.onmessage=e=>To(this,void 0,void 0,(function*(){var n,o,c,l;let d;if("string"==typeof e.data){const t=JSON.parse(e.data);d=nl.fromJSON(t)}else{if(!(e.data instanceof ArrayBuffer))return void Bn.error("could not decode websocket message: ".concat(typeof e.data));d=nl.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&&(Bn.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 Hl("did not receive join response, got ".concat(null===(l=d.message)||void 0===l?void 0:l.$case," instead"))),!e)return}this.signalLatency&&(yield ld(this.signalLatency)),this.handleSignalResponse(d)})),this.ws.onclose=e=>{Bn.warn("websocket closed",{ev:e}),this.handleOnClose(e.reason)}}))))}close(){return To(this,void 0,void 0,(function*(){const e=yield 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.readyState<this.ws.CLOSING&&(this.ws.close(),yield Promise.race([e,ld(250)])),this.ws=void 0,this.clearPingInterval()}}finally{e()}}))}sendOffer(e){Bn.debug("sending offer",e),this.sendRequest({$case:"offer",offer:qd(e)})}sendAnswer(e){return Bn.debug("sending answer"),this.sendRequest({$case:"answer",answer:qd(e)})}sendIceCandidate(e,t){return Bn.trace("sending ice candidate",e),this.sendRequest({$case:"trickle",trickle:{candidateInit:JSON.stringify(e),target:t}})}sendMuteTrack(e,t){return this.sendRequest({$case:"mute",mute:{sid:e,muted:t}})}sendAddTrack(e){return this.sendRequest({$case:"addTrack",addTrack:rl.fromPartial(e)})}sendUpdateLocalMetadata(e,t){return this.sendRequest({$case:"updateMetadata",updateMetadata:{metadata:e,name:t}})}sendUpdateTrackSettings(e){this.sendRequest({$case:"trackSetting",trackSetting:e})}sendUpdateSubscription(e){return this.sendRequest({$case:"subscription",subscription:e})}sendSyncState(e){return this.sendRequest({$case:"syncState",syncState:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({$case:"updateLayers",updateLayers:{trackSid:e,layers:t}})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({$case:"subscriptionPermission",subscriptionPermission:{allParticipants:e,trackPermissions:t}})}sendSimulateScenario(e){return this.sendRequest({$case:"simulate",simulate:e})}sendPing(){return Promise.all([this.sendRequest({$case:"ping",ping:Date.now()}),this.sendRequest({$case:"pingReq",pingReq:{timestamp:Date.now(),rtt:this.rtt}})])}sendLeave(){return this.sendRequest({$case:"leave",leave:{canReconnect:!1,reason:Rr.CLIENT_INITIATED}})}sendRequest(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return To(this,void 0,void 0,(function*(){const i=!t&&!function(e){const t=Fd.indexOf(e.$case)>=0;return Bn.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(i&&this.isReconnecting)return void this.queuedRequests.push((()=>To(this,void 0,void 0,(function*(){yield this.sendRequest(e,!0)}))));if(t||(yield this.requestQueue.flush()),this.signalLatency&&(yield ld(this.signalLatency)),!this.ws||this.ws.readyState!==this.ws.OPEN)return void Bn.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(sl.toJSON(s))):this.ws.send(sl.encode(s).finish())}catch(e){Bn.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=jd(s.answer);this.onAnswer&&this.onAnswer(e)}else if("offer"===s.$case){const e=jd(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):"subscriptionResponse"===s.$case?this.onSubscriptionError&&this.onSubscriptionError(s.subscriptionResponse):"pong"===s.$case?this.resetPingTimeout():"pongResp"===s.$case?(this.rtt=Date.now()-s.pongResp.lastPingTimestamp,this.resetPingTimeout()):Bn.debug("unsupported message",s);else Bn.debug("received unsupported message")}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}this.isReconnecting=!1}handleOnClose(e){return To(this,void 0,void 0,(function*(){this.isConnected&&(yield this.close(),Bn.debug("websocket connection closed: ".concat(e)),this.onClose&&this.onClose(e))}))}handleWSError(e){Bn.error("websocket error",e)}resetPingTimeout(){this.clearPingTimeout(),this.pingTimeoutDuration?this.pingTimeout=Yl.setTimeout((()=>{Bn.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString())),this.handleOnClose("ping timeout")}),1e3*this.pingTimeoutDuration):Bn.warn("ping timeout duration not set")}clearPingTimeout(){this.pingTimeout&&Yl.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(Bn.debug("start ping interval"),this.pingInterval=Yl.setInterval((()=>{this.sendPing()}),1e3*this.pingIntervalDuration)):Bn.warn("ping interval duration not set")}clearPingInterval(){Bn.debug("clearing ping interval"),this.clearPingTimeout(),this.pingInterval&&Yl.clearInterval(this.pingInterval)}}function jd(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 qd(e){return{sdp:e.sdp,type:e.type}}const Vd="default";class $d{static getInstance(){return void 0===this.instance&&(this.instance=new $d),this.instance}getDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];var i;return To(this,void 0,void 0,(function*(){if((null===(i=$d.userMediaPromiseMap)||void 0===i?void 0:i.size)>0){Bn.debug("awaiting getUserMedia promise");try{e?yield $d.userMediaPromiseMap.get(e):yield Promise.all($d.userMediaPromiseMap.values())}catch(e){Bn.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(t&&e&&(!$d.userMediaPromiseMap.get(e)||!fd())){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=yield navigator.mediaDevices.getUserMedia(t);s=yield navigator.mediaDevices.enumerateDevices(),i.getTracks().forEach((e=>{e.stop()}))}}return e&&(s=s.filter((t=>t.kind===e))),s}))}normalizeDeviceId(e,t,i){return To(this,void 0,void 0,(function*(){if(t!==Vd)return t;const s=(yield this.getDevices(e)).find((e=>e.groupId===i&&e.deviceId!==Vd));return null==s?void 0:s.deviceId}))}}$d.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],$d.userMediaPromiseMap=new Map;var Jd={},Wd={exports:{}},Hd=Wd.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(Hd).forEach((function(e){Hd[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}));var Gd=Wd.exports;!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=Gd,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}}))}))}}(Jd);var Zd=Gd,zd=/%[sdv%]/g,Kd=function(e){var t=1,i=arguments,s=i.length;return e.replace(zd,(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""}}))},Qd=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 Kd.apply(null,s)},Yd=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Xd=["i","c","b","a"],eh=Jd,th=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||Yd,s=t.innerOrder||Xd,n=[];return i.forEach((function(t){Zd[t].forEach((function(i){i.name in e&&null!=e[i.name]?n.push(Qd(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){n.push(Qd(t,i,e))}))}))})),e.media.forEach((function(e){n.push(Qd("m",Zd.m[0],e)),s.forEach((function(t){Zd[t].forEach((function(i){i.name in e&&null!=e[i.name]?n.push(Qd(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){n.push(Qd(t,i,e))}))}))}))})),n.join("\r\n")+"\r\n"},ih=th,sh=eh.parse;function nh(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}const ah="negotiationStarted",rh="negotiationComplete";class oh extends Jo.EventEmitter{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;super(),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=nh((e=>{this.emit(ah);try{this.createAndSendOffer()}catch(t){if(!e)throw t;e(t)}}),100),this.pc="Chrome"===(null===(i=td())||void 0===i?void 0:i.name)?new RTCPeerConnection(e,t):new RTCPeerConnection(e)}get isICEConnected(){return"connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState}addIceCandidate(e){return To(this,void 0,void 0,(function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)}))}setRemoteDescription(e){return To(this,void 0,void 0,(function*(){if("offer"===e.type){let{stereoMids:t,nackMids:i}=function(e){var t;const i=[],s=[],n=sh(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}yield 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(rh)}))}createAndSendOffer(e){var t;return To(this,void 0,void 0,(function*(){if(void 0===this.onOffer)return;if((null==e?void 0:e.iceRestart)&&(Bn.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);yield this.pc.setRemoteDescription(t)}else if("closed"===this.pc.signalingState)return void Bn.warn("could not createOffer with closed peer connection");Bn.debug("starting to negotiate");const i=yield this.pc.createOffer(e),s=sh(null!==(t=i.sdp)&&void 0!==t?t:"");s.media.forEach((e=>{"audio"===e.type?ch(e,[],[]):"video"===e.type&&(!function(e){var t,i,s,n;const a=null===(i=null===(t=e.rtp[0])||void 0===t?void 0:t.codec)||void 0===i?void 0:i.toLowerCase();if(!ud(a))return;let r=0;const o=null===(s=e.ext)||void 0===s?void 0:s.some((e=>e.uri===cd||(e.value>r&&(r=e.value),!1)));o||null===(n=e.ext)||void 0===n||n.push({value:r+1,uri:cd})}(e),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-start-bitrate")||(e.config+=";x-google-start-bitrate=".concat(.7*t.maxbr)),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-start-bitrate=".concat(.7*t.maxbr,";x-google-max-bitrate=").concat(t.maxbr)})),!0})))})),this.trackBitrates=[],yield this.setMungedLocalDescription(i,ih(s)),this.onOffer(i)}))}createAndSetAnswer(){var e;return To(this,void 0,void 0,(function*(){const t=yield this.pc.createAnswer(),i=sh(null!==(e=t.sdp)&&void 0!==e?e:"");return i.media.forEach((e=>{"audio"===e.type&&ch(e,this.remoteStereoMids,this.remoteNackMids)})),yield this.setMungedLocalDescription(t,ih(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()}setMungedLocalDescription(e,t){return To(this,void 0,void 0,(function*(){const i=e.sdp;e.sdp=t;try{return Bn.debug("setting munged local description"),void(yield this.pc.setLocalDescription(e))}catch(t){Bn.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),{error:t}),e.sdp=i}try{yield this.pc.setLocalDescription(e)}catch(e){let t="unknown error";throw e instanceof Error?t=e.message:"string"==typeof e&&(t=e),new Ql(t)}}))}}function ch(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))))}class lh{constructor(e,t){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}isCloud(){return Sd(this.serverUrl)}getNextBestRegionUrl(e){return To(this,void 0,void 0,(function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(e));const t=this.regionSettings.regions.filter((e=>!this.attemptedRegions.find((t=>t.url===e.url))));if(t.length>0){const e=t[0];return this.attemptedRegions.push(e),Bn.debug("next region: ".concat(e.region)),e.url}return null}))}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return To(this,void 0,void 0,(function*(){const t=yield fetch("".concat((i=this.serverUrl,"".concat(i.protocol.replace("ws","http"),"//").concat(i.host,"/settings")),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});var i;if(t.ok){const e=yield t.json();return this.lastUpdateAt=Date.now(),e}throw new Hl("Could not fetch region settings: ".concat(t.statusText),401===t.status?0:void 0,t.status)}))}}class dh{constructor(e,t,i,s,n){this.width=e,this.height=t,this.encoding={maxBitrate:i,maxFramerate:s,priority:n}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.width/this.height}}}const hh=["vp8","h264"];function uh(e){return!!hh.find((t=>t===e))}function ph(e,t){return(null==e?void 0:e.toLowerCase().replace(/audio\/|video\//y,""))===(null==t?void 0:t.toLowerCase().replace(/audio\/|video\//y,""))}var mh;!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}}(mh||(mh={}));const gh={h90:new dh(160,90,6e4,15),h180:new dh(320,180,12e4,15),h216:new dh(384,216,18e4,15),h360:new dh(640,360,3e5,20),h540:new dh(960,540,6e5,25),h720:new dh(1280,720,17e5,30),h1080:new dh(1920,1080,3e6,30),h1440:new dh(2560,1440,5e6,30),h2160:new dh(3840,2160,8e6,30)},fh={h120:new dh(160,120,8e4,15),h180:new dh(240,180,1e5,15),h240:new dh(320,240,15e4,15),h360:new dh(480,360,225e3,20),h480:new dh(640,480,3e5,20),h540:new dh(720,540,45e4,25),h720:new dh(960,720,15e5,30),h1080:new dh(1440,1080,25e5,30),h1440:new dh(1920,1440,35e5,30)},vh={h360fps3:new dh(640,360,2e5,3,"medium"),h720fps5:new dh(1280,720,4e5,5,"medium"),h720fps15:new dh(1280,720,1e6,15,"medium"),h1080fps15:new dh(1920,1080,15e5,15,"medium"),h1080fps30:new dh(1920,1080,3e6,30,"medium")},bh={audioBitrate:mh.music.maxBitrate,audioPreset:mh.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:vh.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:"vp8",backupCodec:{codec:"vp8",encoding:gh.h540.encoding}},yh={autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0},Sh={resolution:gh.h720.resolution},Ch={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new class{constructor(e){this._retryDelays=void 0!==e?[...e]:wo}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},kh={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3};var Eh,wh,Th,Ph;!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.ParticipantNameChanged="participantNameChanged",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",e.DCBufferStatusChanged="dcBufferStatusChanged"}(Eh||(Eh={})),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.ParticipantNameChanged="participantNameChanged",e.DataReceived="dataReceived",e.IsSpeakingChanged="isSpeakingChanged",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.MediaDevicesError="mediaDevicesError",e.ParticipantPermissionsChanged="participantPermissionsChanged"}(wh||(wh={})),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.SignalRestarted="signalRestarted",e.Closing="closing",e.MediaTrackAdded="mediaTrackAdded",e.ActiveSpeakersUpdate="activeSpeakersUpdate",e.DataPacketReceived="dataPacketReceived",e.DCBufferStatusChanged="dcBufferStatusChanged"}(Th||(Th={})),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",e.SubscriptionFailed="subscriptionFailed"}(Ph||(Ph={}));const Mh=[];class Rh extends Jo.EventEmitter{constructor(e,t){super(),this.attachedElements=[],this.isMuted=!1,this.streamState=Rh.StreamState.Active,this.isInBackground=!1,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=Rh.Source.Unknown}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===Rh.Kind.Video&&(t="video"),0===this.attachedElements.length&&Rh.Kind.Video&&this.addAppVisibilityListener(),e||("audio"===t&&(Mh.forEach((t=>{null!==t.parentElement||e||(e=t)})),e&&Mh.splice(Mh.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),Nh(this.mediaStreamTrack,e);const i=e.srcObject.getTracks();return i.some((e=>"audio"===e.kind))&&e.play().then((()=>{this.emit(Ph.AudioPlaybackStarted)})).catch((t=>{"NotAllowedError"===t.name?this.emit(Ph.AudioPlaybackFailed,t):Bn.warn("could not playback audio",t),e&&i.some((e=>"video"===e.kind))&&"NotAllowedError"===t.name&&(e.muted=!0,e.play().catch((()=>{})))})),this.emit(Ph.ElementAttached,e),e}detach(e){try{if(e){_h(this.mediaStreamTrack,e);const t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(Ph.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach((e=>{_h(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(Ph.ElementDetached,e)})),this.attachedElements=[],t}finally{0===this.attachedElements.length&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}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(),Mh.forEach((e=>{e.parentElement||(t=!1)})),t&&Mh.push(e)}}handleAppVisibilityChanged(){return To(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState}))}addAppVisibilityListener(){bd()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){bd()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Nh(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,(fd()||gd())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=i,t.play().catch((()=>{}))}),0))}function _h(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 Er.AUDIO;case t.Video:return Er.VIDEO;default:return Er.UNRECOGNIZED}},e.kindFromProto=function(e){switch(e){case Er.AUDIO:return t.Audio;case Er.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case i.Camera:return wr.CAMERA;case i.Microphone:return wr.MICROPHONE;case i.ScreenShare:return wr.SCREEN_SHARE;case i.ScreenShareAudio:return wr.SCREEN_SHARE_AUDIO;default:return wr.UNRECOGNIZED}},e.sourceFromProto=function(e){switch(e){case wr.CAMERA:return i.Camera;case wr.MICROPHONE:return i.Microphone;case wr.SCREEN_SHARE:return i.ScreenShare;case wr.SCREEN_SHARE_AUDIO:return i.ScreenShareAudio;default:return i.Unknown}},e.streamStateFromProto=function(e){switch(e){case Kc.ACTIVE:return s.Active;case Kc.PAUSED:return s.Paused;default:return s.Unknown}}}(Rh||(Rh={}));const Dh="_lossy",Ih="_reliable",Ah="leave-reconnect";var Oh;!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"}(Oh||(Oh={}));class Uh extends Jo.EventEmitter{get isClosed(){return this._isClosed}constructor(e){super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=kh.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=Oh.New,this._isClosed=!0,this.pendingTrackResolvers={},this.hasPublished=!1,this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.handleDataChannel=e=>{let{channel:t}=e;return To(this,void 0,void 0,(function*(){if(t){if(t.label===Ih)this.reliableDCSub=t;else{if(t.label!==Dh)return;this.lossyDCSub=t}Bn.debug("on data channel ".concat(t.id,", ").concat(t.label)),t.onmessage=this.handleDataMessage}}))},this.handleDataMessage=e=>To(this,void 0,void 0,(function*(){var t,i;const s=yield this.dataProcessLock.lock();try{let s;if(e.data instanceof ArrayBuffer)s=e.data;else{if(!(e.data instanceof Blob))return void Bn.error("unsupported data type",e.data);s=yield e.data.arrayBuffer()}const n=oo.decode(new Uint8Array(s));"speaker"===(null===(t=n.value)||void 0===t?void 0:t.$case)?this.emit(Th.ActiveSpeakersUpdate,n.value.speaker.speakers):"user"===(null===(i=n.value)||void 0===i?void 0:i.$case)&&this.emit(Th.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;Bn.error("DataChannel error on ".concat(t,": ").concat(e.message),i)}else Bn.error("Unknown DataChannel Error on ".concat(t),e)},this.handleBufferedAmountLow=e=>{const t=0===e.currentTarget.maxRetransmits?Ar.LOSSY:Ar.RELIABLE;this.updateAndEmitDCBufferStatus(t)},this.handleDisconnect=(e,t)=>{if(this._isClosed)return;Bn.warn("".concat(e," disconnected")),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());const i=e=>{Bn.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(e,"ms. giving up")),this.emit(Th.Disconnected),this.close()},s=Date.now()-this.reconnectStart;let n=this.getNextRetryDelay({elapsedMs:s,retryCount:this.reconnectAttempts});null!==n?(e===Ah&&(n=0),Bn.debug("reconnecting in ".concat(n,"ms")),this.clearReconnectTimeout(),this.url&&this.token&&Sd(new URL(this.url))&&(this.regionUrlProvider=new lh(this.url,this.token)),this.reconnectTimeout=Yl.setTimeout((()=>this.attemptReconnect(t)),n)):i(s)},this.waitForRestarted=()=>new Promise(((e,t)=>{this.pcState===Oh.Connected&&e();const i=()=>{this.off(Th.Disconnected,s),e()},s=()=>{this.off(Th.Restarted,i),t()};this.once(Th.Restarted,i),this.once(Th.Disconnected,s)})),this.updateAndEmitDCBufferStatus=e=>{const t=this.isBufferStatusLow(e);void 0!==t&&t!==this.dcBufferStatus.get(e)&&(this.dcBufferStatus.set(e,t),this.emit(Th.DCBufferStatusChanged,t,e))},this.isBufferStatusLow=e=>{const t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.isReconnecting&&(this.clearReconnectTimeout(),this.attemptReconnect(Nr.RR_SIGNAL_DISCONNECTED))},this.client=new Bd,this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Ud,this.dataProcessLock=new Ud,this.dcBufferStatus=new Map([[Ar.LOSSY,!0],[Ar.RELIABLE,!0]])}join(e,t,i,s){return To(this,void 0,void 0,(function*(){this.url=e,this.token=t,this.signalOpts=i;try{this.joinAttempts+=1;const n=yield this.client.join(e,t,i,s);return this._isClosed=!1,this.latestJoinResponse=n,this.subscriberPrimary=n.subscriberPrimary,this.publisher||this.configure(n),this.subscriberPrimary||this.negotiate(),this.clientConfiguration=n.clientConfiguration,n}catch(n){if(n instanceof Hl&&1===n.reason&&(Bn.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}}))}close(){return To(this,void 0,void 0,(function*(){const e=yield this.closingLock.lock();if(this.isClosed)e();else try{this._isClosed=!0,this.emit(Th.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){Bn.warn("could not removeTrack",{error:e})}})),this.publisher.close(),this.publisher=void 0),this.subscriber&&(this.subscriber.close(),this.subscriber=void 0),yield this.client.close()}finally{e()}}))}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Zl("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 Hl("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){Bn.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}getConnectedServerAddress(){return To(this,void 0,void 0,(function*(){if(void 0!==this.primaryPC)return function(e){var t;return To(this,void 0,void 0,(function*(){let i="";const s=new Map,n=new Map;if((yield 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;return void 0!==a?n.get(a):void 0}))}(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 oh(i,{optional:[{googDscp:!0}]}),this.subscriber=new oh(i),this.emit(Th.TransportsCreated,this.publisher,this.subscriber),this.publisher.pc.onicecandidate=e=>{e.candidate&&(Bn.trace("adding ICE candidate for peer",e.candidate),this.client.sendIceCandidate(e.candidate,zc.PUBLISHER))},this.subscriber.pc.onicecandidate=e=>{e.candidate&&this.client.sendIceCandidate(e.candidate,zc.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=()=>To(this,void 0,void 0,(function*(){if(Bn.debug("primary PC state changed ".concat(s.connectionState)),"connected"===s.connectionState){const t=this.pcState===Oh.New;this.pcState=Oh.Connected,t&&this.emit(Th.Connected,e)}else"failed"===s.connectionState&&this.pcState===Oh.Connected&&(this.pcState=Oh.Disconnected,this.handleDisconnect("primary peerconnection",a?Nr.RR_SUBSCRIBER_FAILED:Nr.RR_PUBLISHER_FAILED))})),n.onconnectionstatechange=()=>To(this,void 0,void 0,(function*(){Bn.debug("secondary PC state changed ".concat(n.connectionState)),"failed"===n.connectionState&&this.handleDisconnect("secondary peerconnection",a?Nr.RR_PUBLISHER_FAILED:Nr.RR_SUBSCRIBER_FAILED)})),this.subscriber.pc.ontrack=e=>{this.emit(Th.MediaTrackAdded,e.track,e.streams[0],e.receiver)},this.createDataChannels(),this.client.onAnswer=e=>To(this,void 0,void 0,(function*(){this.publisher&&(Bn.debug("received server answer",{RTCSdpType:e.type,signalingState:this.publisher.pc.signalingState}),yield this.publisher.setRemoteDescription(e))})),this.client.onTrickle=(e,t)=>{this.publisher&&this.subscriber&&(Bn.trace("got ICE candidate from peer",{candidate:e,target:t}),t===zc.PUBLISHER?this.publisher.addIceCandidate(e):this.subscriber.addIceCandidate(e))},this.client.onOffer=e=>To(this,void 0,void 0,(function*(){if(!this.subscriber)return;Bn.debug("received server offer",{RTCSdpType:e.type,signalingState:this.subscriber.pc.signalingState}),yield this.subscriber.setRemoteDescription(e);const t=yield this.subscriber.createAndSetAnswer();this.client.sendAnswer(t)})),this.client.onLocalTrackPublished=e=>{Bn.debug("received trackPublishedResponse",e);const{resolve:t}=this.pendingTrackResolvers[e.cid];t?(delete this.pendingTrackResolvers[e.cid],t(e.track)):Bn.error("missing track resolver for ".concat(e.cid))},this.client.onTokenRefresh=e=>{this.token=e},this.client.onClose=()=>{this.handleDisconnect("signal",Nr.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{(null==e?void 0:e.canReconnect)?(this.fullReconnectOnNext=!0,this.primaryPC=void 0,this.handleDisconnect(Ah)):(this.emit(Th.Disconnected,null==e?void 0:e.reason),this.close()),Bn.trace("leave request",{leave:e})}}makeRTCConfiguration(e){const t=Object.assign({},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===Mr.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(Dh,{ordered:!0,maxRetransmits:0}),this.reliableDC=this.publisher.pc.createDataChannel(Ih,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}setPreferredCodec(e,t,i){if(!("getCapabilities"in RTCRtpSender))return;const s=RTCRtpSender.getCapabilities(t);if(!s)return;Bn.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)})),function(e){if(!bd())return!1;if(!("setCodecPreferences"in e))return!1;const t=td();if(!(null==t?void 0:t.name)||!t.version)return!1;const i=md[t.name];return!!i&&wd(t.version,i)>=0}(e)&&e.setCodecPreferences(n.concat(a,r))}createSender(e,t,i){return To(this,void 0,void 0,(function*(){if(dd())return this.createTransceiverRTCRtpSender(e,t,i);if(hd())return Bn.debug("using add-track fallback"),this.createRTCRtpSender(e.mediaStreamTrack);throw new Kl("Required webRTC APIs not supported on this device")}))}createSimulcastSender(e,t,i,s){return To(this,void 0,void 0,(function*(){if(dd())return this.createSimulcastTransceiverSender(e,t,i,s);if(hd())return Bn.debug("using add-track fallback"),this.createRTCRtpSender(e.mediaStreamTrack);throw new Kl("Cannot stream on this device")}))}createTransceiverRTCRtpSender(e,t,i){return To(this,void 0,void 0,(function*(){if(!this.publisher)throw new Kl("publisher is closed");const s={direction:"sendonly"};i&&(s.sendEncodings=i);const n=yield this.publisher.pc.addTransceiver(e.mediaStreamTrack,s);return e.kind===Rh.Kind.Video&&t.videoCodec&&(this.setPreferredCodec(n,e.kind,t.videoCodec),e.codec=t.videoCodec),n.sender}))}createSimulcastTransceiverSender(e,t,i,s){return To(this,void 0,void 0,(function*(){if(!this.publisher)throw new Kl("publisher is closed");const n={direction:"sendonly"};s&&(n.sendEncodings=s);const a=yield 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}))}createRTCRtpSender(e){return To(this,void 0,void 0,(function*(){if(!this.publisher)throw new Kl("publisher is closed");return this.publisher.pc.addTrack(e)}))}attemptReconnect(e){var t,i,s;return To(this,void 0,void 0,(function*(){if(!this._isClosed&&!this.attemptingReconnect){(null===(t=this.clientConfiguration)||void 0===t?void 0:t.resumeConnection)!==Mr.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?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(e){this.reconnectAttempts+=1;let t=!0;e instanceof Kl?(Bn.debug("received unrecoverable error",{error:e}),t=!1):e instanceof xh||(this.fullReconnectOnNext=!0),t?this.handleDisconnect("reconnect",Nr.RR_UNKOWN):(Bn.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up")),this.emit(Th.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}}))}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){Bn.warn("encountered error in reconnect policy",{error:e})}return null}restartConnection(e){var t,i,s,n,a;return To(this,void 0,void 0,(function*(){try{if(!this.url||!this.token)throw new Kl("could not reconnect, url or token not saved");let n;Bn.info("reconnecting, attempt: ".concat(this.reconnectAttempts)),this.emit(Th.Restarting),this.client.isConnected&&(yield this.client.sendLeave()),yield this.client.close(),this.primaryPC=void 0,null===(t=this.publisher)||void 0===t||t.close(),this.publisher=void 0,null===(i=this.subscriber)||void 0===i||i.close(),this.subscriber=void 0;try{if(!this.signalOpts)throw Bn.warn("attempted connection restart, without signal options present"),new xh;n=yield this.join(null!=e?e:this.url,this.token,this.signalOpts)}catch(e){if(e instanceof Hl&&0===e.reason)throw new Kl("could not reconnect, token might be expired");throw new xh}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");this.client.setReconnected(),this.emit(Th.SignalRestarted,n),yield this.waitForPCReconnected(),null===(s=this.regionUrlProvider)||void 0===s||s.resetAttempts(),this.emit(Th.Restarted)}catch(e){const t=yield null===(n=this.regionUrlProvider)||void 0===n?void 0:n.getNextBestRegionUrl();if(t)return void(yield this.restartConnection(t));throw null===(a=this.regionUrlProvider)||void 0===a||a.resetAttempts(),e}}))}resumeConnection(e){var t;return To(this,void 0,void 0,(function*(){if(!this.url||!this.token)throw new Kl("could not reconnect, url or token not saved");if(!this.publisher||!this.subscriber)throw new Kl("publisher and subscriber connections unset");Bn.info("resuming signal connection, attempt ".concat(this.reconnectAttempts)),this.emit(Th.Resuming);try{const t=yield 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="";if(e instanceof Error&&(t=e.message),e instanceof Hl&&0===e.reason)throw new Kl("could not reconnect, token might be expired");throw new xh(t)}if(this.emit(Th.SignalResumed),this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");this.subscriber.restartingIce=!0,this.hasPublished&&(yield this.publisher.createAndSendOffer({iceRestart:!0})),yield this.waitForPCReconnected(),this.client.setReconnected(),"open"===(null===(t=this.reliableDC)||void 0===t?void 0:t.readyState)&&null===this.reliableDC.id&&this.createDataChannels(),this.emit(Th.Resumed)}))}waitForPCInitialConnection(e,t){return To(this,void 0,void 0,(function*(){if(this.pcState!==Oh.Connected){if(this.pcState!==Oh.New)throw new Kl("Expected peer connection to be new on initial connection");return new Promise(((i,s)=>{const n=()=>{Bn.warn("closing engine"),Yl.clearTimeout(r),s(new Hl("room connection has been cancelled",3))};(null==t?void 0:t.signal.aborted)&&n(),null==t||t.signal.addEventListener("abort",n);const a=()=>{Yl.clearTimeout(r),null==t||t.signal.removeEventListener("abort",n),i()},r=Yl.setTimeout((()=>{this.off(Th.Connected,a),s(new Hl("could not establish pc connection"))}),null!=e?e:this.peerConnectionTimeout);this.once(Th.Connected,a)}))}}))}waitForPCReconnected(){var e;return To(this,void 0,void 0,(function*(){const t=Date.now();let i=t;for(this.pcState=Oh.Reconnecting,Bn.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=Oh.Connected),this.pcState===Oh.Connected)return;yield ld(100),i=Date.now()}throw new Hl("could not establish PC connection")}))}sendDataPacket(e,t){return To(this,void 0,void 0,(function*(){const i=oo.encode(e).finish();yield this.ensurePublisherConnected(t);const s=this.dataChannelForKind(t);s&&s.send(i),this.updateAndEmitDCBufferStatus(t)}))}ensureDataTransportConnected(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;var i,s,n;return To(this,void 0,void 0,(function*(){const a=t?this.subscriber:this.publisher,r=t?"Subscriber":"Publisher";if(!a)throw new Hl("".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;yield ld(50)}throw new Hl("could not establish ".concat(r," connection, state: ").concat(a.pc.iceConnectionState))}))}ensurePublisherConnected(e){return To(this,void 0,void 0,(function*(){yield this.ensureDataTransportConnected(e,!1)}))}verifyTransport(){if(!this.primaryPC)return!1;if("closed"===this.primaryPC.connectionState||"failed"===this.primaryPC.connectionState)return!1;if(this.hasPublished&&this.subscriberPrimary){if(!this.publisher)return!1;if("closed"===this.publisher.pc.connectionState||"failed"===this.publisher.pc.connectionState)return!1}return!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return new Promise(((e,t)=>{if(!this.publisher)return void t(new Ql("publisher is not defined"));this.hasPublished=!0;const i=()=>{Bn.debug("engine disconnected while negotiation was ongoing"),n(),e()};this.on(Th.Closing,i);const s=setTimeout((()=>{t("negotiation timed out"),this.handleDisconnect("negotiation",Nr.RR_SIGNAL_DISCONNECTED)}),this.peerConnectionTimeout),n=()=>{clearTimeout(s),this.off(Th.Closing,i)};this.publisher.once(ah,(()=>{var t;null===(t=this.publisher)||void 0===t||t.once(rh,(()=>{n(),e()}))})),this.publisher.negotiate((e=>{n(),t(e),e instanceof Ql&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Nr.RR_UNKOWN)}))}))}dataChannelForKind(e,t){if(t){if(e===Ar.LOSSY)return this.lossyDCSub;if(e===Ar.RELIABLE)return this.reliableDCSub}else{if(e===Ar.LOSSY)return this.lossyDC;if(e===Ar.RELIABLE)return this.reliableDC}}failNext(){this.shouldFailNext=!0}clearReconnectTimeout(){this.reconnectTimeout&&Yl.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){bd()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){bd()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class xh extends Error{}const Lh=2e3;function Fh(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)}class Bh extends Rh{constructor(e,t,i){let s=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(e,t),this.isSettingUpProcessor=!1,this._isUpstreamPaused=!1,this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this.emit(Ph.Ended,this)},this._mediaStreamTrack.addEventListener("ended",this.handleEnded),this.constraints=null!=i?i:e.getConstraints(),this.reacquireTrack=!1,this.providedByUser=s,this.muteLock=new Ud,this.pauseUpstreamLock=new Ud}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==Rh.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}get mediaStreamTrack(){var e,t;return null!==(t=null===(e=this.processor)||void 0===e?void 0:e.processedTrack)&&void 0!==t?t:this._mediaStreamTrack}waitForDimensions(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;return To(this,void 0,void 0,(function*(){if(this.kind===Rh.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;yield ld(50)}throw new Zl("unable to get track dimensions after timeout")}))}getDeviceId(){return To(this,void 0,void 0,(function*(){if(this.source===Rh.Source.ScreenShare)return;const{deviceId:e,groupId:t}=this._mediaStreamTrack.getSettings(),i=this.kind===Rh.Kind.Audio?"audioinput":"videoinput";return $d.getInstance().normalizeDeviceId(i,e,t)}))}mute(){return To(this,void 0,void 0,(function*(){return this.setTrackMuted(!0),this}))}unmute(){return To(this,void 0,void 0,(function*(){return this.setTrackMuted(!1),this}))}replaceTrack(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return To(this,void 0,void 0,(function*(){if(!this.sender)throw new Zl("unable to replace an unpublished track");return this.attachedElements.forEach((e=>{_h(this._mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this.providedByUser||this._mediaStreamTrack.stop(),e.addEventListener("ended",this.handleEnded),Bn.debug("replace MediaStreamTrack"),this.sender&&(yield this.sender.replaceTrack(e)),this._mediaStreamTrack=e,this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach((t=>{Nh(e,t)})),this.mediaStream=new MediaStream([e]),this.providedByUser=t,this.processor&&(yield this.stopProcessor()),this}))}restart(e){return To(this,void 0,void 0,(function*(){e||(e=this.constraints),Bn.debug("restarting track with constraints",e);const t={audio:!1,video:!1};this.kind===Rh.Kind.Video?t.video=e:t.audio=e,this.attachedElements.forEach((e=>{_h(this.mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const i=yield navigator.mediaDevices.getUserMedia(t),s=i.getTracks()[0];if(s.addEventListener("ended",this.handleEnded),Bn.debug("re-acquired MediaStreamTrack"),this.sender&&(yield this.sender.replaceTrack(s)),this._mediaStreamTrack=s,yield this.resumeUpstream(),this.mediaStream=i,this.constraints=e,this.processor){const e=this.processor;yield this.setProcessor(e)}else this.attachedElements.forEach((e=>{Nh(this._mediaStreamTrack,e)}));return this.emit(Ph.Restarted,this),this}))}setTrackMuted(e){Bn.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?Ph.Muted:Ph.Unmuted,this))}get needsReAcquisition(){return"live"!==this._mediaStreamTrack.readyState||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return To(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),vd()&&(Bn.debug("visibility changed, is in Background: ".concat(this.isInBackground)),this.isInBackground||!this.needsReAcquisition||this.isUserProvided||this.isMuted||(Bn.debug("track needs to be reaquired, restarting ".concat(this.source)),yield this.restart(),this.reacquireTrack=!1))}))}stop(){var e;super.stop(),null===(e=this.processor)||void 0===e||e.destroy(),this.processor=void 0}pauseUpstream(){return To(this,void 0,void 0,(function*(){const e=yield this.pauseUpstreamLock.lock();try{if(!0===this._isUpstreamPaused)return;if(!this.sender)return void Bn.warn("unable to pause upstream for an unpublished track");this._isUpstreamPaused=!0,this.emit(Ph.UpstreamPaused,this);const e=td();if("Safari"===(null==e?void 0:e.name)&&wd(e.version,"12.0")<0)throw new Gl("pauseUpstream is not supported on Safari < 12.");yield this.sender.replaceTrack(null)}finally{e()}}))}resumeUpstream(){return To(this,void 0,void 0,(function*(){const e=yield this.pauseUpstreamLock.lock();try{if(!1===this._isUpstreamPaused)return;if(!this.sender)return void Bn.warn("unable to resume upstream for an unpublished track");this._isUpstreamPaused=!1,this.emit(Ph.UpstreamResumed,this),yield this.sender.replaceTrack(this._mediaStreamTrack)}finally{e()}}))}setProcessor(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];var i,s;return To(this,void 0,void 0,(function*(){if(this.isSettingUpProcessor)return void Bn.warn("already trying to set up a processor");if(Bn.debug("setting up processor"),this.isSettingUpProcessor=!0,this.processor&&(yield this.stopProcessor()),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");this.processorElement=null!==(i=this.processorElement)&&void 0!==i?i:document.createElement(this.kind),this.processorElement.muted=!0,Nh(this._mediaStreamTrack,this.processorElement),this.processorElement.play().catch((e=>Bn.error(e)));const n={kind:this.kind,track:this._mediaStreamTrack,element:this.processorElement};if(yield e.init(n),this.processor=e,this.processor.processedTrack){for(const e of this.attachedElements)e!==this.processorElement&&t&&(_h(this._mediaStreamTrack,e),Nh(this.processor.processedTrack,e));yield null===(s=this.sender)||void 0===s?void 0:s.replaceTrack(this.processor.processedTrack)}this.isSettingUpProcessor=!1}))}getProcessor(){return this.processor}stopProcessor(){var e,t;return To(this,void 0,void 0,(function*(){this.processor&&(Bn.debug("stopping processor"),null===(e=this.processor.processedTrack)||void 0===e||e.stop(),yield this.processor.destroy(),this.processor=void 0,null===(t=this.processorElement)||void 0===t||t.remove(),this.processorElement=void 0,yield this.restart())}))}}class jh extends Bh{constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];super(e,Rh.Kind.Audio,t,i),this.stopOnMute=!1,this.monitorSender=()=>To(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(e){return void Bn.error("could not get audio sender stats",{error:e})}e&&this.prevStats&&(this._currentBitrate=Fh(e,this.prevStats)),this.prevStats=e})),this.checkForSilence()}setDeviceId(e){return To(this,void 0,void 0,(function*(){this.constraints.deviceId!==e&&(this.constraints.deviceId=e,this.isMuted||(yield this.restartTrack()))}))}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return To(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.source===Rh.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(Bn.debug("stopping mic track"),this._mediaStreamTrack.stop()),yield e.mute.call(this),this}finally{t()}}))}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return To(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.source!==Rh.Source.Microphone||!this.stopOnMute&&"ended"!==this._mediaStreamTrack.readyState||this.isUserProvided||(Bn.debug("reacquiring mic track"),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}}))}restartTrack(e){return To(this,void 0,void 0,(function*(){let t;if(e){const i=rd({audio:e});"boolean"!=typeof i.audio&&(t=i.audio)}yield this.restart(t)}))}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return To(this,void 0,void 0,(function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i}))}startMonitor(){bd()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),Lh)))}getSenderStats(){var e;return To(this,void 0,void 0,(function*(){if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;let t;return(yield 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}))}checkForSilence(){return To(this,void 0,void 0,(function*(){const e=yield function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return To(this,void 0,void 0,(function*(){const i=od();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),yield ld(t),s.getByteTimeDomainData(a);const r=a.some((e=>128!==e&&0!==e));return i.close(),!r}return!1}))}(this);return e&&(this.isMuted||Bn.warn("silence detected on local audio track"),this.emit(Ph.AudioSilenceDetected)),e}))}}function qh(e,t){switch(e.kind){case"audio":return new jh(e,t,!1);case"video":return new tu(e,t,!1);default:throw new Zl("unsupported track type: ".concat(e.kind))}}const Vh=Object.values(gh),$h=Object.values(fh),Jh=Object.values(vh),Wh=[gh.h180,gh.h360],Hh=[fh.h180,fh.h360],Gh=e=>[{scaleResolutionDownBy:2,fps:3}].map((t=>{var i;return new dh(Math.floor(e.width/t.scaleResolutionDownBy),Math.floor(e.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(e.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*((null!==(i=e.encoding.maxFramerate)&&void 0!==i?i:30)/t.fps)))),t.fps,e.encoding.priority)})),Zh=["q","h","f"];function zh(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 Jh;const s=t>i?t/i:i/t;if(Math.abs(s-16/9)<Math.abs(s-4/3))return Vh;return $h}(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)switch(s){case"av1":a=Object.assign({},a),a.maxBitrate=.7*a.maxBitrate;break;case"vp9":a=Object.assign({},a),a.maxBitrate=.85*a.maxBitrate}return a}(e,t,i,l),Bn.debug("using video encoding",r));const d=new dh(t,i,r.maxBitrate,r.maxFramerate);if(c&&ud(l)){Bn.debug("using svc with scalabilityMode ".concat(c));const e=[];switch(c){case"L3T3":case"L3T3_KEY":return e.push({rid:Zh[2],maxBitrate:r.maxBitrate,maxFramerate:d.encoding.maxFramerate,scalabilityMode:c}),Bn.debug("encodings",e),e;default:throw new Error("unsupported scalabilityMode: ".concat(c))}}if(!o)return[r];let h,u=[];if(u=e?null!==(n=Xh(null==s?void 0:s.screenShareSimulcastLayers))&&void 0!==n?n:Qh(e,d):null!==(a=Xh(null==s?void 0:s.videoSimulcastLayers))&&void 0!==a?a:Qh(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 Yh(t,i,[e,h,d]);if(s>=480)return Yh(t,i,[e,d])}return Yh(t,i,[d])}function Kh(e,t,i){var s,n,a,r;if(!i.backupCodec||i.backupCodec.codec===i.videoCodec)return;t!==i.backupCodec.codec&&Bn.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 zh(e.source===Rh.Source.ScreenShare,c,l,i)}function Qh(e,t){if(e)return Gh(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)?Wh:Hh}function Yh(e,t,i){const s=[];if(i.forEach(((i,n)=>{if(n>=Zh.length)return;const a=Math.min(e,t),r={rid:Zh[n],scaleResolutionDownBy:Math.max(1,a/Math.min(i.width,i.height)),maxBitrate:i.encoding.maxBitrate};i.encoding.maxFramerate&&(r.maxFramerate=i.encoding.maxFramerate),i.encoding.priority&&(r.priority=i.encoding.priority,r.networkPriority=i.encoding.priority),s.push(r)})),yd()&&"ios"===kd()){let e;s.forEach((t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate}));let t=!0;s.forEach((i=>{var s;i.maxFramerate!=e&&(t&&(t=!1,Bn.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),Bn.info('Setting framerate of encoding "'.concat(null!==(s=i.rid)&&void 0!==s?s:"",'" to ').concat(e)),i.maxFramerate=e)}))}return s}function Xh(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 eu{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat(null!==(e=this.suffix)&&void 0!==e?e:"")}}class tu extends Bh{constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];super(e,Rh.Kind.Video,t,i),this.simulcastCodecs=new Map,this.monitorSender=()=>To(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(e){return void Bn.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+=Fh(t,n)})),this._currentBitrate=e}this.prevStats=t})),this.senderLock=new Ud}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!bd())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()}),Lh))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((e=>{e.mediaStreamTrack.stop()})),super.stop()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return To(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.source!==Rh.Source.Camera||this.isUserProvided||(Bn.debug("stopping camera track"),this._mediaStreamTrack.stop()),yield e.mute.call(this),this}finally{t()}}))}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return To(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.source!==Rh.Source.Camera||this.isUserProvided||(Bn.debug("reacquiring camera track"),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}}))}getSenderStats(){var e;return To(this,void 0,void 0,(function*(){if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return[];const t=[],i=yield 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=Tr.LOW;i<=Tr.HIGH;i+=1)t.push({quality:i,enabled:i<=e});Bn.debug("setting publishing quality. max quality ".concat(e)),this.setPublishingLayers(t)}setDeviceId(e){return To(this,void 0,void 0,(function*(){this.constraints.deviceId!==e&&(this.constraints.deviceId=e,this.isMuted||(yield this.restartTrack()))}))}restartTrack(e){return To(this,void 0,void 0,(function*(){let t;if(e){const i=rd({video:e});"boolean"!=typeof i.video&&(t=i.video)}yield 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))}setPublishingCodecs(e){var t,i,s,n,a,r,o;return To(this,void 0,void 0,(function*(){if(Bn.debug("setting publishing codecs",{codecs:e,currentCodec:this.codec}),!this.codec&&e.length>0)return yield this.setPublishingLayers(e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,i=Mo(e);s=yield i.next(),!(n=s.done);t=!0){o=s.value,t=!1;const e=o;if(this.codec&&this.codec!==e.codec){const t=this.simulcastCodecs.get(e.codec);if(Bn.debug("try setPublishingCodec for ".concat(e.codec),t),t&&t.sender)t.encodings&&(Bn.debug("try setPublishingLayersForSender ".concat(e.codec)),yield iu(t.sender,t.encodings,e.qualities,this.senderLock));else for(const t of e.qualities)if(t.enabled){c.push(e.codec);break}}else yield this.setPublishingLayers(e.qualities)}}catch(e){a={error:e}}finally{try{t||n||!(r=i.return)||(yield r.call(i))}finally{if(a)throw a.error}}return c}))}setPublishingLayers(e){return To(this,void 0,void 0,(function*(){Bn.debug("setting publishing layers",e),this.sender&&this.encodings&&(yield iu(this.sender,this.encodings,e,this.senderLock))}))}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return To(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),vd()&&this.isInBackground&&this.source===Rh.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}))}}function iu(e,t,i,s){return To(this,void 0,void 0,(function*(){const n=yield s.lock();Bn.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 Bn.warn("cannot set publishing layers, encodings mismatch");let a=!1;if(1===n.length&&n[0].scalabilityMode){const e=n[0];let t=Tr.OFF;i.forEach((e=>{e.enabled&&(t===Tr.OFF||e.quality>t)&&(t=e.quality)})),t===Tr.OFF?e.active&&(e.active=!1,a=!0):e.active||(a=!0,e.active=!0)}else n.forEach(((e,s)=>{var n;let r=null!==(n=e.rid)&&void 0!==n?n:"";""===r&&(r="q");const o=su(r),c=i.find((e=>e.quality===o));c&&e.active!==c.enabled&&(a=!0,e.active=c.enabled,Bn.debug("setting layer ".concat(c.quality," to ").concat(e.active?"enabled":"disabled")),gd()&&(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,Bn.debug("setting encodings",s.encodings),yield e.setParameters(s))}finally{n()}}))}function su(e){switch(e){case"f":return Tr.HIGH;case"h":return Tr.MEDIUM;case"q":return Tr.LOW;default:return Tr.UNRECOGNIZED}}function nu(e,t,i){if(!i)return[{quality:Tr.HIGH,width:e,height:t,bitrate:0,ssrc:0}];if(1===i.length&&i[0].scalabilityMode){const s=new eu(i[0].scalabilityMode),n=[];for(let a=0;a<s.spatial;a+=1)n.push({quality:Tr.HIGH-a,width:e/Math.pow(2,a),height:t/Math.pow(2,a),bitrate:i[0].maxBitrate?i[0].maxBitrate/Math.pow(3,a):0,ssrc:0});return n}return i.map((s=>{var n,a,r;const o=null!==(n=s.scaleResolutionDownBy)&&void 0!==n?n:1;let c=su(null!==(a=s.rid)&&void 0!==a?a:"");return c===Tr.UNRECOGNIZED&&1===i.length&&(c=Tr.HIGH),{quality:c,width:e/o,height:t/o,bitrate:null!==(r=s.maxBitrate)&&void 0!==r?r:0,ssrc:0}}))}class au extends Rh{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?Ph.Muted:Ph.Unmuted,this))}setMediaStream(e){this.mediaStream=e,e.onremovetrack=()=>{this.receiver=void 0,this._currentBitrate=0,this.emit(Ph.Ended,this)}}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval((()=>this.monitorReceiver()),Lh))}}class ru extends au{constructor(e,t,i,s,n){super(e,t,Rh.Kind.Audio,i),this.monitorReceiver=()=>To(this,void 0,void 0,(function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=Fh(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}setSinkId(e){return To(this,void 0,void 0,(function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map((t=>{if(pd(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&&pd(e)&&e.setSinkId(this.sinkId),this.audioContext&&t&&(Bn.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(Ph.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))})).catch((e=>{this.emit(Ph.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}getReceiverStats(){return To(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;let e;return(yield 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}))}}class ou extends au{constructor(e,t,i,s){super(e,t,Rh.Kind.Video,i),this.elementInfos=[],this.isObserved=!1,this.monitorReceiver=()=>To(this,void 0,void 0,(function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=Fh(e,this.prevStats)),this.prevStats=e})),this.debouncedHandleResize=nh((()=>{this.updateDimensions()}),100),this.adaptiveStreamSettings=s}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}get mediaStreamTrack(){return this.isAdaptiveStream&&!this.isObserved&&Bn.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?_h(this._mediaStreamTrack,t):Nh(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 cu(e);this.observeElementInfo(t)}return 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(),this.isObserved=!0):Bn.warn("visibility resize observer not triggered")}stopObservingElementInfo(e){if(!this.isAdaptiveStream)return void Bn.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}getReceiverStats(){return To(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;let e;return(yield 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))}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return To(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),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?Yl.setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=a,this.emit(Ph.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?Ed():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(Ph.VideoDimensionsChanged,this.lastDimensions,this))}}class cu{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:lu(e),this.isPiP=bd()&&document.pictureInPictureElement===e,this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){this.isIntersecting=lu(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,_d().observe(this.element),Rd().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP)}stopObserving(){var e,t;null===(e=_d())||void 0===e||e.unobserve(this.element),null===(t=Rd())||void 0===t||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP)}}function lu(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 du extends Jo.EventEmitter{constructor(e,t,i){super(),this.metadataMuted=!1,this.handleMuted=()=>{this.emit(Ph.Muted)},this.handleUnmuted=()=>{this.emit(Ph.Unmuted)},this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=Rh.Source.Unknown}setTrack(e){this.track&&(this.track.off(Ph.Muted,this.handleMuted),this.track.off(Ph.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(Ph.Muted,this.handleMuted),e.on(Ph.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 jh||this.track instanceof ru)return this.track}get videoTrack(){if(this.track instanceof tu||this.track instanceof ou)return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=Rh.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===Rh.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.trackInfo=e,Bn.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"}(du||(du={}));class hu extends du{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(Ph.Ended)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&this.track.off(Ph.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(Ph.Ended,this.handleTrackEnded)}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}mute(){var e;return To(this,void 0,void 0,(function*(){return null===(e=this.track)||void 0===e?void 0:e.mute()}))}unmute(){var e;return To(this,void 0,void 0,(function*(){return null===(e=this.track)||void 0===e?void 0:e.unmute()}))}pauseUpstream(){var e;return To(this,void 0,void 0,(function*(){yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()}))}resumeUpstream(){var e;return To(this,void 0,void 0,(function*(){yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()}))}}var uu,pu;!function(e){e.Excellent="excellent",e.Good="good",e.Poor="poor",e.Unknown="unknown"}(uu||(uu={}));class mu extends Jo.EventEmitter{constructor(e,t,i,s){super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=uu.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(Rh.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrack(Rh.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrack(Rh.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*this.participantInfo.joinedAt):new Date}updateInfo(e){return!(this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version)&&(this.identity=e.identity,this.sid=e.sid,this.setName(e.name),this.setMetadata(e.metadata),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,Bn.trace("update participant info",{info:e}),!0)}setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(wh.ParticipantMetadataChanged,i)}setName(e){const t=this.name!==e;this.name=e,t&&this.emit(wh.ParticipantNameChanged,e)}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(wh.ParticipantPermissionsChanged,r),o}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(wh.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=function(e){switch(e){case Pr.EXCELLENT:return uu.Excellent;case Pr.GOOD:return uu.Good;case Pr.POOR:return uu.Poor;default:return uu.Unknown}}(e),t!==this._connectionQuality&&this.emit(wh.ConnectionQualityChanged,this._connectionQuality)}addTrackPublication(e){e.on(Ph.Muted,(()=>{this.emit(wh.TrackMuted,e)})),e.on(Ph.Unmuted,(()=>{this.emit(wh.TrackUnmuted,e)}));const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.tracks.set(e.trackSid,e),e.kind){case Rh.Kind.Audio:this.audioTracks.set(e.trackSid,e);break;case Rh.Kind.Video:this.videoTracks.set(e.trackSid,e)}}}class gu extends du{constructor(e,t,i){super(e,t.sid,t.name),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=Tr.HIGH,this.handleEnded=e=>{this.setTrack(void 0),this.emit(Ph.Ended,e)},this.handleVisibilityChange=e=>{Bn.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(e),{trackSid:this.trackSid}),this.disabled=!e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{Bn.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(Ph.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?du.SubscriptionStatus.Unsubscribed:super.isSubscribed?du.SubscriptionStatus.Subscribed:du.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?du.PermissionStatus.Allowed:du.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 ou&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&this.track instanceof ou&&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(Ph.VideoDimensionsChanged,this.handleVideoDimensionsChange),s.off(Ph.VisibilityChanged,this.handleVisibilityChange),s.off(Ph.Ended,this.handleEnded),s.detach(),s.stopMonitor(),this.emit(Ph.Unsubscribed,s)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(Ph.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(Ph.VisibilityChanged,this.handleVisibilityChange),e.on(Ph.Ended,this.handleEnded),this.emit(Ph.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(Ph.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?Ph.Muted:Ph.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(Ph.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(Ph.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.kind===Rh.Kind.Video&&this.isAdaptiveStream?(Bn.warn("adaptive stream is enabled, cannot change video track settings",{trackSid:this.trackSid}),!1):!!this.isDesired||(Bn.warn("cannot update track settings when not subscribed",{trackSid:this.trackSid}),!1)}get isAdaptiveStream(){return this.track instanceof ou&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=vl.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=Tr.HIGH,this.emit(Ph.UpdateSettings,e)}}class fu extends mu{static fromParticipantInfo(e,t){return new fu(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(Ph.UpdateSettings,(e=>{Bn.debug("send update settings",e),this.signalClient.sendUpdateTrackSettings(e)})),e.on(Ph.UpdateSubscription,(e=>{e.participantTracks.forEach((e=>{e.participantSid=this.sid})),this.signalClient.sendUpdateSubscription(e)})),e.on(Ph.SubscriptionPermissionChanged,(t=>{this.emit(wh.TrackSubscriptionPermissionChanged,e,t)})),e.on(Ph.SubscriptionStatusChanged,(t=>{this.emit(wh.TrackSubscriptionStatusChanged,e,t)})),e.on(Ph.Subscribed,(t=>{this.emit(wh.TrackSubscribed,t,e)})),e.on(Ph.Unsubscribed,(t=>{this.emit(wh.TrackUnsubscribed,t,e)})),e.on(Ph.SubscriptionFailed,(t=>{this.emit(wh.TrackSubscriptionFailed,e.trackSid,t)}))}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(Rh.Source.Microphone);t&&t.track&&t.track.setVolume(e)}getVolume(){const e=this.getTrack(Rh.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?(Bn.error("could not find published track",{participant:this.sid,trackSid:t}),void this.emit(wh.TrackSubscriptionFailed,t)):(void 0===a&&(a=20),void setTimeout((()=>{this.addSubscribedMediaTrack(e,t,i,s,n,a-1)}),150));if("ended"===e.readyState)return Bn.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",{participant:this.sid,trackSid:t}),void this.emit(wh.TrackSubscriptionFailed,t);let o;return o="video"===e.kind?new ou(e,t,s,n):new ru(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 ru&&o.source===Rh.Source.Microphone&&o.setVolume(this.volume),r}get hasMetadata(){return!!this.participantInfo}getTrackPublication(e){return this.tracks.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,i=new Map;return e.tracks.forEach((s=>{var n;let a=this.getTrackPublication(s.sid);if(a)a.updateInfo(s);else{const t=Rh.kindFromProto(s.type);if(!t)return;a=new gu(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!==Rh.Source.Unknown&&Bn.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)||(Bn.trace("detected removed track on remote participant, unpublishing",{publication:e,participantSid:this.sid}),this.unpublishTrack(e.trackSid,!0))})),i.forEach((e=>{this.emit(wh.TrackPublished,e)})),!0}unpublishTrack(e,t){const i=this.tracks.get(e);if(!i)return;const{track:s}=i;switch(s&&(s.stop(),i.setTrack(void 0)),this.tracks.delete(e),i.kind){case Rh.Kind.Audio:this.audioTracks.delete(e);break;case Rh.Kind.Video:this.videoTracks.delete(e)}t&&this.emit(wh.TrackUnpublished,i)}setAudioContext(e){this.audioContext=e,this.audioTracks.forEach((t=>t.track instanceof ru&&t.track.setAudioContext(e)))}setAudioOutput(e){return To(this,void 0,void 0,(function*(){this.audioOutput=e;const t=[];this.audioTracks.forEach((i=>{var s;i.track instanceof ru&&t.push(i.track.setSinkId(null!==(s=e.deviceId)&&void 0!==s?s:"default"))})),yield Promise.all(t)}))}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];return Bn.trace("participant event",{participant:this.sid,event:e,args:i}),super.emit(e,...i)}}class vu extends mu{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 Od)},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=()=>{Bn.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):Bn.error("could not update mute status for unpublished track",e)},this.onTrackUpstreamPaused=e=>{Bn.debug("upstream paused"),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{Bn.debug("upstream resumed"),this.onTrackMuted(e,e.isMuted)},this.handleSubscribedQualityUpdate=e=>To(this,void 0,void 0,(function*(){var t,i,s,n,a,r;if(!(null===(a=this.roomOptions)||void 0===a?void 0:a.dynacast))return;const o=this.videoTracks.get(e.trackSid);if(o)if(e.subscribedCodecs.length>0){if(!o.videoTrack)return;const a=yield o.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var c,l=!0,d=Mo(a);!(t=(c=yield d.next()).done);l=!0){n=c.value,l=!1;const e=n;uh(e)&&(Bn.debug("publish ".concat(e," for ").concat(o.videoTrack.sid)),yield this.publishAdditionalCodecForTrack(o.videoTrack,e,o.options))}}catch(e){i={error:e}}finally{try{l||t||!(s=d.return)||(yield s.call(d))}finally{if(i)throw i.error}}}else e.subscribedQualities.length>0&&(yield null===(r=o.videoTrack)||void 0===r?void 0:r.setPublishingLayers(e.subscribedQualities));else Bn.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):Bn.warn("received unpublished event for unknown track",{method:"handleLocalTrackUnpublished",trackSid:e.trackSid})},this.handleTrackEnded=e=>To(this,void 0,void 0,(function*(){if(e.source===Rh.Source.ScreenShare||e.source===Rh.Source.ScreenShareAudio)Bn.debug("unpublishing local track due to TrackEnded",{track:e.sid}),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(e instanceof jh||e instanceof tu)try{if(bd())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===Rh.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw Bn.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||(Bn.debug("track ended, attempting to use a different device"),yield e.restartTrack())}catch(t){Bn.warn("could not restart track, muting instead"),yield 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(Th.Connected,this.handleReconnected).on(Th.Restarted,this.handleReconnected).on(Th.Resumed,this.handleReconnected).on(Th.Restarting,this.handleReconnecting).on(Th.Resuming,this.handleReconnecting).on(Th.Disconnected,this.handleDisconnected)}setMetadata(e){var t;super.setMetadata(e),this.engine.client.sendUpdateLocalMetadata(e,null!==(t=this.name)&&void 0!==t?t:"")}setName(e){var t;super.setName(e),this.engine.client.sendUpdateLocalMetadata(null!==(t=this.metadata)&&void 0!==t?t:"",e)}setCameraEnabled(e,t,i){return this.setTrackEnabled(Rh.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(Rh.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(Rh.Source.ScreenShare,e,t,i)}setTrackEnabled(e,t,i,s){var n,a;return To(this,void 0,void 0,(function*(){Bn.debug("setTrackEnabled",{source:e,enabled:t});let r=this.getTrack(e);if(t)if(r)yield r.unmute();else{let t;if(this.pendingPublishing.has(e))return void Bn.info("skipping duplicate published source",{source:e});this.pendingPublishing.add(e);try{switch(e){case Rh.Source.Camera:t=yield this.createTracks({video:null===(n=i)||void 0===n||n});break;case Rh.Source.Microphone:t=yield this.createTracks({audio:null===(a=i)||void 0===a||a});break;case Rh.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},i));break;default:throw new Zl(e)}const o=[];for(const e of t)Bn.info("publishing track",{localTrack:e}),o.push(this.publishTrack(e,s));const c=yield Promise.all(o);[r]=c}catch(e){throw e instanceof Error&&!(e instanceof Zl)&&this.emit(wh.MediaDevicesError,e),e}finally{this.pendingPublishing.delete(e)}}else if(r&&r.track)if(e===Rh.Source.ScreenShare){r=yield this.unpublishTrack(r.track);const e=this.getTrack(Rh.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield r.mute();return r}))}enableCameraAndMicrophone(){return To(this,void 0,void 0,(function*(){if(!this.pendingPublishing.has(Rh.Source.Camera)&&!this.pendingPublishing.has(Rh.Source.Microphone)){this.pendingPublishing.add(Rh.Source.Camera),this.pendingPublishing.add(Rh.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map((e=>this.publishTrack(e))))}finally{this.pendingPublishing.delete(Rh.Source.Camera),this.pendingPublishing.delete(Rh.Source.Microphone)}}}))}createTracks(e){var t,i;return To(this,void 0,void 0,(function*(){const s=rd(nd(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=yield 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=qh(t,a);return o.kind===Rh.Kind.Video?o.source=Rh.Source.Camera:o.kind===Rh.Kind.Audio&&(o.source=Rh.Source.Microphone),o.mediaStream=n,o}))}))}createScreenTracks(e){var t;return To(this,void 0,void 0,(function*(){void 0===e&&(e={}),void 0===e.resolution&&(e.resolution=vh.h1080fps15.resolution);let i=!0;if(e.resolution&&(i=fd()?{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 Gl("getDisplayMedia not supported");const s=yield 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 Zl("no video track found");const a=new tu(n[0],void 0,!1);a.source=Rh.Source.ScreenShare;const r=[a];if(s.getAudioTracks().length>0){const e=new jh(s.getAudioTracks()[0],void 0,!1);e.source=Rh.Source.ScreenShareAudio,r.push(e)}return r}))}publishTrack(e,t){var i,s,n;return To(this,void 0,void 0,(function*(){if(yield null===(i=this.reconnectFuture)||void 0===i?void 0:i.promise,e instanceof Bh&&this.pendingPublishPromises.has(e)&&(yield this.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new jh(e,void 0,!0);break;case"video":e=new tu(e,void 0,!0);break;default:throw new Zl("unsupported MediaStreamTrack kind ".concat(e.kind))}let a;if(this.tracks.forEach((t=>{t.track&&t.track===e&&(a=t)})),a)return Bn.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&&Bn.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work."),void 0===t.red&&Bn.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=Object.assign(Object.assign({},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 yield c}catch(e){throw e}finally{this.pendingPublishPromises.delete(e)}}))}publish(e,t,i,s){var n,a,r,o,c,l,d,h,u,p,m,g,f;return To(this,void 0,void 0,(function*(){const v=Array.from(this.tracks.values()).find((t=>e instanceof Bh&&t.source===e.source));if(v&&e.source!==Rh.Source.Unknown)try{throw Error("publishing a second track with the same source: ".concat(e.source))}catch(t){t instanceof Error&&Bn.warn(t.message,{oldTrack:v,newTrack:e,trace:t.stack})}t.stopMicTrackOnMute&&e instanceof jh&&(e.stopOnMute=!0),e.source===Rh.Source.ScreenShare&&gd()&&(t.simulcast=!1),"av1"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/AV1"===i.mimeType){t=!0;break}return t}()||(t.videoCodec=void 0),"vp9"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/VP9"===i.mimeType){t=!0;break}return t}()||(t.videoCodec=void 0),e.on(Ph.Muted,this.onTrackMuted),e.on(Ph.Unmuted,this.onTrackUnmuted),e.on(Ph.Ended,this.handleTrackEnded),e.on(Ph.UpstreamPaused,this.onTrackUpstreamPaused),e.on(Ph.UpstreamResumed,this.onTrackUpstreamResumed);const b=rl.fromPartial({cid:e.mediaStreamTrack.id,name:null==i?void 0:i.name,type:Rh.kindToProto(e.kind),muted:e.isMuted,source:Rh.sourceToProto(e.source),disableDtx:!(null===(n=t.dtx)||void 0===n||n),stereo:s,disableRed:!(null===(a=t.red)||void 0===a||a)});let y,S;if(e.kind===Rh.Kind.Video){let i={width:0,height:0};try{i=yield e.waitForDimensions()}catch(e){const t=null!==(o=null===(r=this.roomOptions.videoCaptureDefaults)||void 0===r?void 0:r.resolution)&&void 0!==o?o:gh.h720.resolution;i={width:t.width,height:t.height},Bn.error("could not determine track dimensions, using defaults",i)}if(b.width=i.width,b.height=i.height,e instanceof tu)if(ud(t.videoCodec)&&(t.scalabilityMode=null!==(c=t.scalabilityMode)&&void 0!==c?c:"L3T3_KEY"),t.videoCodec&&t.backupCodec&&t.videoCodec!==t.backupCodec.codec){const i=Object.assign({},t);i.simulcast=!0,S=Kh(e,t.backupCodec.codec,i),b.simulcastCodecs=[{codec:t.videoCodec,cid:e.mediaStreamTrack.id,enableSimulcastLayers:!0},{codec:t.backupCodec.codec,cid:"",enableSimulcastLayers:!0}]}else t.videoCodec&&(b.simulcastCodecs=[{codec:t.videoCodec,cid:e.mediaStreamTrack.id,enableSimulcastLayers:null!==(l=t.simulcast)&&void 0!==l&&l}]);y=zh(e.source===Rh.Source.ScreenShare,i.width,i.height,t),b.layers=nu(b.width,b.height,y)}else e.kind===Rh.Kind.Audio&&(y=[{maxBitrate:null!==(h=null===(d=t.audioPreset)||void 0===d?void 0:d.maxBitrate)&&void 0!==h?h:t.audioBitrate,priority:null!==(p=null===(u=t.audioPreset)||void 0===u?void 0:u.priority)&&void 0!==p?p:"high",networkPriority:null!==(g=null===(m=t.audioPreset)||void 0===m?void 0:m.priority)&&void 0!==g?g:"high"}]);if(!this.engine||this.engine.isClosed)throw new Kl("cannot publish track when not connected");const C=yield this.engine.addTrack(b);let k=!1,E=!1;if(C.codecs.forEach((e=>{ph(e.mimeType,t.videoCodec)?k=!0:t.backupCodec&&ph(e.mimeType,t.backupCodec.codec)&&(E=!0)})),b.simulcastCodecs.length>0){if(!k&&!E)throw Error("cannot publish track, codec not supported by server");if(!k&&t.backupCodec){const e=t.backupCodec;t=Object.assign({},t),Bn.debug("primary codec ".concat(t.videoCodec," not supported, fallback to ").concat(e.codec)),t.videoCodec=e.codec,t.videoEncoding=e.encoding,y=S}}const w=new hu(e.kind,C,e);if(w.options=t,e.sid=C.sid,!this.engine.publisher)throw new Kl("publisher is closed");return Bn.debug("publishing ".concat(e.kind," with encodings"),{encodings:y,trackInfo:C}),e.sender=yield this.engine.createSender(e,t,y),e.codec&&ud(e.codec)&&y&&(null===(f=y[0])||void 0===f?void 0:f.maxBitrate)&&this.engine.publisher.setTrackCodecBitrate(b.cid,e.codec,y[0].maxBitrate/1e3),this.engine.negotiate(),e instanceof tu?e.startMonitor(this.engine.client):e instanceof jh&&e.startMonitor(),this.addTrackPublication(w),this.emit(wh.LocalTrackPublished,w),w}))}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){var s;return To(this,void 0,void 0,(function*(){let n;if(this.tracks.forEach((t=>{t.track&&t.track===e&&(n=t)})),!n)throw new Zl("track is not published");if(!(e instanceof tu))throw new Zl("track is not a video track");const a=Object.assign(Object.assign({},null===(s=this.roomOptions)||void 0===s?void 0:s.publishDefaults),i),r=Kh(e,t,a);if(!r)return void Bn.info("backup codec has been disabled, ignoring request to add additional codec for track");const o=e.addSimulcastTrack(t,r),c=rl.fromPartial({cid:o.mediaStreamTrack.id,type:Rh.kindToProto(e.kind),muted:e.isMuted,source:Rh.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:o.mediaStreamTrack.id,enableSimulcastLayers:a.simulcast}]});if(c.layers=nu(c.width,c.height,r),!this.engine||this.engine.isClosed)throw new Kl("cannot publish track when not connected");const l=yield this.engine.addTrack(c);yield this.engine.createSimulcastSender(e,o,a,r),this.engine.negotiate(),Bn.debug("published ".concat(t," for track ").concat(e.sid),{encodings:r,trackInfo:l})}))}unpublishTrack(e,t){var i,s;return To(this,void 0,void 0,(function*(){const n=this.getPublicationForTrack(e);if(Bn.debug("unpublishing track",{track:e,method:"unpublishTrack"}),!n||!n.track)return void Bn.warn("track was not unpublished because no publication was found",{track:e,method:"unpublishTrack"});(e=n.track).off(Ph.Muted,this.onTrackMuted),e.off(Ph.Unmuted,this.onTrackUnmuted),e.off(Ph.Ended,this.handleTrackEnded),e.off(Ph.UpstreamPaused,this.onTrackUpstreamPaused),e.off(Ph.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{for(const e of this.engine.publisher.pc.getTransceivers())e.sender===r&&(e.direction="inactive",a=!0);if(this.engine.removeTrack(r)&&(a=!0),e instanceof tu){for(const[,t]of e.simulcastCodecs)t.sender&&(this.engine.removeTrack(t.sender)&&(a=!0),t.sender=void 0);e.simulcastCodecs.clear()}}catch(e){Bn.warn("failed to unpublish track",{error:e,method:"unpublishTrack"})}switch(this.tracks.delete(n.trackSid),n.kind){case Rh.Kind.Audio:this.audioTracks.delete(n.trackSid);break;case Rh.Kind.Video:this.videoTracks.delete(n.trackSid)}return this.emit(wh.LocalTrackUnpublished,n),n.setTrack(void 0),a&&(yield this.engine.negotiate()),n}))}unpublishTracks(e){return To(this,void 0,void 0,(function*(){return(yield Promise.all(e.map((e=>this.unpublishTrack(e))))).filter((e=>e instanceof hu))}))}republishAllTracks(e){return To(this,void 0,void 0,(function*(){const t=[];this.tracks.forEach((i=>{i.track&&(e&&(i.options=Object.assign(Object.assign({},i.options),e)),t.push(i))})),yield Promise.all(t.map((e=>To(this,void 0,void 0,(function*(){const t=e.track;yield this.unpublishTrack(t,!1),yield this.publishTrack(t,e.options)})))))}))}publishData(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return To(this,void 0,void 0,(function*(){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 fu?n.push(e.sid):n.push(e)}));const r={kind:t,value:{$case:"user",user:{participantSid:this.sid,payload:e,destinationSids:n,topic:a}}};yield 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){return 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&&(Bn.debug("updating server mute state after reconcile",{sid:e.sid,muted:n}),this.engine.client.sendMuteTrack(e.sid,n))}})),!0))}getPublicationForTrack(e){let t;return this.tracks.forEach((i=>{const s=i.track;s&&(e instanceof MediaStreamTrack?(s instanceof jh||s instanceof tu)&&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(Ar.LOSSY),zc.PUBLISHER),t(this.engine.dataChannelForKind(Ar.RELIABLE),zc.PUBLISHER),t(this.engine.dataChannelForKind(Ar.LOSSY,!0),zc.SUBSCRIBER),t(this.engine.dataChannelForKind(Ar.RELIABLE,!0),zc.SUBSCRIBER),e}}!function(e){e.Disconnected="disconnected",e.Connecting="connecting",e.Connected="connected",e.Reconnecting="reconnecting"}(pu||(pu={}));class bu extends Jo.EventEmitter{constructor(e){var t;super(),t=this,this.state=pu.Disconnected,this.activeSpeakers=[],this.audioEnabled=!0,this.connect=(e,t,i)=>To(this,void 0,void 0,(function*(){const s=yield this.disconnectLock.lock();if(this.state===pu.Connected)return Bn.info("already connected to room ".concat(this.name)),s(),Promise.resolve();if(this.connectFuture)return s(),this.connectFuture.promise;this.setAndEmitConnectionState(pu.Connecting);const n=new lh(e,t),a=(r,o,c)=>To(this,void 0,void 0,(function*(){var l;this.abortController&&this.abortController.abort(),this.abortController=new AbortController,null==s||s();try{yield this.attemptConnection(null!=c?c:e,t,i,this.abortController),this.abortController=void 0,r()}catch(t){if(Sd(new URL(e))&&t instanceof Hl&&3!==t.reason){let e=null;try{e=yield n.getNextBestRegionUrl(null===(l=this.abortController)||void 0===l?void 0:l.signal)}catch(e){if(e instanceof Hl&&(401===e.status||3===e.reason))return void o(e)}e?(Bn.debug("initial connection failed, retrying with another region"),yield a(r,o,e)):o(t)}else o(t)}}));return this.connectFuture=new Od(a,(()=>{this.clearConnectionFutures()})),this.connectFuture.promise})),this.connectSignal=(e,t,i,s,n,a)=>To(this,void 0,void 0,(function*(){const r=yield i.join(e,t,{autoSubscribe:s.autoSubscribe,publishOnly:s.publishOnly,adaptiveStream:"object"==typeof n.adaptiveStream||n.adaptiveStream,maxRetries:s.maxRetries},a.signal);let o=r.serverInfo;if(o||(o={version:r.serverVersion,region:r.serverRegion}),Bn.debug("connected to Livekit Server ".concat(Object.entries(o).map((e=>{let[t,i]=e;return"".concat(t,": ").concat(i)})).join(", "))),!r.serverVersion)throw new zl("unknown server version");return"0.15.1"===r.serverVersion&&this.options.dynacast&&(Bn.debug("disabling dynacast due to server version"),n.dynacast=!1),r})),this.applyJoinResponse=e=>{const t=e.participant;this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(e,t,i,s)=>To(this,void 0,void 0,(function*(){var n;this.state===pu.Reconnecting?(Bn.info("Reconnection attempt replaced by new connection attempt"),this.recreateEngine()):this.maybeCreateEngine(),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},kh),i),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const i=yield this.connectSignal(e,t,this.engine,this.connOptions,this.options,s);this.applyJoinResponse(i),this.setupLocalParticipantEvents(),this.emit(Eh.SignalConnected)}catch(e){this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish);const t=new Hl("could not establish signal connection");throw e instanceof Error&&(t.message="".concat(t.message,": ").concat(e.message)),e instanceof Hl&&(t.reason=e.reason,t.status=e.status),Bn.debug("error trying to establish signal connection",{error:e}),t}if(s.signal.aborted)throw this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),new Hl("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,s)}catch(e){throw this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),e}bd()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave),null===(n=navigator.mediaDevices)||void 0===n||n.addEventListener("devicechange",this.handleDeviceChange)),this.setAndEmitConnectionState(pu.Connected),this.emit(Eh.Connected),this.registerConnectionReconcile()})),this.disconnect=function(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return To(t,void 0,void 0,(function*(){var t,i,s,n;const a=yield this.disconnectLock.lock();try{if(this.state===pu.Disconnected)return void Bn.debug("already disconnected");Bn.info("disconnect from room",{identity:this.localParticipant.identity}),this.state!==pu.Connecting&&this.state!==pu.Reconnecting||(Bn.warn("abort connection attempt"),null===(t=this.abortController)||void 0===t||t.abort(),null===(s=null===(i=this.connectFuture)||void 0===i?void 0:i.reject)||void 0===s||s.call(i,new Hl("Client initiated disconnect")),this.connectFuture=void 0),(null===(n=this.engine)||void 0===n?void 0:n.client.isConnected)&&(yield this.engine.client.sendLeave()),this.engine&&(yield this.engine.close()),this.handleDisconnect(e,Rr.CLIENT_INITIATED),this.engine=void 0}finally{a()}}))},this.onPageLeave=()=>To(this,void 0,void 0,(function*(){yield this.disconnect()})),this.handleRestarting=()=>{this.clearConnectionReconcile();for(const e of this.participants.values())this.handleParticipantDisconnected(e.sid,e);this.setAndEmitConnectionState(pu.Reconnecting)&&this.emit(Eh.Reconnecting)},this.handleSignalRestarted=e=>To(this,void 0,void 0,(function*(){Bn.debug("signal reconnected to server",{region:e.serverRegion}),this.cachedParticipantSids=[],this.applyJoinResponse(e);try{const e=[];this.localParticipant.tracks.forEach((t=>{t.track&&e.push(t)})),yield Promise.all(e.map((e=>To(this,void 0,void 0,(function*(){const t=e.track;this.localParticipant.unpublishTrack(t,!1),t.isMuted||((t instanceof jh||t instanceof tu)&&!t.isUserProvided&&(Bn.debug("restarting existing track",{track:e.trackSid}),yield t.restartTrack()),Bn.debug("publishing new track",{track:e.trackSid}),yield this.localParticipant.publishTrack(t,e.options))})))))}catch(e){Bn.error("error trying to re-publish tracks after reconnection",{error:e})}try{yield this.engine.waitForRestarted(),Bn.debug("fully reconnected to server",{region:e.serverRegion})}catch(e){return}this.setAndEmitConnectionState(pu.Connected),this.emit(Eh.Reconnected),this.registerConnectionReconcile(),this.participants.forEach((e=>{this.emit(Eh.ParticipantConnected,e)}))})),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===Dr.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(Eh.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(Eh.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=Rh.streamStateFromProto(e.state),t.emit(wh.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(Eh.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.handleSubscriptionError=e=>{const t=Array.from(this.participants.values()).find((t=>t.tracks.has(e.trackSid)));if(!t)return;const i=t.getTrackPublication(e.trackSid);i&&i.setSubscriptionError(e.err)},this.handleDataPacket=(e,t)=>{const i=this.participants.get(e.participantSid);this.emit(Eh.DataReceived,e.payload,i,t,e.topic),null==i||i.emit(wh.DataReceived,e.payload,t)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(Eh.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=e=>{Bn.warn("could not playback audio",e),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(Eh.AudioPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>To(this,void 0,void 0,(function*(){this.emit(Eh.MediaDevicesChanged)})),this.handleRoomUpdate=e=>{const t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected(Eh.RoomMetadataChanged,e.metadata),(null==t?void 0:t.activeRecording)!==e.activeRecording&&this.emitWhenConnected(Eh.RecordingStatusChanged,e.activeRecording)},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(Eh.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit(Eh.ParticipantNameChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(Eh.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(Eh.TrackUnmuted,e,this.localParticipant)},this.onLocalTrackPublished=e=>To(this,void 0,void 0,(function*(){if(this.emit(Eh.LocalTrackPublished,e,this.localParticipant),e.track instanceof jh){(yield e.track.checkForSilence())&&this.emit(Eh.LocalAudioSilenceDetected,e)}})),this.onLocalTrackUnpublished=e=>{this.emit(Eh.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalConnectionQualityChanged=e=>{this.emit(Eh.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=e=>{this.emit(Eh.MediaDevicesError,e)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(Eh.ParticipantPermissionsChanged,e,this.localParticipant)},this.setMaxListeners(100),this.participants=new Map,this.cachedParticipantSids=[],this.identityToSid=new Map,this.options=Object.assign(Object.assign({},Ch),e),this.options.audioCaptureDefaults=Object.assign(Object.assign({},yh),null==e?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Sh),null==e?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},bh),null==e?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Ud,this.localParticipant=new vu("","",this.engine,this.options)}get isRecording(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.activeRecording)&&void 0!==t&&t}get sid(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.sid)&&void 0!==t?t:""}get name(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.name)&&void 0!==t?t:""}get metadata(){var e;return null===(e=this.roomInfo)||void 0===e?void 0:e.metadata}get numParticipants(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numParticipants)&&void 0!==t?t:0}get numPublishers(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numPublishers)&&void 0!==t?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new Uh(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.client.onSubscriptionError=this.handleSubscriptionError,this.engine.on(Th.MediaTrackAdded,((e,t,i)=>{this.onTrackAdded(e,t,i)})).on(Th.Disconnected,(e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)})).on(Th.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(Th.DataPacketReceived,this.handleDataPacket).on(Th.Resuming,(()=>{this.clearConnectionReconcile(),this.setAndEmitConnectionState(pu.Reconnecting)&&this.emit(Eh.Reconnecting),this.cachedParticipantSids=Array.from(this.participants.keys())})).on(Th.Resumed,(()=>{this.setAndEmitConnectionState(pu.Connected),this.emit(Eh.Reconnected),this.registerConnectionReconcile(),this.updateSubscriptions();Array.from(this.participants.values()).filter((e=>!this.cachedParticipantSids.includes(e.sid))).forEach((e=>this.emit(Eh.ParticipantConnected,e))),this.cachedParticipantSids=[]})).on(Th.SignalResumed,(()=>{this.state===pu.Reconnecting&&this.sendSyncState()})).on(Th.Restarting,this.handleRestarting).on(Th.SignalRestarted,this.handleSignalRestarted).on(Th.DCBufferStatusChanged,((e,t)=>{this.emit(Eh.DCBufferStatusChanged,e,t)})),this.localParticipant&&this.localParticipant.setupEngine(this.engine))}static getLocalDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return $d.getInstance().getDevices(e,t)}prepareConnection(e){return To(this,void 0,void 0,(function*(){yield 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}simulateScenario(e){return To(this,void 0,void 0,(function*(){let t,i=()=>{};switch(e){case"signal-reconnect":yield this.engine.client.close(),this.engine.client.onClose&&this.engine.client.onClose("simulate disconnect");break;case"speaker":t=xl.fromPartial({scenario:{$case:"speakerUpdate",speakerUpdate:3}});break;case"node-failure":t=xl.fromPartial({scenario:{$case:"nodeFailure",nodeFailure:!0}});break;case"server-leave":t=xl.fromPartial({scenario:{$case:"serverLeave",serverLeave:!0}});break;case"migration":t=xl.fromPartial({scenario:{$case:"migration",migration:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.close(),this.engine.client.onClose&&this.engine.client.onClose("simulate resume-reconnect");break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.close(),this.engine.client.onClose&&this.engine.client.onClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":t=xl.fromPartial({scenario:{$case:"switchCandidateProtocol",switchCandidateProtocol:"force-tls"===e?2:1}}),i=()=>To(this,void 0,void 0,(function*(){const e=this.engine.client.onLeave;e&&e({reason:Rr.CLIENT_INITIATED,canReconnect:!0})}))}t&&(this.engine.client.sendSimulateScenario(t),i())}))}startAudio(){return To(this,void 0,void 0,(function*(){yield this.acquireAudioContext();const e=[];this.participants.forEach((t=>{t.audioTracks.forEach((t=>{t.track&&t.track.attachedElements.forEach((t=>{e.push(t)}))}))}));try{yield 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:""}switchActiveDevice(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];var s,n;return To(this,void 0,void 0,(function*(){const a=i?{exact:t}:t;if("audioinput"===e){const e=this.options.audioCaptureDefaults.deviceId;this.options.audioCaptureDefaults.deviceId=a;const t=Array.from(this.localParticipant.audioTracks.values()).filter((e=>e.source===Rh.Source.Microphone));try{yield Promise.all(t.map((e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(a)})))}catch(t){throw this.options.audioCaptureDefaults.deviceId=e,t}}else if("videoinput"===e){const e=this.options.videoCaptureDefaults.deviceId;this.options.videoCaptureDefaults.deviceId=a;const t=Array.from(this.localParticipant.videoTracks.values()).filter((e=>e.source===Rh.Source.Camera));try{yield Promise.all(t.map((e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(a)})))}catch(t){throw this.options.videoCaptureDefaults.deviceId=e,t}}else if("audiooutput"===e){if(!pd())throw new Error("cannot switch audio output, setSinkId not supported");null!==(s=(n=this.options).audioOutput)&&void 0!==s||(n.audioOutput={});const e=this.options.audioOutput.deviceId;this.options.audioOutput.deviceId=t;try{yield 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(wh.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(wh.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(wh.TrackMuted,this.onLocalTrackMuted).on(wh.TrackUnmuted,this.onLocalTrackUnmuted).on(wh.LocalTrackPublished,this.onLocalTrackPublished).on(wh.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(wh.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(wh.MediaDevicesError,this.onMediaDevicesError).on(wh.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===pu.Connecting||this.state===pu.Reconnecting){const s=()=>{this.onTrackAdded(e,t,i),n()},n=()=>{this.off(Eh.Reconnected,s),this.off(Eh.Connected,s),this.off(Eh.Disconnected,n)};return this.once(Eh.Reconnected,s),this.once(Eh.Connected,s),void this.once(Eh.Disconnected,n)}if(this.state===pu.Disconnected)return void Bn.warn("skipping incoming track after Room disconnected");const s=function(e){const t=e.split("|");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 Bn.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;if(this.clearConnectionReconcile(),this.state!==pu.Disconnected)try{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(wh.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(wh.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(wh.TrackMuted,this.onLocalTrackMuted).off(wh.TrackUnmuted,this.onLocalTrackUnmuted).off(wh.LocalTrackPublished,this.onLocalTrackPublished).off(wh.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(wh.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(wh.MediaDevicesError,this.onMediaDevicesError).off(wh.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),bd()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),null===(i=navigator.mediaDevices)||void 0===i||i.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(pu.Disconnected),this.emit(Eh.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(Eh.ParticipantDisconnected,t))}acquireAudioContext(){var e,t;return To(this,void 0,void 0,(function*(){"boolean"!=typeof this.options.expWebAudioMix&&this.options.expWebAudioMix.audioContext?(this.audioContext=this.options.expWebAudioMix.audioContext,yield this.audioContext.resume()):this.audioContext=null!==(e=od())&&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(Eh.AudioPlaybackStatusChanged,i))}))}createParticipant(e,t){let i;return i=t?fu.fromParticipantInfo(this.engine.client,t):new fu(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(Eh.ParticipantConnected,i)),i.on(wh.TrackPublished,(e=>{this.emitWhenConnected(Eh.TrackPublished,e,i)})).on(wh.TrackSubscribed,((e,t)=>{e.kind===Rh.Kind.Audio&&(e.on(Ph.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(Ph.AudioPlaybackFailed,this.handleAudioPlaybackFailed)),this.emit(Eh.TrackSubscribed,e,t,i)})).on(wh.TrackUnpublished,(e=>{this.emit(Eh.TrackUnpublished,e,i)})).on(wh.TrackUnsubscribed,((e,t)=>{this.emit(Eh.TrackUnsubscribed,e,t,i)})).on(wh.TrackSubscriptionFailed,(e=>{this.emit(Eh.TrackSubscriptionFailed,e,i)})).on(wh.TrackMuted,(e=>{this.emitWhenConnected(Eh.TrackMuted,e,i)})).on(wh.TrackUnmuted,(e=>{this.emitWhenConnected(Eh.TrackUnmuted,e,i)})).on(wh.ParticipantMetadataChanged,(e=>{this.emitWhenConnected(Eh.ParticipantMetadataChanged,e,i)})).on(wh.ParticipantNameChanged,(e=>{this.emitWhenConnected(Eh.ParticipantNameChanged,e,i)})).on(wh.ConnectionQualityChanged,(e=>{this.emitWhenConnected(Eh.ConnectionQualityChanged,e,i)})).on(wh.ParticipantPermissionsChanged,(e=>{this.emitWhenConnected(Eh.ParticipantPermissionsChanged,e,i)})).on(wh.TrackSubscriptionStatusChanged,((e,t)=>{this.emitWhenConnected(Eh.TrackSubscriptionStatusChanged,e,t,i)})).on(wh.TrackSubscriptionFailed,((e,t)=>{this.emit(Eh.TrackSubscriptionFailed,e,i,t)})).on(wh.TrackSubscriptionPermissionChanged,((e,t)=>{this.emitWhenConnected(Eh.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:qd({sdp:i.sdp,type:i.type}),offer:s?qd({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 gu&&t.emitTrackUpdate()}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Yl.setInterval((()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?e=0:(e++,Bn.warn("detected connection state mismatch",{numFailures:e}),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Rr.STATE_MISMATCH)))}),2e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&Yl.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e!==this.state&&(this.state=e,this.emit(Eh.ConnectionStateChanged,this.state),!0)}emitWhenConnected(e){if(this.state===pu.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}simulateParticipants(e){var t,i;return To(this,void 0,void 0,(function*(){const s=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),n=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo={sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:(new Date).getTime(),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1},this.localParticipant.updateInfo(so.fromPartial({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(Eh.SignalConnected),this.emit(Eh.Connected),this.setAndEmitConnectionState(pu.Connected),s.video){const e=new hu(Rh.Kind.Video,ao.fromPartial({source:wr.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Er.AUDIO,name:"video-dummy"}),new tu(s.useRealTracks?(yield navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Id(null!==(t=160*n.aspectRatios[0])&&void 0!==t?t:1,160,!0,!0)));this.localParticipant.addTrackPublication(e),this.localParticipant.emit(wh.LocalTrackPublished,e)}if(s.audio){const e=new hu(Rh.Kind.Audio,ao.fromPartial({source:wr.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Er.AUDIO}),new jh(s.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Ad()));this.localParticipant.addTrackPublication(e),this.localParticipant.emit(wh.LocalTrackPublished,e)}for(let e=0;e<n.count-1;e+=1){let t=so.fromPartial({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:Dr.ACTIVE,tracks:[],joinedAt:Date.now()});const s=this.getOrCreateParticipant(t.identity,t);if(n.video){const a=Id(null!==(i=160*n.aspectRatios[e%n.aspectRatios.length])&&void 0!==i?i:1,160,!1,!0),r=ao.fromPartial({source:wr.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Er.AUDIO});s.addSubscribedMediaTrack(a,r.sid,new MediaStream([a])),t.tracks=[...t.tracks,r]}if(n.audio){const e=Ad(),i=ao.fromPartial({source:wr.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Er.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!==Eh.ActiveSpeakersChanged&&Bn.debug("room event ".concat(e),{event:e,args:i}),super.emit(e,...i)}}var yu;!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"}(yu||(yu={}));Jo.EventEmitter;Jo.EventEmitter;class Su 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(Qi.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 Cu 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(Rh.Source.Camera),c=r.getTrack(Rh.Source.Microphone);e.push(t().createElement(Su,{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 ku extends t().PureComponent{constructor(e){super(e),this.state={room:void 0,participants:{},activeSpeaker:void 0,previousOnInfo:void 0},this.isOutgoingCall=1==e.callState;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 fu){e.on(wh.TrackMuted,(t=>{console.log("track was muted",t.trackSid,e.identity),this.forceUpdate()})).on(wh.TrackUnmuted,(t=>{console.log("track was unmuted",t.trackSid,e.identity),this.forceUpdate()})).on(wh.IsSpeakingChanged,(e=>{this.forceUpdate()})).on(wh.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,os.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 fu&&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(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(Rh.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:[gh.h90,gh.h216],videoCodec:"vp8"},videoCaptureDefaults:{resolution:gh.h720.resolution}},i=new bu(t);this.setState({room:i});const s=Date.now(),n=(this.props.tinode.getTopic(this.props.topic),this.isOutgoingCall||!this.isBroadcast);i.on(Eh.ParticipantConnected,this.handleParticipantConnected).on(Eh.ParticipantDisconnected,this.handleParticipantDisconnected).on(Eh.DataReceived,this.handleData).on(Eh.TrackSubscribed,this.handleTrackSubscribed).on(Eh.TrackUnsubscribed,this.handleTrackUnsubscribed).on(Eh.ActiveSpeakersChanged,this.handleActiveSpeakerChange).on(Eh.Disconnected,this.handleDisconnect).on(Eh.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(Eh.LocalTrackPublished,this.handleLocalTrackPublished).on(Eh.RoomMetadataChanged,(e=>{console.log("VC room new metadata ",e)})).on(Eh.MediaDevicesChanged,this.handleDevicesChanged).on(Eh.AudioPlaybackStatusChanged,(e=>{console.log("Audio playback status change: ",e)})).on(Eh.MediaDevicesError,(e=>{const t=jl.getFailure(e);this.reportError(t)})).on(Eh.ConnectionQualityChanged,((e,t)=>{const i=t?t.identity:"nil";console.log("Connection quality changed",i," -> ",e)})).on(Eh.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,cs.Th)(this.props.title,Wi.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(Cu,{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(Qi.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 Eu=(0,s.injectIntl)(ku),wu=(0,s.defineMessages)({unrecognized_video_format:{id:"unrecognized_video_format",defaultMessage:[{type:0,value:"Format of this video is not recognized"}]}});class Tu 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(wu.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(kn,{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,es.FK)(this.props.content.size)))))}}const Pu=(0,s.injectIntl)(Tu);var Mu=r(5030);const Ru=(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 Nu(e){if(e){const t=e.getExcessive()||"";return e.isJoiner("given")&&(t.includes("R")||t.includes("W"))}return!1}function _u(e){if(e){const t=e.getMissing()||"";return e.isJoiner("want")&&(t.includes("R")||t.includes("W"))}return!1}function Du(e){return 1==e||3==e}class Iu extends t().Component{constructor(e){super(e),this.state=Iu.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,s=!1;return this.chatMessageRefs.every(((n,a)=>{if(n.current){const{top:r,bottom:o,height:c}=n.current.getBoundingClientRect();if(r<=e.top?e.top-r<=c:o-e.bottom<=c)s=!0,t=Math.min(t,a),i=Math.max(i,a);else if(s)return!1}return!0})),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&&!$i.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&&!Wi.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,os.PD)(s.public.photo)}):Object.assign(i,{title:"",avatar:null});const a=s.p2pPeerDesc();a?Object.assign(i,{peerMessagingDisabled:_u(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&&Du(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&&Du(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,subsVersion: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)),Nu(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(Wi.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 Mu.Z.navigateTo(Mu.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=Iu.getDerivedStateFromProps({},{});t.title=this.props.intl.formatMessage(Ru.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&&!this.processingScrollEvent){if(e.target.scrollTop<=40){const t=this.props.tinode.getTopic(this.state.topic);if(t&&t.isSubscribed()){this.processingScrollEvent=!0;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(Wi.Hm,n,i,s).catch((e=>this.props.onError(e.message,"err"))).finally((e=>this.setState({fetchingMessages:!1})))}))}}this.processingScrollEvent=!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,os.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:Nu(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()+Wi.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,subsVersion:this.state.subsVersion+1},s=t.p2pPeerDesc();s?Object.assign(i,{peerMessagingDisabled:_u(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)>=$i.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})),Wi.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($i.Drafty.attachJSON($i.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,Wi.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=$i.Drafty.parse(e)),e=$i.Drafty.append($i.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",Wi.kd)-1024|0;if(e.size>t){const t=this.props.tinode.getLargeFileHelper();if(!t)return void this.props.onError(this.props.intl.formatMessage(Ru.cannot_initiate_upload));const i=t.upload(e),s=$i.Drafty.attachFile(null,{mime:e.type,filename:e.name,size:e.size,urlPromise:i});this.sendMessage(s,i,t)}else(0,os.sT)(e).then((t=>this.sendMessage($i.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",Wi.GQ);e.size>t?this.props.onError(this.props.intl.formatMessage(Ru.file_attachment_too_large,{size:(0,es.FK)(e.size),limit:(0,es.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",Wi.kd)-1024|0;if(t.size>r){const r=this.props.tinode.getLargeFileHelper();if(!r)return void this.props.onError(this.props.intl.formatMessage(Ru.cannot_initiate_upload));const o=r.upload(t);(0,os.EA)(t,Wi.H2,Wi.H2,-1,!1).then((e=>(0,os.w8)(e.blob))).then((c=>{let l=$i.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=$i.Drafty.appendLineBreak(l),l=$i.Drafty.append(l,$i.Drafty.parse(e))),this.sendMessage(l,o,r)})).catch((e=>this.props.onError(e,"err")))}else(0,os.w8)(t).then((i=>{let r=$i.Drafty.insertImage(null,0,{mime:i.mime,bits:i.bits,width:s,height:n,filename:a,size:t.size});e&&(r=$i.Drafty.appendLineBreak(r),r=$i.Drafty.append(r,$i.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",Wi.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(Ru.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,os.w8)(t),(0,os.w8)(i)]).then((i=>{const[r,o]=i;let c=$i.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=$i.Drafty.appendLineBreak(c),c=$i.Drafty.append(c,$i.Drafty.parse(e))),this.sendMessage(c)}));const l=Promise.all(o),d=[];d[0]=o[0]?null:(0,os.w8)(t),d[1]=o[1]?null:(0,os.EA)(i,Wi.yW,Wi.yW,-1,!1).then((e=>(0,os.w8)(e.blob))),d[2]=(0,os.EA)(i,Wi.ly,Wi.ly,-1,!1).then((e=>(0,os.w8)(e.blob))),Promise.all(d).then((i=>{const[r,o,d]=i;let h=$i.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=$i.Drafty.appendLineBreak(h),h=$i.Drafty.append(h,$i.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",Wi.GQ);e.type.startsWith("video/")?this.setState({videoPreview:{url:URL.createObjectURL(e),blob:e,filename:e.name,size:e.size,mime:e.type}}):(0,os.EA)(e,Wi.yW,Wi.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",Wi.kd)-1024;if(e.size>s){const s=this.props.tinode.getLargeFileHelper();if(!s)return void this.props.onError(this.props.intl.formatMessage(Ru.cannot_initiate_upload));const n=s.upload(e),a=$i.Drafty.appendAudio(null,{mime:e.type,size:e.size,duration:i,preview:t,urlPromise:n});this.sendMessage(a,n,s)}else(0,os.w8)(e).then((s=>{this.sendMessage($i.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?$i.Drafty.init(t):t,t=$i.Drafty.isValid(t)?$i.Drafty.replyContent(t,Wi.cl):$i.Drafty.append($i.Drafty.init("⚠ "),$i.Drafty.wrapInto(this.props.intl.formatMessage(Ru.invalid_content),"EM")),this.setState({reply:{content:$i.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?$i.Drafty.init(t):t;const i=$i.Drafty.toMarkdown(t);t=$i.Drafty.isValid(t)?$i.Drafty.replyContent(t,Wi.nT):$i.Drafty.append($i.Drafty.init("⚠ "),$i.Drafty.wrapInto(this.props.intl.formatMessage(Ru.invalid_content),"EM")),this.setState({reply:{content:$i.Drafty.quote(this.props.intl.formatMessage(Ru.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(Tn,{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(Pu,{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(Tn,{content:this.state.imagePostview,onClose:this.handleClosePreview});else if(this.state.videoPostview)n=t().createElement(Pu,{content:this.state.videoPostview,tinode:this.props.tinode,onError:this.props.onError,onClose:this.handleClosePreview});else if(this.state.docPreview)n=t().createElement(En,{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=$i.Tinode.isP2PTopicName(this.state.rtcPanel)?t().createElement(dn,{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(Eu,{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,os.PD)(y.public.photo)),u=r?"chat-box group":"chat-box";const S=this.getOrCreateMessageRef(e.seq);let C=e.head?parseInt(e.head.reply):null;if(C&&!isNaN(C)||(C=null),e.hi)l.push(t().createElement(Nn,{deleted:!0,key:e.seq}));else{const i=new Date(e.ts);h&&h.toDateString()==i.toDateString()||(l.push(t().createElement(Nn,{date:(0,es.EZ)(e.ts),locale:this.props.intl.locale,key:"date-"+e.seq})),h=i),l.push(t().createElement(bn,{tinode:this.props.tinode,topic:this.state.topic,content:e.content,mimeType:e.head&&e.head.mime,replyToSeq:C,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(Ru.channel);else{const t=this.props.tinode.getMeTopic().getContact(this.state.topic);t&&$i.Tinode.isP2PTopicName(t.topic)&&(t.online?p=e(Ru.online_now):t.seen&&(p=e(Ru.last_seen)+": "+(0,es.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(Pn,{onAction:this.handleNewChatAcceptance}):t().createElement(kn,{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(Qi.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(Ki,{badges:o})),t().createElement("div",{id:"topic-last-seen"},p)),t().createElement("div",{style:{marginLeft:"auto"}}),this.props.displayMobile?null:t().createElement(Dn,{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(wn,{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(Dn,{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(Us,{level:this.props.errorLevel,text:this.props.errorText,onClearError:this.props.onError})):null,t().createElement(Mn.Z,{show:this.state.fetchingMessages}),v,this.state.dragging&&this.isDragEnabled()?t().createElement("div",{className:"drag-n-drop"},e(Ru.drag_file)):null)}i=t().createElement("div",{id:"topic-view",ref:this.mountDnDEvents},n)}else i=t().createElement(Rn,{serverVersion:this.props.serverVersion,serverAddress:this.props.serverAddress});return i}}const Au=(0,s.injectIntl)(Iu);class Ou 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 Uu 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 xu 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 Lu 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,cs.Fv)(this.props.avatar,"image"))),t().createElement("div",{id:"side-caption-panel",className:"caption-panel"},this.props.onCancel?t().createElement(Ou,{onBack:this.props.onCancel}):null,i?t().createElement("div",{id:"self-avatar",className:"avatar-box"},t().createElement(Qi.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(Ki,{badges:e})),"login"===this.props.state?t().createElement(xu,{onSignUp:this.props.onSignUp,onSettings:this.props.onSettings}):"contacts"===this.props.state?t().createElement(Uu,{onNewTopic:this.props.onNewTopic,onSettings:this.props.onSettings}):null)}}const Fu=(0,s.defineMessages)({archived_contacts_title:{id:"archived_contacts",defaultMessage:[{type:0,value:"Archived contacts ("},{type:1,value:"count"},{type:0,value:")"}]}});class Bu extends t().Component{constructor(e){super(e),this.handleAction=this.handleAction.bind(this),this.state=Bu.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:Fu.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=Bu.deriveStateFromProps(this.props);this.setState(e),e.unreadThreads!=t.unreadThreads&&(0,cs.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(Ts,{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 ju 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(As.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(As.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(As.Z,{name:"incognito",id:"incognito-mode",checked:this.props.incognitoMode,onChange:this.handleCheckboxClick})))}}const qu=(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 Vu 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(qu.delete_account),t(qu.delete_account_warning),(e=>this.props.onDeleteAccount()),null,!0,null)}render(){return t().createElement(t().Fragment,null,this.state.showPermissionEditorFor?t().createElement($s,{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(Hs,{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 $u=(0,s.injectIntl)(Vu);class Ju extends t().PureComponent{render(){return t().createElement("div",{className:"scrollable-panel"},t().createElement("div",{className:"panel-form-column"},t().createElement("a",{href:Wi.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:Wi.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:Wi.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:"}]})),Wi.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:"}]})),$i.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 Wu 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(Ws.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(As.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 Hu=(0,s.defineMessages)({invalid_id:{id:"error_invalid_id",defaultMessage:[{type:0,value:"Invalid ID"}]}});class Gu 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(Hu.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 Zu=(0,s.injectIntl)(Gu);class zu 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>Wi.uv){this.props.tinode.getLargeFileHelper().upload(i).then((e=>this.setState({imageUrl:e}))).catch((e=>this.props.onError(e.message,"err")))}else(0,os.w8)(i).then((e=>this.setState({imageUrl:(0,os.PD)({data:e.bits,type:t})})))};i>Wi.IX||s>Wi.IX||i!=s?(0,os.EA)(t,Wi.IX,Wi.IX,Wi.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,Wi.S8),i=this.state.private.trim().substring(0,Wi.S8),s=this.state.description.trim().substring(0,Wi.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(Js.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(Is.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(As.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(Gs,{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 Ku=(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 Qu 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(),Mu.Z.navigateTo(Mu.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:$i.Tinode.isNullValue(e)?null:e})}handleSearchResultSelected(e){"find"==this.state.tabSelected&&(Mu.Z.navigateTo(Mu.Z.removeUrlParam(window.location.hash,"tab")),this.props.onCreateTopic(e))}handleNewGroupSubmit(e,t,i,s,n,a){Mu.Z.navigateTo(Mu.Z.removeUrlParam(window.location.hash,"tab")),this.props.onCreateTopic(void 0,{public:(0,cs.n$)(e,i,null,t),private:s,tags:n},a)}handleGroupByID(e){Mu.Z.navigateTo(Mu.Z.removeUrlParam(window.location.hash,"tab")),this.props.onCreateTopic(e)}render(){const{formatMessage:e}=this.props.intl,i=e(this.state.searchQuery?Ku.search_no_results:Ku.search_for_contacts),n=e(Ku.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(zu,{tinode:this.props.tinode,onSubmit:this.handleNewGroupSubmit,onError:this.props.onError}):"byid"===this.state.tabSelected?t().createElement(Zu,{onSubmit:this.handleGroupByID,onError:this.props.onError}):t().createElement("div",{className:"flex-column"},t().createElement(Ps,{placeholder:n,onSearchContacts:this.handleSearchContacts}),t().createElement(Ts,{tinode:this.props.tinode,contacts:this.props.searchResults,myUserId:this.props.myUserId,emptyListMessage:i,showOnline:!1,showUnread:!1,showContextMenu:!1,onTopicSelected:this.handleSearchResultSelected})))}}const Yu=(0,s.injectIntl)(Qu);class Xu 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 Wi.Rc){let s=Wi.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 ep 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(Xu,{serverAddress:this.state.serverAddress,onServerAddressChange:this.handleServerAddressChange}),t().createElement("div",{className:"panel-form-row"},t().createElement(As.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 tp=(0,s.defineMessages)({phone:{id:"phone_dative",defaultMessage:[{type:0,value:"phone"}]},email:{id:"email_dative",defaultMessage:[{type:0,value:"email"}]}});class ip 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(tp.email),tel:e(tp.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 sp=(0,s.injectIntl)(ip),np=t().lazy((e=>Promise.all([r.e(203),r.e(365)]).then(r.bind(r,1365)))),ap=t().lazy((e=>Promise.all([r.e(203),r.e(327)]).then(r.bind(r,327)))),rp=t().lazy((e=>Promise.all([r.e(203),r.e(311)]).then(r.bind(r,1311)))),op=(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 cp 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(op[n]),r=!1,o=null),-1==["login","contacts"].indexOf(n)&&(c=this.props.onCancel),t().createElement("div",{id:"sidepanel"},t().createElement(Lu,{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(Us,{level:this.props.errorLevel,text:this.props.errorText,action:this.props.errorAction,actionText:this.props.errorActionText,onClearError:this.props.onError}),t().createElement(Mn.Z,{show:this.props.loadSpinnerVisible}),"login"===n?t().createElement(Wu,{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(ap,{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(ep,{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(np,{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(zs,{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(ju,{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($u,{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(Ju,{serverAddress:this.props.serverAddress,serverVersion:this.props.serverVersion}):"contacts"===n||"archive"==n||"blocked"==n?t().createElement(Bu,{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(Yu,{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(sp,{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(rp,{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 lp=(0,s.injectIntl)(cp);var dp=r(3119);function hp(){let e=Wi.Mv;return"object"==typeof window.location&&("file:"==window.location.protocol||"localhost"==window.location.hostname?e=Wi.Rc.local:window.location.hostname&&(e=window.location.hostname+(window.location.port?":"+window.location.port:""))),e}function up(){return"object"==typeof window.location&&"https:"==window.location.protocol}var pp=r(320);const mp=t().lazy((e=>r.e(290).then(r.bind(r,1290)))),gp=new Audio("audio/msg.m4a"),fp=(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"}]},password_reset_success:{id:"password_reset_success",defaultMessage:[{type:0,value:"Password reset successfully"}]}});class vp 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=pp.Z.getObject("settings")||{},t=!!pp.Z.getObject("keep-logged-in");return{connected:!1,ready:!1,autoLogin:!1,transport:e.transport||null,serverAddress:e.serverAddress||hp(),secureConnection:void 0===e.secureConnection?up():e.secureConnection,serverVersion:"no connection",messageSounds:!e.messageSoundsOff,incognitoMode:!1,desktopAlerts:t&&!!e.desktopAlerts,desktopAlertsEnabled:(up()||"object"==typeof window.location&&"localhost"==window.location.hostname)&&void 0!==ce&&"undefined"!=typeof navigator&&"undefined"!=typeof FIREBASE_INIT,firebaseToken:t?pp.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<=Wi.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=vp.tnSetup(this.state.serverAddress,up(),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?pp.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=Mu.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?Mu.Z.addUrlParam("","cred_done",i.params.cred_done):"";Mu.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 $i.Tinode({appName:Wi.iC,host:e,apiKey:Wi.$h,transport:i,secure:t,persist:n},a);return r.setHumanLanguage(s),r.enableLogging(Wi.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(fp.push_init_failed),"err"),this.setState({firebaseToken:null}),pp.Z.updateObject("settings",{desktopAlerts:!1})};try{return this.fcm=Bi(ce(FIREBASE_INIT,Wi.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:dp.l})),vp.requestFCMToken(this.fcm,e)))).then((e=>{const t=pp.Z.getObject("keep-logged-in");e!=this.state.firebaseToken&&(this.tinode.setDeviceToken(e),t&&pp.Z.setObject("firebase-token",e)),this.setState({firebaseToken:e,desktopAlerts:!0}),t&&pp.Z.updateObject("settings",{desktopAlerts:!0}),Vi(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 ji(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 ji(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<=Wi.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=Mu.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&&($i.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,vp.stateForError(this.props.intl.formatMessage(fp.cred_confirmed_successfully),"info")),this.setState(t)}handleOnline(e){e?(this.handleError(),clearInterval(this.reconnectCountdown),this.tinode.reconnect()):this.handleError(this.props.intl.formatMessage(fp.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(vp.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=>{pp.Z.setObject("keep-logged-in",!0),this.setState({persist:!0})})):this.tinode.clearStorage().then((e=>{pp.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,es.nH)(s):s;this.handleError(i(fp.reconnect_countdown,{seconds:t}),"warn",(e=>{clearInterval(this.reconnectCountdown),this.tinode.reconnect()}),i(fp.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 Mu.Z.navigateTo("");let n=i||(this.tinode.getAuthToken()||{}).token;if(!(e&&t||n))return Mu.Z.navigateTo(""),void this.setState({loginDisabled:!1});s=$i.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(fp.code_doesnot_match),"warn"),vp.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(),Mu.Z.navigateTo(""))}))}static navigateToCredentialsView(e){const t=Mu.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,Mu.Z.navigateTo(Mu.Z.composeUrlHash(t.path,t.params))}handleLoginSuccessful(){this.handleError(),pp.Z.getObject("keep-logged-in")&&pp.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"),Mu.Z.navigateTo("")})).finally((e=>{this.setState({loadSpinnerVisible:!1})}));let i=Mu.Z.setUrlSidePanel(window.location.hash,"contacts");e&&(i=Mu.Z.setUrlTopic(i,e)),Mu.Z.navigateTo(i)}tnMeMetaDesc(e){if(e){if(e.public&&this.setState({sidePanelTitle:e.public.fn,sidePanelAvatar:(0,os.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)&&gp.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)$i.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=vp.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:vp.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}),Mu.Z.navigateTo(Mu.Z.setUrlTopic("",e)))):(this.setState({topicSelected:null,errorText:"",errorLevel:null,mobilePanel:"sidepanel",topicSelectedOnline:!1,topicSelectedAcs:null,infoPanel:void 0,forwardMessage:null}),Mu.Z.navigateTo(Mu.Z.setUrlTopic("",null)))}handleHideMessagesView(){this.setState({mobilePanel:"sidepanel"}),Mu.Z.navigateTo(Mu.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(),Mu.Z.navigateTo(Mu.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:$i.Tinode.credential(s),attachments:r})})).then((e=>{e.code>=300&&"validate credentials"==e.text?vp.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(),Mu.Z.navigateTo(Mu.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=vp.tnSetup(t,s,i,this.props.intl.locale,pp.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}),pp.Z.setObject("settings",{serverAddress:t,transport:i,secureConnection:s}),Mu.Z.navigateTo(Mu.Z.setUrlSidePanel(window.location.hash,""))}handleShowArchive(){Mu.Z.navigateTo(Mu.Z.setUrlSidePanel(window.location.hash,this.state.myUserId?"archive":""))}handleShowBlocked(){Mu.Z.navigateTo(Mu.Z.setUrlSidePanel(window.location.hash,this.state.myUserId?"blocked":""))}toggleFCMToken(e){e?(this.setState({desktopAlerts:null}),this.state.firebaseToken?(this.setState({desktopAlerts:!0}),pp.Z.getObject("keep-logged-in")&&pp.Z.updateObject("settings",{desktopAlerts:!0})):this.initFCMessaging()):this.state.firebaseToken&&this.fcm?qi(this.fcm).catch((e=>{console.error("Unable to delete token.",e)})).finally((e=>{pp.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}),pp.Z.updateObject("settings",{desktopAlerts:!1}))}handleToggleMessageSounds(e){this.setState({messageSounds:e}),pp.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){vp.navigateToCredentialsView({cred:[e],code:t})}handleSidepanelCancel(){const e=Mu.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),Mu.Z.navigateTo(Mu.Z.composeUrlHash(e.path,e.params)),this.setState({errorText:"",errorLevel:null})}basicNavigator(e){Mu.Z.navigateTo(Mu.Z.setUrlSidePanel(window.location.hash,e))}infoNavigator(e){Mu.Z.navigateTo(Mu.Z.setUrlInfoPanel(window.location.hash,e))}handleStartTopicRequest(e,t,i){if(e&&this.tinode.isTopicCached(e))return void this.handleTopicSelected(e);const s={};$i.Tinode.isP2PTopicName(e)?(s.sub={mode:Wi.RK},s.desc={defacs:{auth:Wi.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:3,callShouldStart:!1}),this.state.topicSelected==e&&e!=t&&(i.topicSelected=t),this.setState(i,(e=>{Mu.Z.navigateTo(Mu.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!=$i.Tinode.DEL_CHAR?a=[t.photo.ref]:t.photo.data&&t.photo.data!=$i.Tinode.DEL_CHAR||(t.photo=$i.Tinode.DEL_CHAR)),e.public=t),"string"==typeof i&&(e.private=i===$i.Tinode.DEL_CHAR?$i.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,cs.J_)(0),localStorage.removeItem("auth-token"),localStorage.removeItem("firebase-token"),localStorage.removeItem("settings"),this.state.firebaseToken&&qi(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=vp.tnSetup(this.state.serverAddress,up(),this.state.transport,this.props.intl.locale,pp.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,Mu.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=>{Mu.Z.navigateTo(Mu.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=>{Mu.Z.navigateTo(Mu.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=>{Mu.Z.navigateTo(Mu.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=>{Mu.Z.navigateTo(Mu.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?$i.Drafty.init(e.content):$i.Drafty.forwardedContent(e.content),s=$i.Drafty.preview(i,Wi.vX,!0),n=$i.Drafty.append($i.Drafty.appendLineBreak($i.Drafty.mention(t,e.userFrom)),i),a=$i.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(fp.menu_item_info),handler:this.handleShowInfoView}:null,a&&$i.Tinode.isP2PTopicName(e)&&c?{title:this.props.intl.formatMessage(fp.menu_item_audio_call),handler:this.handleStartAudioCall}:null,a&&c?{title:this.props.intl.formatMessage(fp.menu_item_video_call),disabled:$i.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(){Mu.Z.navigateTo(Mu.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=>Mu.Z.navigateTo(Mu.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,os.DC)(t.secret);i&&t.scheme?this.tinode.connect().then((s=>this.tinode.updateAccountBasic(null,null,e,{scheme:t.scheme,secret:i}))).then((e=>{this.handleError(this.props.intl.formatMessage(fp.password_reset_success),"info"),Mu.Z.navigateTo("")})).catch((e=>{this.handleError(e.message,"err")})):this.handleError(this.props.intl.formatMessage(fp.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(mp,{selected:i,onSubmit:(e,t)=>{this.setState({alertVisible:!1}),a(e,t)}})),null,null,(e=>{}),"Cancel")}handleStartVideoCall(){this.setState({callTopic:this.state.topicSelected,callState:1,callAudioOnly:!1})}handleStartAudioCall(){this.setState({callTopic:this.state.topicSelected,callState:1,callAudioOnly:!0})}handleCallInvite(e,t,i,s){switch(i){case 1:const i={webrtc:Ns,aonly:!!s},n=$i.Drafty.videoCall(s);return $i.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 3: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:3};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($i.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:3});break;case"hang-up":this.handleCallClose()}}handleDataMessage(e){if(e.head&&e.head.webrtc&&e.head.webrtc==Ns&&$i.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==Ns&&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(Zi,{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(Ms,{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(Ds,{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(Ji,{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(lp,{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(Au,{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(tn,{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 bp=(0,s.injectIntl)(vp);if("undefined"!=typeof FIREBASE_INIT&&FIREBASE_INIT&&FIREBASE_INIT.measurementId){const Mp=document.getElementsByTagName("head")[0];let Rp=document.createElement("script");function Np(){dataLayer.push(arguments)}Rp.src="https://www.googletagmanager.com/gtag/js?id="+FIREBASE_INIT.measurementId,Rp.async=!0,Mp.prepend(Rp),window.dataLayer=window.dataLayer||[],Np("js",new Date),Np("config",FIREBASE_INIT.measurementId)}const yp={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:Sp}=Mu.Z.parseUrlHash(window.location.hash),Cp=Sp&&Sp.hl||navigator.languages&&navigator.languages[0]||navigator.language||navigator.userLanguage||"en",kp=Cp.replace("_","-"),Ep=kp.split("-")[0].toLowerCase(),wp=yp[kp]?Cp:yp[Ep]?Ep:"en";document.getElementsByTagName("html")[0].setAttribute("lang",wp);const Tp=(0,i.s)(document.getElementById("mountPoint"));yp[wp]().then((e=>Tp.render(t().createElement(s.IntlProvider,{locale:Cp,messages:e,textComponent:t().Fragment},t().createElement(bp,null)))))})()})();
//# sourceMappingURL=index.prod.js.map