liveroom-client-element 0.0.49 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/constants-Crg5Qc0w.js +3 -0
- package/dist/constants-X_93hTEi.cjs +1 -0
- package/dist/livekit-client.esm-B1rknK61.js +19569 -0
- package/dist/livekit-client.esm-DiyxitqE.cjs +39 -0
- package/dist/liveroom-client-element.cjs +59 -56
- package/dist/liveroom-client-element.js +1542 -19395
- package/dist/main.cjs +1 -1
- package/dist/main.js +37 -59
- package/package.json +14 -14
- package/dist/constants-C8O2fXxM.js +0 -57
- package/dist/constants-mjPxcM4R.cjs +0 -1
|
@@ -1,63 +1,66 @@
|
|
|
1
|
-
"use strict";var Tc=Object.defineProperty;var Cc=(n,e,t)=>e in n?Tc(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var x=(n,e,t)=>(Cc(n,typeof e!="symbol"?e+"":e,t),t);const Fs=require("./constants-mjPxcM4R.cjs");function mn(){}function zr(n){return n()}function Bs(){return Object.create(null)}function Cn(n){n.forEach(zr)}function Wr(n){return typeof n=="function"}function Sc(n,e){return n!=n?e==e:n!==e||n&&typeof n=="object"||typeof n=="function"}function _c(n){return Object.keys(n).length===0}function we(n,e){n.appendChild(e)}function Ec(n,e,t){const i=wc(n);if(!i.getElementById(e)){const s=Ne("style");s.id=e,s.textContent=t,Pc(i,s)}}function wc(n){if(!n)return document;const e=n.getRootNode?n.getRootNode():n.ownerDocument;return e&&e.host?e:n.ownerDocument}function Pc(n,e){return we(n.head||n,e),e.sheet}function Tt(n,e,t){n.insertBefore(e,t||null)}function ut(n){n.parentNode&&n.parentNode.removeChild(n)}function Ne(n){return document.createElement(n)}function Vs(n){return document.createElementNS("http://www.w3.org/2000/svg",n)}function ps(n){return document.createTextNode(n)}function en(){return ps(" ")}function Rc(){return ps("")}function V(n,e,t){t==null?n.removeAttribute(e):n.getAttribute(e)!==t&&n.setAttribute(e,t)}function Ic(n){return Array.from(n.childNodes)}function Oc(n,e){e=""+e,n.data!==e&&(n.data=e)}function Ve(n,e,t,i){t==null?n.style.removeProperty(e):n.style.setProperty(e,t,"")}function Mc(n){const e={};return n.childNodes.forEach(t=>{e[t.slot||"default"]=!0}),e}let gn;function an(n){gn=n}function Jr(){if(!gn)throw new Error("Function called outside component initialization");return gn}function xc(n){Jr().$$.on_mount.push(n)}function Ac(n){Jr().$$.on_destroy.push(n)}const At=[],Ai=[];let Lt=[];const $s=[],Dc=Promise.resolve();let Di=!1;function Nc(){Di||(Di=!0,Dc.then(ct))}function Ni(n){Lt.push(n)}const bi=new Set;let It=0;function ct(){if(It!==0)return;const n=gn;do{try{for(;It<At.length;){const e=At[It];It++,an(e),Lc(e.$$)}}catch(e){throw At.length=0,It=0,e}for(an(null),At.length=0,It=0;Ai.length;)Ai.pop()();for(let e=0;e<Lt.length;e+=1){const t=Lt[e];bi.has(t)||(bi.add(t),t())}Lt.length=0}while(At.length);for(;$s.length;)$s.pop()();Di=!1,bi.clear(),an(n)}function Lc(n){if(n.fragment!==null){n.update(),Cn(n.before_update);const e=n.dirty;n.dirty=[-1],n.fragment&&n.fragment.p(n.ctx,e),n.after_update.forEach(Ni)}}function Uc(n){const e=[],t=[];Lt.forEach(i=>n.indexOf(i)===-1?e.push(i):t.push(i)),t.forEach(i=>i()),Lt=e}const jc=new Set;function Kr(n,e){n&&n.i&&(jc.delete(n),n.i(e))}function Hs(n){return(n==null?void 0:n.length)!==void 0?n:Array.from(n)}function Fc(n,e){n.d(1),e.delete(n.key)}function Bc(n,e,t,i,s,r,a,o,c,d,l,u){let p=n.length,m=r.length,k=p;const v={};for(;k--;)v[n[k].key]=k;const S=[],O=new Map,w=new Map,F=[];for(k=m;k--;){const N=u(s,r,k),X=t(N);let A=a.get(X);A?F.push(()=>A.p(N,e)):(A=d(X,N),A.c()),O.set(X,S[k]=A),X in v&&w.set(X,Math.abs(k-v[X]))}const W=new Set,he=new Set;function de(N){Kr(N,1),N.m(o,l),a.set(N.key,N),l=N.first,m--}for(;p&&m;){const N=S[m-1],X=n[p-1],A=N.key,H=X.key;N===X?(l=N.first,p--,m--):O.has(H)?!a.has(A)||W.has(A)?de(N):he.has(H)?p--:w.get(A)>w.get(H)?(he.add(A),de(N)):(W.add(H),p--):(c(X,a),p--)}for(;p--;){const N=n[p];O.has(N.key)||c(N,a)}for(;m;)de(S[m-1]);return Cn(F),S}function Vc(n,e,t){const{fragment:i,after_update:s}=n.$$;i&&i.m(e,t),Ni(()=>{const r=n.$$.on_mount.map(zr).filter(Wr);n.$$.on_destroy?n.$$.on_destroy.push(...r):Cn(r),n.$$.on_mount=[]}),s.forEach(Ni)}function $c(n,e){const t=n.$$;t.fragment!==null&&(Uc(t.after_update),Cn(t.on_destroy),t.fragment&&t.fragment.d(e),t.on_destroy=t.fragment=null,t.ctx=[])}function Hc(n,e){n.$$.dirty[0]===-1&&(At.push(n),Nc(),n.$$.dirty.fill(0)),n.$$.dirty[e/31|0]|=1<<e%31}function qc(n,e,t,i,s,r,a=null,o=[-1]){const c=gn;an(n);const d=n.$$={fragment:null,ctx:[],props:r,update:mn,not_equal:s,bound:Bs(),on_mount:[],on_destroy:[],on_disconnect:[],before_update:[],after_update:[],context:new Map(e.context||(c?c.$$.context:[])),callbacks:Bs(),dirty:o,skip_bound:!1,root:e.target||c.$$.root};a&&a(d.root);let l=!1;if(d.ctx=t?t(n,e.props||{},(u,p,...m)=>{const k=m.length?m[0]:p;return d.ctx&&s(d.ctx[u],d.ctx[u]=k)&&(!d.skip_bound&&d.bound[u]&&d.bound[u](k),l&&Hc(n,u)),p}):[],d.update(),l=!0,Cn(d.before_update),d.fragment=i?i(d.ctx):!1,e.target){if(e.hydrate){const u=Ic(e.target);d.fragment&&d.fragment.l(u),u.forEach(ut)}else d.fragment&&d.fragment.c();e.intro&&Kr(n.$$.fragment),Vc(n,e.target,e.anchor),ct()}an(c)}let Qr;typeof HTMLElement=="function"&&(Qr=class extends HTMLElement{constructor(e,t,i){super();x(this,"$$ctor");x(this,"$$s");x(this,"$$c");x(this,"$$cn",!1);x(this,"$$d",{});x(this,"$$r",!1);x(this,"$$p_d",{});x(this,"$$l",{});x(this,"$$l_u",new Map);this.$$ctor=e,this.$$s=t,i&&this.attachShadow({mode:"open"})}addEventListener(e,t,i){if(this.$$l[e]=this.$$l[e]||[],this.$$l[e].push(t),this.$$c){const s=this.$$c.$on(e,t);this.$$l_u.set(t,s)}super.addEventListener(e,t,i)}removeEventListener(e,t,i){if(super.removeEventListener(e,t,i),this.$$c){const s=this.$$l_u.get(t);s&&(s(),this.$$l_u.delete(t))}}async connectedCallback(){if(this.$$cn=!0,!this.$$c){let e=function(r){return()=>{let a;return{c:function(){a=Ne("slot"),r!=="default"&&V(a,"name",r)},m:function(d,l){Tt(d,a,l)},d:function(d){d&&ut(a)}}}};if(await Promise.resolve(),!this.$$cn||this.$$c)return;const t={},i=Mc(this);for(const r of this.$$s)r in i&&(t[r]=[e(r)]);for(const r of this.attributes){const a=this.$$g_p(r.name);a in this.$$d||(this.$$d[a]=jn(a,r.value,this.$$p_d,"toProp"))}for(const r in this.$$p_d)!(r in this.$$d)&&this[r]!==void 0&&(this.$$d[r]=this[r],delete this[r]);this.$$c=new this.$$ctor({target:this.shadowRoot||this,props:{...this.$$d,$$slots:t,$$scope:{ctx:[]}}});const s=()=>{this.$$r=!0;for(const r in this.$$p_d)if(this.$$d[r]=this.$$c.$$.ctx[this.$$c.$$.props[r]],this.$$p_d[r].reflect){const a=jn(r,this.$$d[r],this.$$p_d,"toAttribute");a==null?this.removeAttribute(this.$$p_d[r].attribute||r):this.setAttribute(this.$$p_d[r].attribute||r,a)}this.$$r=!1};this.$$c.$$.after_update.push(s),s();for(const r in this.$$l)for(const a of this.$$l[r]){const o=this.$$c.$on(r,a);this.$$l_u.set(a,o)}this.$$l={}}}attributeChangedCallback(e,t,i){var s;this.$$r||(e=this.$$g_p(e),this.$$d[e]=jn(e,i,this.$$p_d,"toProp"),(s=this.$$c)==null||s.$set({[e]:this.$$d[e]}))}disconnectedCallback(){this.$$cn=!1,Promise.resolve().then(()=>{this.$$cn||(this.$$c.$destroy(),this.$$c=void 0)})}$$g_p(e){return Object.keys(this.$$p_d).find(t=>this.$$p_d[t].attribute===e||!this.$$p_d[t].attribute&&t.toLowerCase()===e)||e}});function jn(n,e,t,i){var r;const s=(r=t[n])==null?void 0:r.type;if(e=s==="Boolean"&&typeof e!="boolean"?e!=null:e,!i||!t[n])return e;if(i==="toAttribute")switch(s){case"Object":case"Array":return e==null?null:JSON.stringify(e);case"Boolean":return e?"":null;case"Number":return e??null;default:return e}else switch(s){case"Object":case"Array":return e&&JSON.parse(e);case"Boolean":return e;case"Number":return e!=null?+e:e;default:return e}}function Gc(n,e,t,i,s,r){let a=class extends Qr{constructor(){super(n,t,s),this.$$p_d=e}static get observedAttributes(){return Object.keys(e).map(o=>(e[o].attribute||o).toLowerCase())}};return Object.keys(e).forEach(o=>{Object.defineProperty(a.prototype,o,{get(){return this.$$c&&o in this.$$c?this.$$c[o]:this.$$d[o]},set(c){var d;c=jn(o,c,e),this.$$d[o]=c,(d=this.$$c)==null||d.$set({[o]:c})}})}),i.forEach(o=>{Object.defineProperty(a.prototype,o,{get(){var c;return(c=this.$$c)==null?void 0:c[o]}})}),n.element=a,a}class zc{constructor(){x(this,"$$");x(this,"$$set")}$destroy(){$c(this,1),this.$destroy=mn}$on(e,t){if(!Wr(t))return mn;const i=this.$$.callbacks[e]||(this.$$.callbacks[e]=[]);return i.push(t),()=>{const s=i.indexOf(t);s!==-1&&i.splice(s,1)}}$set(e){this.$$set&&!_c(e)&&(this.$$.skip_bound=!0,this.$$set(e),this.$$.skip_bound=!1)}}const Wc="4";typeof window<"u"&&(window.__svelte||(window.__svelte={v:new Set})).v.add(Wc);const{isArray:Jc}=Array,Kc=Object.keys,vn=n=>{if(!n)return n;if(Jc(n)){const e=[],t=n.length;for(let i=0;i<t;i++)e.push(vn(n[i]));return e}else if(typeof n=="object"){const e=Kc(n),t=e.length,i={};for(let s=0;s<t;s++){const r=e[s];i[r]=vn(n[r])}return i}return n};class Re{constructor(e){x(this,"path");x(this,"from");this.path=e}}const Qc=/~1/g,Yc=/~0/g,Xc=/~/g,Zc=/\//g;function ed(n){return n.indexOf("~")===-1?n:n.replace(Qc,"/").replace(Yc,"~")}function td(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(Xc,"~0").replace(Zc,"~1")}function nd(n){return n?n.slice(1).split("/").map(ed):[]}function z(n){return id(n)?"":"/"+n.map(e=>td(String(e))).join("/")}const B=n=>typeof n=="string"?nd(n):n,id=n=>!n.length,sd=Object.prototype.hasOwnProperty;function rd(n,e){return sd.call(n,e)}const{isArray:Yr}=Array,ne=(n,e)=>{const t=e.length;if(!t)return{val:n};let i,s;for(let a=0;a<t;a++)if(i=n,s=e[a],Yr(i)){const o=i.length;if(s==="-")s=o;else if(typeof s=="string"){const c=~~s;if(""+c!==s)throw new Error("INVALID_INDEX");if(s=c,s<0)throw new Error("INVALID_INDEX")}n=i[s]}else if(typeof i=="object"&&i)n=rd(i,s)?i[s]:void 0;else throw new Error("NOT_FOUND");return{val:n,obj:i,key:s}},Sn=n=>Yr(n.obj)&&typeof n.key=="number",ai=n=>typeof n.obj=="object"&&typeof n.key=="string";class fs extends Re{constructor(t,i){super(t);x(this,"value");this.value=i}op(){return"add"}code(){return 0}apply(t){const{val:i,key:s,obj:r}=ne(t,this.path),a=vn(this.value);if(!r)t=a;else if(typeof s=="string")r[s]=a;else{const o=r.length;if(s<o)r.splice(s,0,a);else{if(s>o)throw new Error("INVALID_INDEX");r.push(a)}}return{doc:t,old:i}}toJson(t){return{op:"add",path:z(this.path),value:this.value}}toCompact(t,i){return[i?"add":0,this.path,this.value]}encode(t){t.encodeArrayHeader(3),t.writer.u8(0),t.encodeArray(this.path),t.encodeAny(this.value)}}class Xr extends Re{constructor(t,i){super(t);x(this,"oldValue");this.oldValue=i}op(){return"remove"}code(){return 1}apply(t){const i=ne(t,this.path);if(i.val===void 0)throw new Error("NOT_FOUND");return ai(i)?delete i.obj[i.key]:Sn(i)?i.val!==void 0&&i.obj.splice(i.key,1):t=null,{doc:t,old:i.val}}toJson(t){const i={op:"remove",path:z(this.path)};return this.oldValue!==void 0&&(i.oldValue=this.oldValue),i}toCompact(t,i){const s=i?"remove":1;return this.oldValue===void 0?[s,this.path]:[s,this.path,this.oldValue]}encode(t,i){const s=this.oldValue!==void 0;t.encodeArrayHeader(s?3:2),t.writer.u8(1),t.encodeArray(this.path),s&&t.encodeAny(this.oldValue)}}class ad extends Re{constructor(t,i,s){super(t);x(this,"value");x(this,"oldValue");this.value=i,this.oldValue=s}op(){return"replace"}code(){return 2}apply(t){const i=ne(t,this.path);if(i.val===void 0)throw new Error("NOT_FOUND");return ai(i)?i.obj[i.key]=this.value:Sn(i)?i.obj[i.key]=this.value:t=this.value,{doc:t,old:i.val}}toJson(t){const i={op:"replace",path:z(this.path),value:this.value};return this.oldValue!==void 0&&(i.oldValue=this.oldValue),i}toCompact(t,i){const s=i?"replace":2;return this.oldValue===void 0?[s,this.path,this.value]:[s,this.path,this.value,this.oldValue]}encode(t,i){const s=this.oldValue!==void 0;t.encodeArrayHeader(s?4:3),t.writer.u8(2),t.encodeArray(this.path),t.encodeAny(this.value),s&&t.encodeAny(this.oldValue)}}class od extends Re{constructor(t,i){super(t);x(this,"from");this.from=i}op(){return"move"}code(){return 4}apply(t){const i=new Xr(B(this.from),void 0).apply(t);return new fs(this.path,i.old).apply(i.doc)}toJson(t){return{op:"move",path:z(this.path),from:z(this.from)}}toCompact(t,i){return[i?"move":4,this.path,this.from]}encode(t,i){t.encodeArrayHeader(3),t.writer.u8(4),t.encodeArray(this.path),t.encodeArray(this.from)}}class cd extends Re{constructor(t,i){super(t);x(this,"from");this.from=i}op(){return"copy"}code(){return 3}apply(t){const{val:i}=ne(t,this.from);if(i===void 0)throw new Error("NOT_FOUND");return new fs(this.path,vn(i)).apply(t)}toJson(t){return{op:"copy",path:z(this.path),from:z(this.from)}}toCompact(t,i){return[i?"copy":3,this.path,this.from]}encode(t,i){t.encodeArrayHeader(3),t.writer.u8(3),t.encodeArray(this.path),t.encodeArray(this.from)}}class Ce extends Re{apply(e){if(!this.test(e))throw new Error("TEST");return{doc:e}}}const Qn=(n,e)=>{if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){if(n.constructor!==e.constructor)return!1;let t,i,s;if(Array.isArray(n)){if(t=n.length,t!==e.length)return!1;for(i=t;i--!==0;)if(!Qn(n[i],e[i]))return!1;return!0}if(s=Object.keys(n),t=s.length,t!==Object.keys(e).length)return!1;for(i=t;i--!==0;){const r=s[i];if(!Qn(n[r],e[r]))return!1}return!0}return!1};class dd extends Ce{constructor(t,i,s){super(t);x(this,"value");x(this,"not");this.value=i,this.not=s}op(){return"test"}code(){return 5}test(t){const{val:i}=ne(t,this.path);if(i===void 0)return!!this.not;const s=Qn(i,this.value);return this.not?!s:s}toJson(t){const i={op:"test",path:z(t?this.path.slice(t.path.length):this.path),value:this.value};return this.not&&(i.not=this.not),i}toCompact(t,i){const s=t?this.path.slice(t.path.length):this.path,r=i?"test":5;return this.not?[r,s,this.value,1]:[r,s,this.value]}encode(t,i){t.encodeArrayHeader(this.not?4:3),t.writer.u8(5),t.encodeArray(i?this.path.slice(i.path.length):this.path),t.encodeAny(this.value),this.not&&t.writer.u8(1)}}class ld extends Re{constructor(e){super(e)}op(){return"flip"}code(){return 8}apply(e){const t=ne(e,this.path);return t.obj?t.obj[t.key]=!t.val:e=!t.val,{doc:e,old:t.val}}toJson(e){return{op:"flip",path:z(this.path)}}toCompact(e,t){return[t?"flip":8,this.path]}encode(e,t){e.encodeArrayHeader(2),e.writer.u8(8),e.encodeArray(this.path)}}class ud extends Re{constructor(t,i){super(t);x(this,"inc");this.inc=i}op(){return"inc"}code(){return 9}apply(t){const i=ne(t,this.path),s=this.inc+Number(i.val);return i.obj?i.obj[i.key]=s:t=s,{doc:t,old:i.val}}toJson(t){return{op:"inc",path:z(this.path),inc:this.inc}}toCompact(t,i){return[i?"inc":9,this.path,this.inc]}encode(t,i){t.encodeArrayHeader(3),t.writer.u8(9),t.encodeArray(this.path),t.encodeNumber(this.inc)}}class hd extends Re{constructor(t,i,s){super(t);x(this,"pos");x(this,"str");this.pos=i,this.str=s}op(){return"str_ins"}code(){return 6}apply(t){const{val:i,key:s,obj:r}=ne(t,this.path);if(typeof i!="string"){if(i!==void 0)throw new Error("NOT_A_STRING");if(this.pos!==0)throw new Error("POS")}const a=typeof i=="string"?i:"",o=Math.min(this.pos,a.length),c=a.slice(0,o),d=a.slice(o),l=c+this.str+d;return r?r[s]=l:t=l,{doc:t,old:i}}toJson(t){return{op:"str_ins",path:z(this.path),pos:this.pos,str:this.str}}toCompact(t,i){return[i?"str_ins":6,this.path,this.pos,this.str]}encode(t,i){t.encodeArrayHeader(4),t.writer.u8(6),t.encodeArray(this.path),t.encodeNumber(this.pos),t.encodeString(this.str)}}class pd extends Re{constructor(t,i,s,r){super(t);x(this,"pos");x(this,"str");x(this,"len");this.pos=i,this.str=s,this.len=r}op(){return"str_del"}code(){return 7}deleteLength(){return typeof this.str=="string"?this.str.length:this.len}apply(t){const{val:i,key:s,obj:r}=ne(t,this.path);if(typeof i!="string")throw new Error("NOT_A_STRING");const a=i.length,o=Math.min(this.pos,i.length),c=Math.min(o,a),d=this.str!==void 0?this.str.length:this.len,l=Math.min(o+d,a),u=i.slice(0,c),p=i.substr(l),m=u+p;return r?r[s]=m:t=m,{doc:t,old:i}}toJson(t){return typeof this.str=="string"?{op:"str_del",path:z(this.path),pos:this.pos,str:this.str}:{op:"str_del",path:z(this.path),pos:this.pos,len:this.len}}toCompact(t,i){const s=i?"str_del":7;return typeof this.str=="string"?[s,this.path,this.pos,this.str]:[s,this.path,this.pos,0,this.len]}encode(t,i){const s=typeof this.str=="string";t.encodeArrayHeader(s?4:5),t.writer.u8(7),t.encodeArray(this.path),t.encodeNumber(this.pos),s?t.encodeString(this.str):(t.writer.u8(0),t.encodeNumber(this.len))}}const{isArray:fd}=Array,Li=n=>!!n&&typeof n=="object"&&typeof n.text=="string",Ui=n=>!!n&&typeof n=="object"&&fd(n.children),md=(n,e)=>{const t=new RegExp(n,e?"i":void 0);return i=>t.test(i)};class gd extends Re{constructor(t,i,s){super(t);x(this,"pos");x(this,"props");this.pos=i,this.props=s}op(){return"split"}code(){return 10}apply(t){const i=ne(t,this.path);if(i.val===void 0)throw new Error("NOT_FOUND");const s=this.split(i.val);return ai(i)?i.obj[i.key]=s:Sn(i)?(i.obj[i.key]=s[0],i.obj.splice(i.key+1,0,s[1])):t=s,{doc:t,old:i.val}}split(t){if(typeof t=="string"){const{pos:i,props:s}=this,r=t.slice(0,i),a=t.slice(i);return s?[{...s,text:r},{...s,text:a}]:[r,a]}else if(Li(t)){const{pos:i,props:s}=this,r=t.text.slice(0,i),a=t.text.slice(i);return[{...t,...s,text:r},{...t,...s,text:a}]}else if(Ui(t)){const{pos:i,props:s}=this,r=t.children.slice(0,i),a=t.children.slice(i);return[{...t,...s,children:r},{...t,...s,children:a}]}else if(typeof t=="number"){const{pos:i}=this;return[i,t-i]}else return[t,t]}toJson(t){const i={op:"split",path:z(this.path),pos:this.pos};return this.props&&(i.props=this.props),i}toCompact(t,i){const s=i?"split":10;return this.props?[s,this.path,this.pos,this.props]:[s,this.path,this.pos]}encode(t,i){t.encodeArrayHeader(this.props?4:3),t.writer.u8(10),t.encodeArray(this.path),t.encodeNumber(this.pos),this.props&&t.encodeObject(this.props)}}class vd extends Re{constructor(t,i,s){super(t);x(this,"pos");x(this,"props");this.pos=i,this.props=s}op(){return"merge"}code(){return 11}apply(t){const i=ne(t,this.path);if(!Sn(i))throw new Error("INVALID_TARGET");if(i.key<=0)throw new Error("INVALID_KEY");const s=i.obj[i.key-1],r=i.obj[i.key],a=this.merge(s,r);return i.obj[i.key-1]=a,i.obj.splice(i.key,1),{doc:t,old:[s,r]}}merge(t,i){return typeof t=="string"&&typeof i=="string"||typeof t=="number"&&typeof i=="number"?t+i:Li(t)&&Li(i)?{...t,...i,text:t.text+i.text}:Ui(t)&&Ui(i)?{...t,...i,children:[...t.children,...i.children]}:[t,i]}toJson(t){const i={op:"merge",path:z(this.path),pos:this.pos};return this.props&&(i.props=this.props),i}toCompact(t,i){const s=i?"merge":11;return this.props?[s,this.path,this.pos,this.props]:[s,this.path,this.pos]}encode(t,i){t.encodeArrayHeader(this.props?4:3),t.writer.u8(11),t.encodeArray(this.path),t.encodeNumber(this.pos),this.props&&t.encodeAny(this.props)}}const{isArray:kd}=Array;class yd extends Re{constructor(t,i,s){super(t);x(this,"props");x(this,"deleteNull");this.props=i,this.deleteNull=s}op(){return"extend"}code(){return 12}apply(t){const i=ne(t,this.path);return Sn(i)?i.val!==void 0&&(i.obj[i.key]=this.extend(i.val)):ai(i)?i.obj[i.key]=this.extend(i.val):t=this.extend(t),{doc:t}}extend(t){if(kd(t)||typeof t!="object"||!t)return t;for(const[i,s]of Object.entries(this.props)){if(i==="__proto__")throw new Error("NO_PROTO");if(s===null&&this.deleteNull){delete t[i];continue}t[i]=s}return t}toJson(t){const i={op:"extend",path:z(this.path),props:this.props};return this.deleteNull&&(i.deleteNull=this.deleteNull),i}toCompact(t,i){const s=i?"extend":12;return this.deleteNull?[s,this.path,this.props,1]:[s,this.path,this.props]}encode(t,i){const{deleteNull:s}=this;t.encodeArrayHeader(s?4:3),t.writer.u8(12),t.encodeArray(this.path),t.encodeObject(this.props),s&&t.writer.u8(1)}}class bd extends Ce{constructor(e){super(e)}op(){return"defined"}code(){return 31}test(e){const{val:t}=ne(e,this.path);return t!==void 0}toJson(e){return{op:"defined",path:z(e?this.path.slice(e.path.length):this.path)}}toCompact(e,t){return[t?"defined":31,e?this.path.slice(e.path.length):this.path]}encode(e,t){e.encodeArrayHeader(2),e.writer.u8(31),e.encodeArray(t?this.path.slice(t.path.length):this.path)}}class Td extends Ce{constructor(e){super(e)}op(){return"undefined"}code(){return 38}test(e){try{const{val:t}=ne(e,this.path);return t===void 0}catch(t){if(t.message==="NOT_FOUND")return!0;throw t}}toJson(e){return{op:"undefined",path:z(e?this.path.slice(e.path.length):this.path)}}toCompact(e,t){return[t?"undefined":38,e?this.path.slice(e.path.length):this.path]}encode(e,t){e.encodeArrayHeader(2),e.writer.u8(38),e.encodeArray(t?this.path.slice(t.path.length):this.path)}}const{isArray:Cd}=Array;class Sd extends Ce{constructor(t,i){super(t);x(this,"type");this.type=i}op(){return"test_type"}code(){return 39}test(t){const{val:i}=ne(t,this.path);return i===null?this.type.indexOf("null")>-1:Cd(i)?this.type.indexOf("array")>-1:this.type.indexOf(typeof i)>-1||typeof i=="number"&&i===Math.round(i)&&this.type.indexOf("integer")>-1}toJson(t){return{op:"test_type",path:z(t?this.path.slice(t.path.length):this.path),type:this.type}}toCompact(t,i){return[i?"test_type":39,t?this.path.slice(t.path.length):this.path,this.type]}encode(t,i){t.encodeArrayHeader(3),t.writer.u8(39),t.encodeArray(i?this.path.slice(i.path.length):this.path),t.encodeArray(this.type)}}class _d extends Ce{constructor(t,i,s,r){super(t);x(this,"pos");x(this,"str");x(this,"not");this.pos=i,this.str=s,this.not=r}op(){return"test_string"}code(){return 40}test(t){const{val:i}=ne(t,this.path);if(typeof i!="string")return!1;const s=i.length,r=Math.min(this.pos,s),a=Math.min(this.pos+this.str.length,s),o=i.substring(r,a)===this.str;return this.not?!o:o}toJson(t){const i={op:"test_string",path:z(t?this.path.slice(t.path.length):this.path),pos:this.pos,str:this.str};return this.not&&(i.not=this.not),i}toCompact(t,i){const s=i?"test_string":40,r=t?this.path.slice(t.path.length):this.path;return this.not?[s,r,this.pos,this.str,1]:[s,r,this.pos,this.str]}encode(t,i){t.encodeArrayHeader(this.not?5:4),t.writer.u8(40),t.encodeArray(i?this.path.slice(i.path.length):this.path),t.encodeNumber(this.pos),t.encodeString(this.str),this.not&&t.writer.u8(1)}}class Ed extends Ce{constructor(t,i,s){super(t);x(this,"len");x(this,"not");this.len=i,this.not=s}op(){return"test_string_len"}code(){return 41}test(t){const{val:i}=ne(t,this.path);if(typeof i!="string")return!1;const r=i.length>=this.len;return this.not?!r:r}toJson(t){const i={op:"test_string_len",path:z(t?this.path.slice(t.path.length):this.path),len:this.len};return this.not&&(i.not=this.not),i}toCompact(t,i){const s=i?"test_string_len":41,r=t?this.path.slice(t.path.length):this.path;return this.not?[s,r,this.len,1]:[s,r,this.len]}encode(t,i){t.encodeArrayHeader(this.not?4:3),t.writer.u8(41),t.encodeArray(i?this.path.slice(i.path.length):this.path),t.encodeNumber(this.len),this.not&&t.writer.u8(1)}}class wd extends Ce{constructor(t,i,s){super(t);x(this,"value");x(this,"ignore_case");this.value=i,this.ignore_case=s}op(){return"contains"}code(){return 30}test(t){const{val:i}=ne(t,this.path);if(typeof i!="string")return!1;const s=this.ignore_case?i.toLowerCase():i,r=this.ignore_case?this.value.toLowerCase():this.value;return s.indexOf(r)>-1}toJson(t){const i={op:"contains",path:z(t?this.path.slice(t.path.length):this.path),value:this.value};return this.ignore_case&&(i.ignore_case=this.ignore_case),i}toCompact(t,i){const s=i?"contains":30;return this.ignore_case?[s,t?this.path.slice(t.path.length):this.path,this.value,1]:[s,t?this.path.slice(t.path.length):this.path,this.value]}encode(t,i){const s=this.ignore_case;t.encodeArrayHeader(s?4:3),t.writer.u8(30),t.encodeArray(i?this.path.slice(i.path.length):this.path),t.encodeString(this.value),s&&t.writer.u8(1)}}class Pd extends Ce{constructor(t,i,s){super(t);x(this,"value");x(this,"ignore_case");this.value=i,this.ignore_case=s}op(){return"ends"}code(){return 32}test(t){const{val:i}=ne(t,this.path);if(typeof i!="string")return!1;const s=this.ignore_case?i.toLowerCase():i,r=this.ignore_case?this.value.toLowerCase():this.value;return s.endsWith(r)}toJson(t){const i={op:"ends",path:z(t?this.path.slice(t.path.length):this.path),value:this.value};return this.ignore_case&&(i.ignore_case=this.ignore_case),i}toCompact(t,i){const s=i?"ends":32;return this.ignore_case?[s,t?this.path.slice(t.path.length):this.path,this.value,1]:[s,t?this.path.slice(t.path.length):this.path,this.value]}encode(t,i){const s=this.ignore_case;t.encodeArrayHeader(s?4:3),t.writer.u8(32),t.encodeArray(i?this.path.slice(i.path.length):this.path),t.encodeString(this.value),s&&t.writer.u8(1)}}class Rd extends Ce{constructor(t,i,s){super(t);x(this,"value");x(this,"ignore_case");this.value=i,this.ignore_case=s}op(){return"starts"}code(){return 37}test(t){const{val:i}=ne(t,this.path);if(typeof i!="string")return!1;const s=this.ignore_case?i.toLowerCase():i,r=this.ignore_case?this.value.toLowerCase():this.value;return s.startsWith(r)}toJson(t){const i={op:"starts",path:z(t?this.path.slice(t.path.length):this.path),value:this.value};return this.ignore_case&&(i.ignore_case=this.ignore_case),i}toCompact(t,i){const s=i?"starts":37;return this.ignore_case?[s,t?this.path.slice(t.path.length):this.path,this.value,1]:[s,t?this.path.slice(t.path.length):this.path,this.value]}encode(t,i){const s=this.ignore_case;t.encodeArrayHeader(s?4:3),t.writer.u8(37),t.encodeArray(i?this.path.slice(i.path.length):this.path),t.encodeString(this.value),s&&t.writer.u8(1)}}class Id extends Ce{constructor(t,i){super(t);x(this,"value");this.value=i}op(){return"in"}code(){return 33}test(t){const{val:i}=ne(t,this.path);for(const s of this.value)if(Qn(i,s))return!0;return!1}toJson(t){return{op:"in",path:z(t?this.path.slice(t.path.length):this.path),value:this.value}}toCompact(t,i){return[i?"in":33,t?this.path.slice(t.path.length):this.path,this.value]}encode(t,i){t.encodeArrayHeader(3),t.writer.u8(33),t.encodeArray(i?this.path.slice(i.path.length):this.path),t.encodeArray(this.value)}}class Od extends Ce{constructor(t,i){super(t);x(this,"value");this.value=i}op(){return"less"}code(){return 34}test(t){const{val:i}=ne(t,this.path);return typeof i!="number"?!1:i<this.value}toJson(t){return{op:"less",path:z(t?this.path.slice(t.path.length):this.path),value:this.value}}toCompact(t,i){return[i?"less":34,t?this.path.slice(t.path.length):this.path,this.value]}encode(t,i){t.encodeArrayHeader(3),t.writer.u8(34),t.encodeArray(i?this.path.slice(i.path.length):this.path),t.encodeNumber(this.value)}}class Md extends Ce{constructor(t,i){super(t);x(this,"value");this.value=i}op(){return"more"}code(){return 36}test(t){const{val:i}=ne(t,this.path);return typeof i!="number"?!1:i>this.value}toJson(t){return{op:"more",path:z(t?this.path.slice(t.path.length):this.path),value:this.value}}toCompact(t,i){return[i?"more":36,t?this.path.slice(t.path.length):this.path,this.value]}encode(t,i){t.encodeArrayHeader(3),t.writer.u8(36),t.encodeArray(i?this.path.slice(i.path.length):this.path),t.encodeNumber(this.value)}}class ms extends Ce{constructor(t,i){super(t);x(this,"ops");this.ops=i}}class xd extends ms{constructor(t,i){super(t,i);x(this,"ops");this.ops=i}op(){return"and"}code(){return 43}test(t){for(const i of this.ops)if(!i.test(t))return!1;return!0}toJson(t){return{op:"and",path:z(t?this.path.slice(t.path.length):this.path),apply:this.ops.map(s=>s.toJson(this))}}toCompact(t,i){return[i?"and":43,t?this.path.slice(t.path.length):this.path,this.ops.map(r=>r.toCompact(this,i))]}encode(t,i){const s=i?this.path.slice(i.path.length):this.path;t.encodeArrayHeader(3),t.writer.u8(43),t.encodeArray(s);const r=this.ops.length;t.encodeArrayHeader(r);for(let a=0;a<r;a++)this.ops[a].encode(t,this)}}class Ad extends ms{constructor(t,i){super(t,i);x(this,"ops");this.ops=i}op(){return"or"}code(){return 45}test(t){for(const i of this.ops)if(i.test(t))return!0;return!1}toJson(t){return{op:"or",path:z(t?this.path.slice(t.path.length):this.path),apply:this.ops.map(s=>s.toJson(this))}}toCompact(t,i){return[i?"or":45,t?this.path.slice(t.path.length):this.path,this.ops.map(r=>r.toCompact(this,i))]}encode(t,i){t.encodeArrayHeader(3),t.writer.u8(45),t.encodeArray(i?this.path.slice(i.path.length):this.path);const s=this.ops.length;t.encodeArrayHeader(s);for(let r=0;r<s;r++)this.ops[r].encode(t,this)}}class Dd extends ms{constructor(t,i){super(t,i);x(this,"ops");this.ops=i}op(){return"not"}code(){return 44}test(t){for(const i of this.ops)if(i.test(t))return!1;return!0}toJson(t){return{op:"not",path:z(t?this.path.slice(t.path.length):this.path),apply:this.ops.map(s=>s.toJson(this))}}toCompact(t,i){return[i?"not":44,t?this.path.slice(t.path.length):this.path,this.ops.map(r=>r.toCompact(this,i))]}encode(t,i){t.encodeArrayHeader(3),t.writer.u8(44),t.encodeArray(i?this.path.slice(i.path.length):this.path);const s=this.ops.length;t.encodeArrayHeader(s);for(let r=0;r<s;r++)this.ops[r].encode(t,this)}}class Nd extends Ce{constructor(t,i,s,r){super(t);x(this,"value");x(this,"ignore_case");x(this,"matcher");this.value=i,this.ignore_case=s,this.matcher=r(i,s)}op(){return"matches"}code(){return 35}test(t){const{val:i}=ne(t,this.path);return typeof i!="string"?!1:this.matcher(i)}toJson(t){const i={op:"matches",path:z(t?this.path.slice(t.path.length):this.path),value:this.value};return this.ignore_case&&(i.ignore_case=this.ignore_case),i}toCompact(t,i){const s=i?"matches":35;return this.ignore_case?[s,t?this.path.slice(t.path.length):this.path,this.value,1]:[s,t?this.path.slice(t.path.length):this.path,this.value]}encode(t,i){const s=this.ignore_case;t.encodeArrayHeader(s?4:3),t.writer.u8(35),t.encodeArray(i?this.path.slice(i.path.length):this.path),t.encodeString(this.value),s&&t.writer.u8(1)}}const{isArray:Ld}=Array;class Ud extends Ce{constructor(t,i){super(t);x(this,"value");this.value=i}op(){return"type"}code(){return 42}test(t){const{val:i}=ne(t,this.path);return i===null?this.value==="null":Ld(i)?this.value==="array":typeof i===this.value||typeof i=="number"&&i===Math.round(i)&&this.value==="integer"}toJson(t){return{op:"type",path:z(t?this.path.slice(t.path.length):this.path),value:this.value}}toCompact(t,i){return[i?"type":42,t?this.path.slice(t.path.length):this.path,this.value]}encode(t,i){t.encodeArrayHeader(3),t.writer.u8(42),t.encodeArray(i?this.path.slice(i.path.length):this.path),t.encodeString(this.value)}}const jd=(n,e)=>{switch(n.op){case"add":return new fs(B(n.path),n.value);case"remove":return new Xr(B(n.path),n.oldValue);case"replace":return new ad(B(n.path),n.value,n.oldValue);case"move":return new od(B(n.path),B(n.from));case"copy":return new cd(B(n.path),B(n.from));case"flip":return new ld(B(n.path));case"inc":return new ud(B(n.path),n.inc);case"str_ins":return new hd(B(n.path),n.pos,n.str);case"str_del":return new pd(B(n.path),n.pos,n.str,n.len);case"split":return new gd(B(n.path),n.pos,n.props||null);case"merge":return new vd(B(n.path),n.pos,n.props||null);case"extend":return new yd(B(n.path),n.props,!!n.deleteNull);default:return Fn(n,e)}},Fn=(n,e)=>{switch(n.op){case"test":return new dd(B(n.path),n.value,!!n.not);case"defined":return new bd(B(n.path));case"undefined":return new Td(B(n.path));case"type":return new Ud(B(n.path),n.value);case"test_type":return new Sd(B(n.path),n.type);case"test_string":return new _d(B(n.path),n.pos,n.str,!!n.not);case"test_string_len":return new Ed(B(n.path),n.len,!!n.not);case"contains":return new wd(B(n.path),n.value,!!n.ignore_case);case"ends":return new Pd(B(n.path),n.value,!!n.ignore_case);case"starts":return new Rd(B(n.path),n.value,!!n.ignore_case);case"matches":return new Nd(B(n.path),n.value,!!n.ignore_case,e.createMatcher||md);case"in":return new Id(B(n.path),n.value);case"less":return new Od(B(n.path),n.value);case"more":return new Md(B(n.path),n.value);case"and":{const t=B(n.path);return new xd(t,n.apply.map(i=>Fn({...i,path:[...t,...B(i.path)]},e)))}case"or":{const t=B(n.path);return new Ad(t,n.apply.map(i=>Fn({...i,path:[...t,...B(i.path)]},e)))}case"not":{const t=B(n.path);return new Dd(t,n.apply.map(i=>Fn({...i,path:[...t,...B(i.path)]},e)))}default:throw new Error("OP_UNKNOWN")}};function Fd(n,e,t){n=vn(n);const i=[],s=e.length;for(let r=0;r<s;r++){const o=jd(e[r],t).apply(n);n=o.doc,i.push(o)}return{doc:n,res:i}}var on=n=>typeof n=="function"?n:function(){return n},Bd=typeof self<"u"?self:null,tn=typeof window<"u"?window:null,cn=Bd||tn||cn,Vd="2.0.0",He={connecting:0,open:1,closing:2,closed:3},$d=1e4,Hd=1e3,Ee={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Qe={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},ji={longpoll:"longpoll",websocket:"websocket"},qd={complete:4},Dn=class{constructor(n,e,t,i){this.channel=n,this.event=e,this.payload=t||function(){return{}},this.receivedResp=null,this.timeout=i,this.timeoutTimer=null,this.recHooks=[],this.sent=!1}resend(n){this.timeout=n,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(n,e){return this.hasReceived(n)&&e(this.receivedResp.response),this.recHooks.push({status:n,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}matchReceive({status:n,response:e,_ref:t}){this.recHooks.filter(i=>i.status===n).forEach(i=>i.callback(e))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,n=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=n,this.matchReceive(n)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(n){return this.receivedResp&&this.receivedResp.status===n}trigger(n,e){this.channel.trigger(this.refEvent,{status:n,response:e})}},Zr=class{constructor(n,e){this.callback=n,this.timerCalc=e,this.timer=null,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},Gd=class{constructor(n,e,t){this.state=Ee.closed,this.topic=n,this.params=on(e||{}),this.socket=t,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new Dn(this,Qe.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new Zr(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=Ee.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(i=>i.send()),this.pushBuffer=[]}),this.joinPush.receive("error",()=>{this.state=Ee.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic} ${this.joinRef()}`),this.state=Ee.closed,this.socket.remove(this)}),this.onError(i=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,i),this.isJoining()&&this.joinPush.reset(),this.state=Ee.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic} (${this.joinRef()})`,this.joinPush.timeout),new Dn(this,Qe.leave,on({}),this.timeout).send(),this.state=Ee.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(Qe.reply,(i,s)=>{this.trigger(this.replyEventName(s),i)})}join(n=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=n,this.joinedOnce=!0,this.rejoin(),this.joinPush}onClose(n){this.on(Qe.close,n)}onError(n){return this.on(Qe.error,e=>n(e))}on(n,e){let t=this.bindingRef++;return this.bindings.push({event:n,ref:t,callback:e}),t}off(n,e){this.bindings=this.bindings.filter(t=>!(t.event===n&&(typeof e>"u"||e===t.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(n,e,t=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${n}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let i=new Dn(this,n,function(){return e},t);return this.canPush()?i.send():(i.startTimeout(),this.pushBuffer.push(i)),i}leave(n=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=Ee.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(Qe.close,"leave")},t=new Dn(this,Qe.leave,on({}),n);return t.receive("ok",()=>e()).receive("timeout",()=>e()),t.send(),this.canPush()||t.trigger("ok",{}),t}onMessage(n,e,t){return e}isMember(n,e,t,i){return this.topic!==n?!1:i&&i!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:n,event:e,payload:t,joinRef:i}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(n=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=Ee.joining,this.joinPush.resend(n))}trigger(n,e,t,i){let s=this.onMessage(n,e,t,i);if(e&&!s)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let r=this.bindings.filter(a=>a.event===n);for(let a=0;a<r.length;a++)r[a].callback(s,t,i||this.joinRef())}replyEventName(n){return`chan_reply_${n}`}isClosed(){return this.state===Ee.closed}isErrored(){return this.state===Ee.errored}isJoined(){return this.state===Ee.joined}isJoining(){return this.state===Ee.joining}isLeaving(){return this.state===Ee.leaving}},Yn=class{static request(n,e,t,i,s,r,a){if(cn.XDomainRequest){let o=new cn.XDomainRequest;return this.xdomainRequest(o,n,e,i,s,r,a)}else{let o=new cn.XMLHttpRequest;return this.xhrRequest(o,n,e,t,i,s,r,a)}}static xdomainRequest(n,e,t,i,s,r,a){return n.timeout=s,n.open(e,t),n.onload=()=>{let o=this.parseJSON(n.responseText);a&&a(o)},r&&(n.ontimeout=r),n.onprogress=()=>{},n.send(i),n}static xhrRequest(n,e,t,i,s,r,a,o){return n.open(e,t,!0),n.timeout=r,n.setRequestHeader("Content-Type",i),n.onerror=()=>o&&o(null),n.onreadystatechange=()=>{if(n.readyState===qd.complete&&o){let c=this.parseJSON(n.responseText);o(c)}},a&&(n.ontimeout=a),n.send(s),n}static parseJSON(n){if(!n||n==="")return null;try{return JSON.parse(n)}catch{return console&&console.log("failed to parse JSON response",n),null}}static serialize(n,e){let t=[];for(var i in n){if(!Object.prototype.hasOwnProperty.call(n,i))continue;let s=e?`${e}[${i}]`:i,r=n[i];typeof r=="object"?t.push(this.serialize(r,s)):t.push(encodeURIComponent(s)+"="+encodeURIComponent(r))}return t.join("&")}static appendParams(n,e){if(Object.keys(e).length===0)return n;let t=n.match(/\?/)?"&":"?";return`${n}${t}${this.serialize(e)}`}},Ti=class{constructor(n){this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(n),this.readyState=He.connecting,this.poll()}normalizeEndpoint(n){return n.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+ji.websocket),"$1/"+ji.longpoll)}endpointURL(){return Yn.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(n,e,t){this.close(n,e,t),this.readyState=He.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===He.open||this.readyState===He.connecting}poll(){this.ajax("GET",null,()=>this.ontimeout(),n=>{if(n){var{status:e,token:t,messages:i}=n;this.token=t}else e=0;switch(e){case 200:i.forEach(s=>{setTimeout(()=>this.onmessage({data:s}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=He.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${e}`)}})}send(n){this.ajax("POST",n,()=>this.onerror("timeout"),e=>{(!e||e.status!==200)&&(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",!1))})}close(n,e,t){for(let s of this.reqs)s.abort();this.readyState=He.closed;let i=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:n,reason:e,wasClean:t});typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",i)):this.onclose(i)}ajax(n,e,t,i){let s,r=()=>{this.reqs.delete(s),t()};s=Yn.request(n,this.endpointURL(),"application/json",e,this.timeout,r,a=>{this.reqs.delete(s),this.isActive()&&i(a)}),this.reqs.add(s)}},Nn={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(n,e){if(n.payload.constructor===ArrayBuffer)return e(this.binaryEncode(n));{let t=[n.join_ref,n.ref,n.topic,n.event,n.payload];return e(JSON.stringify(t))}},decode(n,e){if(n.constructor===ArrayBuffer)return e(this.binaryDecode(n));{let[t,i,s,r,a]=JSON.parse(n);return e({join_ref:t,ref:i,topic:s,event:r,payload:a})}},binaryEncode(n){let{join_ref:e,ref:t,event:i,topic:s,payload:r}=n,a=this.META_LENGTH+e.length+t.length+s.length+i.length,o=new ArrayBuffer(this.HEADER_LENGTH+a),c=new DataView(o),d=0;c.setUint8(d++,this.KINDS.push),c.setUint8(d++,e.length),c.setUint8(d++,t.length),c.setUint8(d++,s.length),c.setUint8(d++,i.length),Array.from(e,u=>c.setUint8(d++,u.charCodeAt(0))),Array.from(t,u=>c.setUint8(d++,u.charCodeAt(0))),Array.from(s,u=>c.setUint8(d++,u.charCodeAt(0))),Array.from(i,u=>c.setUint8(d++,u.charCodeAt(0)));var l=new Uint8Array(o.byteLength+r.byteLength);return l.set(new Uint8Array(o),0),l.set(new Uint8Array(r),o.byteLength),l.buffer},binaryDecode(n){let e=new DataView(n),t=e.getUint8(0),i=new TextDecoder;switch(t){case this.KINDS.push:return this.decodePush(n,e,i);case this.KINDS.reply:return this.decodeReply(n,e,i);case this.KINDS.broadcast:return this.decodeBroadcast(n,e,i)}},decodePush(n,e,t){let i=e.getUint8(1),s=e.getUint8(2),r=e.getUint8(3),a=this.HEADER_LENGTH+this.META_LENGTH-1,o=t.decode(n.slice(a,a+i));a=a+i;let c=t.decode(n.slice(a,a+s));a=a+s;let d=t.decode(n.slice(a,a+r));a=a+r;let l=n.slice(a,n.byteLength);return{join_ref:o,ref:null,topic:c,event:d,payload:l}},decodeReply(n,e,t){let i=e.getUint8(1),s=e.getUint8(2),r=e.getUint8(3),a=e.getUint8(4),o=this.HEADER_LENGTH+this.META_LENGTH,c=t.decode(n.slice(o,o+i));o=o+i;let d=t.decode(n.slice(o,o+s));o=o+s;let l=t.decode(n.slice(o,o+r));o=o+r;let u=t.decode(n.slice(o,o+a));o=o+a;let p=n.slice(o,n.byteLength),m={status:u,response:p};return{join_ref:c,ref:d,topic:l,event:Qe.reply,payload:m}},decodeBroadcast(n,e,t){let i=e.getUint8(1),s=e.getUint8(2),r=this.HEADER_LENGTH+2,a=t.decode(n.slice(r,r+i));r=r+i;let o=t.decode(n.slice(r,r+s));r=r+s;let c=n.slice(r,n.byteLength);return{join_ref:null,ref:null,topic:a,event:o,payload:c}}},zd=class{constructor(n,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.timeout=e.timeout||$d,this.transport=e.transport||cn.WebSocket||Ti,this.establishedConnections=0,this.defaultEncoder=Nn.encode.bind(Nn),this.defaultDecoder=Nn.decode.bind(Nn),this.closeWasClean=!1,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.transport!==Ti?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let t=null;tn&&tn.addEventListener&&(tn.addEventListener("pagehide",i=>{this.conn&&(this.disconnect(),t=this.connectClock)}),tn.addEventListener("pageshow",i=>{t===this.connectClock&&(t=null,this.connect())})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.rejoinAfterMs=i=>e.rejoinAfterMs?e.rejoinAfterMs(i):[1e3,2e3,5e3][i-1]||1e4,this.reconnectAfterMs=i=>e.reconnectAfterMs?e.reconnectAfterMs(i):[10,50,100,150,200,250,500,1e3,2e3][i-1]||5e3,this.logger=e.logger||null,this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=on(e.params||{}),this.endPoint=`${n}/${ji.websocket}`,this.vsn=e.vsn||Vd,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new Zr(()=>{this.teardown(()=>this.connect())},this.reconnectAfterMs)}getLongPollTransport(){return Ti}replaceTransport(n){this.connectClock++,this.closeWasClean=!0,this.reconnectTimer.reset(),this.sendBuffer=[],this.conn&&(this.conn.close(),this.conn=null),this.transport=n}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let n=Yn.appendParams(Yn.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return n.charAt(0)!=="/"?n:n.charAt(1)==="/"?`${this.protocol()}:${n}`:`${this.protocol()}://${location.host}${n}`}disconnect(n,e,t){this.connectClock++,this.closeWasClean=!0,this.reconnectTimer.reset(),this.teardown(n,e,t)}connect(n){n&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=on(n)),!this.conn&&(this.connectClock++,this.closeWasClean=!1,this.conn=new this.transport(this.endPointURL()),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e))}log(n,e,t){this.logger(n,e,t)}hasLogger(){return this.logger!==null}onOpen(n){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,n]),e}onClose(n){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,n]),e}onError(n){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,n]),e}onMessage(n){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,n]),e}ping(n){if(!this.isConnected())return!1;let e=this.makeRef(),t=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let i=this.onMessage(s=>{s.ref===e&&(this.off([i]),n(Date.now()-t))});return!0}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.resetHeartbeat(),this.stateChangeCallbacks.open.forEach(([,n])=>n())}heartbeatTimeout(){this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection"),this.triggerChanError(),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),Hd,"heartbeat timeout"))}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(n,e,t){if(!this.conn)return n&&n();this.waitForBufferDone(()=>{this.conn&&(e?this.conn.close(e,t||""):this.conn.close()),this.waitForSocketClosed(()=>{this.conn&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),n&&n()})})}waitForBufferDone(n,e=1){if(e===5||!this.conn||!this.conn.bufferedAmount){n();return}setTimeout(()=>{this.waitForBufferDone(n,e+1)},150*e)}waitForSocketClosed(n,e=1){if(e===5||!this.conn||this.conn.readyState===He.closed){n();return}setTimeout(()=>{this.waitForSocketClosed(n,e+1)},150*e)}onConnClose(n){let e=n&&n.code;this.hasLogger()&&this.log("transport","close",n),this.triggerChanError(),this.clearHeartbeats(),!this.closeWasClean&&e!==1e3&&this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(([,t])=>t(n))}onConnError(n){this.hasLogger()&&this.log("transport",n);let e=this.transport,t=this.establishedConnections;this.stateChangeCallbacks.error.forEach(([,i])=>{i(n,e,t)}),(e===this.transport||t>0)&&this.triggerChanError()}triggerChanError(){this.channels.forEach(n=>{n.isErrored()||n.isLeaving()||n.isClosed()||n.trigger(Qe.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case He.connecting:return"connecting";case He.open:return"open";case He.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(n){this.off(n.stateChangeRefs),this.channels=this.channels.filter(e=>e.joinRef()!==n.joinRef())}off(n){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([t])=>n.indexOf(t)===-1)}channel(n,e={}){let t=new Gd(n,e,this);return this.channels.push(t),t}push(n){if(this.hasLogger()){let{topic:e,event:t,payload:i,ref:s,join_ref:r}=n;this.log("push",`${e} ${t} (${r}, ${s})`,i)}this.isConnected()?this.encode(n,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(n,e=>this.conn.send(e)))}makeRef(){let n=this.ref+1;return n===this.ref?this.ref=0:this.ref=n,this.ref.toString()}sendHeartbeat(){this.pendingHeartbeatRef&&!this.isConnected()||(this.pendingHeartbeatRef=this.makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs))}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(n=>n()),this.sendBuffer=[])}onConnMessage(n){this.decode(n.data,e=>{let{topic:t,event:i,payload:s,ref:r,join_ref:a}=e;r&&r===this.pendingHeartbeatRef&&(this.clearHeartbeats(),this.pendingHeartbeatRef=null,this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)),this.hasLogger()&&this.log("receive",`${s.status||""} ${t} ${i} ${r&&"("+r+")"||""}`,s);for(let o=0;o<this.channels.length;o++){const c=this.channels[o];c.isMember(t,i,s,a)&&c.trigger(i,s,r,a)}for(let o=0;o<this.stateChangeCallbacks.message.length;o++){let[,c]=this.stateChangeCallbacks.message[o];c(e)}})}leaveOpenTopic(n){let e=this.channels.find(t=>t.topic===n&&(t.isJoined()||t.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${n}"`),e.leave())}};class Wd{constructor(e){this.connected=!1,this.config=e,this.socket=new zd(this.config.url,this.config.socketOptions||{logger:(t,i,s)=>{console.debug(`${t}: ${i}`,s)}}),this.channel=this.socket.channel(this.config.topic,this.config.params),this.eventTarget=new EventTarget}connect(){this.connected||(this.socket.onError(e=>this.emitError("socket error",e)),this.socket.connect(),this.channel.onError(e=>this.emitError("channel error",e)),this.channel.join().receive("ok",e=>{console.debug("channel joined",e)}).receive("error",e=>{this.emitError("channel join error",e)}),this.channel.on("state:change",e=>this.handleChange(e)),this.channel.on("state:patch",e=>this.handlePatch(e)),this.channel.on("error",e=>this.emitServerError(e)),this.connected=!0)}disconnect(){this.channel&&this.channel.leave(),this.socket.disconnect(),this.connected=!1}addEventListener(e,t,i){var s;this.eventTarget.addEventListener(e,t,i),e.startsWith("livestate-")||(s=this.channel)==null||s.on(e,r=>{this.eventTarget.dispatchEvent(new CustomEvent(e,{detail:r}))})}removeEventListener(e,t,i){return this.eventTarget.removeEventListener(e,t,i)}subscribe(e){this.addEventListener("livestate-change",e)}unsubscribe(e){this.removeEventListener("livestate-change",e)}emitServerError(e){this.eventTarget.dispatchEvent(new CustomEvent("livestate-error",{detail:e}))}emitError(e,t){this.eventTarget.dispatchEvent(new CustomEvent("livestate-error",{detail:{type:e,message:this.extractMessage(t)}}))}extractMessage(e){if(e&&typeof(e=="object")){const t=[e.reason,e.name,e.message].find(i=>i);return console.log(t),t}else if(typeof e=="string")return e}handleChange({state:e,version:t}){this.state=e,this.stateVersion=t,this.eventTarget.dispatchEvent(new CustomEvent("livestate-change",{detail:{state:this.state,version:this.stateVersion}}))}handlePatch({patch:e,version:t}){if(this.eventTarget.dispatchEvent(new CustomEvent("livestate-patch",{detail:{patch:e,version:t}})),this.versionMatches(t)){const{doc:i,res:s}=Fd(this.state,e,{mutate:!1});this.state=i,this.stateVersion=t,this.eventTarget.dispatchEvent(new CustomEvent("livestate-change",{detail:{state:this.state,version:this.stateVersion}}))}else this.channel.push("lvs_refresh")}versionMatches(e){return e===this.stateVersion+1||e===0}pushEvent(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))}dispatchEvent(e){return this.channel.push(`lvs_evt:${e.type}`,e.detail),!0}pushCustomEvent(e){this.dispatchEvent(e)}}const ea=32;let ce,je,Xn=n=>(ce=0,je=n,n=rt(),je[ce]?nt():n||""),nt=(n="Bad syntax",e=je[ce],t=je.slice(0,ce).split(`
|
|
2
|
-
`),i=t.pop())=>{let s=je.slice(ce-108,ce).split(`
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
***************************************************************************** */var zs;(function(n){(function(e){var t=typeof Gs=="object"?Gs:typeof self=="object"?self:typeof this=="object"?this:Function("return this;")(),i=s(n);typeof t.Reflect>"u"?t.Reflect=n:i=s(t.Reflect,i),e(i);function s(r,a){return function(o,c){typeof r[o]!="function"&&Object.defineProperty(r,o,{configurable:!0,writable:!0,value:c}),a&&a(o,c)}}})(function(e){var t=Object.prototype.hasOwnProperty,i=typeof Symbol=="function",s=i&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",r=i&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",a=typeof Object.create=="function",o={__proto__:[]}instanceof Array,c=!a&&!o,d={create:a?function(){return yi(Object.create(null))}:o?function(){return yi({__proto__:null})}:function(){return yi({})},has:c?function(g,y){return t.call(g,y)}:function(g,y){return y in g},get:c?function(g,y){return t.call(g,y)?g[y]:void 0}:function(g,y){return g[y]}},l=Object.getPrototypeOf(Function),u=typeof process=="object"&&process.env&&process.env.REFLECT_METADATA_USE_MAP_POLYFILL==="true",p=!u&&typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:kc(),m=!u&&typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:yc(),k=!u&&typeof WeakMap=="function"?WeakMap:bc(),v=new k;function S(g,y,C,P){if(Y(C)){if(!Ns(g))throw new TypeError;if(!Ls(y))throw new TypeError;return H(g,y)}else{if(!Ns(g))throw new TypeError;if(!le(y))throw new TypeError;if(!le(P)&&!Y(P)&&!be(P))throw new TypeError;return be(P)&&(P=void 0),C=Je(C),ze(g,y,C,P)}}e("decorate",S);function O(g,y){function C(P,D){if(!le(P))throw new TypeError;if(!Y(D)&&!pc(D))throw new TypeError;Mn(g,y,P,D)}return C}e("metadata",O);function w(g,y,C,P){if(!le(C))throw new TypeError;return Y(P)||(P=Je(P)),Mn(g,y,C,P)}e("defineMetadata",w);function F(g,y,C){if(!le(y))throw new TypeError;return Y(C)||(C=Je(C)),Wt(g,y,C)}e("hasMetadata",F);function W(g,y,C){if(!le(y))throw new TypeError;return Y(C)||(C=Je(C)),wt(g,y,C)}e("hasOwnMetadata",W);function he(g,y,C){if(!le(y))throw new TypeError;return Y(C)||(C=Je(C)),On(g,y,C)}e("getMetadata",he);function de(g,y,C){if(!le(y))throw new TypeError;return Y(C)||(C=Je(C)),Jt(g,y,C)}e("getOwnMetadata",de);function N(g,y){if(!le(g))throw new TypeError;return Y(y)||(y=Je(y)),R(g,y)}e("getMetadataKeys",N);function X(g,y){if(!le(g))throw new TypeError;return Y(y)||(y=Je(y)),pe(g,y)}e("getOwnMetadataKeys",X);function A(g,y,C){if(!le(y))throw new TypeError;Y(C)||(C=Je(C));var P=Be(y,C,!1);if(Y(P)||!P.delete(g))return!1;if(P.size>0)return!0;var D=v.get(y);return D.delete(C),D.size>0||v.delete(y),!0}e("deleteMetadata",A);function H(g,y){for(var C=g.length-1;C>=0;--C){var P=g[C],D=P(y);if(!Y(D)&&!be(D)){if(!Ls(D))throw new TypeError;y=D}}return y}function ze(g,y,C,P){for(var D=g.length-1;D>=0;--D){var Se=g[D],U=Se(y,C,P);if(!Y(U)&&!be(U)){if(!le(U))throw new TypeError;P=U}}return P}function Be(g,y,C){var P=v.get(g);if(Y(P)){if(!C)return;P=new p,v.set(g,P)}var D=P.get(y);if(Y(D)){if(!C)return;D=new p,P.set(y,D)}return D}function Wt(g,y,C){var P=wt(g,y,C);if(P)return!0;var D=ki(y);return be(D)?!1:Wt(g,D,C)}function wt(g,y,C){var P=Be(y,C,!1);return Y(P)?!1:We(P.has(g))}function On(g,y,C){var P=wt(g,y,C);if(P)return Jt(g,y,C);var D=ki(y);if(!be(D))return On(g,D,C)}function Jt(g,y,C){var P=Be(y,C,!1);if(!Y(P))return P.get(g)}function Mn(g,y,C,P){var D=Be(C,P,!0);D.set(g,y)}function R(g,y){var C=pe(g,y),P=ki(g);if(P===null)return C;var D=R(P,y);if(D.length<=0)return C;if(C.length<=0)return D;for(var Se=new m,U=[],j=0,L=C;j<L.length;j++){var q=L[j],G=Se.has(q);G||(Se.add(q),U.push(q))}for(var at=0,js=D;at<js.length;at++){var q=js[at],G=Se.has(q);G||(Se.add(q),U.push(q))}return U}function pe(g,y){var C=[],P=Be(g,y,!1);if(Y(P))return C;for(var D=P.keys(),Se=fc(D),U=0;;){var j=gc(Se);if(!j)return C.length=U,C;var L=mc(j);try{C[U]=L}catch(q){try{vc(Se)}finally{throw q}}U++}}function fe(g){if(g===null)return 1;switch(typeof g){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return g===null?1:6;default:return 6}}function Y(g){return g===void 0}function be(g){return g===null}function Pt(g){return typeof g=="symbol"}function le(g){return typeof g=="object"?g!==null:typeof g=="function"}function xn(g,y){switch(fe(g)){case 0:return g;case 1:return g;case 2:return g;case 3:return g;case 4:return g;case 5:return g}var C="string",P=Us(g,s);if(P!==void 0){var D=P.call(g,C);if(le(D))throw new TypeError;return D}return Rt(g)}function Rt(g,y){var C,P;{var D=g.toString;if(An(D)){var P=D.call(g);if(!le(P))return P}var C=g.valueOf;if(An(C)){var P=C.call(g);if(!le(P))return P}}throw new TypeError}function We(g){return!!g}function hc(g){return""+g}function Je(g){var y=xn(g);return Pt(y)?y:hc(y)}function Ns(g){return Array.isArray?Array.isArray(g):g instanceof Object?g instanceof Array:Object.prototype.toString.call(g)==="[object Array]"}function An(g){return typeof g=="function"}function Ls(g){return typeof g=="function"}function pc(g){switch(fe(g)){case 3:return!0;case 4:return!0;default:return!1}}function Us(g,y){var C=g[y];if(C!=null){if(!An(C))throw new TypeError;return C}}function fc(g){var y=Us(g,r);if(!An(y))throw new TypeError;var C=y.call(g);if(!le(C))throw new TypeError;return C}function mc(g){return g.value}function gc(g){var y=g.next();return y.done?!1:y}function vc(g){var y=g.return;y&&y.call(g)}function ki(g){var y=Object.getPrototypeOf(g);if(typeof g!="function"||g===l||y!==l)return y;var C=g.prototype,P=C&&Object.getPrototypeOf(C);if(P==null||P===Object.prototype)return y;var D=P.constructor;return typeof D!="function"||D===g?y:D}function kc(){var g={},y=[],C=function(){function U(j,L,q){this._index=0,this._keys=j,this._values=L,this._selector=q}return U.prototype["@@iterator"]=function(){return this},U.prototype[r]=function(){return this},U.prototype.next=function(){var j=this._index;if(j>=0&&j<this._keys.length){var L=this._selector(this._keys[j],this._values[j]);return j+1>=this._keys.length?(this._index=-1,this._keys=y,this._values=y):this._index++,{value:L,done:!1}}return{value:void 0,done:!0}},U.prototype.throw=function(j){throw this._index>=0&&(this._index=-1,this._keys=y,this._values=y),j},U.prototype.return=function(j){return this._index>=0&&(this._index=-1,this._keys=y,this._values=y),{value:j,done:!0}},U}();return function(){function U(){this._keys=[],this._values=[],this._cacheKey=g,this._cacheIndex=-2}return Object.defineProperty(U.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),U.prototype.has=function(j){return this._find(j,!1)>=0},U.prototype.get=function(j){var L=this._find(j,!1);return L>=0?this._values[L]:void 0},U.prototype.set=function(j,L){var q=this._find(j,!0);return this._values[q]=L,this},U.prototype.delete=function(j){var L=this._find(j,!1);if(L>=0){for(var q=this._keys.length,G=L+1;G<q;G++)this._keys[G-1]=this._keys[G],this._values[G-1]=this._values[G];return this._keys.length--,this._values.length--,j===this._cacheKey&&(this._cacheKey=g,this._cacheIndex=-2),!0}return!1},U.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=g,this._cacheIndex=-2},U.prototype.keys=function(){return new C(this._keys,this._values,P)},U.prototype.values=function(){return new C(this._keys,this._values,D)},U.prototype.entries=function(){return new C(this._keys,this._values,Se)},U.prototype["@@iterator"]=function(){return this.entries()},U.prototype[r]=function(){return this.entries()},U.prototype._find=function(j,L){return this._cacheKey!==j&&(this._cacheIndex=this._keys.indexOf(this._cacheKey=j)),this._cacheIndex<0&&L&&(this._cacheIndex=this._keys.length,this._keys.push(j),this._values.push(void 0)),this._cacheIndex},U}();function P(U,j){return U}function D(U,j){return j}function Se(U,j){return[U,j]}}function yc(){return function(){function g(){this._map=new p}return Object.defineProperty(g.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),g.prototype.has=function(y){return this._map.has(y)},g.prototype.add=function(y){return this._map.set(y,y),this},g.prototype.delete=function(y){return this._map.delete(y)},g.prototype.clear=function(){this._map.clear()},g.prototype.keys=function(){return this._map.keys()},g.prototype.values=function(){return this._map.values()},g.prototype.entries=function(){return this._map.entries()},g.prototype["@@iterator"]=function(){return this.keys()},g.prototype[r]=function(){return this.keys()},g}()}function bc(){var g=16,y=d.create(),C=P();return function(){function L(){this._key=P()}return L.prototype.has=function(q){var G=D(q,!1);return G!==void 0?d.has(G,this._key):!1},L.prototype.get=function(q){var G=D(q,!1);return G!==void 0?d.get(G,this._key):void 0},L.prototype.set=function(q,G){var at=D(q,!0);return at[this._key]=G,this},L.prototype.delete=function(q){var G=D(q,!1);return G!==void 0?delete G[this._key]:!1},L.prototype.clear=function(){this._key=P()},L}();function P(){var L;do L="@@WeakMap@@"+j();while(d.has(y,L));return y[L]=!0,L}function D(L,q){if(!t.call(L,C)){if(!q)return;Object.defineProperty(L,C,{value:d.create()})}return L[C]}function Se(L,q){for(var G=0;G<q;++G)L[G]=Math.random()*255|0;return L}function U(L){return typeof Uint8Array=="function"?typeof crypto<"u"?crypto.getRandomValues(new Uint8Array(L)):typeof msCrypto<"u"?msCrypto.getRandomValues(new Uint8Array(L)):Se(new Uint8Array(L),L):Se(new Array(L),L)}function j(){var L=U(g);L[6]=L[6]&79|64,L[8]=L[8]&191|128;for(var q="",G=0;G<g;++G){var at=L[G];(G===4||G===6||G===8)&&(q+="-"),at<16&&(q+="0"),q+=at.toString(16).toLowerCase()}return q}}function yi(g){return g.__=void 0,delete g.__,g}})})(zs||(zs={}));function sl(n,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(i){if(i!=="default"&&!(i in n)){var s=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(n,i,s.get?s:{enumerable:!0,get:function(){return t[i]}})}})}),Object.freeze(n)}function Te(n,e){if(!n)throw new Error(e)}const rl=34028234663852886e22,al=-34028234663852886e22,ol=4294967295,cl=2147483647,dl=-2147483648;function Bn(n){if(typeof n!="number")throw new Error("invalid int 32: "+typeof n);if(!Number.isInteger(n)||n>cl||n<dl)throw new Error("invalid int 32: "+n)}function Bi(n){if(typeof n!="number")throw new Error("invalid uint 32: "+typeof n);if(!Number.isInteger(n)||n>ol||n<0)throw new Error("invalid uint 32: "+n)}function la(n){if(typeof n!="number")throw new Error("invalid float 32: "+typeof n);if(Number.isFinite(n)&&(n>rl||n<al))throw new Error("invalid float 32: "+n)}const ua=Symbol("@bufbuild/protobuf/enum-type");function ll(n){const e=n[ua];return Te(e,"missing enum type on enum object"),e}function ha(n,e,t,i){n[ua]=pa(e,t.map(s=>({no:s.no,name:s.name,localName:n[s.no]})))}function pa(n,e,t){const i=Object.create(null),s=Object.create(null),r=[];for(const a of e){const o=fa(a);r.push(o),i[a.name]=o,s[a.no]=o}return{typeName:n,values:r,findName(a){return i[a]},findNumber(a){return s[a]}}}function ul(n,e,t){const i={};for(const s of e){const r=fa(s);i[r.localName]=r.no,i[r.no]=r.localName}return ha(i,n,e),i}function fa(n){return"localName"in n?n:Object.assign(Object.assign({},n),{localName:n.name})}class Ht{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const i=this.getType(),s=i.runtime.bin,r=s.makeReadOptions(t);return s.readMessage(this,r.readerFactory(e),e.byteLength,r),this}fromJson(e,t){const i=this.getType(),s=i.runtime.json,r=s.makeReadOptions(t);return s.readMessage(i,e,r,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(s){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(s instanceof Error?s.message:String(s)))}return this.fromJson(i,t)}toBinary(e){const t=this.getType(),i=t.runtime.bin,s=i.makeWriteOptions(e),r=s.writerFactory();return i.writeMessage(this,r,s),r.finish()}toJson(e){const t=this.getType(),i=t.runtime.json,s=i.makeWriteOptions(e);return i.writeMessage(this,s)}toJsonString(e){var t;const i=this.toJson(e);return JSON.stringify(i,null,(t=e==null?void 0:e.prettySpaces)!==null&&t!==void 0?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function hl(n,e,t,i){var s;const r=(s=i==null?void 0:i.localName)!==null&&s!==void 0?s:e.substring(e.lastIndexOf(".")+1),a={[r]:function(o){n.util.initFields(this),n.util.initPartial(o,this)}}[r];return Object.setPrototypeOf(a.prototype,new Ht),Object.assign(a,{runtime:n,typeName:e,fields:n.util.newFieldList(t),fromBinary(o,c){return new a().fromBinary(o,c)},fromJson(o,c){return new a().fromJson(o,c)},fromJsonString(o,c){return new a().fromJsonString(o,c)},equals(o,c){return n.util.equals(a,o,c)}}),a}var b;(function(n){n[n.DOUBLE=1]="DOUBLE",n[n.FLOAT=2]="FLOAT",n[n.INT64=3]="INT64",n[n.UINT64=4]="UINT64",n[n.INT32=5]="INT32",n[n.FIXED64=6]="FIXED64",n[n.FIXED32=7]="FIXED32",n[n.BOOL=8]="BOOL",n[n.STRING=9]="STRING",n[n.BYTES=12]="BYTES",n[n.UINT32=13]="UINT32",n[n.SFIXED32=15]="SFIXED32",n[n.SFIXED64=16]="SFIXED64",n[n.SINT32=17]="SINT32",n[n.SINT64=18]="SINT64"})(b||(b={}));var Ct;(function(n){n[n.BIGINT=0]="BIGINT",n[n.STRING=1]="STRING"})(Ct||(Ct={}));function pl(){let n=0,e=0;for(let i=0;i<28;i+=7){let s=this.buf[this.pos++];if(n|=(s&127)<<i,!(s&128))return this.assertBounds(),[n,e]}let t=this.buf[this.pos++];if(n|=(t&15)<<28,e=(t&112)>>4,!(t&128))return this.assertBounds(),[n,e];for(let i=3;i<=31;i+=7){let s=this.buf[this.pos++];if(e|=(s&127)<<i,!(s&128))return this.assertBounds(),[n,e]}throw new Error("invalid varint")}function Ci(n,e,t){for(let r=0;r<28;r=r+7){const a=n>>>r,o=!(!(a>>>7)&&e==0),c=(o?a|128:a)&255;if(t.push(c),!o)return}const i=n>>>28&15|(e&7)<<4,s=!!(e>>3);if(t.push((s?i|128:i)&255),!!s){for(let r=3;r<31;r=r+7){const a=e>>>r,o=!!(a>>>7),c=(o?a|128:a)&255;if(t.push(c),!o)return}t.push(e>>>31&1)}}const Vn=4294967296;function Ws(n){const e=n[0]==="-";e&&(n=n.slice(1));const t=1e6;let i=0,s=0;function r(a,o){const c=Number(n.slice(a,o));s*=t,i=i*t+c,i>=Vn&&(s=s+(i/Vn|0),i=i%Vn)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),e?ga(i,s):ks(i,s)}function fl(n,e){let t=ks(n,e);const i=t.hi&2147483648;i&&(t=ga(t.lo,t.hi));const s=ma(t.lo,t.hi);return i?"-"+s:s}function ma(n,e){if({lo:n,hi:e}=ml(n,e),e<=2097151)return String(Vn*e+n);const t=n&16777215,i=(n>>>24|e<<8)&16777215,s=e>>16&65535;let r=t+i*6777216+s*6710656,a=i+s*8147497,o=s*2;const c=1e7;return r>=c&&(a+=Math.floor(r/c),r%=c),a>=c&&(o+=Math.floor(a/c),a%=c),o.toString()+Js(a)+Js(r)}function ml(n,e){return{lo:n>>>0,hi:e>>>0}}function ks(n,e){return{lo:n|0,hi:e|0}}function ga(n,e){return e=~e,n?n=~n+1:e+=1,ks(n,e)}const Js=n=>{const e=String(n);return"0000000".slice(e.length)+e};function Ks(n,e){if(n>=0){for(;n>127;)e.push(n&127|128),n=n>>>7;e.push(n)}else{for(let t=0;t<9;t++)e.push(n&127|128),n=n>>7;e.push(1)}}function gl(){let n=this.buf[this.pos++],e=n&127;if(!(n&128))return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<7,!(n&128))return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<14,!(n&128))return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<21,!(n&128))return this.assertBounds(),e;n=this.buf[this.pos++],e|=(n&15)<<28;for(let t=5;n&128&&t<10;t++)n=this.buf[this.pos++];if(n&128)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function vl(){const n=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof n.getBigInt64=="function"&&typeof n.getBigUint64=="function"&&typeof n.setBigInt64=="function"&&typeof n.setBigUint64=="function"&&(typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){const s=BigInt("-9223372036854775808"),r=BigInt("9223372036854775807"),a=BigInt("0"),o=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(c){const d=typeof c=="bigint"?c:BigInt(c);if(d>r||d<s)throw new Error("int64 invalid: ".concat(c));return d},uParse(c){const d=typeof c=="bigint"?c:BigInt(c);if(d>o||d<a)throw new Error("uint64 invalid: ".concat(c));return d},enc(c){return n.setBigInt64(0,this.parse(c),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},uEnc(c){return n.setBigInt64(0,this.uParse(c),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},dec(c,d){return n.setInt32(0,c,!0),n.setInt32(4,d,!0),n.getBigInt64(0,!0)},uDec(c,d){return n.setInt32(0,c,!0),n.setInt32(4,d,!0),n.getBigUint64(0,!0)}}}const t=s=>Te(/^-?[0-9]+$/.test(s),"int64 invalid: ".concat(s)),i=s=>Te(/^[0-9]+$/.test(s),"uint64 invalid: ".concat(s));return{zero:"0",supported:!1,parse(s){return typeof s!="string"&&(s=s.toString()),t(s),s},uParse(s){return typeof s!="string"&&(s=s.toString()),i(s),s},enc(s){return typeof s!="string"&&(s=s.toString()),t(s),Ws(s)},uEnc(s){return typeof s!="string"&&(s=s.toString()),i(s),Ws(s)},dec(s,r){return fl(s,r)},uDec(s,r){return ma(s,r)}}}const se=vl();var ee;(function(n){n[n.Varint=0]="Varint",n[n.Bit64=1]="Bit64",n[n.LengthDelimited=2]="LengthDelimited",n[n.StartGroup=3]="StartGroup",n[n.EndGroup=4]="EndGroup",n[n.Bit32=5]="Bit32"})(ee||(ee={}));class kl{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let s=0;s<this.chunks.length;s++)e+=this.chunks[s].length;let t=new Uint8Array(e),i=0;for(let s=0;s<this.chunks.length;s++)t.set(this.chunks[s],i),i+=this.chunks[s].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(Bi(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Bn(e),Ks(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){la(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){Bi(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Bn(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Bn(e),e=(e<<1^e>>31)>>>0,Ks(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),s=se.enc(e);return i.setInt32(0,s.lo,!0),i.setInt32(4,s.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),s=se.uEnc(e);return i.setInt32(0,s.lo,!0),i.setInt32(4,s.hi,!0),this.raw(t)}int64(e){let t=se.enc(e);return Ci(t.lo,t.hi,this.buf),this}sint64(e){let t=se.enc(e),i=t.hi>>31,s=t.lo<<1^i,r=(t.hi<<1|t.lo>>>31)^i;return Ci(s,r,this.buf),this}uint64(e){let t=se.uEnc(e);return Ci(t.lo,t.hi,this.buf),this}}class yl{constructor(e,t){this.varint64=pl,this.uint32=gl,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=e&7;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e){let t=this.pos;switch(e){case ee.Varint:for(;this.buf[this.pos++]&128;);break;case ee.Bit64:this.pos+=4;case ee.Bit32:this.pos+=4;break;case ee.LengthDelimited:let i=this.uint32();this.pos+=i;break;case ee.StartGroup:let s;for(;(s=this.tag()[1])!==ee.EndGroup;)this.skip(s);break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(t,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return se.dec(...this.varint64())}uint64(){return se.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(e&1);return e=(e>>>1|(t&1)<<31)^i,t=t>>>1^i,se.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return se.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return se.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}}function ot(n,e,t){if(e===t)return!0;if(n==b.BYTES){if(!(e instanceof Uint8Array)||!(t instanceof Uint8Array)||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0}switch(n){case b.UINT64:case b.FIXED64:case b.INT64:case b.SFIXED64:case b.SINT64:return e==t}return!1}function Zn(n,e){switch(n){case b.BOOL:return!1;case b.UINT64:case b.FIXED64:case b.INT64:case b.SFIXED64:case b.SINT64:return e==0?se.zero:"0";case b.DOUBLE:case b.FLOAT:return 0;case b.BYTES:return new Uint8Array(0);case b.STRING:return"";default:return 0}}function va(n,e){const t=e===void 0;let i=ee.Varint,s=e===0;switch(n){case b.STRING:s=t||!e.length,i=ee.LengthDelimited;break;case b.BOOL:s=e===!1;break;case b.DOUBLE:i=ee.Bit64;break;case b.FLOAT:i=ee.Bit32;break;case b.INT64:s=t||e==0;break;case b.UINT64:s=t||e==0;break;case b.FIXED64:s=t||e==0,i=ee.Bit64;break;case b.BYTES:s=t||!e.byteLength,i=ee.LengthDelimited;break;case b.FIXED32:i=ee.Bit32;break;case b.SFIXED32:i=ee.Bit32;break;case b.SFIXED64:s=t||e==0,i=ee.Bit64;break;case b.SINT64:s=t||e==0;break}const r=b[n].toLowerCase();return[i,r,t||s]}function bl(n,e,t,i){let s;return{typeName:e,extendee:t,get field(){if(!s){const r=typeof i=="function"?i():i;r.name=e.split(".").pop(),r.jsonName="[".concat(e,"]"),s=n.util.newFieldList([r]).list()[0]}return s},runtime:n}}function ka(n){const e=n.field.localName,t=Object.create(null);return t[e]=Tl(n),[t,()=>t[e]]}function Tl(n){const e=n.field;if(e.repeated)return[];if(e.default!==void 0)return e.default;switch(e.kind){case"enum":return e.T.values[0].no;case"scalar":return Zn(e.T,e.L);case"message":const t=e.T,i=new t;return t.fieldWrapper?t.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}function Cl(n,e){if(!e.repeated&&(e.kind=="enum"||e.kind=="scalar")){for(let t=n.length-1;t>=0;--t)if(n[t].no==e.no)return[n[t]];return[]}return n.filter(t=>t.no===e.no)}function Sl(n,e,t,i){return{syntax:n,json:e,bin:t,util:i,makeMessageType(s,r,a){return hl(this,s,r,a)},makeEnum:ul,makeEnumType:pa,getEnumType:ll,makeExtension(s,r,a){return bl(this,s,r,a)}}}function ya(n,e){return e instanceof Ht||!n.fieldWrapper?e:n.fieldWrapper.wrapField(e)}b.DOUBLE,b.FLOAT,b.INT64,b.UINT64,b.INT32,b.UINT32,b.BOOL,b.STRING,b.BYTES;const Ot=Symbol("@bufbuild/protobuf/unknown-fields"),Qs={readUnknownFields:!0,readerFactory:n=>new yl(n)},Ys={writeUnknownFields:!0,writerFactory:()=>new kl};function _l(n){return n?Object.assign(Object.assign({},Qs),n):Qs}function El(n){return n?Object.assign(Object.assign({},Ys),n):Ys}function wl(){return{makeReadOptions:_l,makeWriteOptions:El,listUnknownFields(n){var e;return(e=n[Ot])!==null&&e!==void 0?e:[]},discardUnknownFields(n){delete n[Ot]},writeUnknownFields(n,e){const i=n[Ot];if(i)for(const s of i)e.tag(s.no,s.wireType).raw(s.data)},onUnknownField(n,e,t,i){const s=n;Array.isArray(s[Ot])||(s[Ot]=[]),s[Ot].push({no:e,wireType:t,data:i})},readMessage(n,e,t,i,s){const r=n.getType(),a=s?e.len:e.pos+t;let o,c;for(;e.pos<a&&([o,c]=e.tag(),c!=ee.EndGroup);){const d=r.fields.find(o);if(!d){const l=e.skip(c);i.readUnknownFields&&this.onUnknownField(n,o,c,l);continue}Xs(n,e,d,c,i)}if(s&&(c!=ee.EndGroup||o!==t))throw new Error("invalid end group tag")},readField:Xs}}function Xs(n,e,t,i,s){let{repeated:r,localName:a}=t;switch(t.oneof&&(n=n[t.oneof.localName],n.case!=a&&delete n.value,n.case=a,a="value"),t.kind){case"scalar":case"enum":const o=t.kind=="enum"?b.INT32:t.T;let c=ei;if(t.kind=="scalar"&&t.L>0&&(c=Rl),r){let p=n[a];if(i==ee.LengthDelimited&&o!=b.STRING&&o!=b.BYTES){let k=e.uint32()+e.pos;for(;e.pos<k;)p.push(c(e,o))}else p.push(c(e,o))}else n[a]=c(e,o);break;case"message":const d=t.T;r?n[a].push($n(e,new d,s,t)):n[a]instanceof Ht?$n(e,n[a],s,t):(n[a]=$n(e,new d,s,t),d.fieldWrapper&&!t.oneof&&!t.repeated&&(n[a]=d.fieldWrapper.unwrapField(n[a])));break;case"map":let[l,u]=Pl(t,e,s);n[a][l]=u;break}}function $n(n,e,t,i){const s=e.getType().runtime.bin,r=i==null?void 0:i.delimited;return s.readMessage(e,n,r?i==null?void 0:i.no:n.uint32(),t,r),e}function Pl(n,e,t){const i=e.uint32(),s=e.pos+i;let r,a;for(;e.pos<s;){let[o]=e.tag();switch(o){case 1:r=ei(e,n.K);break;case 2:switch(n.V.kind){case"scalar":a=ei(e,n.V.T);break;case"enum":a=e.int32();break;case"message":a=$n(e,new n.V.T,t,void 0);break}break}}if(r===void 0){let o=Zn(n.K,Ct.BIGINT);r=n.K==b.BOOL?o.toString():o}if(typeof r!="string"&&typeof r!="number"&&(r=r.toString()),a===void 0)switch(n.V.kind){case"scalar":a=Zn(n.V.T,Ct.BIGINT);break;case"enum":a=0;break;case"message":a=new n.V.T;break}return[r,a]}function Rl(n,e){const t=ei(n,e);return typeof t=="bigint"?t.toString():t}function ei(n,e){switch(e){case b.STRING:return n.string();case b.BOOL:return n.bool();case b.DOUBLE:return n.double();case b.FLOAT:return n.float();case b.INT32:return n.int32();case b.INT64:return n.int64();case b.UINT64:return n.uint64();case b.FIXED64:return n.fixed64();case b.BYTES:return n.bytes();case b.FIXED32:return n.fixed32();case b.SFIXED32:return n.sfixed32();case b.SFIXED64:return n.sfixed64();case b.SINT64:return n.sint64();case b.UINT32:return n.uint32();case b.SINT32:return n.sint32()}}function Il(n,e,t,i,s){n.tag(t.no,ee.LengthDelimited),n.fork();let r=i;switch(t.K){case b.INT32:case b.FIXED32:case b.UINT32:case b.SFIXED32:case b.SINT32:r=Number.parseInt(i);break;case b.BOOL:Te(i=="true"||i=="false"),r=i=="true";break}switch(ln(n,t.K,1,r,!0),t.V.kind){case"scalar":ln(n,t.V.T,2,s,!0);break;case"enum":ln(n,b.INT32,2,s,!0);break;case"message":n.tag(2,ee.LengthDelimited).bytes(s.toBinary(e));break}n.join()}function Zs(n,e,t,i){const s=ya(t.T,i);t!=null&&t.delimited?n.tag(t.no,ee.StartGroup).raw(s.toBinary(e)).tag(t.no,ee.EndGroup):n.tag(t.no,ee.LengthDelimited).bytes(s.toBinary(e))}function ln(n,e,t,i,s){let[r,a,o]=va(e,i);(!o||s)&&n.tag(t,r)[a](i)}function Ol(n,e,t,i){if(!i.length)return;n.tag(t,ee.LengthDelimited).fork();let[,s]=va(e);for(let r=0;r<i.length;r++)n[s](i[r]);n.join()}function Ml(){return Object.assign(Object.assign({},wl()),{writeField:er,writeMessage(n,e,t){const i=n.getType();for(const s of i.fields.byNumber()){let r,a=s.localName;if(s.oneof){const o=n[s.oneof.localName];if(o.case!==a)continue;r=o.value}else r=n[a];er(s,r,e,t)}return t.writeUnknownFields&&this.writeUnknownFields(n,e),e}})}function er(n,e,t,i){const s=n.repeated;switch(n.kind){case"scalar":case"enum":let r=n.kind=="enum"?b.INT32:n.T;if(s)if(n.packed)Ol(t,r,n.no,e);else for(const a of e)ln(t,r,n.no,a,!0);else e!==void 0&&ln(t,r,n.no,e,!!n.oneof||n.opt);break;case"message":if(s)for(const a of e)Zs(t,i,n,a);else e!==void 0&&Zs(t,i,n,e);break;case"map":for(const[a,o]of Object.entries(e))Il(t,i,n,a,o);break}}let Xe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),ci=[];for(let n=0;n<Xe.length;n++)ci[Xe[n].charCodeAt(0)]=n;ci[45]=Xe.indexOf("+");ci[95]=Xe.indexOf("/");const ba={dec(n){let e=n.length*3/4;n[n.length-2]=="="?e-=2:n[n.length-1]=="="&&(e-=1);let t=new Uint8Array(e),i=0,s=0,r,a=0;for(let o=0;o<n.length;o++){if(r=ci[n.charCodeAt(o)],r===void 0)switch(n[o]){case"=":s=0;case`
|
|
18
|
-
`:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(s){case 0:a=r,s=1;break;case 1:t[i++]=a<<2|(r&48)>>4,a=r,s=2;break;case 2:t[i++]=(a&15)<<4|(r&60)>>2,a=r,s=3;break;case 3:t[i++]=(a&3)<<6|r,s=0;break}}if(s==1)throw Error("invalid base64 string.");return t.subarray(0,i)},enc(n){let e="",t=0,i,s=0;for(let r=0;r<n.length;r++)switch(i=n[r],t){case 0:e+=Xe[i>>2],s=(i&3)<<4,t=1;break;case 1:e+=Xe[s|i>>4],s=(i&15)<<2,t=2;break;case 2:e+=Xe[s|i>>6],e+=Xe[i&63],t=0;break}return t&&(e+=Xe[s],e+="=",t==1&&(e+="=")),e}};function xl(n,e,t){Ca(e,n);const i=e.runtime.bin.makeReadOptions(t),s=Cl(n.getType().runtime.bin.listUnknownFields(n),e.field),[r,a]=ka(e);for(const o of s)e.runtime.bin.readField(r,i.readerFactory(o.data),e.field,o.wireType,i);return a()}function Al(n,e,t,i){Ca(e,n);const s=e.runtime.bin.makeReadOptions(i),r=e.runtime.bin.makeWriteOptions(i);if(Ta(n,e)){const d=n.getType().runtime.bin.listUnknownFields(n).filter(l=>l.no!=e.field.no);n.getType().runtime.bin.discardUnknownFields(n);for(const l of d)n.getType().runtime.bin.onUnknownField(n,l.no,l.wireType,l.data)}const a=r.writerFactory();let o=e.field;!o.opt&&!o.repeated&&(o.kind=="enum"||o.kind=="scalar")&&(o=Object.assign(Object.assign({},e.field),{opt:!0})),e.runtime.bin.writeField(o,t,a,r);const c=s.readerFactory(a.finish());for(;c.pos<c.len;){const[d,l]=c.tag(),u=c.skip(l);n.getType().runtime.bin.onUnknownField(n,d,l,u)}}function Ta(n,e){const t=n.getType();return e.extendee.typeName===t.typeName&&!!t.runtime.bin.listUnknownFields(n).find(i=>i.no==e.field.no)}function Ca(n,e){Te(n.extendee.typeName==e.getType().typeName,"extension ".concat(n.typeName," can only be applied to message ").concat(n.extendee.typeName))}const tr={ignoreUnknownFields:!1},nr={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function Dl(n){return n?Object.assign(Object.assign({},tr),n):tr}function Nl(n){return n?Object.assign(Object.assign({},nr),n):nr}function Ll(n,e){const t=e(Ul,sr);return{makeReadOptions:Dl,makeWriteOptions:Nl,readMessage(i,s,r,a){if(s==null||Array.isArray(s)||typeof s!="object")throw new Error("cannot decode message ".concat(i.typeName," from JSON: ").concat($e(s)));a=a??new i;const o=new Map,c=r.typeRegistry;for(const[d,l]of Object.entries(s)){const u=i.fields.findJsonName(d);if(u){if(u.oneof){if(l===null&&u.kind=="scalar")continue;const p=o.get(u.oneof);if(p!==void 0)throw new Error("cannot decode message ".concat(i.typeName,' from JSON: multiple keys for oneof "').concat(u.oneof.name,'" present: "').concat(p,'", "').concat(d,'"'));o.set(u.oneof,d)}ir(a,l,u,r,i,n)}else{let p=!1;if(c!=null&&c.findExtension&&d.startsWith("[")&&d.endsWith("]")){const m=c.findExtension(d.substring(1,d.length-1));if(m&&m.extendee.typeName==i.typeName){p=!0;const[k,v]=ka(m);ir(k,l,m.field,r,m,!0),Al(a,m,v(),r)}}if(!p&&!r.ignoreUnknownFields)throw new Error("cannot decode message ".concat(i.typeName,' from JSON: key "').concat(d,'" is unknown'))}}return a},writeMessage(i,s){const r=i.getType(),a={};let o;try{for(const d of r.fields.byMember()){let l;if(d.kind=="oneof"){const u=i[d.localName];if(u.value===void 0)continue;if(o=d.findField(u.case),!o)throw"oneof case not found: "+u.case;l=t(o,u.value,s)}else o=d,l=t(o,i[o.localName],s);l!==void 0&&(a[s.useProtoFieldName?o.name:o.jsonName]=l)}const c=s.typeRegistry;if(c!=null&&c.findExtensionFor)for(const d of r.runtime.bin.listUnknownFields(i)){const l=c.findExtensionFor(r.typeName,d.no);if(l&&Ta(i,l)){const u=xl(i,l,s),p=t(l.field,u,s);p!==void 0&&(a[l.field.jsonName]=p)}}}catch(c){const d=o?"cannot encode field ".concat(r.typeName,".").concat(o.name," to JSON"):"cannot encode message ".concat(r.typeName," to JSON"),l=c instanceof Error?c.message:String(c);throw new Error(d+(l.length>0?": ".concat(l):""))}return a},readScalar:(i,s,r)=>nn(i,s,r,n),writeScalar:sr,debug:$e}}function $e(n){if(n===null)return"null";switch(typeof n){case"object":return Array.isArray(n)?"array":"object";case"string":return n.length>100?"string":'"'.concat(n.split('"').join('\\"'),'"');default:return String(n)}}function ir(n,e,t,i,s,r){let a=t.localName;if(t.oneof){if(e===null&&t.kind=="scalar")return;n=n[t.oneof.localName]={case:a},a="value"}if(t.repeated){if(e===null)return;if(!Array.isArray(e))throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat($e(e)));const o=n[a];for(const c of e){if(c===null)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat($e(c)));let d;switch(t.kind){case"message":d=t.T.fromJson(c,i);break;case"enum":if(d=Si(t.T,c,i.ignoreUnknownFields,!0),d===void 0)continue;break;case"scalar":try{d=nn(t.T,c,t.L,!0)}catch(l){let u="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat($e(c));throw l instanceof Error&&l.message.length>0&&(u+=": ".concat(l.message)),new Error(u)}break}o.push(d)}}else if(t.kind=="map"){if(e===null)return;if(typeof e!="object"||Array.isArray(e))throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat($e(e)));const o=n[a];for(const[c,d]of Object.entries(e)){if(d===null)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: map value null"));let l;switch(t.V.kind){case"message":l=t.V.T.fromJson(d,i);break;case"enum":if(l=Si(t.V.T,d,i.ignoreUnknownFields,!0),l===void 0)continue;break;case"scalar":try{l=nn(t.V.T,d,Ct.BIGINT,!0)}catch(u){let p="cannot decode map value for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat($e(e));throw u instanceof Error&&u.message.length>0&&(p+=": ".concat(u.message)),new Error(p)}break}try{o[nn(t.K,t.K==b.BOOL?c=="true"?!0:c=="false"?!1:c:c,Ct.BIGINT,!0).toString()]=l}catch(u){let p="cannot decode map key for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat($e(e));throw u instanceof Error&&u.message.length>0&&(p+=": ".concat(u.message)),new Error(p)}}}else switch(t.kind){case"message":const o=t.T;if(e===null&&o.typeName!="google.protobuf.Value"){if(t.oneof)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: null is invalid for oneof field"));return}n[a]instanceof Ht?n[a].fromJson(e,i):(n[a]=o.fromJson(e,i),o.fieldWrapper&&!t.oneof&&(n[a]=o.fieldWrapper.unwrapField(n[a])));break;case"enum":const c=Si(t.T,e,i.ignoreUnknownFields,r);c!==void 0&&(n[a]=c);break;case"scalar":try{n[a]=nn(t.T,e,t.L,r)}catch(d){let l="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat($e(e));throw d instanceof Error&&d.message.length>0&&(l+=": ".concat(d.message)),new Error(l)}break}}function nn(n,e,t,i){switch(n){case b.DOUBLE:case b.FLOAT:if(e===null)return i?0:void 0;if(e==="NaN")return Number.NaN;if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e===""||typeof e=="string"&&e.trim().length!==e.length||typeof e!="string"&&typeof e!="number")break;const s=Number(e);if(Number.isNaN(s)||!Number.isFinite(s))break;return n==b.FLOAT&&la(s),s;case b.INT32:case b.FIXED32:case b.SFIXED32:case b.SINT32:case b.UINT32:if(e===null)return i?0:void 0;let r;if(typeof e=="number"?r=e:typeof e=="string"&&e.length>0&&e.trim().length===e.length&&(r=Number(e)),r===void 0)break;return n==b.UINT32?Bi(r):Bn(r),r;case b.INT64:case b.SFIXED64:case b.SINT64:if(e===null)return i?se.zero:void 0;if(typeof e!="number"&&typeof e!="string")break;const a=se.parse(e);return t?a.toString():a;case b.FIXED64:case b.UINT64:if(e===null)return i?se.zero:void 0;if(typeof e!="number"&&typeof e!="string")break;const o=se.uParse(e);return t?o.toString():o;case b.BOOL:if(e===null)return i?!1:void 0;if(typeof e!="boolean")break;return e;case b.STRING:if(e===null)return i?"":void 0;if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case b.BYTES:if(e===null)return i?new Uint8Array(0):void 0;if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return ba.dec(e)}throw new Error}function Si(n,e,t,i){if(e===null)return i?n.values[0].no:void 0;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":const s=n.findName(e);if(s||t)return s==null?void 0:s.no;break}throw new Error("cannot decode enum ".concat(n.typeName," from JSON: ").concat($e(e)))}function Ul(n,e,t,i){var s;if(e===void 0)return e;if(!t&&n.values[0].no===e)return;if(i)return e;if(n.typeName=="google.protobuf.NullValue")return null;const r=n.findNumber(e);return(s=r==null?void 0:r.name)!==null&&s!==void 0?s:e}function sr(n,e,t){if(e!==void 0)switch(n){case b.INT32:case b.SFIXED32:case b.SINT32:case b.FIXED32:case b.UINT32:return Te(typeof e=="number"),e!=0||t?e:void 0;case b.FLOAT:case b.DOUBLE:return Te(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e!==0||t?e:void 0;case b.STRING:return Te(typeof e=="string"),e.length>0||t?e:void 0;case b.BOOL:return Te(typeof e=="boolean"),e||t?e:void 0;case b.UINT64:case b.FIXED64:case b.INT64:case b.SFIXED64:case b.SINT64:return Te(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),t||e!=0?e.toString(10):void 0;case b.BYTES:return Te(e instanceof Uint8Array),t||e.byteLength>0?ba.enc(e):void 0}}function jl(){return Ll(!0,(n,e)=>function(i,s,r){if(i.kind=="map"){const a={};switch(i.V.kind){case"scalar":for(const[c,d]of Object.entries(s)){const l=e(i.V.T,d,!0);Te(l!==void 0),a[c.toString()]=l}break;case"message":for(const[c,d]of Object.entries(s))a[c.toString()]=d.toJson(r);break;case"enum":const o=i.V.T;for(const[c,d]of Object.entries(s)){Te(d===void 0||typeof d=="number");const l=n(o,d,!0,r.enumAsInteger);Te(l!==void 0),a[c.toString()]=l}break}return r.emitDefaultValues||Object.keys(a).length>0?a:void 0}else if(i.repeated){const a=[];switch(i.kind){case"scalar":for(let o=0;o<s.length;o++)a.push(e(i.T,s[o],!0));break;case"enum":for(let o=0;o<s.length;o++)a.push(n(i.T,s[o],!0,r.enumAsInteger));break;case"message":for(let o=0;o<s.length;o++)a.push(s[o].toJson(r));break}return r.emitDefaultValues||a.length>0?a:void 0}else{if(s===void 0)return;switch(i.kind){case"scalar":return e(i.T,s,!!i.oneof||i.opt||r.emitDefaultValues);case"enum":return n(i.T,s,!!i.oneof||i.opt||r.emitDefaultValues,r.enumAsInteger);case"message":return ya(i.T,s).toJson(r)}}})}function Fl(){return{setEnumType:ha,initPartial(n,e){if(n===void 0)return;const t=e.getType();for(const i of t.fields.byMember()){const s=i.localName,r=e,a=n;if(a[s]!==void 0)switch(i.kind){case"oneof":const o=a[s].case;if(o===void 0)continue;const c=i.findField(o);let d=a[s].value;c&&c.kind=="message"&&!(d instanceof c.T)?d=new c.T(d):c&&c.kind==="scalar"&&c.T===b.BYTES&&(d=Kt(d)),r[s]={case:o,value:d};break;case"scalar":case"enum":let l=a[s];i.T===b.BYTES&&(l=i.repeated?l.map(Kt):Kt(l)),r[s]=l;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===b.BYTES)for(const[m,k]of Object.entries(a[s]))r[s][m]=Kt(k);else Object.assign(r[s],a[s]);break;case"message":const p=i.V.T;for(const m of Object.keys(a[s])){let k=a[s][m];p.fieldWrapper||(k=new p(k)),r[s][m]=k}break}break;case"message":const u=i.T;if(i.repeated)r[s]=a[s].map(p=>p instanceof u?p:new u(p));else if(a[s]!==void 0){const p=a[s];u.fieldWrapper?u.typeName==="google.protobuf.BytesValue"?r[s]=Kt(p):r[s]=p:r[s]=p instanceof u?p:new u(p)}break}}},equals(n,e,t){return e===t?!0:!e||!t?!1:n.fields.byMember().every(i=>{const s=e[i.localName],r=t[i.localName];if(i.repeated){if(s.length!==r.length)return!1;switch(i.kind){case"message":return s.every((a,o)=>i.T.equals(a,r[o]));case"scalar":return s.every((a,o)=>ot(i.T,a,r[o]));case"enum":return s.every((a,o)=>ot(b.INT32,a,r[o]))}throw new Error("repeated cannot contain ".concat(i.kind))}switch(i.kind){case"message":return i.T.equals(s,r);case"enum":return ot(b.INT32,s,r);case"scalar":return ot(i.T,s,r);case"oneof":if(s.case!==r.case)return!1;const a=i.findField(s.case);if(a===void 0)return!0;switch(a.kind){case"message":return a.T.equals(s.value,r.value);case"enum":return ot(b.INT32,s.value,r.value);case"scalar":return ot(a.T,s.value,r.value)}throw new Error("oneof cannot contain ".concat(a.kind));case"map":const o=Object.keys(s).concat(Object.keys(r));switch(i.V.kind){case"message":const c=i.V.T;return o.every(l=>c.equals(s[l],r[l]));case"enum":return o.every(l=>ot(b.INT32,s[l],r[l]));case"scalar":const d=i.V.T;return o.every(l=>ot(d,s[l],r[l]))}break}})},clone(n){const e=n.getType(),t=new e,i=t;for(const s of e.fields.byMember()){const r=n[s.localName];let a;if(s.repeated)a=r.map(Ln);else if(s.kind=="map"){a=i[s.localName];for(const[o,c]of Object.entries(r))a[o]=Ln(c)}else s.kind=="oneof"?a=s.findField(r.case)?{case:r.case,value:Ln(r.value)}:{case:void 0}:a=Ln(r);i[s.localName]=a}return t}}}function Ln(n){if(n===void 0)return n;if(n instanceof Ht)return n.clone();if(n instanceof Uint8Array){const e=new Uint8Array(n.byteLength);return e.set(n),e}return n}function Kt(n){return n instanceof Uint8Array?n:new Uint8Array(n)}class Bl{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const t={};for(const i of this.list())t[i.jsonName]=t[i.name]=i;this.jsonNames=t}return this.jsonNames[e]}find(e){if(!this.numbers){const t={};for(const i of this.list())t[i.no]=i;this.numbers=t}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((e,t)=>e.no-t.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const i of this.list())i.oneof?i.oneof!==t&&(t=i.oneof,e.push(t)):e.push(i)}return this.members}}function Sa(n,e){const t=_a(n);return e?t:zl(Gl(t))}function Vl(n){return Sa(n,!1)}const $l=_a;function _a(n){let e=!1;const t=[];for(let i=0;i<n.length;i++){let s=n.charAt(i);switch(s){case"_":e=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":t.push(s),e=!1;break;default:e&&(e=!1,s=s.toUpperCase()),t.push(s);break}}return t.join("")}const Hl=new Set(["constructor","toString","toJSON","valueOf"]),ql=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Ea=n=>"".concat(n,"$"),Gl=n=>ql.has(n)?Ea(n):n,zl=n=>Hl.has(n)?Ea(n):n;class Wl{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=Vl(e)}addField(e){Te(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let t=0;t<this.fields.length;t++)this._lookup[this.fields[t].localName]=this.fields[t]}return this._lookup[e]}}const h=Sl("proto3",jl(),Ml(),Object.assign(Object.assign({},Fl()),{newFieldList(n){return new Bl(n,Jl)},initFields(n){for(const e of n.getType().fields.byMember()){if(e.opt)continue;const t=e.localName,i=n;if(e.repeated){i[t]=[];continue}switch(e.kind){case"oneof":i[t]={case:void 0};break;case"enum":i[t]=0;break;case"map":i[t]={};break;case"scalar":i[t]=Zn(e.T,e.L);break}}}}));function Jl(n){var e,t,i,s;const r=[];let a;for(const o of typeof n=="function"?n():n){const c=o;if(c.localName=Sa(o.name,o.oneof!==void 0),c.jsonName=(e=o.jsonName)!==null&&e!==void 0?e:$l(o.name),c.repeated=(t=o.repeated)!==null&&t!==void 0?t:!1,o.kind=="scalar"&&(c.L=(i=o.L)!==null&&i!==void 0?i:Ct.BIGINT),o.oneof!==void 0){const d=typeof o.oneof=="string"?o.oneof:o.oneof.name;(!a||a.name!=d)&&(a=new Wl(d)),c.oneof=a,a.addField(c)}o.kind=="message"&&(c.delimited=!1),c.packed=(s=o.packed)!==null&&s!==void 0?s:o.kind=="enum"||o.kind=="scalar"&&o.T!=b.BYTES&&o.T!=b.STRING,r.push(c)}return r}class ge extends Ht{constructor(e){super(),this.seconds=se.zero,this.nanos=0,h.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(h.json.debug(e)));const i=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const s=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(s))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(s<Date.parse("0001-01-01T00:00:00Z")||s>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=se.parse(s/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){const t=Number(this.seconds)*1e3;if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){const s=(this.nanos+1e9).toString().substring(1);s.substring(3)==="000000"?i="."+s.substring(0,3)+"Z":s.substring(6)==="000"?i="."+s.substring(0,6)+"Z":i="."+s+"Z"}return new Date(t).toISOString().replace(".000Z",i)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return ge.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new ge({seconds:se.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new ge().fromBinary(e,t)}static fromJson(e,t){return new ge().fromJson(e,t)}static fromJsonString(e,t){return new ge().fromJsonString(e,t)}static equals(e,t){return h.util.equals(ge,e,t)}}ge.runtime=h;ge.typeName="google.protobuf.Timestamp";ge.fields=h.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const wa=h.makeEnum("livekit.AudioCodec",[{no:0,name:"DEFAULT_AC"},{no:1,name:"OPUS"},{no:2,name:"AAC"}]),Pa=h.makeEnum("livekit.VideoCodec",[{no:0,name:"DEFAULT_VC"},{no:1,name:"H264_BASELINE"},{no:2,name:"H264_MAIN"},{no:3,name:"H264_HIGH"},{no:4,name:"VP8"}]),Kl=h.makeEnum("livekit.ImageCodec",[{no:0,name:"IC_DEFAULT"},{no:1,name:"IC_JPEG"}]),Le=h.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),me=h.makeEnum("livekit.TrackSource",[{no:0,name:"UNKNOWN"},{no:1,name:"CAMERA"},{no:2,name:"MICROPHONE"},{no:3,name:"SCREEN_SHARE"},{no:4,name:"SCREEN_SHARE_AUDIO"}]),ys=h.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),sn=h.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),yn=h.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),un=h.makeEnum("livekit.DisconnectReason",[{no:0,name:"UNKNOWN_REASON"},{no:1,name:"CLIENT_INITIATED"},{no:2,name:"DUPLICATE_IDENTITY"},{no:3,name:"SERVER_SHUTDOWN"},{no:4,name:"PARTICIPANT_REMOVED"},{no:5,name:"ROOM_DELETED"},{no:6,name:"STATE_MISMATCH"},{no:7,name:"JOIN_FAILURE"},{no:8,name:"MIGRATION"},{no:9,name:"SIGNAL_CLOSE"}]),Mt=h.makeEnum("livekit.ReconnectReason",[{no:0,name:"RR_UNKNOWN"},{no:1,name:"RR_SIGNAL_DISCONNECTED"},{no:2,name:"RR_PUBLISHER_FAILED"},{no:3,name:"RR_SUBSCRIBER_FAILED"},{no:4,name:"RR_SWITCH_CANDIDATE"}]),Ql=h.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),qt=h.makeMessageType("livekit.Room",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"empty_timeout",kind:"scalar",T:13},{no:14,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:5,name:"creation_time",kind:"scalar",T:3},{no:6,name:"turn_password",kind:"scalar",T:9},{no:7,name:"enabled_codecs",kind:"message",T:Vi,repeated:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"num_participants",kind:"scalar",T:13},{no:11,name:"num_publishers",kind:"scalar",T:13},{no:10,name:"active_recording",kind:"scalar",T:8},{no:13,name:"version",kind:"message",T:Na}]),Vi=h.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]);h.makeMessageType("livekit.PlayoutDelay",()=>[{no:1,name:"enabled",kind:"scalar",T:8},{no:2,name:"min",kind:"scalar",T:13},{no:3,name:"max",kind:"scalar",T:13}]);const Ra=h.makeMessageType("livekit.ParticipantPermission",()=>[{no:1,name:"can_subscribe",kind:"scalar",T:8},{no:2,name:"can_publish",kind:"scalar",T:8},{no:3,name:"can_publish_data",kind:"scalar",T:8},{no:9,name:"can_publish_sources",kind:"enum",T:h.getEnumType(me),repeated:!0},{no:7,name:"hidden",kind:"scalar",T:8},{no:8,name:"recorder",kind:"scalar",T:8},{no:10,name:"can_update_metadata",kind:"scalar",T:8},{no:11,name:"agent",kind:"scalar",T:8}]),mt=h.makeMessageType("livekit.ParticipantInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:h.getEnumType($i)},{no:4,name:"tracks",kind:"message",T:Ze,repeated:!0},{no:5,name:"metadata",kind:"scalar",T:9},{no:6,name:"joined_at",kind:"scalar",T:3},{no:9,name:"name",kind:"scalar",T:9},{no:10,name:"version",kind:"scalar",T:13},{no:11,name:"permission",kind:"message",T:Ra},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:h.getEnumType(Yl)}]),$i=h.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),Yl=h.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]);h.makeMessageType("livekit.Encryption",[]);const Oe=h.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),Xl=h.makeMessageType("livekit.SimulcastCodecInfo",()=>[{no:1,name:"mime_type",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:ht,repeated:!0}]),Ze=h.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:h.getEnumType(Le)},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"muted",kind:"scalar",T:8},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"simulcast",kind:"scalar",T:8},{no:8,name:"disable_dtx",kind:"scalar",T:8},{no:9,name:"source",kind:"enum",T:h.getEnumType(me)},{no:10,name:"layers",kind:"message",T:ht,repeated:!0},{no:11,name:"mime_type",kind:"scalar",T:9},{no:12,name:"mid",kind:"scalar",T:9},{no:13,name:"codecs",kind:"message",T:Xl,repeated:!0},{no:14,name:"stereo",kind:"scalar",T:8},{no:15,name:"disable_red",kind:"scalar",T:8},{no:16,name:"encryption",kind:"enum",T:h.getEnumType(Oe)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Na}]),ht=h.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:h.getEnumType(ys)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13}]),Ia=h.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:h.getEnumType(ke)},{no:4,name:"participant_identity",kind:"scalar",T:9},{no:5,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:2,name:"user",kind:"message",T:Ma,oneof:"value"},{no:3,name:"speaker",kind:"message",T:Zl,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:eu,oneof:"value"}]),ke=h.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),Zl=h.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:Oa,repeated:!0}]),Oa=h.makeMessageType("livekit.SpeakerInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"level",kind:"scalar",T:2},{no:3,name:"active",kind:"scalar",T:8}]),Ma=h.makeMessageType("livekit.UserPacket",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:5,name:"participant_identity",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"destination_sids",kind:"scalar",T:9,repeated:!0},{no:6,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:4,name:"topic",kind:"scalar",T:9,opt:!0}]),eu=h.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),bs=h.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),tu=h.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:h.getEnumType(xa)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"region",kind:"scalar",T:9},{no:5,name:"node_id",kind:"scalar",T:9},{no:6,name:"debug_info",kind:"scalar",T:9}]),xa=h.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),nu=h.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:h.getEnumType(Aa)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"os",kind:"scalar",T:9},{no:5,name:"os_version",kind:"scalar",T:9},{no:6,name:"device_model",kind:"scalar",T:9},{no:7,name:"browser",kind:"scalar",T:9},{no:8,name:"browser_version",kind:"scalar",T:9},{no:9,name:"address",kind:"scalar",T:9},{no:10,name:"network",kind:"scalar",T:9}]),Aa=h.makeEnum("livekit.ClientInfo.SDK",[{no:0,name:"UNKNOWN"},{no:1,name:"JS"},{no:2,name:"SWIFT"},{no:3,name:"ANDROID"},{no:4,name:"FLUTTER"},{no:5,name:"GO"},{no:6,name:"UNITY"},{no:7,name:"REACT_NATIVE"},{no:8,name:"RUST"},{no:9,name:"PYTHON"},{no:10,name:"CPP"}]),Da=h.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:rr},{no:2,name:"screen",kind:"message",T:rr},{no:3,name:"resume_connection",kind:"enum",T:h.getEnumType(yn)},{no:4,name:"disabled_codecs",kind:"message",T:iu},{no:5,name:"force_relay",kind:"enum",T:h.getEnumType(yn)}]),rr=h.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:h.getEnumType(yn)}]),iu=h.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:Vi,repeated:!0},{no:2,name:"publish",kind:"message",T:Vi,repeated:!0}]),ar=h.makeMessageType("livekit.RTPDrift",()=>[{no:1,name:"start_time",kind:"message",T:ge},{no:2,name:"end_time",kind:"message",T:ge},{no:3,name:"duration",kind:"scalar",T:1},{no:4,name:"start_timestamp",kind:"scalar",T:4},{no:5,name:"end_timestamp",kind:"scalar",T:4},{no:6,name:"rtp_clock_ticks",kind:"scalar",T:4},{no:7,name:"drift_samples",kind:"scalar",T:3},{no:8,name:"drift_ms",kind:"scalar",T:1},{no:9,name:"clock_rate",kind:"scalar",T:1}]);h.makeMessageType("livekit.RTPStats",()=>[{no:1,name:"start_time",kind:"message",T:ge},{no:2,name:"end_time",kind:"message",T:ge},{no:3,name:"duration",kind:"scalar",T:1},{no:4,name:"packets",kind:"scalar",T:13},{no:5,name:"packet_rate",kind:"scalar",T:1},{no:6,name:"bytes",kind:"scalar",T:4},{no:39,name:"header_bytes",kind:"scalar",T:4},{no:7,name:"bitrate",kind:"scalar",T:1},{no:8,name:"packets_lost",kind:"scalar",T:13},{no:9,name:"packet_loss_rate",kind:"scalar",T:1},{no:10,name:"packet_loss_percentage",kind:"scalar",T:2},{no:11,name:"packets_duplicate",kind:"scalar",T:13},{no:12,name:"packet_duplicate_rate",kind:"scalar",T:1},{no:13,name:"bytes_duplicate",kind:"scalar",T:4},{no:40,name:"header_bytes_duplicate",kind:"scalar",T:4},{no:14,name:"bitrate_duplicate",kind:"scalar",T:1},{no:15,name:"packets_padding",kind:"scalar",T:13},{no:16,name:"packet_padding_rate",kind:"scalar",T:1},{no:17,name:"bytes_padding",kind:"scalar",T:4},{no:41,name:"header_bytes_padding",kind:"scalar",T:4},{no:18,name:"bitrate_padding",kind:"scalar",T:1},{no:19,name:"packets_out_of_order",kind:"scalar",T:13},{no:20,name:"frames",kind:"scalar",T:13},{no:21,name:"frame_rate",kind:"scalar",T:1},{no:22,name:"jitter_current",kind:"scalar",T:1},{no:23,name:"jitter_max",kind:"scalar",T:1},{no:24,name:"gap_histogram",kind:"map",K:5,V:{kind:"scalar",T:13}},{no:25,name:"nacks",kind:"scalar",T:13},{no:37,name:"nack_acks",kind:"scalar",T:13},{no:26,name:"nack_misses",kind:"scalar",T:13},{no:38,name:"nack_repeated",kind:"scalar",T:13},{no:27,name:"plis",kind:"scalar",T:13},{no:28,name:"last_pli",kind:"message",T:ge},{no:29,name:"firs",kind:"scalar",T:13},{no:30,name:"last_fir",kind:"message",T:ge},{no:31,name:"rtt_current",kind:"scalar",T:13},{no:32,name:"rtt_max",kind:"scalar",T:13},{no:33,name:"key_frames",kind:"scalar",T:13},{no:34,name:"last_key_frame",kind:"message",T:ge},{no:35,name:"layer_lock_plis",kind:"scalar",T:13},{no:36,name:"last_layer_lock_pli",kind:"message",T:ge},{no:44,name:"packet_drift",kind:"message",T:ar},{no:45,name:"report_drift",kind:"message",T:ar}]);const Na=h.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),su=h.makeEnum("livekit.EncodedFileType",[{no:0,name:"DEFAULT_FILETYPE"},{no:1,name:"MP4"},{no:2,name:"OGG"}]),ru=h.makeEnum("livekit.SegmentedFileProtocol",[{no:0,name:"DEFAULT_SEGMENTED_FILE_PROTOCOL"},{no:1,name:"HLS_PROTOCOL"}]),au=h.makeEnum("livekit.SegmentedFileSuffix",[{no:0,name:"INDEX"},{no:1,name:"TIMESTAMP"}]),ou=h.makeEnum("livekit.ImageFileSuffix",[{no:0,name:"IMAGE_SUFFIX_INDEX"},{no:1,name:"IMAGE_SUFFIX_TIMESTAMP"}]),cu=h.makeEnum("livekit.StreamProtocol",[{no:0,name:"DEFAULT_PROTOCOL"},{no:1,name:"RTMP"}]),En=h.makeEnum("livekit.EncodingOptionsPreset",[{no:0,name:"H264_720P_30"},{no:1,name:"H264_720P_60"},{no:2,name:"H264_1080P_30"},{no:3,name:"H264_1080P_60"},{no:4,name:"PORTRAIT_H264_720P_30"},{no:5,name:"PORTRAIT_H264_720P_60"},{no:6,name:"PORTRAIT_H264_1080P_30"},{no:7,name:"PORTRAIT_H264_1080P_60"}]),du=h.makeEnum("livekit.EgressStatus",[{no:0,name:"EGRESS_STARTING"},{no:1,name:"EGRESS_ACTIVE"},{no:2,name:"EGRESS_ENDING"},{no:3,name:"EGRESS_COMPLETE"},{no:4,name:"EGRESS_FAILED"},{no:5,name:"EGRESS_ABORTED"},{no:6,name:"EGRESS_LIMIT_REACHED"}]),La=h.makeMessageType("livekit.RoomCompositeEgressRequest",()=>[{no:1,name:"room_name",kind:"scalar",T:9},{no:2,name:"layout",kind:"scalar",T:9},{no:3,name:"audio_only",kind:"scalar",T:8},{no:4,name:"video_only",kind:"scalar",T:8},{no:5,name:"custom_base_url",kind:"scalar",T:9},{no:6,name:"file",kind:"message",T:gt,oneof:"output"},{no:7,name:"stream",kind:"message",T:St,oneof:"output"},{no:10,name:"segments",kind:"message",T:vt,oneof:"output"},{no:8,name:"preset",kind:"enum",T:h.getEnumType(En),oneof:"options"},{no:9,name:"advanced",kind:"message",T:In,oneof:"options"},{no:11,name:"file_outputs",kind:"message",T:gt,repeated:!0},{no:12,name:"stream_outputs",kind:"message",T:St,repeated:!0},{no:13,name:"segment_outputs",kind:"message",T:vt,repeated:!0},{no:14,name:"image_outputs",kind:"message",T:di,repeated:!0}]),lu=h.makeMessageType("livekit.WebEgressRequest",()=>[{no:1,name:"url",kind:"scalar",T:9},{no:2,name:"audio_only",kind:"scalar",T:8},{no:3,name:"video_only",kind:"scalar",T:8},{no:12,name:"await_start_signal",kind:"scalar",T:8},{no:4,name:"file",kind:"message",T:gt,oneof:"output"},{no:5,name:"stream",kind:"message",T:St,oneof:"output"},{no:6,name:"segments",kind:"message",T:vt,oneof:"output"},{no:7,name:"preset",kind:"enum",T:h.getEnumType(En),oneof:"options"},{no:8,name:"advanced",kind:"message",T:In,oneof:"options"},{no:9,name:"file_outputs",kind:"message",T:gt,repeated:!0},{no:10,name:"stream_outputs",kind:"message",T:St,repeated:!0},{no:11,name:"segment_outputs",kind:"message",T:vt,repeated:!0},{no:13,name:"image_outputs",kind:"message",T:di,repeated:!0}]),uu=h.makeMessageType("livekit.ParticipantEgressRequest",()=>[{no:1,name:"room_name",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"screen_share",kind:"scalar",T:8},{no:4,name:"preset",kind:"enum",T:h.getEnumType(En),oneof:"options"},{no:5,name:"advanced",kind:"message",T:In,oneof:"options"},{no:6,name:"file_outputs",kind:"message",T:gt,repeated:!0},{no:7,name:"stream_outputs",kind:"message",T:St,repeated:!0},{no:8,name:"segment_outputs",kind:"message",T:vt,repeated:!0},{no:9,name:"image_outputs",kind:"message",T:di,repeated:!0}]),hu=h.makeMessageType("livekit.TrackCompositeEgressRequest",()=>[{no:1,name:"room_name",kind:"scalar",T:9},{no:2,name:"audio_track_id",kind:"scalar",T:9},{no:3,name:"video_track_id",kind:"scalar",T:9},{no:4,name:"file",kind:"message",T:gt,oneof:"output"},{no:5,name:"stream",kind:"message",T:St,oneof:"output"},{no:8,name:"segments",kind:"message",T:vt,oneof:"output"},{no:6,name:"preset",kind:"enum",T:h.getEnumType(En),oneof:"options"},{no:7,name:"advanced",kind:"message",T:In,oneof:"options"},{no:11,name:"file_outputs",kind:"message",T:gt,repeated:!0},{no:12,name:"stream_outputs",kind:"message",T:St,repeated:!0},{no:13,name:"segment_outputs",kind:"message",T:vt,repeated:!0},{no:14,name:"image_outputs",kind:"message",T:di,repeated:!0}]),pu=h.makeMessageType("livekit.TrackEgressRequest",()=>[{no:1,name:"room_name",kind:"scalar",T:9},{no:2,name:"track_id",kind:"scalar",T:9},{no:3,name:"file",kind:"message",T:fu,oneof:"output"},{no:4,name:"websocket_url",kind:"scalar",T:9,oneof:"output"}]),gt=h.makeMessageType("livekit.EncodedFileOutput",()=>[{no:1,name:"file_type",kind:"enum",T:h.getEnumType(su)},{no:2,name:"filepath",kind:"scalar",T:9},{no:6,name:"disable_manifest",kind:"scalar",T:8},{no:3,name:"s3",kind:"message",T:wn,oneof:"output"},{no:4,name:"gcp",kind:"message",T:Pn,oneof:"output"},{no:5,name:"azure",kind:"message",T:Rn,oneof:"output"},{no:7,name:"aliOSS",kind:"message",T:li,oneof:"output"}]),vt=h.makeMessageType("livekit.SegmentedFileOutput",()=>[{no:1,name:"protocol",kind:"enum",T:h.getEnumType(ru)},{no:2,name:"filename_prefix",kind:"scalar",T:9},{no:3,name:"playlist_name",kind:"scalar",T:9},{no:11,name:"live_playlist_name",kind:"scalar",T:9},{no:4,name:"segment_duration",kind:"scalar",T:13},{no:10,name:"filename_suffix",kind:"enum",T:h.getEnumType(au)},{no:8,name:"disable_manifest",kind:"scalar",T:8},{no:5,name:"s3",kind:"message",T:wn,oneof:"output"},{no:6,name:"gcp",kind:"message",T:Pn,oneof:"output"},{no:7,name:"azure",kind:"message",T:Rn,oneof:"output"},{no:9,name:"aliOSS",kind:"message",T:li,oneof:"output"}]),fu=h.makeMessageType("livekit.DirectFileOutput",()=>[{no:1,name:"filepath",kind:"scalar",T:9},{no:5,name:"disable_manifest",kind:"scalar",T:8},{no:2,name:"s3",kind:"message",T:wn,oneof:"output"},{no:3,name:"gcp",kind:"message",T:Pn,oneof:"output"},{no:4,name:"azure",kind:"message",T:Rn,oneof:"output"},{no:6,name:"aliOSS",kind:"message",T:li,oneof:"output"}]),di=h.makeMessageType("livekit.ImageOutput",()=>[{no:1,name:"capture_interval",kind:"scalar",T:13},{no:2,name:"width",kind:"scalar",T:5},{no:3,name:"height",kind:"scalar",T:5},{no:4,name:"filename_prefix",kind:"scalar",T:9},{no:5,name:"filename_suffix",kind:"enum",T:h.getEnumType(ou)},{no:6,name:"image_codec",kind:"enum",T:h.getEnumType(Kl)},{no:7,name:"disable_manifest",kind:"scalar",T:8},{no:8,name:"s3",kind:"message",T:wn,oneof:"output"},{no:9,name:"gcp",kind:"message",T:Pn,oneof:"output"},{no:10,name:"azure",kind:"message",T:Rn,oneof:"output"},{no:11,name:"aliOSS",kind:"message",T:li,oneof:"output"}]),wn=h.makeMessageType("livekit.S3Upload",()=>[{no:1,name:"access_key",kind:"scalar",T:9},{no:2,name:"secret",kind:"scalar",T:9},{no:3,name:"region",kind:"scalar",T:9},{no:4,name:"endpoint",kind:"scalar",T:9},{no:5,name:"bucket",kind:"scalar",T:9},{no:6,name:"force_path_style",kind:"scalar",T:8},{no:7,name:"metadata",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:8,name:"tagging",kind:"scalar",T:9},{no:9,name:"content_disposition",kind:"scalar",T:9}]),Pn=h.makeMessageType("livekit.GCPUpload",()=>[{no:1,name:"credentials",kind:"scalar",T:9},{no:2,name:"bucket",kind:"scalar",T:9},{no:3,name:"endpoint",kind:"scalar",T:9}]),Rn=h.makeMessageType("livekit.AzureBlobUpload",()=>[{no:1,name:"account_name",kind:"scalar",T:9},{no:2,name:"account_key",kind:"scalar",T:9},{no:3,name:"container_name",kind:"scalar",T:9}]),li=h.makeMessageType("livekit.AliOSSUpload",()=>[{no:1,name:"access_key",kind:"scalar",T:9},{no:2,name:"secret",kind:"scalar",T:9},{no:3,name:"region",kind:"scalar",T:9},{no:4,name:"endpoint",kind:"scalar",T:9},{no:5,name:"bucket",kind:"scalar",T:9}]),St=h.makeMessageType("livekit.StreamOutput",()=>[{no:1,name:"protocol",kind:"enum",T:h.getEnumType(cu)},{no:2,name:"urls",kind:"scalar",T:9,repeated:!0}]),In=h.makeMessageType("livekit.EncodingOptions",()=>[{no:1,name:"width",kind:"scalar",T:5},{no:2,name:"height",kind:"scalar",T:5},{no:3,name:"depth",kind:"scalar",T:5},{no:4,name:"framerate",kind:"scalar",T:5},{no:5,name:"audio_codec",kind:"enum",T:h.getEnumType(wa)},{no:6,name:"audio_bitrate",kind:"scalar",T:5},{no:11,name:"audio_quality",kind:"scalar",T:5},{no:7,name:"audio_frequency",kind:"scalar",T:5},{no:8,name:"video_codec",kind:"enum",T:h.getEnumType(Pa)},{no:9,name:"video_bitrate",kind:"scalar",T:5},{no:12,name:"video_quality",kind:"scalar",T:5},{no:10,name:"key_frame_interval",kind:"scalar",T:1}]);h.makeMessageType("livekit.UpdateLayoutRequest",()=>[{no:1,name:"egress_id",kind:"scalar",T:9},{no:2,name:"layout",kind:"scalar",T:9}]);h.makeMessageType("livekit.UpdateStreamRequest",()=>[{no:1,name:"egress_id",kind:"scalar",T:9},{no:2,name:"add_output_urls",kind:"scalar",T:9,repeated:!0},{no:3,name:"remove_output_urls",kind:"scalar",T:9,repeated:!0}]);h.makeMessageType("livekit.ListEgressRequest",()=>[{no:1,name:"room_name",kind:"scalar",T:9},{no:2,name:"egress_id",kind:"scalar",T:9},{no:3,name:"active",kind:"scalar",T:8}]);h.makeMessageType("livekit.ListEgressResponse",()=>[{no:1,name:"items",kind:"message",T:Ua,repeated:!0}]);h.makeMessageType("livekit.StopEgressRequest",()=>[{no:1,name:"egress_id",kind:"scalar",T:9}]);const Ua=h.makeMessageType("livekit.EgressInfo",()=>[{no:1,name:"egress_id",kind:"scalar",T:9},{no:2,name:"room_id",kind:"scalar",T:9},{no:13,name:"room_name",kind:"scalar",T:9},{no:3,name:"status",kind:"enum",T:h.getEnumType(du)},{no:10,name:"started_at",kind:"scalar",T:3},{no:11,name:"ended_at",kind:"scalar",T:3},{no:18,name:"updated_at",kind:"scalar",T:3},{no:21,name:"details",kind:"scalar",T:9},{no:9,name:"error",kind:"scalar",T:9},{no:4,name:"room_composite",kind:"message",T:La,oneof:"request"},{no:14,name:"web",kind:"message",T:lu,oneof:"request"},{no:19,name:"participant",kind:"message",T:uu,oneof:"request"},{no:5,name:"track_composite",kind:"message",T:hu,oneof:"request"},{no:6,name:"track",kind:"message",T:pu,oneof:"request"},{no:7,name:"stream",kind:"message",T:mu,oneof:"result"},{no:8,name:"file",kind:"message",T:or,oneof:"result"},{no:12,name:"segments",kind:"message",T:cr,oneof:"result"},{no:15,name:"stream_results",kind:"message",T:ja,repeated:!0},{no:16,name:"file_results",kind:"message",T:or,repeated:!0},{no:17,name:"segment_results",kind:"message",T:cr,repeated:!0},{no:20,name:"image_results",kind:"message",T:vu,repeated:!0}]),mu=h.makeMessageType("livekit.StreamInfoList",()=>[{no:1,name:"info",kind:"message",T:ja,repeated:!0}]),ja=h.makeMessageType("livekit.StreamInfo",()=>[{no:1,name:"url",kind:"scalar",T:9},{no:2,name:"started_at",kind:"scalar",T:3},{no:3,name:"ended_at",kind:"scalar",T:3},{no:4,name:"duration",kind:"scalar",T:3},{no:5,name:"status",kind:"enum",T:h.getEnumType(gu)},{no:6,name:"error",kind:"scalar",T:9}]),gu=h.makeEnum("livekit.StreamInfo.Status",[{no:0,name:"ACTIVE"},{no:1,name:"FINISHED"},{no:2,name:"FAILED"}]),or=h.makeMessageType("livekit.FileInfo",()=>[{no:1,name:"filename",kind:"scalar",T:9},{no:2,name:"started_at",kind:"scalar",T:3},{no:3,name:"ended_at",kind:"scalar",T:3},{no:6,name:"duration",kind:"scalar",T:3},{no:4,name:"size",kind:"scalar",T:3},{no:5,name:"location",kind:"scalar",T:9}]),cr=h.makeMessageType("livekit.SegmentsInfo",()=>[{no:1,name:"playlist_name",kind:"scalar",T:9},{no:8,name:"live_playlist_name",kind:"scalar",T:9},{no:2,name:"duration",kind:"scalar",T:3},{no:3,name:"size",kind:"scalar",T:3},{no:4,name:"playlist_location",kind:"scalar",T:9},{no:9,name:"live_playlist_location",kind:"scalar",T:9},{no:5,name:"segment_count",kind:"scalar",T:3},{no:6,name:"started_at",kind:"scalar",T:3},{no:7,name:"ended_at",kind:"scalar",T:3}]),vu=h.makeMessageType("livekit.ImagesInfo",()=>[{no:1,name:"image_count",kind:"scalar",T:3},{no:2,name:"started_at",kind:"scalar",T:3},{no:3,name:"ended_at",kind:"scalar",T:3}]),ku=h.makeMessageType("livekit.AutoParticipantEgress",()=>[{no:1,name:"preset",kind:"enum",T:h.getEnumType(En),oneof:"options"},{no:2,name:"advanced",kind:"message",T:In,oneof:"options"},{no:3,name:"file_outputs",kind:"message",T:gt,repeated:!0},{no:4,name:"segment_outputs",kind:"message",T:vt,repeated:!0}]),yu=h.makeMessageType("livekit.AutoTrackEgress",()=>[{no:1,name:"filepath",kind:"scalar",T:9},{no:5,name:"disable_manifest",kind:"scalar",T:8},{no:2,name:"s3",kind:"message",T:wn,oneof:"output"},{no:3,name:"gcp",kind:"message",T:Pn,oneof:"output"},{no:4,name:"azure",kind:"message",T:Rn,oneof:"output"}]);h.makeMessageType("livekit.CreateRoomRequest",()=>[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"empty_timeout",kind:"scalar",T:13},{no:10,name:"departure_timeout",kind:"scalar",T:13},{no:3,name:"max_participants",kind:"scalar",T:13},{no:4,name:"node_id",kind:"scalar",T:9},{no:5,name:"metadata",kind:"scalar",T:9},{no:6,name:"egress",kind:"message",T:bu},{no:7,name:"min_playout_delay",kind:"scalar",T:13},{no:8,name:"max_playout_delay",kind:"scalar",T:13},{no:9,name:"sync_streams",kind:"scalar",T:8}]);const bu=h.makeMessageType("livekit.RoomEgress",()=>[{no:1,name:"room",kind:"message",T:La},{no:3,name:"participant",kind:"message",T:ku},{no:2,name:"tracks",kind:"message",T:yu}]);h.makeMessageType("livekit.ListRoomsRequest",()=>[{no:1,name:"names",kind:"scalar",T:9,repeated:!0}]);h.makeMessageType("livekit.ListRoomsResponse",()=>[{no:1,name:"rooms",kind:"message",T:qt,repeated:!0}]);h.makeMessageType("livekit.DeleteRoomRequest",()=>[{no:1,name:"room",kind:"scalar",T:9}]);h.makeMessageType("livekit.DeleteRoomResponse",[]);h.makeMessageType("livekit.ListParticipantsRequest",()=>[{no:1,name:"room",kind:"scalar",T:9}]);h.makeMessageType("livekit.ListParticipantsResponse",()=>[{no:1,name:"participants",kind:"message",T:mt,repeated:!0}]);h.makeMessageType("livekit.RoomParticipantIdentity",()=>[{no:1,name:"room",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9}]);h.makeMessageType("livekit.RemoveParticipantResponse",[]);h.makeMessageType("livekit.MuteRoomTrackRequest",()=>[{no:1,name:"room",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"track_sid",kind:"scalar",T:9},{no:4,name:"muted",kind:"scalar",T:8}]);h.makeMessageType("livekit.MuteRoomTrackResponse",()=>[{no:1,name:"track",kind:"message",T:Ze}]);h.makeMessageType("livekit.UpdateParticipantRequest",()=>[{no:1,name:"room",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"metadata",kind:"scalar",T:9},{no:4,name:"permission",kind:"message",T:Ra},{no:5,name:"name",kind:"scalar",T:9}]);h.makeMessageType("livekit.UpdateSubscriptionsRequest",()=>[{no:1,name:"room",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:4,name:"subscribe",kind:"scalar",T:8},{no:5,name:"participant_tracks",kind:"message",T:bs,repeated:!0}]);h.makeMessageType("livekit.UpdateSubscriptionsResponse",[]);h.makeMessageType("livekit.SendDataRequest",()=>[{no:1,name:"room",kind:"scalar",T:9},{no:2,name:"data",kind:"scalar",T:12},{no:3,name:"kind",kind:"enum",T:h.getEnumType(ke)},{no:4,name:"destination_sids",kind:"scalar",T:9,repeated:!0},{no:6,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:5,name:"topic",kind:"scalar",T:9,opt:!0}]);h.makeMessageType("livekit.SendDataResponse",[]);h.makeMessageType("livekit.UpdateRoomMetadataRequest",()=>[{no:1,name:"room",kind:"scalar",T:9},{no:2,name:"metadata",kind:"scalar",T:9}]);const Fa=h.makeEnum("livekit.JobType",[{no:0,name:"JT_ROOM"},{no:1,name:"JT_PUBLISHER"}]),Tu=h.makeEnum("livekit.WorkerStatus",[{no:0,name:"WS_AVAILABLE"},{no:1,name:"WS_FULL"}]),Cu=h.makeEnum("livekit.JobStatus",[{no:0,name:"JS_UNKNOWN"},{no:1,name:"JS_SUCCESS"},{no:2,name:"JS_FAILED"}]);h.makeMessageType("livekit.AgentInfo",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"version",kind:"scalar",T:9}]);const Ba=h.makeMessageType("livekit.Job",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:h.getEnumType(Fa)},{no:3,name:"room",kind:"message",T:qt},{no:4,name:"participant",kind:"message",T:mt,opt:!0}]);h.makeMessageType("livekit.WorkerMessage",()=>[{no:1,name:"register",kind:"message",T:Su,oneof:"message"},{no:2,name:"availability",kind:"message",T:wu,oneof:"message"},{no:3,name:"status",kind:"message",T:Iu,oneof:"message"},{no:4,name:"job_update",kind:"message",T:Pu,oneof:"message"}]);h.makeMessageType("livekit.ServerMessage",()=>[{no:1,name:"register",kind:"message",T:_u,oneof:"message"},{no:2,name:"availability",kind:"message",T:Eu,oneof:"message"},{no:3,name:"assignment",kind:"message",T:Ru,oneof:"message"}]);const Su=h.makeMessageType("livekit.RegisterWorkerRequest",()=>[{no:1,name:"type",kind:"enum",T:h.getEnumType(Fa)},{no:2,name:"worker_id",kind:"scalar",T:9},{no:3,name:"version",kind:"scalar",T:9},{no:4,name:"name",kind:"scalar",T:9}]),_u=h.makeMessageType("livekit.RegisterWorkerResponse",()=>[{no:1,name:"worker_id",kind:"scalar",T:9},{no:2,name:"server_version",kind:"scalar",T:9}]),Eu=h.makeMessageType("livekit.AvailabilityRequest",()=>[{no:1,name:"job",kind:"message",T:Ba}]),wu=h.makeMessageType("livekit.AvailabilityResponse",()=>[{no:1,name:"job_id",kind:"scalar",T:9},{no:2,name:"available",kind:"scalar",T:8}]),Pu=h.makeMessageType("livekit.JobStatusUpdate",()=>[{no:1,name:"job_id",kind:"scalar",T:9},{no:2,name:"status",kind:"enum",T:h.getEnumType(Cu)},{no:3,name:"error",kind:"scalar",T:9},{no:4,name:"user_data",kind:"scalar",T:9}]),Ru=h.makeMessageType("livekit.JobAssignment",()=>[{no:1,name:"job",kind:"message",T:Ba}]),Iu=h.makeMessageType("livekit.UpdateWorkerStatus",()=>[{no:1,name:"status",kind:"enum",T:h.getEnumType(Tu)}]),Ue=h.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),Hi=h.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),Ou=h.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),Mu=h.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:_t,oneof:"message"},{no:2,name:"answer",kind:"message",T:_t,oneof:"message"},{no:3,name:"trickle",kind:"message",T:Ts,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Gi,oneof:"message"},{no:5,name:"mute",kind:"message",T:Cs,oneof:"message"},{no:6,name:"subscription",kind:"message",T:ui,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Va,oneof:"message"},{no:8,name:"leave",kind:"message",T:hi,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:$a,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:za,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Wa,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Ke,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:Ha,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Ka,oneof:"message"}]),dr=h.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:xu,oneof:"message"},{no:2,name:"answer",kind:"message",T:_t,oneof:"message"},{no:3,name:"offer",kind:"message",T:_t,oneof:"message"},{no:4,name:"trickle",kind:"message",T:Ts,oneof:"message"},{no:5,name:"update",kind:"message",T:Nu,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Ss,oneof:"message"},{no:8,name:"leave",kind:"message",T:hi,oneof:"message"},{no:9,name:"mute",kind:"message",T:Cs,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Uu,oneof:"message"},{no:11,name:"room_update",kind:"message",T:ju,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:Bu,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:$u,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:qu,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Gu,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Du,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:Au,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:zu,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:Ku,oneof:"message"}]),qi=h.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}]),Gi=h.makeMessageType("livekit.AddTrackRequest",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"type",kind:"enum",T:h.getEnumType(Le)},{no:4,name:"width",kind:"scalar",T:13},{no:5,name:"height",kind:"scalar",T:13},{no:6,name:"muted",kind:"scalar",T:8},{no:7,name:"disable_dtx",kind:"scalar",T:8},{no:8,name:"source",kind:"enum",T:h.getEnumType(me)},{no:9,name:"layers",kind:"message",T:ht,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:qi,repeated:!0},{no:11,name:"sid",kind:"scalar",T:9},{no:12,name:"stereo",kind:"scalar",T:8},{no:13,name:"disable_red",kind:"scalar",T:8},{no:14,name:"encryption",kind:"enum",T:h.getEnumType(Oe)},{no:15,name:"stream",kind:"scalar",T:9}]),Ts=h.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:h.getEnumType(Ue)}]),Cs=h.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),xu=h.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:qt},{no:2,name:"participant",kind:"message",T:mt},{no:3,name:"other_participants",kind:"message",T:mt,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:qa,repeated:!0},{no:6,name:"subscriber_primary",kind:"scalar",T:8},{no:7,name:"alternative_url",kind:"scalar",T:9},{no:8,name:"client_configuration",kind:"message",T:Da},{no:9,name:"server_region",kind:"scalar",T:9},{no:10,name:"ping_timeout",kind:"scalar",T:5},{no:11,name:"ping_interval",kind:"scalar",T:5},{no:12,name:"server_info",kind:"message",T:tu},{no:13,name:"sif_trailer",kind:"scalar",T:12}]),Au=h.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:qa,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Da}]),Ss=h.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Ze}]),Du=h.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),_t=h.makeMessageType("livekit.SessionDescription",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9}]),Nu=h.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:mt,repeated:!0}]),ui=h.makeMessageType("livekit.UpdateSubscription",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"participant_tracks",kind:"message",T:bs,repeated:!0}]),Va=h.makeMessageType("livekit.UpdateTrackSettings",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:3,name:"disabled",kind:"scalar",T:8},{no:4,name:"quality",kind:"enum",T:h.getEnumType(ys)},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"fps",kind:"scalar",T:13},{no:8,name:"priority",kind:"scalar",T:13}]),hi=h.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:h.getEnumType(un)},{no:3,name:"action",kind:"enum",T:h.getEnumType(Lu)},{no:4,name:"regions",kind:"message",T:Wu}]),Lu=h.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),$a=h.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:ht,repeated:!0}]),Ha=h.makeMessageType("livekit.UpdateParticipantMetadata",()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9}]),qa=h.makeMessageType("livekit.ICEServer",()=>[{no:1,name:"urls",kind:"scalar",T:9,repeated:!0},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"credential",kind:"scalar",T:9}]),Uu=h.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:Oa,repeated:!0}]),ju=h.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:qt}]),Fu=h.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:h.getEnumType(sn)},{no:3,name:"score",kind:"scalar",T:2}]),Bu=h.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:Fu,repeated:!0}]),Vu=h.makeMessageType("livekit.StreamStateInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:h.getEnumType(Hi)}]),$u=h.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:Vu,repeated:!0}]),_s=h.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:h.getEnumType(ys)},{no:2,name:"enabled",kind:"scalar",T:8}]),Hu=h.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:_s,repeated:!0}]),qu=h.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:_s,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:Hu,repeated:!0}]),Ga=h.makeMessageType("livekit.TrackPermission",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"all_tracks",kind:"scalar",T:8},{no:3,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:4,name:"participant_identity",kind:"scalar",T:9}]),za=h.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Ga,repeated:!0}]),Gu=h.makeMessageType("livekit.SubscriptionPermissionUpdate",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"allowed",kind:"scalar",T:8}]),Wa=h.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:_t},{no:2,name:"subscription",kind:"message",T:ui},{no:3,name:"publish_tracks",kind:"message",T:Ss,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Ja,repeated:!0},{no:5,name:"offer",kind:"message",T:_t},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0}]),Ja=h.makeMessageType("livekit.DataChannelInfo",()=>[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:13},{no:3,name:"target",kind:"enum",T:h.getEnumType(Ue)}]),Ke=h.makeMessageType("livekit.SimulateScenario",()=>[{no:1,name:"speaker_update",kind:"scalar",T:5,oneof:"scenario"},{no:2,name:"node_failure",kind:"scalar",T:8,oneof:"scenario"},{no:3,name:"migration",kind:"scalar",T:8,oneof:"scenario"},{no:4,name:"server_leave",kind:"scalar",T:8,oneof:"scenario"},{no:5,name:"switch_candidate_protocol",kind:"enum",T:h.getEnumType(Ou),oneof:"scenario"},{no:6,name:"subscriber_bandwidth",kind:"scalar",T:3,oneof:"scenario"},{no:7,name:"disconnect_signal_on_resume",kind:"scalar",T:8,oneof:"scenario"},{no:8,name:"disconnect_signal_on_resume_no_messages",kind:"scalar",T:8,oneof:"scenario"}]),Ka=h.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),zu=h.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),Wu=h.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:Ju,repeated:!0}]),Ju=h.makeMessageType("livekit.RegionInfo",()=>[{no:1,name:"region",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9},{no:3,name:"distance",kind:"scalar",T:3}]),Ku=h.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:h.getEnumType(Ql)}]),Qa=h.makeEnum("livekit.IngressInput",[{no:0,name:"RTMP_INPUT"},{no:1,name:"WHIP_INPUT"},{no:2,name:"URL_INPUT"}]),Qu=h.makeEnum("livekit.IngressAudioEncodingPreset",[{no:0,name:"OPUS_STEREO_96KBPS"},{no:1,name:"OPUS_MONO_64KBS"}]),Yu=h.makeEnum("livekit.IngressVideoEncodingPreset",[{no:0,name:"H264_720P_30FPS_3_LAYERS"},{no:1,name:"H264_1080P_30FPS_3_LAYERS"},{no:2,name:"H264_540P_25FPS_2_LAYERS"},{no:3,name:"H264_720P_30FPS_1_LAYER"},{no:4,name:"H264_1080P_30FPS_1_LAYER"},{no:5,name:"H264_720P_30FPS_3_LAYERS_HIGH_MOTION"},{no:6,name:"H264_1080P_30FPS_3_LAYERS_HIGH_MOTION"},{no:7,name:"H264_540P_25FPS_2_LAYERS_HIGH_MOTION"},{no:8,name:"H264_720P_30FPS_1_LAYER_HIGH_MOTION"},{no:9,name:"H264_1080P_30FPS_1_LAYER_HIGH_MOTION"}]);h.makeMessageType("livekit.CreateIngressRequest",()=>[{no:1,name:"input_type",kind:"enum",T:h.getEnumType(Qa)},{no:9,name:"url",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"room_name",kind:"scalar",T:9},{no:4,name:"participant_identity",kind:"scalar",T:9},{no:5,name:"participant_name",kind:"scalar",T:9},{no:10,name:"participant_metadata",kind:"scalar",T:9},{no:8,name:"bypass_transcoding",kind:"scalar",T:8},{no:6,name:"audio",kind:"message",T:Es},{no:7,name:"video",kind:"message",T:ws}]);const Es=h.makeMessageType("livekit.IngressAudioOptions",()=>[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"source",kind:"enum",T:h.getEnumType(me)},{no:3,name:"preset",kind:"enum",T:h.getEnumType(Qu),oneof:"encoding_options"},{no:4,name:"options",kind:"message",T:Xu,oneof:"encoding_options"}]),ws=h.makeMessageType("livekit.IngressVideoOptions",()=>[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"source",kind:"enum",T:h.getEnumType(me)},{no:3,name:"preset",kind:"enum",T:h.getEnumType(Yu),oneof:"encoding_options"},{no:4,name:"options",kind:"message",T:Zu,oneof:"encoding_options"}]),Xu=h.makeMessageType("livekit.IngressAudioEncodingOptions",()=>[{no:1,name:"audio_codec",kind:"enum",T:h.getEnumType(wa)},{no:2,name:"bitrate",kind:"scalar",T:13},{no:3,name:"disable_dtx",kind:"scalar",T:8},{no:4,name:"channels",kind:"scalar",T:13}]),Zu=h.makeMessageType("livekit.IngressVideoEncodingOptions",()=>[{no:1,name:"video_codec",kind:"enum",T:h.getEnumType(Pa)},{no:2,name:"frame_rate",kind:"scalar",T:1},{no:3,name:"layers",kind:"message",T:ht,repeated:!0}]),Ya=h.makeMessageType("livekit.IngressInfo",()=>[{no:1,name:"ingress_id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"stream_key",kind:"scalar",T:9},{no:4,name:"url",kind:"scalar",T:9},{no:5,name:"input_type",kind:"enum",T:h.getEnumType(Qa)},{no:13,name:"bypass_transcoding",kind:"scalar",T:8},{no:6,name:"audio",kind:"message",T:Es},{no:7,name:"video",kind:"message",T:ws},{no:8,name:"room_name",kind:"scalar",T:9},{no:9,name:"participant_identity",kind:"scalar",T:9},{no:10,name:"participant_name",kind:"scalar",T:9},{no:14,name:"participant_metadata",kind:"scalar",T:9},{no:11,name:"reusable",kind:"scalar",T:8},{no:12,name:"state",kind:"message",T:eh}]),eh=h.makeMessageType("livekit.IngressState",()=>[{no:1,name:"status",kind:"enum",T:h.getEnumType(th)},{no:2,name:"error",kind:"scalar",T:9},{no:3,name:"video",kind:"message",T:nh},{no:4,name:"audio",kind:"message",T:ih},{no:5,name:"room_id",kind:"scalar",T:9},{no:7,name:"started_at",kind:"scalar",T:3},{no:8,name:"ended_at",kind:"scalar",T:3},{no:9,name:"resource_id",kind:"scalar",T:9},{no:6,name:"tracks",kind:"message",T:Ze,repeated:!0}]),th=h.makeEnum("livekit.IngressState.Status",[{no:0,name:"ENDPOINT_INACTIVE"},{no:1,name:"ENDPOINT_BUFFERING"},{no:2,name:"ENDPOINT_PUBLISHING"},{no:3,name:"ENDPOINT_ERROR"},{no:4,name:"ENDPOINT_COMPLETE"}]),nh=h.makeMessageType("livekit.InputVideoState",()=>[{no:1,name:"mime_type",kind:"scalar",T:9},{no:2,name:"average_bitrate",kind:"scalar",T:13},{no:3,name:"width",kind:"scalar",T:13},{no:4,name:"height",kind:"scalar",T:13},{no:5,name:"framerate",kind:"scalar",T:1}]),ih=h.makeMessageType("livekit.InputAudioState",()=>[{no:1,name:"mime_type",kind:"scalar",T:9},{no:2,name:"average_bitrate",kind:"scalar",T:13},{no:3,name:"channels",kind:"scalar",T:13},{no:4,name:"sample_rate",kind:"scalar",T:13}]);h.makeMessageType("livekit.UpdateIngressRequest",()=>[{no:1,name:"ingress_id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"room_name",kind:"scalar",T:9},{no:4,name:"participant_identity",kind:"scalar",T:9},{no:5,name:"participant_name",kind:"scalar",T:9},{no:9,name:"participant_metadata",kind:"scalar",T:9},{no:8,name:"bypass_transcoding",kind:"scalar",T:8,opt:!0},{no:6,name:"audio",kind:"message",T:Es},{no:7,name:"video",kind:"message",T:ws}]);h.makeMessageType("livekit.ListIngressRequest",()=>[{no:1,name:"room_name",kind:"scalar",T:9},{no:2,name:"ingress_id",kind:"scalar",T:9}]);h.makeMessageType("livekit.ListIngressResponse",()=>[{no:1,name:"items",kind:"message",T:Ya,repeated:!0}]);h.makeMessageType("livekit.DeleteIngressRequest",()=>[{no:1,name:"ingress_id",kind:"scalar",T:9}]);h.makeMessageType("livekit.WebhookEvent",()=>[{no:1,name:"event",kind:"scalar",T:9},{no:2,name:"room",kind:"message",T:qt},{no:3,name:"participant",kind:"message",T:mt},{no:9,name:"egress_info",kind:"message",T:Ua},{no:10,name:"ingress_info",kind:"message",T:Ya},{no:8,name:"track",kind:"message",T:Ze},{no:6,name:"id",kind:"scalar",T:9},{no:7,name:"created_at",kind:"scalar",T:3},{no:11,name:"num_dropped",kind:"scalar",T:5}]);h.makeMessageType("livekit.CreateSIPTrunkRequest",()=>[{no:1,name:"inbound_addresses",kind:"scalar",T:9,repeated:!0},{no:2,name:"outbound_address",kind:"scalar",T:9},{no:3,name:"outbound_number",kind:"scalar",T:9},{no:4,name:"inbound_numbers_regex",kind:"scalar",T:9,repeated:!0},{no:9,name:"inbound_numbers",kind:"scalar",T:9,repeated:!0},{no:5,name:"inbound_username",kind:"scalar",T:9},{no:6,name:"inbound_password",kind:"scalar",T:9},{no:7,name:"outbound_username",kind:"scalar",T:9},{no:8,name:"outbound_password",kind:"scalar",T:9}]);const sh=h.makeMessageType("livekit.SIPTrunkInfo",()=>[{no:1,name:"sip_trunk_id",kind:"scalar",T:9},{no:2,name:"inbound_addresses",kind:"scalar",T:9,repeated:!0},{no:3,name:"outbound_address",kind:"scalar",T:9},{no:4,name:"outbound_number",kind:"scalar",T:9},{no:5,name:"inbound_numbers_regex",kind:"scalar",T:9,repeated:!0},{no:10,name:"inbound_numbers",kind:"scalar",T:9,repeated:!0},{no:6,name:"inbound_username",kind:"scalar",T:9},{no:7,name:"inbound_password",kind:"scalar",T:9},{no:8,name:"outbound_username",kind:"scalar",T:9},{no:9,name:"outbound_password",kind:"scalar",T:9}]);h.makeMessageType("livekit.ListSIPTrunkRequest",[]);h.makeMessageType("livekit.ListSIPTrunkResponse",()=>[{no:1,name:"items",kind:"message",T:sh,repeated:!0}]);h.makeMessageType("livekit.DeleteSIPTrunkRequest",()=>[{no:1,name:"sip_trunk_id",kind:"scalar",T:9}]);const rh=h.makeMessageType("livekit.SIPDispatchRuleDirect",()=>[{no:1,name:"room_name",kind:"scalar",T:9},{no:2,name:"pin",kind:"scalar",T:9}]),ah=h.makeMessageType("livekit.SIPDispatchRuleIndividual",()=>[{no:1,name:"room_prefix",kind:"scalar",T:9},{no:2,name:"pin",kind:"scalar",T:9}]),Xa=h.makeMessageType("livekit.SIPDispatchRule",()=>[{no:1,name:"dispatch_rule_direct",kind:"message",T:rh,oneof:"rule"},{no:2,name:"dispatch_rule_individual",kind:"message",T:ah,oneof:"rule"}]);h.makeMessageType("livekit.CreateSIPDispatchRuleRequest",()=>[{no:1,name:"rule",kind:"message",T:Xa},{no:2,name:"trunk_ids",kind:"scalar",T:9,repeated:!0},{no:3,name:"hide_phone_number",kind:"scalar",T:8}]);const oh=h.makeMessageType("livekit.SIPDispatchRuleInfo",()=>[{no:1,name:"sip_dispatch_rule_id",kind:"scalar",T:9},{no:2,name:"rule",kind:"message",T:Xa},{no:3,name:"trunk_ids",kind:"scalar",T:9,repeated:!0},{no:4,name:"hide_phone_number",kind:"scalar",T:8}]);h.makeMessageType("livekit.ListSIPDispatchRuleRequest",[]);h.makeMessageType("livekit.ListSIPDispatchRuleResponse",()=>[{no:1,name:"items",kind:"message",T:oh,repeated:!0}]);h.makeMessageType("livekit.DeleteSIPDispatchRuleRequest",()=>[{no:1,name:"sip_dispatch_rule_id",kind:"scalar",T:9}]);h.makeMessageType("livekit.CreateSIPParticipantRequest",()=>[{no:1,name:"sip_trunk_id",kind:"scalar",T:9},{no:2,name:"sip_call_to",kind:"scalar",T:9},{no:3,name:"room_name",kind:"scalar",T:9},{no:4,name:"participant_identity",kind:"scalar",T:9}]);h.makeMessageType("livekit.SIPParticipantInfo",()=>[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"participant_identity",kind:"scalar",T:9},{no:3,name:"room_name",kind:"scalar",T:9}]);var ch=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function dh(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var Za={exports:{}};(function(n){(function(e,t){n.exports?n.exports=t():e.log=t()})(ch,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 r(v,S){var O=v[S];if(typeof O.bind=="function")return O.bind(v);try{return Function.prototype.bind.call(O,v)}catch{return function(){return Function.prototype.apply.apply(O,[v,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 o(v){return v==="debug"&&(v="log"),typeof console===t?!1:v==="trace"&&i?a:console[v]!==void 0?r(console,v):console.log!==void 0?r(console,"log"):e}function c(v,S){for(var O=0;O<s.length;O++){var w=s[O];this[w]=O<v?e:this.methodFactory(w,v,S)}this.log=this.debug}function d(v,S,O){return function(){typeof console!==t&&(c.call(this,S,O),this[v].apply(this,arguments))}}function l(v,S,O){return o(v)||d.apply(this,arguments)}function u(v,S,O){var w=this,F;S=S??"WARN";var W="loglevel";typeof v=="string"?W+=":"+v:typeof v=="symbol"&&(W=void 0);function he(A){var H=(s[A]||"silent").toUpperCase();if(!(typeof window===t||!W)){try{window.localStorage[W]=H;return}catch{}try{window.document.cookie=encodeURIComponent(W)+"="+H+";"}catch{}}}function de(){var A;if(!(typeof window===t||!W)){try{A=window.localStorage[W]}catch{}if(typeof A===t)try{var H=window.document.cookie,ze=H.indexOf(encodeURIComponent(W)+"=");ze!==-1&&(A=/^([^;]+)/.exec(H.slice(ze))[1])}catch{}return w.levels[A]===void 0&&(A=void 0),A}}function N(){if(!(typeof window===t||!W)){try{window.localStorage.removeItem(W);return}catch{}try{window.document.cookie=encodeURIComponent(W)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}w.name=v,w.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},w.methodFactory=O||l,w.getLevel=function(){return F},w.setLevel=function(A,H){if(typeof A=="string"&&w.levels[A.toUpperCase()]!==void 0&&(A=w.levels[A.toUpperCase()]),typeof A=="number"&&A>=0&&A<=w.levels.SILENT){if(F=A,H!==!1&&he(A),c.call(w,A,v),typeof console===t&&A<w.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+A},w.setDefaultLevel=function(A){S=A,de()||w.setLevel(A,!1)},w.resetLevel=function(){w.setLevel(S,!1),N()},w.enableAll=function(A){w.setLevel(w.levels.TRACE,A)},w.disableAll=function(A){w.setLevel(w.levels.SILENT,A)};var X=de();X==null&&(X=S),w.setLevel(X,!1)}var p=new u,m={};p.getLogger=function(S){if(typeof S!="symbol"&&typeof S!="string"||S==="")throw new TypeError("You must supply a name when creating a logger.");var O=m[S];return O||(O=m[S]=new u(S,p.getLevel(),p.methodFactory)),O};var k=typeof window!==t?window.log:void 0;return p.noConflict=function(){return typeof window!==t&&window.log===p&&(window.log=k),p},p.getLoggers=function(){return m},p.default=p,p})})(Za);var pi=Za.exports,zi;(function(n){n[n.trace=0]="trace",n[n.debug=1]="debug",n[n.info=2]="info",n[n.warn=3]="warn",n[n.error=4]="error",n[n.silent=5]="silent"})(zi||(zi={}));var Fe;(function(n){n.Default="livekit",n.Room="livekit-room",n.Participant="livekit-participant",n.Track="livekit-track",n.Publication="livekit-track-publication",n.Engine="livekit-engine",n.Signal="livekit-signal",n.PCManager="livekit-pc-manager",n.PCTransport="livekit-pc-transport",n.E2EE="lk-e2ee"})(Fe||(Fe={}));let $=pi.getLogger("livekit");Object.values(Fe).map(n=>pi.getLogger(n));$.setDefaultLevel(zi.info);function it(n){const e=pi.getLogger(n);return e.setDefaultLevel($.getLevel()),e}const lh=pi.getLogger("lk-e2ee"),Qt=7e3,uh=[0,300,2*2*300,3*3*300,4*4*300,Qt,Qt,Qt,Qt,Qt];class hh{constructor(e){this._retryDelays=e!==void 0?[...e]:uh}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+Math.random()*1e3}}function f(n,e,t,i){function s(r){return r instanceof t?r:new t(function(a){a(r)})}return new(t||(t=Promise))(function(r,a){function o(l){try{d(i.next(l))}catch(u){a(u)}}function c(l){try{d(i.throw(l))}catch(u){a(u)}}function d(l){l.done?r(l.value):s(l.value).then(o,c)}d((i=i.apply(n,[])).next())})}function lr(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],i=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&i>=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Dt(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof lr=="function"?lr(n):n[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(r){t[r]=n[r]&&function(a){return new Promise(function(o,c){a=n[r](a),s(o,c,a.done,a.value)})}}function s(r,a,o,c){Promise.resolve(c).then(function(d){r({value:d,done:o})},a)}}var Ps={exports:{}},Ut=typeof Reflect=="object"?Reflect:null,ur=Ut&&typeof Ut.apply=="function"?Ut.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)},Hn;Ut&&typeof Ut.ownKeys=="function"?Hn=Ut.ownKeys:Object.getOwnPropertySymbols?Hn=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Hn=function(e){return Object.getOwnPropertyNames(e)};function ph(n){console&&console.warn&&console.warn(n)}var eo=Number.isNaN||function(e){return e!==e};function Q(){Q.init.call(this)}Ps.exports=Q;Ps.exports.once=vh;Q.EventEmitter=Q;Q.prototype._events=void 0;Q.prototype._eventsCount=0;Q.prototype._maxListeners=void 0;var hr=10;function fi(n){if(typeof n!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof n)}Object.defineProperty(Q,"defaultMaxListeners",{enumerable:!0,get:function(){return hr},set:function(n){if(typeof n!="number"||n<0||eo(n))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+n+".");hr=n}});Q.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};Q.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||eo(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};function to(n){return n._maxListeners===void 0?Q.defaultMaxListeners:n._maxListeners}Q.prototype.getMaxListeners=function(){return to(this)};Q.prototype.emit=function(e){for(var t=[],i=1;i<arguments.length;i++)t.push(arguments[i]);var s=e==="error",r=this._events;if(r!==void 0)s=s&&r.error===void 0;else if(!s)return!1;if(s){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var c=r[e];if(c===void 0)return!1;if(typeof c=="function")ur(c,this,t);else for(var d=c.length,l=ao(c,d),i=0;i<d;++i)ur(l[i],this,t);return!0};function no(n,e,t,i){var s,r,a;if(fi(t),r=n._events,r===void 0?(r=n._events=Object.create(null),n._eventsCount=0):(r.newListener!==void 0&&(n.emit("newListener",e,t.listener?t.listener:t),r=n._events),a=r[e]),a===void 0)a=r[e]=t,++n._eventsCount;else if(typeof a=="function"?a=r[e]=i?[t,a]:[a,t]:i?a.unshift(t):a.push(t),s=to(n),s>0&&a.length>s&&!a.warned){a.warned=!0;var o=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");o.name="MaxListenersExceededWarning",o.emitter=n,o.type=e,o.count=a.length,ph(o)}return n}Q.prototype.addListener=function(e,t){return no(this,e,t,!1)};Q.prototype.on=Q.prototype.addListener;Q.prototype.prependListener=function(e,t){return no(this,e,t,!0)};function fh(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function io(n,e,t){var i={fired:!1,wrapFn:void 0,target:n,type:e,listener:t},s=fh.bind(i);return s.listener=t,i.wrapFn=s,s}Q.prototype.once=function(e,t){return fi(t),this.on(e,io(this,e,t)),this};Q.prototype.prependOnceListener=function(e,t){return fi(t),this.prependListener(e,io(this,e,t)),this};Q.prototype.removeListener=function(e,t){var i,s,r,a,o;if(fi(t),s=this._events,s===void 0)return this;if(i=s[e],i===void 0)return this;if(i===t||i.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete s[e],s.removeListener&&this.emit("removeListener",e,i.listener||t));else if(typeof i!="function"){for(r=-1,a=i.length-1;a>=0;a--)if(i[a]===t||i[a].listener===t){o=i[a].listener,r=a;break}if(r<0)return this;r===0?i.shift():mh(i,r),i.length===1&&(s[e]=i[0]),s.removeListener!==void 0&&this.emit("removeListener",e,o||t)}return this};Q.prototype.off=Q.prototype.removeListener;Q.prototype.removeAllListeners=function(e){var t,i,s;if(i=this._events,i===void 0)return this;if(i.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):i[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete i[e]),this;if(arguments.length===0){var r=Object.keys(i),a;for(s=0;s<r.length;++s)a=r[s],a!=="removeListener"&&this.removeAllListeners(a);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=i[e],typeof t=="function")this.removeListener(e,t);else if(t!==void 0)for(s=t.length-1;s>=0;s--)this.removeListener(e,t[s]);return this};function so(n,e,t){var i=n._events;if(i===void 0)return[];var s=i[e];return s===void 0?[]:typeof s=="function"?t?[s.listener||s]:[s]:t?gh(s):ao(s,s.length)}Q.prototype.listeners=function(e){return so(this,e,!0)};Q.prototype.rawListeners=function(e){return so(this,e,!1)};Q.listenerCount=function(n,e){return typeof n.listenerCount=="function"?n.listenerCount(e):ro.call(n,e)};Q.prototype.listenerCount=ro;function ro(n){var e=this._events;if(e!==void 0){var t=e[n];if(typeof t=="function")return 1;if(t!==void 0)return t.length}return 0}Q.prototype.eventNames=function(){return this._eventsCount>0?Hn(this._events):[]};function ao(n,e){for(var t=new Array(e),i=0;i<e;++i)t[i]=n[i];return t}function mh(n,e){for(;e+1<n.length;e++)n[e]=n[e+1];n.pop()}function gh(n){for(var e=new Array(n.length),t=0;t<e.length;++t)e[t]=n[t].listener||n[t];return e}function vh(n,e){return new Promise(function(t,i){function s(a){n.removeListener(e,r),i(a)}function r(){typeof n.removeListener=="function"&&n.removeListener("error",s),t([].slice.call(arguments))}oo(n,e,r,{once:!0}),e!=="error"&&kh(n,s,{once:!0})})}function kh(n,e,t){typeof n.on=="function"&&oo(n,"error",e,t)}function oo(n,e,t,i){if(typeof n.on=="function")i.once?n.once(e,t):n.on(e,t);else if(typeof n.addEventListener=="function")n.addEventListener(e,function s(r){i.once&&n.removeEventListener(e,s),t(r)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof n)}var Ge=Ps.exports;let co=!0,lo=!0;function qn(n,e,t){const i=n.match(e);return i&&i.length>=t&&parseInt(i[t],10)}function Et(n,e,t){if(!n.RTCPeerConnection)return;const i=n.RTCPeerConnection.prototype,s=i.addEventListener;i.addEventListener=function(a,o){if(a!==e)return s.apply(this,arguments);const c=d=>{const l=t(d);l&&(o.handleEvent?o.handleEvent(l):o(l))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(o,c),s.apply(this,[a,c])};const r=i.removeEventListener;i.removeEventListener=function(a,o){if(a!==e||!this._eventMap||!this._eventMap[e])return r.apply(this,arguments);if(!this._eventMap[e].has(o))return r.apply(this,arguments);const c=this._eventMap[e].get(o);return this._eventMap[e].delete(o),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,r.apply(this,[a,c])},Object.defineProperty(i,"on"+e,{get(){return this["_on"+e]},set(a){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),a&&this.addEventListener(e,this["_on"+e]=a)},enumerable:!0,configurable:!0})}function yh(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(co=n,n?"adapter.js logging disabled":"adapter.js logging enabled")}function bh(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(lo=!n,"adapter.js deprecation warnings "+(n?"disabled":"enabled"))}function uo(){if(typeof window=="object"){if(co)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Rs(n,e){lo&&console.warn(n+" is deprecated, please use "+e+" instead.")}function Th(n){const e={browser:null,version:null};if(typeof n>"u"||!n.navigator||!n.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:t}=n;if(t.mozGetUserMedia)e.browser="firefox",e.version=qn(t.userAgent,/Firefox\/(\d+)\./,1);else if(t.webkitGetUserMedia||n.isSecureContext===!1&&n.webkitRTCPeerConnection)e.browser="chrome",e.version=qn(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(n.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=qn(t.userAgent,/AppleWebKit\/(\d+)\./,1),e.supportsUnifiedPlan=n.RTCRtpTransceiver&&"currentDirection"in n.RTCRtpTransceiver.prototype;else return e.browser="Not a supported browser.",e;return e}function pr(n){return Object.prototype.toString.call(n)==="[object Object]"}function ho(n){return pr(n)?Object.keys(n).reduce(function(e,t){const i=pr(n[t]),s=i?ho(n[t]):n[t],r=i&&!Object.keys(s).length;return s===void 0||r?e:Object.assign(e,{[t]:s})},{}):n}function Wi(n,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(i=>{i.endsWith("Id")?Wi(n,n.get(e[i]),t):i.endsWith("Ids")&&e[i].forEach(s=>{Wi(n,n.get(s),t)})}))}function fr(n,e,t){const i=t?"outbound-rtp":"inbound-rtp",s=new Map;if(e===null)return s;const r=[];return n.forEach(a=>{a.type==="track"&&a.trackIdentifier===e.id&&r.push(a)}),r.forEach(a=>{n.forEach(o=>{o.type===i&&o.trackId===a.id&&Wi(n,o,s)})}),s}const mr=uo;function po(n,e){const t=n&&n.navigator;if(!t.mediaDevices)return;const i=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;const c={};return Object.keys(o).forEach(d=>{if(d==="require"||d==="advanced"||d==="mediaSource")return;const l=typeof o[d]=="object"?o[d]:{ideal:o[d]};l.exact!==void 0&&typeof l.exact=="number"&&(l.min=l.max=l.exact);const u=function(p,m){return p?p+m.charAt(0).toUpperCase()+m.slice(1):m==="deviceId"?"sourceId":m};if(l.ideal!==void 0){c.optional=c.optional||[];let p={};typeof l.ideal=="number"?(p[u("min",d)]=l.ideal,c.optional.push(p),p={},p[u("max",d)]=l.ideal,c.optional.push(p)):(p[u("",d)]=l.ideal,c.optional.push(p))}l.exact!==void 0&&typeof l.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[u("",d)]=l.exact):["min","max"].forEach(p=>{l[p]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[u(p,d)]=l[p])})}),o.advanced&&(c.optional=(c.optional||[]).concat(o.advanced)),c},s=function(o,c){if(e.version>=61)return c(o);if(o=JSON.parse(JSON.stringify(o)),o&&typeof o.audio=="object"){const d=function(l,u,p){u in l&&!(p in l)&&(l[p]=l[u],delete l[u])};o=JSON.parse(JSON.stringify(o)),d(o.audio,"autoGainControl","googAutoGainControl"),d(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=i(o.audio)}if(o&&typeof o.video=="object"){let d=o.video.facingMode;d=d&&(typeof d=="object"?d:{ideal:d});const l=e.version<66;if(d&&(d.exact==="user"||d.exact==="environment"||d.ideal==="user"||d.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!l)){delete o.video.facingMode;let u;if(d.exact==="environment"||d.ideal==="environment"?u=["back","rear"]:(d.exact==="user"||d.ideal==="user")&&(u=["front"]),u)return t.mediaDevices.enumerateDevices().then(p=>{p=p.filter(k=>k.kind==="videoinput");let m=p.find(k=>u.some(v=>k.label.toLowerCase().includes(v)));return!m&&p.length&&u.includes("back")&&(m=p[p.length-1]),m&&(o.video.deviceId=d.exact?{exact:m.deviceId}:{ideal:m.deviceId}),o.video=i(o.video),mr("chrome: "+JSON.stringify(o)),c(o)})}o.video=i(o.video)}return mr("chrome: "+JSON.stringify(o)),c(o)},r=function(o){return e.version>=64?o:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[o.name]||o.name,message:o.message,constraint:o.constraint||o.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},a=function(o,c,d){s(o,l=>{t.webkitGetUserMedia(l,c,u=>{d&&d(r(u))})})};if(t.getUserMedia=a.bind(t),t.mediaDevices.getUserMedia){const o=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(c){return s(c,d=>o(d).then(l=>{if(d.audio&&!l.getAudioTracks().length||d.video&&!l.getVideoTracks().length)throw l.getTracks().forEach(u=>{u.stop()}),new DOMException("","NotFoundError");return l},l=>Promise.reject(r(l))))}}}function Ch(n,e){if(!(n.navigator.mediaDevices&&"getDisplayMedia"in n.navigator.mediaDevices)&&n.navigator.mediaDevices){if(typeof e!="function"){console.error("shimGetDisplayMedia: getSourceId argument is not a function");return}n.navigator.mediaDevices.getDisplayMedia=function(i){return e(i).then(s=>{const r=i.video&&i.video.width,a=i.video&&i.video.height,o=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:s,maxFrameRate:o||3}},r&&(i.video.mandatory.maxWidth=r),a&&(i.video.mandatory.maxHeight=a),n.navigator.mediaDevices.getUserMedia(i)})}}}function fo(n){n.MediaStream=n.MediaStream||n.webkitMediaStream}function mo(n){if(typeof n=="object"&&n.RTCPeerConnection&&!("ontrack"in n.RTCPeerConnection.prototype)){Object.defineProperty(n.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(t){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=t)},enumerable:!0,configurable:!0});const e=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=i=>{i.stream.addEventListener("addtrack",s=>{let r;n.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(o=>o.track&&o.track.id===s.track.id):r={track:s.track};const a=new Event("track");a.track=s.track,a.receiver=r,a.transceiver={receiver:r},a.streams=[i.stream],this.dispatchEvent(a)}),i.stream.getTracks().forEach(s=>{let r;n.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(o=>o.track&&o.track.id===s.id):r={track:s};const a=new Event("track");a.track=s,a.receiver=r,a.transceiver={receiver:r},a.streams=[i.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else Et(n,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function go(n){if(typeof n=="object"&&n.RTCPeerConnection&&!("getSenders"in n.RTCPeerConnection.prototype)&&"createDTMFSender"in n.RTCPeerConnection.prototype){const e=function(s,r){return{track:r,get dtmf(){return this._dtmf===void 0&&(r.kind==="audio"?this._dtmf=s.createDTMFSender(r):this._dtmf=null),this._dtmf},_pc:s}};if(!n.RTCPeerConnection.prototype.getSenders){n.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const s=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addTrack=function(o,c){let d=s.apply(this,arguments);return d||(d=e(this,o),this._senders.push(d)),d};const r=n.RTCPeerConnection.prototype.removeTrack;n.RTCPeerConnection.prototype.removeTrack=function(o){r.apply(this,arguments);const c=this._senders.indexOf(o);c!==-1&&this._senders.splice(c,1)}}const t=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(r){this._senders=this._senders||[],t.apply(this,[r]),r.getTracks().forEach(a=>{this._senders.push(e(this,a))})};const i=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(r){this._senders=this._senders||[],i.apply(this,[r]),r.getTracks().forEach(a=>{const o=this._senders.find(c=>c.track===a);o&&this._senders.splice(this._senders.indexOf(o),1)})}}else if(typeof n=="object"&&n.RTCPeerConnection&&"getSenders"in n.RTCPeerConnection.prototype&&"createDTMFSender"in n.RTCPeerConnection.prototype&&n.RTCRtpSender&&!("dtmf"in n.RTCRtpSender.prototype)){const e=n.RTCPeerConnection.prototype.getSenders;n.RTCPeerConnection.prototype.getSenders=function(){const i=e.apply(this,[]);return i.forEach(s=>s._pc=this),i},Object.defineProperty(n.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function vo(n){if(!n.RTCPeerConnection)return;const e=n.RTCPeerConnection.prototype.getStats;n.RTCPeerConnection.prototype.getStats=function(){const[i,s,r]=arguments;if(arguments.length>0&&typeof i=="function")return e.apply(this,arguments);if(e.length===0&&(arguments.length===0||typeof i!="function"))return e.apply(this,[]);const a=function(c){const d={};return c.result().forEach(u=>{const p={id:u.id,timestamp:u.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[u.type]||u.type};u.names().forEach(m=>{p[m]=u.stat(m)}),d[p.id]=p}),d},o=function(c){return new Map(Object.keys(c).map(d=>[d,c[d]]))};if(arguments.length>=2){const c=function(d){s(o(a(d)))};return e.apply(this,[c,i])}return new Promise((c,d)=>{e.apply(this,[function(l){c(o(a(l)))},d])}).then(s,r)}}function ko(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender&&n.RTCRtpReceiver))return;if(!("getStats"in n.RTCRtpSender.prototype)){const t=n.RTCPeerConnection.prototype.getSenders;t&&(n.RTCPeerConnection.prototype.getSenders=function(){const r=t.apply(this,[]);return r.forEach(a=>a._pc=this),r});const i=n.RTCPeerConnection.prototype.addTrack;i&&(n.RTCPeerConnection.prototype.addTrack=function(){const r=i.apply(this,arguments);return r._pc=this,r}),n.RTCRtpSender.prototype.getStats=function(){const r=this;return this._pc.getStats().then(a=>fr(a,r.track,!0))}}if(!("getStats"in n.RTCRtpReceiver.prototype)){const t=n.RTCPeerConnection.prototype.getReceivers;t&&(n.RTCPeerConnection.prototype.getReceivers=function(){const s=t.apply(this,[]);return s.forEach(r=>r._pc=this),s}),Et(n,"track",i=>(i.receiver._pc=i.srcElement,i)),n.RTCRtpReceiver.prototype.getStats=function(){const s=this;return this._pc.getStats().then(r=>fr(r,s.track,!1))}}if(!("getStats"in n.RTCRtpSender.prototype&&"getStats"in n.RTCRtpReceiver.prototype))return;const e=n.RTCPeerConnection.prototype.getStats;n.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof n.MediaStreamTrack){const i=arguments[0];let s,r,a;return this.getSenders().forEach(o=>{o.track===i&&(s?a=!0:s=o)}),this.getReceivers().forEach(o=>(o.track===i&&(r?a=!0:r=o),o.track===i)),a||s&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):s?s.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function yo(n){n.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(a=>this._shimmedLocalStreams[a][0])};const e=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addTrack=function(a,o){if(!o)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const c=e.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(c)===-1&&this._shimmedLocalStreams[o.id].push(c):this._shimmedLocalStreams[o.id]=[o,c],c};const t=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(a){this._shimmedLocalStreams=this._shimmedLocalStreams||{},a.getTracks().forEach(d=>{if(this.getSenders().find(u=>u.track===d))throw new DOMException("Track already exists.","InvalidAccessError")});const o=this.getSenders();t.apply(this,arguments);const c=this.getSenders().filter(d=>o.indexOf(d)===-1);this._shimmedLocalStreams[a.id]=[a].concat(c)};const i=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[a.id],i.apply(this,arguments)};const s=n.RTCPeerConnection.prototype.removeTrack;n.RTCPeerConnection.prototype.removeTrack=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},a&&Object.keys(this._shimmedLocalStreams).forEach(o=>{const c=this._shimmedLocalStreams[o].indexOf(a);c!==-1&&this._shimmedLocalStreams[o].splice(c,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),s.apply(this,arguments)}}function bo(n,e){if(!n.RTCPeerConnection)return;if(n.RTCPeerConnection.prototype.addTrack&&e.version>=65)return yo(n);const t=n.RTCPeerConnection.prototype.getLocalStreams;n.RTCPeerConnection.prototype.getLocalStreams=function(){const l=t.apply(this);return this._reverseStreams=this._reverseStreams||{},l.map(u=>this._reverseStreams[u.id])};const i=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(l){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},l.getTracks().forEach(u=>{if(this.getSenders().find(m=>m.track===u))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[l.id]){const u=new n.MediaStream(l.getTracks());this._streams[l.id]=u,this._reverseStreams[u.id]=l,l=u}i.apply(this,[l])};const s=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(l){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[l.id]||l]),delete this._reverseStreams[this._streams[l.id]?this._streams[l.id].id:l.id],delete this._streams[l.id]},n.RTCPeerConnection.prototype.addTrack=function(l,u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const p=[].slice.call(arguments,1);if(p.length!==1||!p[0].getTracks().find(v=>v===l))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(v=>v.track===l))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const k=this._streams[u.id];if(k)k.addTrack(l),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const v=new n.MediaStream([l]);this._streams[u.id]=v,this._reverseStreams[v.id]=u,this.addStream(v)}return this.getSenders().find(v=>v.track===l)};function r(d,l){let u=l.sdp;return Object.keys(d._reverseStreams||[]).forEach(p=>{const m=d._reverseStreams[p],k=d._streams[m.id];u=u.replace(new RegExp(k.id,"g"),m.id)}),new RTCSessionDescription({type:l.type,sdp:u})}function a(d,l){let u=l.sdp;return Object.keys(d._reverseStreams||[]).forEach(p=>{const m=d._reverseStreams[p],k=d._streams[m.id];u=u.replace(new RegExp(m.id,"g"),k.id)}),new RTCSessionDescription({type:l.type,sdp:u})}["createOffer","createAnswer"].forEach(function(d){const l=n.RTCPeerConnection.prototype[d],u={[d](){const p=arguments;return arguments.length&&typeof arguments[0]=="function"?l.apply(this,[k=>{const v=r(this,k);p[0].apply(null,[v])},k=>{p[1]&&p[1].apply(null,k)},arguments[2]]):l.apply(this,arguments).then(k=>r(this,k))}};n.RTCPeerConnection.prototype[d]=u[d]});const o=n.RTCPeerConnection.prototype.setLocalDescription;n.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?o.apply(this,arguments):(arguments[0]=a(this,arguments[0]),o.apply(this,arguments))};const c=Object.getOwnPropertyDescriptor(n.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(n.RTCPeerConnection.prototype,"localDescription",{get(){const d=c.get.apply(this);return d.type===""?d:r(this,d)}}),n.RTCPeerConnection.prototype.removeTrack=function(l){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!l._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(l._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let p;Object.keys(this._streams).forEach(m=>{this._streams[m].getTracks().find(v=>l.track===v)&&(p=this._streams[m])}),p&&(p.getTracks().length===1?this.removeStream(this._reverseStreams[p.id]):p.removeTrack(l.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Ji(n,e){!n.RTCPeerConnection&&n.webkitRTCPeerConnection&&(n.RTCPeerConnection=n.webkitRTCPeerConnection),n.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=n.RTCPeerConnection.prototype[t],s={[t](){return arguments[0]=new(t==="addIceCandidate"?n.RTCIceCandidate:n.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};n.RTCPeerConnection.prototype[t]=s[t]})}function To(n,e){Et(n,"negotiationneeded",t=>{const i=t.target;if(!((e.version<72||i.getConfiguration&&i.getConfiguration().sdpSemantics==="plan-b")&&i.signalingState!=="stable"))return t})}var gr=Object.freeze({__proto__:null,fixNegotiationNeeded:To,shimAddTrackRemoveTrack:bo,shimAddTrackRemoveTrackWithNative:yo,shimGetDisplayMedia:Ch,shimGetSendersWithDtmf:go,shimGetStats:vo,shimGetUserMedia:po,shimMediaStream:fo,shimOnTrack:mo,shimPeerConnection:Ji,shimSenderReceiverGetStats:ko});function Co(n,e){const t=n&&n.navigator,i=n&&n.MediaStreamTrack;if(t.getUserMedia=function(s,r,a){Rs("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(s).then(r,a)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const s=function(a,o,c){o in a&&!(c in a)&&(a[c]=a[o],delete a[o])},r=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(a){return typeof a=="object"&&typeof a.audio=="object"&&(a=JSON.parse(JSON.stringify(a)),s(a.audio,"autoGainControl","mozAutoGainControl"),s(a.audio,"noiseSuppression","mozNoiseSuppression")),r(a)},i&&i.prototype.getSettings){const a=i.prototype.getSettings;i.prototype.getSettings=function(){const o=a.apply(this,arguments);return s(o,"mozAutoGainControl","autoGainControl"),s(o,"mozNoiseSuppression","noiseSuppression"),o}}if(i&&i.prototype.applyConstraints){const a=i.prototype.applyConstraints;i.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),s(o,"autoGainControl","mozAutoGainControl"),s(o,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[o])}}}}function Sh(n,e){n.navigator.mediaDevices&&"getDisplayMedia"in n.navigator.mediaDevices||n.navigator.mediaDevices&&(n.navigator.mediaDevices.getDisplayMedia=function(i){if(!(i&&i.video)){const s=new DOMException("getDisplayMedia without video constraints is undefined");return s.name="NotFoundError",s.code=8,Promise.reject(s)}return i.video===!0?i.video={mediaSource:e}:i.video.mediaSource=e,n.navigator.mediaDevices.getUserMedia(i)})}function So(n){typeof n=="object"&&n.RTCTrackEvent&&"receiver"in n.RTCTrackEvent.prototype&&!("transceiver"in n.RTCTrackEvent.prototype)&&Object.defineProperty(n.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Ki(n,e){if(typeof n!="object"||!(n.RTCPeerConnection||n.mozRTCPeerConnection))return;!n.RTCPeerConnection&&n.mozRTCPeerConnection&&(n.RTCPeerConnection=n.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(s){const r=n.RTCPeerConnection.prototype[s],a={[s](){return arguments[0]=new(s==="addIceCandidate"?n.RTCIceCandidate:n.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};n.RTCPeerConnection.prototype[s]=a[s]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=n.RTCPeerConnection.prototype.getStats;n.RTCPeerConnection.prototype.getStats=function(){const[r,a,o]=arguments;return i.apply(this,[r||null]).then(c=>{if(e.version<53&&!a)try{c.forEach(d=>{d.type=t[d.type]||d.type})}catch(d){if(d.name!=="TypeError")throw d;c.forEach((l,u)=>{c.set(u,Object.assign({},l,{type:t[l.type]||l.type}))})}return c}).then(a,o)}}function _o(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender)||n.RTCRtpSender&&"getStats"in n.RTCRtpSender.prototype)return;const e=n.RTCPeerConnection.prototype.getSenders;e&&(n.RTCPeerConnection.prototype.getSenders=function(){const s=e.apply(this,[]);return s.forEach(r=>r._pc=this),s});const t=n.RTCPeerConnection.prototype.addTrack;t&&(n.RTCPeerConnection.prototype.addTrack=function(){const s=t.apply(this,arguments);return s._pc=this,s}),n.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Eo(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender)||n.RTCRtpSender&&"getStats"in n.RTCRtpReceiver.prototype)return;const e=n.RTCPeerConnection.prototype.getReceivers;e&&(n.RTCPeerConnection.prototype.getReceivers=function(){const i=e.apply(this,[]);return i.forEach(s=>s._pc=this),i}),Et(n,"track",t=>(t.receiver._pc=t.srcElement,t)),n.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function wo(n){!n.RTCPeerConnection||"removeStream"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.removeStream=function(t){Rs("removeStream","removeTrack"),this.getSenders().forEach(i=>{i.track&&t.getTracks().includes(i.track)&&this.removeTrack(i)})})}function Po(n){n.DataChannel&&!n.RTCDataChannel&&(n.RTCDataChannel=n.DataChannel)}function Ro(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.addTransceiver;e&&(n.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let i=arguments[1]&&arguments[1].sendEncodings;i===void 0&&(i=[]),i=[...i];const s=i.length>0;s&&i.forEach(a=>{if("rid"in a&&!/^[a-z0-9]{0,16}$/i.test(a.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in a&&!(parseFloat(a.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in a&&!(parseFloat(a.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const r=e.apply(this,arguments);if(s){const{sender:a}=r,o=a.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=i,a.sendEncodings=i,this.setParametersPromises.push(a.setParameters(o).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return r})}function Io(n){if(!(typeof n=="object"&&n.RTCRtpSender))return;const e=n.RTCRtpSender.prototype.getParameters;e&&(n.RTCRtpSender.prototype.getParameters=function(){const i=e.apply(this,arguments);return"encodings"in i||(i.encodings=[].concat(this.sendEncodings||[{}])),i})}function Oo(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.createOffer;n.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function Mo(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.createAnswer;n.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}var vr=Object.freeze({__proto__:null,shimAddTransceiver:Ro,shimCreateAnswer:Mo,shimCreateOffer:Oo,shimGetDisplayMedia:Sh,shimGetParameters:Io,shimGetUserMedia:Co,shimOnTrack:So,shimPeerConnection:Ki,shimRTCDataChannel:Po,shimReceiverGetStats:Eo,shimRemoveStream:wo,shimSenderGetStats:_o});function xo(n){if(!(typeof n!="object"||!n.RTCPeerConnection)){if("getLocalStreams"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in n.RTCPeerConnection.prototype)){const e=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addStream=function(i){this._localStreams||(this._localStreams=[]),this._localStreams.includes(i)||this._localStreams.push(i),i.getAudioTracks().forEach(s=>e.call(this,s,i)),i.getVideoTracks().forEach(s=>e.call(this,s,i))},n.RTCPeerConnection.prototype.addTrack=function(i){for(var s=arguments.length,r=new Array(s>1?s-1:0),a=1;a<s;a++)r[a-1]=arguments[a];return r&&r.forEach(o=>{this._localStreams?this._localStreams.includes(o)||this._localStreams.push(o):this._localStreams=[o]}),e.apply(this,arguments)}}"removeStream"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const i=this._localStreams.indexOf(t);if(i===-1)return;this._localStreams.splice(i,1);const s=t.getTracks();this.getSenders().forEach(r=>{s.includes(r.track)&&this.removeTrack(r)})})}}function Ao(n){if(!(typeof n!="object"||!n.RTCPeerConnection)&&("getRemoteStreams"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in n.RTCPeerConnection.prototype))){Object.defineProperty(n.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=i=>{i.streams.forEach(s=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(s))return;this._remoteStreams.push(s);const r=new Event("addstream");r.stream=s,this.dispatchEvent(r)})})}});const e=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){const i=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(s){s.streams.forEach(r=>{if(i._remoteStreams||(i._remoteStreams=[]),i._remoteStreams.indexOf(r)>=0)return;i._remoteStreams.push(r);const a=new Event("addstream");a.stream=r,i.dispatchEvent(a)})}),e.apply(i,arguments)}}}function Do(n){if(typeof n!="object"||!n.RTCPeerConnection)return;const e=n.RTCPeerConnection.prototype,t=e.createOffer,i=e.createAnswer,s=e.setLocalDescription,r=e.setRemoteDescription,a=e.addIceCandidate;e.createOffer=function(d,l){const u=arguments.length>=2?arguments[2]:arguments[0],p=t.apply(this,[u]);return l?(p.then(d,l),Promise.resolve()):p},e.createAnswer=function(d,l){const u=arguments.length>=2?arguments[2]:arguments[0],p=i.apply(this,[u]);return l?(p.then(d,l),Promise.resolve()):p};let o=function(c,d,l){const u=s.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u};e.setLocalDescription=o,o=function(c,d,l){const u=r.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u},e.setRemoteDescription=o,o=function(c,d,l){const u=a.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u},e.addIceCandidate=o}function No(n){const e=n&&n.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,i=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=s=>i(Lo(s))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(i,s,r){e.mediaDevices.getUserMedia(i).then(s,r)}).bind(e))}function Lo(n){return n&&n.video!==void 0?Object.assign({},n,{video:ho(n.video)}):n}function Uo(n){if(!n.RTCPeerConnection)return;const e=n.RTCPeerConnection;n.RTCPeerConnection=function(i,s){if(i&&i.iceServers){const r=[];for(let a=0;a<i.iceServers.length;a++){let o=i.iceServers[a];o.urls===void 0&&o.url?(Rs("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,r.push(o)):r.push(i.iceServers[a])}i.iceServers=r}return new e(i,s)},n.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(n.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function jo(n){typeof n=="object"&&n.RTCTrackEvent&&"receiver"in n.RTCTrackEvent.prototype&&!("transceiver"in n.RTCTrackEvent.prototype)&&Object.defineProperty(n.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Fo(n){const e=n.RTCPeerConnection.prototype.createOffer;n.RTCPeerConnection.prototype.createOffer=function(i){if(i){typeof i.offerToReceiveAudio<"u"&&(i.offerToReceiveAudio=!!i.offerToReceiveAudio);const s=this.getTransceivers().find(a=>a.receiver.track.kind==="audio");i.offerToReceiveAudio===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):i.offerToReceiveAudio===!0&&!s&&this.addTransceiver("audio",{direction:"recvonly"}),typeof i.offerToReceiveVideo<"u"&&(i.offerToReceiveVideo=!!i.offerToReceiveVideo);const r=this.getTransceivers().find(a=>a.receiver.track.kind==="video");i.offerToReceiveVideo===!1&&r?r.direction==="sendrecv"?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":r.direction==="recvonly"&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):i.offerToReceiveVideo===!0&&!r&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function Bo(n){typeof n!="object"||n.AudioContext||(n.AudioContext=n.webkitAudioContext)}var kr=Object.freeze({__proto__:null,shimAudioContext:Bo,shimCallbacksAPI:Do,shimConstraints:Lo,shimCreateOfferLegacy:Fo,shimGetUserMedia:No,shimLocalStreamsAPI:xo,shimRTCIceServerUrls:Uo,shimRemoteStreamsAPI:Ao,shimTrackEventTransceiver:jo}),Vo={exports:{}};(function(n){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(`
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
t=0 0
|
|
49
|
-
`},e.getDirection=function(t,i){const s=e.splitLines(t);for(let r=0;r<s.length;r++)switch(s[r]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return s[r].substring(2)}return i?e.getDirection(i):"sendrecv"},e.getKind=function(t){return e.splitLines(t)[0].split(" ")[0].substring(2)},e.isRejected=function(t){return t.split(" ",2)[1]==="0"},e.parseMLine=function(t){const s=e.splitLines(t)[0].substring(2).split(" ");return{kind:s[0],port:parseInt(s[1],10),protocol:s[2],fmt:s.slice(3).join(" ")}},e.parseOLine=function(t){const s=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:s[0],sessionId:s[1],sessionVersion:parseInt(s[2],10),netType:s[3],addressType:s[4],address:s[5]}},e.isValidSDP=function(t){if(typeof t!="string"||t.length===0)return!1;const i=e.splitLines(t);for(let s=0;s<i.length;s++)if(i[s].length<2||i[s].charAt(1)!=="=")return!1;return!0},n.exports=e})(Vo);var $o=Vo.exports,jt=dh($o),_h=sl({__proto__:null,default:jt},[$o]);function Gn(n){if(!n.RTCIceCandidate||n.RTCIceCandidate&&"foundation"in n.RTCIceCandidate.prototype)return;const e=n.RTCIceCandidate;n.RTCIceCandidate=function(i){if(typeof i=="object"&&i.candidate&&i.candidate.indexOf("a=")===0&&(i=JSON.parse(JSON.stringify(i)),i.candidate=i.candidate.substring(2)),i.candidate&&i.candidate.length){const s=new e(i),r=jt.parseCandidate(i.candidate);for(const a in r)a in s||Object.defineProperty(s,a,{value:r[a]});return s.toJSON=function(){return{candidate:s.candidate,sdpMid:s.sdpMid,sdpMLineIndex:s.sdpMLineIndex,usernameFragment:s.usernameFragment}},s}return new e(i)},n.RTCIceCandidate.prototype=e.prototype,Et(n,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new n.RTCIceCandidate(t.candidate),writable:"false"}),t))}function Qi(n){!n.RTCIceCandidate||n.RTCIceCandidate&&"relayProtocol"in n.RTCIceCandidate.prototype||Et(n,"icecandidate",e=>{if(e.candidate){const t=jt.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function zn(n,e){if(!n.RTCPeerConnection)return;"sctp"in n.RTCPeerConnection.prototype||Object.defineProperty(n.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const t=function(o){if(!o||!o.sdp)return!1;const c=jt.splitSections(o.sdp);return c.shift(),c.some(d=>{const l=jt.parseMLine(d);return l&&l.kind==="application"&&l.protocol.indexOf("SCTP")!==-1})},i=function(o){const c=o.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(c===null||c.length<2)return-1;const d=parseInt(c[1],10);return d!==d?-1:d},s=function(o){let c=65536;return e.browser==="firefox"&&(e.version<57?o===-1?c=16384:c=2147483637:e.version<60?c=e.version===57?65535:65536:c=2147483637),c},r=function(o,c){let d=65536;e.browser==="firefox"&&e.version===57&&(d=65535);const l=jt.matchPrefix(o.sdp,"a=max-message-size:");return l.length>0?d=parseInt(l[0].substring(19),10):e.browser==="firefox"&&c!==-1&&(d=2147483637),d},a=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76){const{sdpSemantics:c}=this.getConfiguration();c==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(t(arguments[0])){const c=i(arguments[0]),d=s(c),l=r(arguments[0],c);let u;d===0&&l===0?u=Number.POSITIVE_INFINITY:d===0||l===0?u=Math.max(d,l):u=Math.min(d,l);const p={};Object.defineProperty(p,"maxMessageSize",{get(){return u}}),this._sctp=p}return a.apply(this,arguments)}}function Wn(n){if(!(n.RTCPeerConnection&&"createDataChannel"in n.RTCPeerConnection.prototype))return;function e(i,s){const r=i.send;i.send=function(){const o=arguments[0],c=o.length||o.size||o.byteLength;if(i.readyState==="open"&&s.sctp&&c>s.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+s.sctp.maxMessageSize+" bytes)");return r.apply(i,arguments)}}const t=n.RTCPeerConnection.prototype.createDataChannel;n.RTCPeerConnection.prototype.createDataChannel=function(){const s=t.apply(this,arguments);return e(s,this),s},Et(n,"datachannel",i=>(e(i.channel,i.target),i))}function Yi(n){if(!n.RTCPeerConnection||"connectionState"in n.RTCPeerConnection.prototype)return;const e=n.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(t){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),t&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=t)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(t=>{const i=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=s=>{const r=s.target;if(r._lastConnectionState!==r.connectionState){r._lastConnectionState=r.connectionState;const a=new Event("connectionstatechange",s);r.dispatchEvent(a)}return s},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function Xi(n,e){if(!n.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e.version>=605)return;const t=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(s){if(s&&s.sdp&&s.sdp.indexOf(`
|
|
50
|
-
a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
|
|
51
|
-
`).filter(a=>a.trim()!=="a=extmap-allow-mixed").join(`
|
|
52
|
-
`);n.RTCSessionDescription&&s instanceof n.RTCSessionDescription?arguments[0]=new n.RTCSessionDescription({type:s.type,sdp:r}):s.sdp=r}return t.apply(this,arguments)}}function Jn(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const t=n.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(n.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Kn(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const t=n.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(n.RTCPeerConnection.prototype.setLocalDescription=function(){let s=arguments[0]||{};if(typeof s!="object"||s.type&&s.sdp)return t.apply(this,arguments);if(s={type:s.type,sdp:s.sdp},!s.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":s.type="offer";break;default:s.type="answer";break}return s.sdp||s.type!=="offer"&&s.type!=="answer"?t.apply(this,[s]):(s.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(a=>t.apply(this,[a]))})}var Eh=Object.freeze({__proto__:null,removeExtmapAllowMixed:Xi,shimAddIceCandidateNullOrEmpty:Jn,shimConnectionState:Yi,shimMaxMessageSize:zn,shimParameterlessSetLocalDescription:Kn,shimRTCIceCandidate:Gn,shimRTCIceCandidateRelayProtocol:Qi,shimSendThrowTypeError:Wn});function wh(){let{window:n}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const t=uo,i=Th(n),s={browserDetails:i,commonShim:Eh,extractVersion:qn,disableLog:yh,disableWarnings:bh,sdp:_h};switch(i.browser){case"chrome":if(!gr||!Ji||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),s;if(i.version===null)return t("Chrome shim can not determine version, not shimming."),s;t("adapter.js shimming chrome."),s.browserShim=gr,Jn(n,i),Kn(n),po(n,i),fo(n),Ji(n,i),mo(n),bo(n,i),go(n),vo(n),ko(n),To(n,i),Gn(n),Qi(n),Yi(n),zn(n,i),Wn(n),Xi(n,i);break;case"firefox":if(!vr||!Ki||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),s;t("adapter.js shimming firefox."),s.browserShim=vr,Jn(n,i),Kn(n),Co(n,i),Ki(n,i),So(n),wo(n),_o(n),Eo(n),Po(n),Ro(n),Io(n),Oo(n),Mo(n),Gn(n),Yi(n),zn(n,i),Wn(n);break;case"safari":if(!kr||!e.shimSafari)return t("Safari shim is not included in this adapter release."),s;t("adapter.js shimming safari."),s.browserShim=kr,Jn(n,i),Kn(n),Uo(n),Fo(n),Do(n),xo(n),Ao(n),jo(n),No(n),Bo(n),Gn(n),Qi(n),zn(n,i),Wn(n),Xi(n,i);break;default:t("Unsupported browser!");break}return s}wh({window:typeof window>"u"?void 0:window});const Ph=10,Un="lk_e2ee",Rh="LKFrameEncryptionKey",Ih={sharedKey:!1,ratchetSalt:Rh,ratchetWindowSize:8,failureTolerance:Ph,keyringSize:16};var pt;(function(n){n.SetKey="setKey",n.RatchetRequest="ratchetRequest",n.KeyRatcheted="keyRatcheted"})(pt||(pt={}));var yr;(function(n){n.KeyRatcheted="keyRatcheted"})(yr||(yr={}));var lt;(function(n){n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError"})(lt||(lt={}));var br;(function(n){n.Error="cryptorError"})(br||(br={}));function Oh(){return Mh()||Zi()}function Zi(){return typeof window.RTCRtpScriptTransform<"u"}function Mh(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class nf extends Ge.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,i)=>{$.debug("key ratcheted event received",{material:t,keyIndex:i})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},Ih),e),this.on(pt.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,i){const s={key:e,participantIdentity:t,keyIndex:i};if(!this.options.sharedKey&&!t)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(t??"shared","-").concat(i??0),s),this.emit(pt.SetKey,s)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(pt.RatchetRequest,e,t)}}class Gt extends Error{constructor(e,t){super(t||"an error has occured"),this.code=e}}class te extends Gt{constructor(e,t,i){super(1,e),this.status=i,this.reason=t}}class Is extends Gt{constructor(e){super(21,e??"device is unsupported")}}class qe extends Gt{constructor(e){super(20,e??"track is invalid")}}class xh extends Gt{constructor(e){super(10,e??"unsupported server")}}class ue extends Gt{constructor(e){super(12,e??"unexpected connection state")}}class es extends Gt{constructor(e){super(13,e??"unable to negotiate")}}var ti;(function(n){n.PermissionDenied="PermissionDenied",n.NotFound="NotFound",n.DeviceInUse="DeviceInUse",n.Other="Other"})(ti||(ti={}));(function(n){function e(t){if(t&&"name"in t)return t.name==="NotFoundError"||t.name==="DevicesNotFoundError"?n.NotFound:t.name==="NotAllowedError"||t.name==="PermissionDeniedError"?n.PermissionDenied:t.name==="NotReadableError"||t.name==="TrackStartError"?n.DeviceInUse:n.Other}n.getFailure=e})(ti||(ti={}));var E;(function(n){n.Connected="connected",n.Reconnecting="reconnecting",n.Reconnected="reconnected",n.Disconnected="disconnected",n.ConnectionStateChanged="connectionStateChanged",n.MediaDevicesChanged="mediaDevicesChanged",n.ParticipantConnected="participantConnected",n.ParticipantDisconnected="participantDisconnected",n.TrackPublished="trackPublished",n.TrackSubscribed="trackSubscribed",n.TrackSubscriptionFailed="trackSubscriptionFailed",n.TrackUnpublished="trackUnpublished",n.TrackUnsubscribed="trackUnsubscribed",n.TrackMuted="trackMuted",n.TrackUnmuted="trackUnmuted",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalAudioSilenceDetected="localAudioSilenceDetected",n.ActiveSpeakersChanged="activeSpeakersChanged",n.ParticipantMetadataChanged="participantMetadataChanged",n.ParticipantNameChanged="participantNameChanged",n.RoomMetadataChanged="roomMetadataChanged",n.DataReceived="dataReceived",n.ConnectionQualityChanged="connectionQualityChanged",n.TrackStreamStateChanged="trackStreamStateChanged",n.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",n.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",n.AudioPlaybackStatusChanged="audioPlaybackChanged",n.VideoPlaybackStatusChanged="videoPlaybackChanged",n.MediaDevicesError="mediaDevicesError",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.SignalConnected="signalConnected",n.RecordingStatusChanged="recordingStatusChanged",n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError",n.DCBufferStatusChanged="dcBufferStatusChanged",n.ActiveDeviceChanged="activeDeviceChanged"})(E||(E={}));var M;(function(n){n.TrackPublished="trackPublished",n.TrackSubscribed="trackSubscribed",n.TrackSubscriptionFailed="trackSubscriptionFailed",n.TrackUnpublished="trackUnpublished",n.TrackUnsubscribed="trackUnsubscribed",n.TrackMuted="trackMuted",n.TrackUnmuted="trackUnmuted",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.ParticipantMetadataChanged="participantMetadataChanged",n.ParticipantNameChanged="participantNameChanged",n.DataReceived="dataReceived",n.IsSpeakingChanged="isSpeakingChanged",n.ConnectionQualityChanged="connectionQualityChanged",n.TrackStreamStateChanged="trackStreamStateChanged",n.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",n.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",n.MediaDevicesError="mediaDevicesError",n.AudioStreamAcquired="audioStreamAcquired",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.PCTrackAdded="pcTrackAdded"})(M||(M={}));var I;(function(n){n.TransportsCreated="transportsCreated",n.Connected="connected",n.Disconnected="disconnected",n.Resuming="resuming",n.Resumed="resumed",n.Restarting="restarting",n.Restarted="restarted",n.SignalResumed="signalResumed",n.SignalRestarted="signalRestarted",n.Closing="closing",n.MediaTrackAdded="mediaTrackAdded",n.ActiveSpeakersUpdate="activeSpeakersUpdate",n.DataPacketReceived="dataPacketReceived",n.RTPVideoMapUpdate="rtpVideoMapUpdate",n.DCBufferStatusChanged="dcBufferStatusChanged",n.ParticipantUpdate="participantUpdate",n.RoomUpdate="roomUpdate",n.SpeakersChanged="speakersChanged",n.StreamStateChanged="streamStateChanged",n.ConnectionQualityUpdate="connectionQualityUpdate",n.SubscriptionError="subscriptionError",n.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",n.RemoteMute="remoteMute",n.SubscribedQualityUpdate="subscribedQualityUpdate",n.LocalTrackUnpublished="localTrackUnpublished",n.Offline="offline"})(I||(I={}));var _;(function(n){n.Message="message",n.Muted="muted",n.Unmuted="unmuted",n.Restarted="restarted",n.Ended="ended",n.Subscribed="subscribed",n.Unsubscribed="unsubscribed",n.UpdateSettings="updateSettings",n.UpdateSubscription="updateSubscription",n.AudioPlaybackStarted="audioPlaybackStarted",n.AudioPlaybackFailed="audioPlaybackFailed",n.AudioSilenceDetected="audioSilenceDetected",n.VisibilityChanged="visibilityChanged",n.VideoDimensionsChanged="videoDimensionsChanged",n.VideoPlaybackStarted="videoPlaybackStarted",n.VideoPlaybackFailed="videoPlaybackFailed",n.ElementAttached="elementAttached",n.ElementDetached="elementDetached",n.UpstreamPaused="upstreamPaused",n.UpstreamResumed="upstreamResumed",n.SubscriptionPermissionChanged="subscriptionPermissionChanged",n.SubscriptionStatusChanged="subscriptionStatusChanged",n.SubscriptionFailed="subscriptionFailed",n.TrackProcessorUpdate="trackProcessorUpdate"})(_||(_={}));function Os(n,e,t){var i,s,r;e===void 0&&(e=50),t===void 0&&(t={});var a=(i=t.isImmediate)!=null&&i,o=(s=t.callback)!=null&&s,c=t.maxWait,d=Date.now(),l=[];function u(){if(c!==void 0){var m=Date.now()-d;if(m+e>=c)return c-m}return e}var p=function(){var m=[].slice.call(arguments),k=this;return new Promise(function(v,S){var O=a&&r===void 0;if(r!==void 0&&clearTimeout(r),r=setTimeout(function(){if(r=void 0,d=Date.now(),!a){var F=n.apply(k,m);o&&o(F),l.forEach(function(W){return(0,W.resolve)(F)}),l=[]}},u()),O){var w=n.apply(k,m);return o&&o(w),v(w)}l.push({resolve:v,reject:S})})};return p.cancel=function(m){r!==void 0&&clearTimeout(r),l.forEach(function(k){return(0,k.reject)(m)}),l=[]},p}const Ah=/version\/(\d+(\.?_?\d+)+)/i;let _i;function st(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const t=navigator.userAgent.toLowerCase();if(_i===void 0||e){const i=Dh.find(s=>{let{test:r}=s;return r.test(t)});_i=i==null?void 0:i.describe(t)}return _i}const Dh=[{test:/firefox|iceweasel|fxios/i,describe(n){return{name:"Firefox",version:Ei(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("fxios")?"iOS":void 0}}},{test:/chrom|crios|crmo/i,describe(n){return{name:"Chrome",version:Ei(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("crios")?"iOS":void 0}}},{test:/safari|applewebkit/i,describe(n){return{name:"Safari",version:Ei(Ah,n),os:n.includes("mobile/")?"iOS":"macOS"}}}];function Ei(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const i=e.match(n);return i&&i.length>=t&&i[t]||""}var Nh="2.0.10";const Lh=Nh,Uh=12;class ve{}ve.setTimeout=function(){return setTimeout(...arguments)};ve.setInterval=function(){return setInterval(...arguments)};ve.clearTimeout=function(){return clearTimeout(...arguments)};ve.clearInterval=function(){return clearInterval(...arguments)};class K{constructor(e,t,i,s,r){if(typeof e=="object")this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(t!==void 0&&i!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:s,priority:r};else throw new TypeError("Unsupported options: provide at least width, height and maxBitrate")}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const jh=["vp8","h264"],Ho=["vp8","h264","vp9","av1"];function Fh(n){return!!jh.find(e=>e===n)}var ts;(function(n){n.telephone={maxBitrate:12e3},n.speech={maxBitrate:2e4},n.music={maxBitrate:32e3},n.musicStereo={maxBitrate:48e3},n.musicHighQuality={maxBitrate:64e3},n.musicHighQualityStereo={maxBitrate:96e3}})(ts||(ts={}));const bn={h90:new K(160,90,9e4,20),h180:new K(320,180,16e4,20),h216:new K(384,216,18e4,20),h360:new K(640,360,45e4,20),h540:new K(960,540,8e5,25),h720:new K(1280,720,17e5,30),h1080:new K(1920,1080,3e6,30),h1440:new K(2560,1440,5e6,30),h2160:new K(3840,2160,8e6,30)},ns={h120:new K(160,120,7e4,20),h180:new K(240,180,125e3,20),h240:new K(320,240,14e4,20),h360:new K(480,360,33e4,20),h480:new K(640,480,5e5,20),h540:new K(720,540,6e5,25),h720:new K(960,720,13e5,30),h1080:new K(1440,1080,23e5,30),h1440:new K(1920,1440,38e5,30)},Ms={h360fps3:new K(640,360,2e5,3,"medium"),h360fps15:new K(640,360,4e5,15,"medium"),h720fps5:new K(1280,720,8e5,5,"medium"),h720fps15:new K(1280,720,15e5,15,"medium"),h720fps30:new K(1280,720,2e6,30,"medium"),h1080fps15:new K(1920,1080,25e5,15,"medium"),h1080fps30:new K(1920,1080,5e6,30,"medium"),original:new K(0,0,7e6,30,"medium")};function Bh(n){if(!(typeof n>"u"))return typeof structuredClone=="function"?structuredClone(n):JSON.parse(JSON.stringify(n))}const Vh=5e3,Yt=[];var Me;(function(n){n[n.LOW=0]="LOW",n[n.MEDIUM=1]="MEDIUM",n[n.HIGH=2]="HIGH"})(Me||(Me={}));class T extends Ge.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var s;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=T.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=$,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),Vh):this.handleAppVisibilityChanged()},this.log=it((s=i.loggerName)!==null&&s!==void 0?s:Fe.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=T.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),Z(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===T.Kind.Video&&(t="video"),this.attachedElements.length===0&&T.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(Yt.forEach(r=>{r.parentElement===null&&!e&&(e=r)}),e&&Yt.splice(Yt.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),Nt(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),s=i.some(r=>r.kind==="audio");return e.play().then(()=>{this.emit(s?_.AudioPlaybackStarted:_.VideoPlaybackStarted)}).catch(r=>{r.name==="NotAllowedError"?this.emit(s?_.AudioPlaybackFailed:_.VideoPlaybackFailed,r):r.name==="AbortError"?$.debug("".concat(s?"audio":"video"," playback aborted, likely due to new play request")):$.warn("could not playback ".concat(s?"audio":"video"),r),s&&e&&i.some(a=>a.kind==="video")&&r.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(_.ElementAttached,e),e}detach(e){try{if(e){Ft(this.mediaStreamTrack,e);const i=this.attachedElements.indexOf(e);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(e),this.emit(_.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(i=>{Ft(this.mediaStreamTrack,i),t.push(i),this.recycleElement(i),this.emit(_.ElementDetached,i)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval)}updateLoggerOptions(e){e.loggerName&&(this.log=it(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Yt.forEach(i=>{i.parentElement||(t=!1)}),t&&Yt.push(e)}}handleAppVisibilityChanged(){return f(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden"})}addAppVisibilityListener(){_e()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){_e()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Nt(n,e){let t;e.srcObject instanceof MediaStream?t=e.srcObject:t=new MediaStream;let i;n.kind==="audio"?i=t.getAudioTracks():i=t.getVideoTracks(),i.includes(n)||(i.forEach(s=>{t.removeTrack(s)}),t.addTrack(n)),(!kt()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(kt()||$t())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function Ft(n,e){if(e.srcObject instanceof MediaStream){const t=e.srcObject;t.removeTrack(n),t.getTracks().length>0?e.srcObject=t:e.srcObject=null}}(function(n){let e;(function(d){d.Audio="audio",d.Video="video",d.Unknown="unknown"})(e=n.Kind||(n.Kind={}));let t;(function(d){d.Camera="camera",d.Microphone="microphone",d.ScreenShare="screen_share",d.ScreenShareAudio="screen_share_audio",d.Unknown="unknown"})(t=n.Source||(n.Source={}));let i;(function(d){d.Active="active",d.Paused="paused",d.Unknown="unknown"})(i=n.StreamState||(n.StreamState={}));function s(d){switch(d){case e.Audio:return Le.AUDIO;case e.Video:return Le.VIDEO;default:return Le.DATA}}n.kindToProto=s;function r(d){switch(d){case Le.AUDIO:return e.Audio;case Le.VIDEO:return e.Video;default:return e.Unknown}}n.kindFromProto=r;function a(d){switch(d){case t.Camera:return me.CAMERA;case t.Microphone:return me.MICROPHONE;case t.ScreenShare:return me.SCREEN_SHARE;case t.ScreenShareAudio:return me.SCREEN_SHARE_AUDIO;default:return me.UNKNOWN}}n.sourceToProto=a;function o(d){switch(d){case me.CAMERA:return t.Camera;case me.MICROPHONE:return t.Microphone;case me.SCREEN_SHARE:return t.ScreenShare;case me.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}n.sourceFromProto=o;function c(d){switch(d){case Hi.ACTIVE:return i.Active;case Hi.PAUSED:return i.Paused;default:return i.Unknown}}n.streamStateFromProto=c})(T||(T={}));function qo(n,e,t){var i;const s=(i=Bh(n))!==null&&i!==void 0?i:{};return s.audio===!0&&(s.audio={}),s.video===!0&&(s.video={}),s.audio&&is(s.audio,e),s.video&&is(s.video,t),s}function is(n,e){return Object.keys(e).forEach(t=>{n[t]===void 0&&(n[t]=e[t])}),n}function mi(n){const e={};if(n.video)if(typeof n.video=="object"){const t={},i=t,s=n.video;Object.keys(s).forEach(r=>{switch(r){case"resolution":is(i,s.resolution);break;default:i[r]=s[r]}}),e.video=t}else e.video=n.video;else e.video=!1;return n.audio?typeof n.audio=="object"?e.audio=n.audio:e.audio=!0:e.audio=!1,e}function $h(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return f(this,void 0,void 0,function*(){const t=Go();if(t){const i=t.createAnalyser();i.fftSize=2048;const s=i.frequencyBinCount,r=new Uint8Array(s);t.createMediaStreamSource(new MediaStream([n.mediaStreamTrack])).connect(i),yield tt(e),i.getByteTimeDomainData(r);const o=r.some(c=>c!==128&&c!==0);return t.close(),!o}return!1})}function Go(){const n=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(n)return new n({latencyHint:"interactive"})}function Hh(n){return n===T.Source.Microphone?"audioinput":n===T.Source.Camera?"videoinput":void 0}function qh(n){var e,t;let i=(e=n.video)!==null&&e!==void 0?e:!0;return n.resolution&&n.resolution.width>0&&n.resolution.height>0&&(i=typeof i=="boolean"?{}:i,kt()?i=Object.assign(Object.assign({},i),{width:{max:n.resolution.width},height:{max:n.resolution.height},frameRate:n.resolution.frameRate}):i=Object.assign(Object.assign({},i),{width:{ideal:n.resolution.width},height:{ideal:n.resolution.height},frameRate:n.resolution.frameRate})),{audio:(t=n.audio)!==null&&t!==void 0?t:!1,video:i,controller:n.controller,selfBrowserSurface:n.selfBrowserSurface,surfaceSwitching:n.surfaceSwitching,systemAudio:n.systemAudio,preferCurrentTab:n.preferCurrentTab}}function zo(n){const e=n.split("/")[1].toLowerCase();if(!Ho.includes(e))throw Error("Video codec not supported: ".concat(e));return e}function Gh(n){const e=[];return n.forEach(t=>{t.track!==void 0&&e.push(new Ss({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function Z(n){return n instanceof T?{trackID:n.sid,source:n.source,muted:n.isMuted,enabled:n.mediaStreamTrack.enabled,kind:n.kind,streamID:n.mediaStreamID,streamTrackID:n.mediaStreamTrack.id}:{trackID:n.trackSid,enabled:n.isEnabled,muted:n.isMuted,trackInfo:Object.assign({mimeType:n.mimeType,name:n.trackName,encrypted:n.isEncrypted,kind:n.kind,source:n.source},n.track?Z(n.track):{})}}const zh="|",Tr="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Wh(n){const e=n.split(zh);return e.length>1?[e[0],n.substr(e[0].length+1)]:[n,""]}function tt(n){return f(this,void 0,void 0,function*(){return new Promise(e=>ve.setTimeout(e,n))})}function ss(){return"addTransceiver"in RTCPeerConnection.prototype}function rs(){return"addTrack"in RTCPeerConnection.prototype}function Jh(){if(!("getCapabilities"in RTCRtpSender)||kt())return!1;const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType==="video/AV1"){e=!0;break}}return e}function Kh(){if(!("getCapabilities"in RTCRtpSender)||$t())return!1;if(kt()){const t=st();if(t!=null&&t.version&&gi(t.version,"16")<0)return!1}const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType==="video/VP9"){e=!0;break}}return e}function ni(n){return n==="av1"||n==="vp9"}function as(n){return document?(n||(n=document.createElement("audio")),"setSinkId"in n):!1}const Qh={Chrome:"100",Safari:"15",Firefox:"100"};function Yh(n){if(!_e()||!("setCodecPreferences"in n))return!1;const e=st();if(!(e!=null&&e.name)||!e.version)return!1;const t=Qh[e.name];return t?gi(e.version,t)>=0:!1}function Xh(){return typeof RTCPeerConnection>"u"?!1:ss()||rs()}function $t(){var n;return((n=st())===null||n===void 0?void 0:n.name)==="Firefox"}function kt(){var n;return((n=st())===null||n===void 0?void 0:n.name)==="Safari"}function Zh(){const n=st();return(n==null?void 0:n.name)==="Safari"&&n.version.startsWith("17.")}function Wo(){return _e()?/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function _e(){return typeof document<"u"}function yt(){return navigator.product=="ReactNative"}function os(n){return n.hostname.endsWith(".livekit.cloud")||n.hostname.endsWith(".livekit.run")}function Jo(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Ko(){if(!yt())return;let n=Jo();if(n)return n.platform}function Cr(){if(_e())return window.devicePixelRatio;if(yt()){let n=Jo();if(n)return n.devicePixelRatio}return 1}function gi(n,e){const t=n.split("."),i=e.split("."),s=Math.min(t.length,i.length);for(let r=0;r<s;++r){const a=parseInt(t[r],10),o=parseInt(i[r],10);if(a>o)return 1;if(a<o)return-1;if(r===s-1&&a===o)return 0}return n===""&&e!==""?-1:e===""?1:t.length==i.length?0:t.length<i.length?-1:1}function ep(n){for(const e of n)e.target.handleResize(e)}function tp(n){for(const e of n)e.target.handleVisibilityChanged(e)}let wi=null;const Sr=()=>(wi||(wi=new ResizeObserver(ep)),wi);let Pi=null;const _r=()=>(Pi||(Pi=new IntersectionObserver(tp,{root:null,rootMargin:"0px"})),Pi);function np(){var n;const e=new nu({sdk:Aa.JS,protocol:Uh,version:Lh});return yt()&&(e.os=(n=Ko())!==null&&n!==void 0?n:""),e}function Er(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const s=document.createElement("canvas");s.width=n,s.height=e;const r=s.getContext("2d");r==null||r.fillRect(0,0,s.width,s.height),i&&r&&(r.beginPath(),r.arc(n/2,e/2,50,0,Math.PI*2,!0),r.closePath(),r.fillStyle="grey",r.fill());const a=s.captureStream(),[o]=a.getTracks();if(!o)throw Error("Could not get empty media stream video track");return o.enabled=t,o}let Xt;function Ri(){if(!Xt){const n=new AudioContext,e=n.createOscillator(),t=n.createGain();t.gain.setValueAtTime(0,0);const i=n.createMediaStreamDestination();if(e.connect(t),t.connect(i),e.start(),[Xt]=i.stream.getAudioTracks(),!Xt)throw Error("Could not get empty media stream audio track");Xt.enabled=!1}return Xt.clone()}class Qo{constructor(e,t){this.onFinally=t,this.promise=new Promise((i,s)=>f(this,void 0,void 0,function*(){this.resolve=i,this.reject=s,e&&(yield e(i,s))})).finally(()=>{var i;return(i=this.onFinally)===null||i===void 0?void 0:i.call(this)})}}class xe{constructor(){this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e;const t=new Promise(s=>e=()=>{this._locks-=1,s()}),i=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),i}}function ip(n){return Ho.includes(n)}function ft(n){if(typeof n=="string")return n;if(Array.isArray(n))return n[0];if(n.exact)return Array.isArray(n.exact)?n.exact[0]:n.exact;if(n.ideal)return Array.isArray(n.ideal)?n.ideal[0]:n.ideal;throw Error("could not unwrap constraint")}function sp(n){return n.startsWith("http")?n.replace(/^(http)/,"ws"):n}function wr(n){return n.startsWith("ws")?n.replace(/^(ws)/,"http"):n}const Pr="default";class ye{static getInstance(){return this.instance===void 0&&(this.instance=new ye),this.instance}getDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;var i;return f(this,void 0,void 0,function*(){if(((i=ye.userMediaPromiseMap)===null||i===void 0?void 0:i.size)>0){$.debug("awaiting getUserMedia promise");try{e?yield ye.userMediaPromiseMap.get(e):yield Promise.all(ye.userMediaPromiseMap.values())}catch{$.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(t&&!(kt()&&this.hasDeviceInUse(e))&&(s.length===0||s.some(a=>{const o=a.label==="",c=e?a.kind===e:!0;return o&&c}))){const a={video:e!=="audioinput"&&e!=="audiooutput",audio:e!=="videoinput"},o=yield navigator.mediaDevices.getUserMedia(a);s=yield navigator.mediaDevices.enumerateDevices(),o.getTracks().forEach(c=>{c.stop()})}return e&&(s=s.filter(r=>r.kind===e)),s})}normalizeDeviceId(e,t,i){return f(this,void 0,void 0,function*(){if(t!==Pr)return t;const s=yield this.getDevices(e),r=new Map(s.map(o=>[o.groupId,0]));s.forEach(o=>{var c;return r.set(o.groupId,((c=r.get(o.groupId))!==null&&c!==void 0?c:0)+1)});const a=s.find(o=>{var c;return(i===o.groupId||((c=r.get(o.groupId))!==null&&c!==void 0?c:0)>1)&&o.deviceId!==Pr});return a==null?void 0:a.deviceId})}hasDeviceInUse(e){return e?ye.userMediaPromiseMap.has(e):ye.userMediaPromiseMap.size>0}}ye.mediaDeviceKinds=["audioinput","audiooutput","videoinput"];ye.userMediaPromiseMap=new Map;const rp=1e3;class Tn extends T{get constraints(){return this._constraints}constructor(e,t,i){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,r=arguments.length>4?arguments[4]:void 0;super(e,t,r),this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=Os(()=>f(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>f(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(_.Ended,this)},this.reacquireTrack=!1,this.providedByUser=s,this.muteLock=new xe,this.pauseUpstreamLock=new xe,this.processorLock=new xe,this.restartLock=new xe,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==T.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return(t=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&t!==void 0?t:this._mediaStreamTrack}setMediaStreamTrack(e,t){return f(this,void 0,void 0,function*(){if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(s=>{Ft(this._mediaStreamTrack,s)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let i;if(this.processor&&e){const s=yield this.processorLock.lock();try{if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Nt(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),i=this.processor.processedTrack}finally{s()}}this.sender&&(yield this.sender.replaceTrack(i??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(s=>{Nt(i??e,s)}))})}waitForDimensions(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:rp;var t;return f(this,void 0,void 0,function*(){if(this.kind===T.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((t=st())===null||t===void 0?void 0:t.os)==="iOS"&&(yield tt(10));const i=Date.now();for(;Date.now()-i<e;){const s=this.dimensions;if(s)return s;yield tt(50)}throw new qe("unable to get track dimensions after timeout")})}getDeviceId(){return f(this,void 0,void 0,function*(){if(this.source===T.Source.ScreenShare)return;const{deviceId:e,groupId:t}=this._mediaStreamTrack.getSettings(),i=this.kind===T.Kind.Audio?"audioinput":"videoinput";return ye.getInstance().normalizeDeviceId(i,e,t)})}mute(){return f(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return f(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return f(this,void 0,void 0,function*(){if(!this.sender)throw new qe("unable to replace an unpublished track");let i,s;return typeof t=="boolean"?i=t:t!==void 0&&(i=t.userProvidedTrack,s=t.stopProcessor),this.providedByUser=i??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),s&&this.processor&&(yield this.stopProcessor()),this})}restart(e){return f(this,void 0,void 0,function*(){const t=yield this.restartLock.lock();try{e||(e=this._constraints),this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const i={audio:!1,video:!1};this.kind===T.Kind.Video?i.video=e:i.audio=e,this.attachedElements.forEach(a=>{Ft(this.mediaStreamTrack,a)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const r=(yield navigator.mediaDevices.getUserMedia(i)).getTracks()[0];return r.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(r),this._constraints=e,this.emit(_.Restarted,this),this}finally{t()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?_.Muted:_.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return f(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Wo()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(e=this.processor)===null||e===void 0||e.destroy(),this.processor=void 0}pauseUpstream(){return f(this,void 0,void 0,function*(){const e=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(_.UpstreamPaused,this);const t=st();if((t==null?void 0:t.name)==="Safari"&&gi(t.version,"12.0")<0)throw new Is("pauseUpstream is not supported on Safari < 12.");yield this.sender.replaceTrack(null)}finally{e()}})}resumeUpstream(){return f(this,void 0,void 0,function*(){const e=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(_.UpstreamResumed,this),yield this.sender.replaceTrack(this._mediaStreamTrack)}finally{e()}})}getRTCStatsReport(){var e;return f(this,void 0,void 0,function*(){return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;var i,s;return f(this,void 0,void 0,function*(){const r=yield this.processorLock.lock();try{this.log.debug("setting up processor",this.logContext),this.processorElement=(i=this.processorElement)!==null&&i!==void 0?i:document.createElement(this.kind);const a={kind:this.kind,track:this._mediaStreamTrack,element:this.processorElement,audioContext:this.audioContext};if(yield e.init(a),this.processor&&(yield this.stopProcessor()),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(Nt(this._mediaStreamTrack,this.processorElement),this.processorElement.muted=!0,this.processorElement.play().catch(o=>this.log.error("failed to play processor element",Object.assign(Object.assign({},this.logContext),{error:o}))),this.processor=e,this.processor.processedTrack){for(const o of this.attachedElements)o!==this.processorElement&&t&&(Ft(this._mediaStreamTrack,o),Nt(this.processor.processedTrack,o));yield(s=this.sender)===null||s===void 0?void 0:s.replaceTrack(this.processor.processedTrack)}this.emit(_.TrackProcessorUpdate,this.processor)}finally{r()}})}getProcessor(){return this.processor}stopProcessor(){var e,t;return f(this,void 0,void 0,function*(){this.processor&&(this.log.debug("stopping processor",this.logContext),(e=this.processor.processedTrack)===null||e===void 0||e.stop(),yield this.processor.destroy(),this.processor=void 0,(t=this.processorElement)===null||t===void 0||t.remove(),this.processorElement=void 0,yield this._mediaStreamTrack.applyConstraints(this._constraints),yield this.setMediaStreamTrack(this._mediaStreamTrack,!0),this.emit(_.TrackProcessorUpdate))})}}class ap extends Ge.EventEmitter{constructor(e){super(),this.onWorkerMessage=t=>{var i,s;const{kind:r,data:a}=t.data;switch(r){case"error":$.error(a.error.message),this.emit(lt.EncryptionError,a.error);break;case"initAck":a.enabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)});break;case"enable":if(this.encryptionEnabled!==a.enabled&&a.participantIdentity===((i=this.room)===null||i===void 0?void 0:i.localParticipant.identity))this.emit(lt.ParticipantEncryptionStatusChanged,a.enabled,this.room.localParticipant),this.encryptionEnabled=a.enabled;else if(a.participantIdentity){const o=(s=this.room)===null||s===void 0?void 0:s.getParticipantByIdentity(a.participantIdentity);if(!o)throw TypeError("couldn't set encryption status, participant not found".concat(a.participantIdentity));this.emit(lt.ParticipantEncryptionStatusChanged,a.enabled,o)}this.encryptionEnabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)});break;case"ratchetKey":this.keyProvider.emit(pt.KeyRatcheted,a.material,a.keyIndex);break}},this.onWorkerError=t=>{$.error("e2ee worker encountered an error:",{error:t.error}),this.emit(lt.EncryptionError,t.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!Oh())throw new Is("tried to setup end-to-end encryption on an unsupported browser");if($.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:lh.getLevel()}};this.worker&&($.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){$.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?$.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(I.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(E.TrackPublished,(i,s)=>this.setParticipantCryptorEnabled(i.trackInfo.encryption!==Oe.NONE,s.identity)),e.on(E.ConnectionStateChanged,i=>{i===J.Connected&&e.remoteParticipants.forEach(s=>{s.trackPublications.forEach(r=>{this.setParticipantCryptorEnabled(r.trackInfo.encryption!==Oe.NONE,s.identity)})})}).on(E.TrackUnsubscribed,(i,s,r)=>{var a;const o={kind:"removeTransform",data:{participantIdentity:r.identity,trackId:i.mediaStreamID}};(a=this.worker)===null||a===void 0||a.postMessage(o)}).on(E.TrackSubscribed,(i,s,r)=>{this.setupE2EEReceiver(i,r.identity,s.trackInfo)}).on(E.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity),t.getKeys().forEach(i=>{this.postKey(i)})}),e.localParticipant.on(M.LocalTrackPublished,i=>f(this,void 0,void 0,function*(){this.setupE2EESender(i.track,i.track.sender)})),t.on(pt.SetKey,i=>this.postKey(i)).on(pt.RatchetRequest,(i,s)=>this.postRatchetRequest(i,s))}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(i)}postKey(e){let{key:t,participantIdentity:i,keyIndex:s}=e;var r;if(!this.worker)throw Error("could not set key, worker is missing");const a={kind:"setKey",data:{participantIdentity:i,isPublisher:i===((r=this.room)===null||r===void 0?void 0:r.localParticipant.identity),key:t,keyIndex:s}};this.worker.postMessage(a)}postEnable(e,t){if(this.worker){const i={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(i)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((t=this.room)===null||t===void 0)&&t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,i){if(e.receiver){if(!(i!=null&&i.mimeType)||i.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?zo(i.mimeType):void 0)}}setupE2EESender(e,t){if(!(e instanceof Tn)||!t){t||$.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,i,s){return f(this,void 0,void 0,function*(){if(this.worker){if(Zi()){const r={kind:"decode",participantIdentity:i,trackId:t,codec:s};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{if(Un in e&&s){const c={kind:"updateCodec",data:{trackId:t,codec:s,participantIdentity:i}};this.worker.postMessage(c);return}let r=e.writableStream,a=e.readableStream;if(!r||!a){const c=e.createEncodedStreams();e.writableStream=c.writable,r=c.writable,e.readableStream=c.readable,a=c.readable}const o={kind:"decode",data:{readableStream:a,writableStream:r,trackId:t,codec:s,participantIdentity:i}};this.worker.postMessage(o,[a,r])}e[Un]=!0}})}handleSender(e,t,i){var s;if(!(Un in e||!this.worker)){if(!(!((s=this.room)===null||s===void 0)&&s.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(Zi()){$.info("initialize script transform");const r={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{$.info("initialize encoded streams");const r=e.createEncodedStreams(),a={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(a,[r.readable,r.writable])}e[Un]=!0}}}var hn;(function(n){n[n.WAITING=0]="WAITING",n[n.RUNNING=1]="RUNNING",n[n.COMPLETED=2]="COMPLETED"})(hn||(hn={}));class op{constructor(){this.pendingTasks=new Map,this.taskMutex=new xe,this.nextTaskIndex=0}run(e){return f(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:hn.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=hn.RUNNING,yield e()}finally{t.status=hn.COMPLETED,this.pendingTasks.delete(t.id),i()}})}flush(){return f(this,void 0,void 0,function*(){return this.run(()=>f(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}const cp=["syncState","trickle","offer","answer","simulate","leave"];function dp(n){const e=cp.indexOf(n.case)>=0;return $.trace("request allowed to bypass queue:",{canPass:e,req:n}),e}var ie;(function(n){n[n.CONNECTING=0]="CONNECTING",n[n.CONNECTED=1]="CONNECTED",n[n.RECONNECTING=2]="RECONNECTING",n[n.DISCONNECTING=3]="DISCONNECTING",n[n.DISCONNECTED=4]="DISCONNECTED"})(ie||(ie={}));class xs{get currentState(){return this.state}get isDisconnected(){return this.state===ie.DISCONNECTING||this.state===ie.DISCONNECTED}get isEstablishingConnection(){return this.state===ie.CONNECTING||this.state===ie.RECONNECTING}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;this.rtt=0,this.state=ie.DISCONNECTED,this.log=$,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0},this.log=it((i=t.loggerName)!==null&&i!==void 0?i:Fe.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new op,this.queuedRequests=[],this.closingLock=new xe,this.connectionLock=new xe,this.state=ie.DISCONNECTED}get logContext(){var e,t;return(t=(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this))!==null&&t!==void 0?t:{}}join(e,t,i,s){return f(this,void 0,void 0,function*(){return this.state=ie.CONNECTING,this.options=i,yield this.connect(e,t,i,s)})}reconnect(e,t,i,s){return f(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);return}return this.state=ie.RECONNECTING,this.clearPingInterval(),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=sp(e),e=e.replace(/\/$/,""),e+="/rtc";const r=np(),a=lp(t,r,i);return new Promise((o,c)=>f(this,void 0,void 0,function*(){const d=yield this.connectionLock.lock();try{const l=()=>f(this,void 0,void 0,function*(){this.close(),clearTimeout(u),c(new te("room connection has been cancelled (signal)"))}),u=setTimeout(()=>{this.close(),c(new te("room connection has timed out (signal)"))},i.websocketTimeout);s!=null&&s.aborted&&l(),s==null||s.addEventListener("abort",l),this.log.debug("connecting to ".concat(e+a),this.logContext),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(e+a),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(u)},this.ws.onerror=p=>f(this,void 0,void 0,function*(){if(this.state!==ie.CONNECTED){this.state=ie.DISCONNECTED,clearTimeout(u);try{const m=yield fetch("http".concat(e.substring(2),"/validate").concat(a));if(m.status.toFixed(0).startsWith("4")){const k=yield m.text();c(new te(k,0,m.status))}else c(new te("Internal error",2,m.status))}catch{c(new te("server was not reachable",1))}return}this.handleWSError(p)}),this.ws.onmessage=p=>f(this,void 0,void 0,function*(){var m,k,v;let S;if(typeof p.data=="string"){const O=JSON.parse(p.data);S=dr.fromJson(O,{ignoreUnknownFields:!0})}else if(p.data instanceof ArrayBuffer)S=dr.fromBinary(new Uint8Array(p.data));else{this.log.error("could not decode websocket message: ".concat(typeof p.data),this.logContext);return}if(this.state!==ie.CONNECTED){let O=!1;if(((m=S.message)===null||m===void 0?void 0:m.case)==="join"?(this.state=ie.CONNECTED,s==null||s.removeEventListener("abort",l),this.pingTimeoutDuration=S.message.value.pingTimeout,this.pingIntervalDuration=S.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.startPingInterval()),o(S.message.value)):this.state===ie.RECONNECTING&&S.message.case!=="leave"?(this.state=ie.CONNECTED,s==null||s.removeEventListener("abort",l),this.startPingInterval(),((k=S.message)===null||k===void 0?void 0:k.case)==="reconnect"?o(S.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),o(void 0),O=!0)):this.isEstablishingConnection&&S.message.case==="leave"?c(new te("Received leave request while trying to (re)connect",4)):i.reconnect||c(new te("did not receive join response, got ".concat((v=S.message)===null||v===void 0?void 0:v.case," instead"))),!O)return}this.signalLatency&&(yield tt(this.signalLatency)),this.handleSignalResponse(S)}),this.ws.onclose=p=>{this.isEstablishingConnection&&c(new te("Websocket got closed during a (re)connection attempt")),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:p.reason,code:p.code,wasClean:p.wasClean,state:this.state})),this.handleOnClose(p.reason)}}finally{d()}}))}close(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return f(this,void 0,void 0,function*(){const t=yield this.closingLock.lock();try{if(e&&(this.state=ie.DISCONNECTING),this.ws){this.ws.onmessage=null,this.ws.onopen=null,this.ws.onclose=null;const i=new Promise(s=>{this.ws?this.ws.onclose=()=>{s()}:s()});this.ws.readyState<this.ws.CLOSING&&(this.ws.close(),yield Promise.race([i,tt(250)])),this.ws=void 0}}finally{e&&(this.state=ie.DISCONNECTED),this.clearPingInterval(),t()}})}sendOffer(e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:ii(e)})}sendAnswer(e){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:ii(e)})}sendIceCandidate(e,t){return this.log.trace("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new Ts({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new Cs({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return this.sendRequest({case:"updateMetadata",value:new Ha({metadata:e,name:t})})}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:"updateLayers",value:new $a({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new za({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:se.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Ka({timestamp:se.parse(Date.now()),rtt:se.parse(this.rtt)})})])}sendLeave(){return this.sendRequest({case:"leave",value:new hi({canReconnect:!1,reason:un.CLIENT_INITIATED})})}sendRequest(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return f(this,void 0,void 0,function*(){if(!t&&!dp(e)&&this.state===ie.RECONNECTING){this.queuedRequests.push(()=>f(this,void 0,void 0,function*(){yield this.sendRequest(e,!0)}));return}if(t||(yield this.requestQueue.flush()),this.signalLatency&&(yield tt(this.signalLatency)),!this.ws||this.ws.readyState!==this.ws.OPEN){this.log.error("cannot send signal request before connected, type: ".concat(e==null?void 0:e.case),this.logContext);return}const s=new Mu({message:e});try{this.useJSON?this.ws.send(s.toJsonString()):this.ws.send(s.toBinary())}catch(r){this.log.error("error sending signal message",Object.assign(Object.assign({},this.logContext),{error:r}))}})}handleSignalResponse(e){var t,i;const s=e.message;if(s==null){this.log.debug("received unsupported message",this.logContext);return}let r=!1;if(s.case==="answer"){const a=Rr(s.value);this.onAnswer&&this.onAnswer(a)}else if(s.case==="offer"){const a=Rr(s.value);this.onOffer&&this.onOffer(a)}else if(s.case==="trickle"){const a=JSON.parse(s.value.candidateInit);this.onTrickle&&this.onTrickle(a,s.value.target)}else s.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((t=s.value.participants)!==null&&t!==void 0?t:[]):s.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(s.value):s.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((i=s.value.speakers)!==null&&i!==void 0?i:[]):s.case==="leave"?this.onLeave&&this.onLeave(s.value):s.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(s.value.sid,s.value.muted):s.case==="roomUpdate"?this.onRoomUpdate&&s.value.room&&this.onRoomUpdate(s.value.room):s.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(s.value):s.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(s.value):s.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(s.value):s.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(s.value):s.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(s.value):s.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(s.value):s.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(s.value):s.case==="pong"||(s.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(s.value.lastPingTimestamp.toString()),this.resetPingTimeout(),r=!0):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:s.case})));r||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return f(this,void 0,void 0,function*(){if(this.state===ie.DISCONNECTED)return;const t=this.onClose;yield this.close(),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)})}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set",this.logContext);return}this.pingTimeout=ve.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&ve.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn("ping interval duration not set",this.logContext);return}this.log.debug("start ping interval",this.logContext),this.pingInterval=ve.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&ve.clearInterval(this.pingInterval)}}function Rr(n){const e={type:"offer",sdp:n.sdp};switch(n.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=n.type;break}return e}function ii(n){return new _t({sdp:n.sdp,type:n.type})}function lp(n,e,t){var i;const s=new URLSearchParams;return s.set("access_token",n),t.reconnect&&(s.set("reconnect","1"),t.sid&&s.set("sid",t.sid)),s.set("auto_subscribe",t.autoSubscribe?"1":"0"),s.set("sdk",yt()?"reactnative":"js"),s.set("version",e.version),s.set("protocol",e.protocol.toString()),e.deviceModel&&s.set("device_model",e.deviceModel),e.os&&s.set("os",e.os),e.osVersion&&s.set("os_version",e.osVersion),e.browser&&s.set("browser",e.browser),e.browserVersion&&s.set("browser_version",e.browserVersion),t.adaptiveStream&&s.set("adaptive_stream","1"),t.reconnectReason&&s.set("reconnect_reason",t.reconnectReason.toString()),!((i=navigator.connection)===null||i===void 0)&&i.type&&s.set("network",navigator.connection.type),"?".concat(s.toString())}var Yo={},Xo={exports:{}},Ir=Xo.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(n){return n.encoding?"rtpmap:%d %s/%s/%s":n.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(n){return n.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(n){return n.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(n){return"extmap:%d"+(n.direction?"/%s":"%v")+(n["encrypt-uri"]?" %s":"%v")+" %s"+(n.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(n){return n.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(n){var e="candidate:%s %d %s %d %s %d typ %s";return e+=n.raddr!=null?" raddr %s rport %d":"%v%v",e+=n.tcptype!=null?" tcptype %s":"%v",n.generation!=null&&(e+=" generation %d"),e+=n["network-id"]!=null?" network-id %d":"%v",e+=n["network-cost"]!=null?" network-cost %d":"%v",e}},{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(n){var e="ssrc:%d";return n.attribute!=null&&(e+=" %s",n.value!=null&&(e+=":%s")),e}},{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(n){return n.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(n){return n.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(n){return"imageattr:%s %s %s"+(n.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(n){return"simulcast:%s %s"+(n.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(n){return"ts-refclk:%s"+(n.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(n){var e="mediaclk:";return e+=n.id!=null?"id=%s %s":"%v%s",e+=n.mediaClockValue!=null?"=%s":"",e+=n.rateNumerator!=null?" rate=%s":"",e+=n.rateDenominator!=null?"/%s":"",e}},{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(Ir).forEach(function(n){var e=Ir[n];e.forEach(function(t){t.reg||(t.reg=/(.*)/),t.format||(t.format="%s")})});var Zo=Xo.exports;(function(n){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,c,d,l){if(l&&!d)c[l]=e(o[1]);else for(var u=0;u<d.length;u+=1)o[u+1]!=null&&(c[d[u]]=e(o[u+1]))},i=function(o,c,d){var l=o.name&&o.names;o.push&&!c[o.push]?c[o.push]=[]:l&&!c[o.name]&&(c[o.name]={});var u=o.push?{}:l?c[o.name]:c;t(d.match(o.reg),u,o.names,o.name),o.push&&c[o.push].push(u)},s=Zo,r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);n.parse=function(o){var c={},d=[],l=c;return o.split(/(\r\n|\r|\n)/).filter(r).forEach(function(u){var p=u[0],m=u.slice(2);p==="m"&&(d.push({rtp:[],fmtp:[]}),l=d[d.length-1]);for(var k=0;k<(s[p]||[]).length;k+=1){var v=s[p][k];if(v.reg.test(m))return i(v,l,m)}}),c.media=d,c};var a=function(o,c){var d=c.split(/=(.+)/,2);return d.length===2?o[d[0]]=e(d[1]):d.length===1&&c.length>1&&(o[d[0]]=void 0),o};n.parseParams=function(o){return o.split(/;\s?/).reduce(a,{})},n.parseFmtpConfig=n.parseParams,n.parsePayloads=function(o){return o.toString().split(" ").map(Number)},n.parseRemoteCandidates=function(o){for(var c=[],d=o.split(" ").map(e),l=0;l<d.length;l+=3)c.push({component:d[l],ip:d[l+1],port:d[l+2]});return c},n.parseImageAttributes=function(o){return o.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(a,{})})},n.parseSimulcastStreamList=function(o){return o.split(";").map(function(c){return c.split(",").map(function(d){var l,u=!1;return d[0]!=="~"?l=e(d):(l=e(d.substring(1,d.length)),u=!0),{scid:l,paused:u}})})}})(Yo);var Ii=Zo,up=/%[sdv%]/g,hp=function(n){var e=1,t=arguments,i=t.length;return n.replace(up,function(s){if(e>=i)return s;var r=t[e];switch(e+=1,s){case"%%":return"%";case"%s":return String(r);case"%d":return Number(r);case"%v":return""}})},Zt=function(n,e,t){var i=e.format instanceof Function?e.format(e.push?t:t[e.name]):e.format,s=[n+"="+i];if(e.names)for(var r=0;r<e.names.length;r+=1){var a=e.names[r];e.name?s.push(t[e.name][a]):s.push(t[e.names[r]])}else s.push(t[e.name]);return hp.apply(null,s)},pp=["v","o","s","i","u","e","p","c","b","t","r","z","a"],fp=["i","c","b","a"],mp=function(n,e){e=e||{},n.version==null&&(n.version=0),n.name==null&&(n.name=" "),n.media.forEach(function(r){r.payloads==null&&(r.payloads="")});var t=e.outerOrder||pp,i=e.innerOrder||fp,s=[];return t.forEach(function(r){Ii[r].forEach(function(a){a.name in n&&n[a.name]!=null?s.push(Zt(r,a,n)):a.push in n&&n[a.push]!=null&&n[a.push].forEach(function(o){s.push(Zt(r,a,o))})})}),n.media.forEach(function(r){s.push(Zt("m",Ii.m[0],r)),i.forEach(function(a){Ii[a].forEach(function(o){o.name in r&&r[o.name]!=null?s.push(Zt(a,o,r)):o.push in r&&r[o.push]!=null&&r[o.push].forEach(function(c){s.push(Zt(a,o,c))})})})}),s.join(`\r
|
|
53
|
-
`)+`\r
|
|
54
|
-
`},gp=Yo,vp=mp,Oi=vp,rn=gp.parse;const kp=.7,Bt={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class Or extends Ge.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;super(),this.log=$,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Os(s=>f(this,void 0,void 0,function*(){this.emit(Bt.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(s)s(r);else throw r}}),100),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=it((i=t.loggerName)!==null&&i!==void 0?i:Fe.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC()}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var i;t.candidate&&((i=this.onIceCandidate)===null||i===void 0||i.call(this,t.candidate))},e.onicecandidateerror=t=>{var i;(i=this.onIceCandidateError)===null||i===void 0||i.call(this,t)},e.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,e.connectionState)},e.ondatachannel=t=>{var i;(i=this.onDataChannel)===null||i===void 0||i.call(this,t)},e.ontrack=t=>{var i;(i=this.onTrack)===null||i===void 0||i.call(this,t)},e}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return f(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e){var t;return f(this,void 0,void 0,function*(){let i;if(e.type==="offer"){let{stereoMids:s,nackMids:r}=bp(e);this.remoteStereoMids=s,this.remoteNackMids=r}else if(e.type==="answer"){const s=rn((t=e.sdp)!==null&&t!==void 0?t:"");s.media.forEach(r=>{r.type==="audio"&&this.trackBitrates.some(a=>{if(!a.transceiver||r.mid!=a.transceiver.mid)return!1;let o=0;if(r.rtp.some(d=>d.codec.toUpperCase()===a.codec.toUpperCase()?(o=d.payload,!0):!1),o===0)return!0;let c=!1;for(const d of r.fmtp)if(d.payload===o){d.config=d.config.split(";").filter(l=>!l.includes("maxaveragebitrate")).join(";"),a.maxbr>0&&(d.config+=";maxaveragebitrate=".concat(a.maxbr*1e3)),c=!0;break}return c||a.maxbr>0&&r.fmtp.push({payload:o,config:"maxaveragebitrate=".concat(a.maxbr*1e3)}),!0})}),i=Oi(s)}yield this.setMungedSDP(e,i,!0),this.pendingCandidates.forEach(s=>{this.pc.addIceCandidate(s)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(Bt.NegotiationComplete),e.sdp&&rn(e.sdp).media.forEach(r=>{r.type==="video"&&this.emit(Bt.RTPVideoPayloadTypes,r.rtp)}))})}createAndSendOffer(e){var t;return f(this,void 0,void 0,function*(){if(this.onOffer===void 0)return;if(e!=null&&e.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const r=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&r)yield this._pc.setRemoteDescription(r);else{this.renegotiate=!0;return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const i=yield this.pc.createOffer(e),s=rn((t=i.sdp)!==null&&t!==void 0?t:"");s.media.forEach(r=>{r.type==="audio"?Mr(r,[],[]):r.type==="video"&&(yp(r),this.trackBitrates.some(a=>{if(!r.msid||!a.cid||!r.msid.includes(a.cid))return!1;let o=0;if(r.rtp.some(d=>d.codec.toUpperCase()===a.codec.toUpperCase()?(o=d.payload,!0):!1),o===0)return!0;const c=Math.round(a.maxbr*kp);for(const d of r.fmtp)if(d.payload===o){d.config.includes("x-google-start-bitrate")||(d.config+=";x-google-start-bitrate=".concat(c));break}return!0}))}),yield this.setMungedSDP(i,Oi(s)),this.onOffer(i)})}createAndSetAnswer(){var e;return f(this,void 0,void 0,function*(){const t=yield this.pc.createAnswer(),i=rn((e=t.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(s=>{s.type==="audio"&&Mr(s,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Oi(i)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new ue("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new ue("PC closed, cannot configure");return(t=this._pc)===null||t===void 0?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var t;return(t=this._pc)===null||t===void 0?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&t!==void 0?t:"closed"}getICEConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&t!==void 0?t:"closed"}getSignallingState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&t!==void 0?t:"closed"}getTransceivers(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[]}getSenders(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&t!==void 0?t:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){var e;return f(this,void 0,void 0,function*(){if(!this._pc)return;let t="";const i=new Map,s=new Map;if((yield this._pc.getStats()).forEach(o=>{switch(o.type){case"transport":t=o.selectedCandidatePairId;break;case"candidate-pair":t===""&&o.selected&&(t=o.id),i.set(o.id,o);break;case"remote-candidate":s.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const a=(e=i.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(a!==void 0)return s.get(a)})}setMungedSDP(e,t,i){return f(this,void 0,void 0,function*(){if(t){const s=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(r){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:r,sdp:t})),e.sdp=s}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(s){let r="unknown error";s instanceof Error?r=s.message:typeof s=="string"&&(r=s);const a={error:r,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(a.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:a})),new es(r)}})}}function Mr(n,e,t){let i=0;n.rtp.some(s=>s.codec==="opus"?(i=s.payload,!0):!1),i>0&&(n.rtcpFb||(n.rtcpFb=[]),t.includes(n.mid)&&!n.rtcpFb.some(s=>s.payload===i&&s.type==="nack")&&n.rtcpFb.push({payload:i,type:"nack"}),e.includes(n.mid)&&n.fmtp.some(s=>s.payload===i?(s.config.includes("stereo=1")||(s.config+=";stereo=1"),!0):!1))}function yp(n){var e,t,i,s;const r=(t=(e=n.rtp[0])===null||e===void 0?void 0:e.codec)===null||t===void 0?void 0:t.toLowerCase();if(!ni(r))return;let a=0;((i=n.ext)===null||i===void 0?void 0:i.some(c=>c.uri===Tr?!0:(c.value>a&&(a=c.value),!1)))||(s=n.ext)===null||s===void 0||s.push({value:a+1,uri:Tr})}function bp(n){var e;const t=[],i=[],s=rn((e=n.sdp)!==null&&e!==void 0?e:"");let r=0;return s.media.forEach(a=>{var o;a.type==="audio"&&(a.rtp.some(c=>c.codec==="opus"?(r=c.payload,!0):!1),!((o=a.rtcpFb)===null||o===void 0)&&o.some(c=>c.payload===r&&c.type==="nack")&&i.push(a.mid),a.fmtp.some(c=>c.payload===r?(c.config.includes("sprop-stereo=1")&&t.push(a.mid),!0):!1))}),{stereoMids:t,nackMids:i}}const cs="vp8",Tp={audioPreset:ts.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Ms.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:cs,backupCodec:!0},ec={autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0},tc={resolution:bn.h720.resolution},Cp={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new hh,disconnectOnPageLeave:!0,webAudioMix:!0},As={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var ae;(function(n){n[n.NEW=0]="NEW",n[n.CONNECTING=1]="CONNECTING",n[n.CONNECTED=2]="CONNECTED",n[n.FAILED=3]="FAILED",n[n.CLOSING=4]="CLOSING",n[n.CLOSED=5]="CLOSED"})(ae||(ae={}));class Sp{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,i){var s;this.peerConnectionTimeout=As.peerConnectionTimeout,this.log=$,this.updateState=()=>{var r;const a=this.state,o=this.requiredTransports.map(c=>c.getConnectionState());o.every(c=>c==="connected")?this.state=ae.CONNECTED:o.some(c=>c==="failed")?this.state=ae.FAILED:o.some(c=>c==="connecting")?this.state=ae.CONNECTING:o.every(c=>c==="closed")?this.state=ae.CLOSED:o.some(c=>c==="closed")?this.state=ae.CLOSING:o.every(c=>c==="new")&&(this.state=ae.NEW),a!==this.state&&(this.log.debug("pc state change: from ".concat(ae[a]," to ").concat(ae[this.state]),this.logContext),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=it((s=i.loggerName)!==null&&s!==void 0?s:Fe.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new Or(e,i),this.subscriber=new Or(e,i),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=r=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,r,Ue.PUBLISHER)},this.subscriber.onIceCandidate=r=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,r,Ue.SUBSCRIBER)},this.subscriber.onDataChannel=r=>{var a;(a=this.onDataChannel)===null||a===void 0||a.call(this,r)},this.subscriber.onTrack=r=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,r)},this.publisher.onOffer=r=>{var a;(a=this.onPublisherOffer)===null||a===void 0||a.call(this,r)},this.state=ae.NEW,this.connectionLock=new xe}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}requireSubscriber(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e){return this.publisher.setRemoteDescription(e)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return f(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const e=this.publisher;for(const t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(i){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:i}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return f(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return f(this,void 0,void 0,function*(){t===Ue.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e){return f(this,void 0,void 0,function*(){return this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber.getSignallingState().toString()})),yield this.subscriber.setRemoteDescription(e),yield this.subscriber.createAndSetAnswer()})}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){var i;return f(this,void 0,void 0,function*(){const s=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((i=this.requiredTransports)===null||i===void 0?void 0:i.map(r=>this.ensureTransportConnected(r,e,t)))}finally{s()}})}negotiate(e){return f(this,void 0,void 0,function*(){return new Promise((t,i)=>f(this,void 0,void 0,function*(){const s=setTimeout(()=>{i("negotiation timed out")},this.peerConnectionTimeout),r=()=>{clearTimeout(s),i("negotiation aborted")};e.signal.addEventListener("abort",r),this.publisher.once(Bt.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Bt.NegotiationComplete,()=>{clearTimeout(s),t()})}),yield this.publisher.negotiate(a=>{clearTimeout(s),i(a)})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===Ue.PUBLISHER?this.publisher.getConnectedAddress():e===Ue.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return f(this,void 0,void 0,function*(){if(e.getConnectionState()!=="connected")return new Promise((r,a)=>f(this,void 0,void 0,function*(){const o=()=>{this.log.warn("abort transport connection",this.logContext),ve.clearTimeout(c),a(new te("room connection has been cancelled",3))};t!=null&&t.signal.aborted&&o(),t==null||t.signal.addEventListener("abort",o);const c=ve.setTimeout(()=>{t==null||t.signal.removeEventListener("abort",o),a(new te("could not establish pc connection"))},i);for(;this.state!==ae.CONNECTED;)if(yield tt(50),t!=null&&t.signal.aborted){a(new te("room connection has been cancelled",3));return}ve.clearTimeout(c),t==null||t.signal.removeEventListener("abort",o),r()}))})}}const xr="_lossy",Ar="_reliable",_p=2*1e3,Dr="leave-reconnect";var Ae;(function(n){n[n.New=0]="New",n[n.Connected=1]="Connected",n[n.Disconnected=2]="Disconnected",n[n.Reconnecting=3]="Reconnecting",n[n.Closed=4]="Closed"})(Ae||(Ae={}));class Ep extends Ge.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=As.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=Ae.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=$,this.handleDataChannel=i=>{let{channel:s}=i;return f(this,void 0,void 0,function*(){if(s){if(s.label===Ar)this.reliableDCSub=s;else if(s.label===xr)this.lossyDCSub=s;else return;this.log.debug("on data channel ".concat(s.id,", ").concat(s.label),this.logContext),s.onmessage=this.handleDataMessage}})},this.handleDataMessage=i=>f(this,void 0,void 0,function*(){var s,r;const a=yield this.dataProcessLock.lock();try{let o;if(i.data instanceof ArrayBuffer)o=i.data;else if(i.data instanceof Blob)o=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:i.data}));return}const c=Ia.fromBinary(new Uint8Array(o));((s=c.value)===null||s===void 0?void 0:s.case)==="speaker"?this.emit(I.ActiveSpeakersUpdate,c.value.value.speakers):((r=c.value)===null||r===void 0?void 0:r.case)==="user"&&this.emit(I.DataPacketReceived,c.value.value,c.kind)}finally{a()}}),this.handleDataError=i=>{const r=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(i instanceof ErrorEvent&&i.error){const{error:a}=i.error;this.log.error("DataChannel error on ".concat(r,": ").concat(i.message),Object.assign(Object.assign({},this.logContext),{error:a}))}else this.log.error("Unknown DataChannel error on ".concat(r),Object.assign(Object.assign({},this.logContext),{event:i}))},this.handleBufferedAmountLow=i=>{const r=i.currentTarget.maxRetransmits===0?ke.LOSSY:ke.RELIABLE;this.updateAndEmitDCBufferStatus(r)},this.handleDisconnect=(i,s)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const r=c=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(c,"ms. giving up"),this.logContext),this.emit(I.Disconnected),this.close()},a=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:a,retryCount:this.reconnectAttempts});if(o===null){r(a);return}i===Dr&&(o=0),this.log.debug("reconnecting in ".concat(o,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=ve.setTimeout(()=>this.attemptReconnect(s).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((i,s)=>{this.pcState===Ae.Connected&&i();const r=()=>{this.off(I.Disconnected,a),i()},a=()=>{this.off(I.Restarted,r),s()};this.once(I.Restarted,r),this.once(I.Disconnected,a)}),this.updateAndEmitDCBufferStatus=i=>{const s=this.isBufferStatusLow(i);typeof s<"u"&&s!==this.dcBufferStatus.get(i)&&(this.dcBufferStatus.set(i,s),this.emit(I.DCBufferStatusChanged,s,i))},this.isBufferStatusLow=i=>{const s=this.dataChannelForKind(i);if(s)return s.bufferedAmount<=s.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===ie.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(Mt.RR_SIGNAL_DISCONNECTED))},this.log=it((t=e.loggerName)!==null&&t!==void 0?t:Fe.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new xs(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new xe,this.dataProcessLock=new xe,this.dcBufferStatus=new Map([[ke.LOSSY,!0],[ke.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(I.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(I.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(I.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(I.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(I.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(I.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(I.StreamStateChanged,i)}get logContext(){var e,t,i,s,r,a,o,c;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(s=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.room)===null||s===void 0?void 0:s.sid,participant:(a=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.participant)===null||a===void 0?void 0:a.identity,pID:(c=(o=this.latestJoinResponse)===null||o===void 0?void 0:o.participant)===null||c===void 0?void 0:c.sid}}join(e,t,i,s){return f(this,void 0,void 0,function*(){this.url=e,this.token=t,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const r=yield this.client.join(e,t,i,s);return this._isClosed=!1,this.latestJoinResponse=r,this.subscriberPrimary=r.subscriberPrimary,this.pcManager||(yield this.configure(r)),this.subscriberPrimary||this.negotiate(),this.clientConfiguration=r.clientConfiguration,r}catch(r){if(r instanceof te&&r.reason===1&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,i,s);throw r}})}close(){return f(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.emit(I.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){var e;return f(this,void 0,void 0,function*(){yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0;const t=i=>{i&&(i.close(),i.onbufferedamountlow=null,i.onclose=null,i.onclosing=null,i.onerror=null,i.onmessage=null,i.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0})}cleanupClient(){return f(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new qe("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 te("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:r=>{clearTimeout(s),t(r)},reject:()=>{clearTimeout(s),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){var e;return f(this,void 0,void 0,function*(){return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){var t;return f(this,void 0,void 0,function*(){if(this.pcManager&&this.pcManager.currentState!==ae.NEW)return;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid;const i=this.makeRTCConfiguration(e);this.pcManager=new Sp(i,e.subscriberPrimary,this.loggerOptions),this.emit(I.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(s,r)=>{this.client.sendIceCandidate(s,r)},this.pcManager.onPublisherOffer=s=>{this.client.sendOffer(s)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(s,r,a)=>f(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(s),this.logContext),s===ae.CONNECTED){const d=this.pcState===Ae.New;this.pcState=Ae.Connected,d&&this.emit(I.Connected,e)}else s===ae.FAILED&&this.pcState===Ae.Connected&&(this.pcState=Ae.Disconnected,this.handleDisconnect("peerconnection failed",a==="failed"?Mt.RR_SUBSCRIBER_FAILED:Mt.RR_PUBLISHER_FAILED));const o=this.client.isDisconnected||this.client.currentState===ie.RECONNECTING,c=[ae.FAILED,ae.CLOSING,ae.CLOSED].includes(s);o&&c&&!this._isClosed&&this.emit(I.Offline)}),this.pcManager.onTrack=s=>{this.emit(I.MediaTrackAdded,s.track,s.streams[0],s.receiver)},this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=e=>f(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.trace("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=e=>f(this,void 0,void 0,function*(){if(!this.pcManager)return;const t=yield this.pcManager.createSubscriberAnswerFromOffer(e);this.client.sendAnswer(t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(t=e.track)===null||t===void 0?void 0:t.sid})),!this.pendingTrackResolvers[e.cid]){this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}const{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(I.LocalTrackUnpublished,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(I.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(I.SubscribedQualityUpdate,e)},this.client.onClose=()=>{this.handleDisconnect("signal",Mt.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{e!=null&&e.canReconnect?(this.fullReconnectOnNext=!0,this.handleDisconnect(Dr)):(this.emit(I.Disconnected,e==null?void 0:e.reason),this.close()),this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e==null?void 0:e.reason}))}}makeRTCConfiguration(e){var t;const i=Object.assign({},this.rtcConfig);if(!((t=this.signalOpts)===null||t===void 0)&&t.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const s=[];e.iceServers.forEach(r=>{const a={urls:r.urls};r.username&&(a.username=r.username),r.credential&&(a.credential=r.credential),s.push(a)}),i.iceServers=s}return e.clientConfiguration&&e.clientConfiguration.forceRelay===yn.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(xr,{ordered:!0,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Ar,{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 RTCRtpReceiver))return;const s=RTCRtpReceiver.getCapabilities(t);if(!s)return;this.log.debug("get receiver capabilities",Object.assign(Object.assign({},this.logContext),{cap:s}));const r=[],a=[],o=[];s.codecs.forEach(c=>{const d=c.mimeType.toLowerCase();if(d==="audio/opus"){r.push(c);return}if(!(d==="video/".concat(i))){o.push(c);return}if(i==="h264"){c.sdpFmtpLine&&c.sdpFmtpLine.includes("profile-level-id=42e01f")?r.push(c):a.push(c);return}r.push(c)}),Yh(e)&&e.setCodecPreferences(r.concat(a,o))}createSender(e,t,i){return f(this,void 0,void 0,function*(){if(ss())return yield this.createTransceiverRTCRtpSender(e,t,i);if(rs())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new ue("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,i,s){return f(this,void 0,void 0,function*(){if(ss())return this.createSimulcastTransceiverSender(e,t,i,s);if(rs())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new ue("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,i){return f(this,void 0,void 0,function*(){if(!this.pcManager)throw new ue("publisher is closed");const s=[];e.mediaStream&&s.push(e.mediaStream);const r={direction:"sendonly",streams:s};i&&(r.sendEncodings=i);const a=yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r);return e.kind===T.Kind.Video&&t.videoCodec&&(this.setPreferredCodec(a,e.kind,t.videoCodec),e.codec=t.videoCodec),a.sender})}createSimulcastTransceiverSender(e,t,i,s){return f(this,void 0,void 0,function*(){if(!this.pcManager)throw new ue("publisher is closed");const r={direction:"sendonly"};s&&(r.sendEncodings=s);const a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(i.videoCodec)return this.setPreferredCodec(a,e.kind,i.videoCodec),e.setSimulcastTrackSender(i.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return f(this,void 0,void 0,function*(){if(!this.pcManager)throw new ue("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){var t,i,s;return f(this,void 0,void 0,function*(){if(!this._isClosed){if(this.attemptingReconnect){$.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===yn.DISABLED||((s=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&s!==void 0?s:ae.NEW)===ae.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(r){this.reconnectAttempts+=1;let a=!0;r instanceof ue?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:r})),a=!1):r instanceof xt||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",Mt.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(I.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(e){var t,i,s;return f(this,void 0,void 0,function*(){try{if(!this.url||!this.token)throw new ue("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(I.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let r;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new xt;r=yield this.join(e??this.url,this.token,this.signalOpts)}catch(a){throw a instanceof te&&a.reason===0?new ue("could not reconnect, token might be expired"):new xt}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(I.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==ie.CONNECTED)throw new xt("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(I.Restarted)}catch(r){const a=yield(i=this.regionUrlProvider)===null||i===void 0?void 0:i.getNextBestRegionUrl();if(a){yield this.restartConnection(a);return}else throw(s=this.regionUrlProvider)===null||s===void 0||s.resetAttempts(),r}})}resumeConnection(e){var t;return f(this,void 0,void 0,function*(){if(!this.url||!this.token)throw new ue("could not reconnect, url or token not saved");if(!this.pcManager)throw new ue("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(I.Resuming);let i;try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(s){let r="";throw s instanceof Error&&(r=s.message,this.log.error(s.message,Object.assign(Object.assign({},this.logContext),{error:s}))),s instanceof te&&s.reason===0?new ue("could not reconnect, token might be expired"):s instanceof te&&s.reason===4?s:new xt(r)}if(this.emit(I.SignalResumed),i){const s=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(s)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==ie.CONNECTED)throw new xt("Signal connection got severed during reconnect");this.client.setReconnected(),((t=this.reliableDC)===null||t===void 0?void 0:t.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),this.emit(I.Resumed)})}waitForPCInitialConnection(e,t){return f(this,void 0,void 0,function*(){if(!this.pcManager)throw new ue("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return f(this,void 0,void 0,function*(){this.pcState=Ae.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield tt(_p),!this.pcManager)throw new ue("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Ae.Connected}catch(e){throw this.pcState=Ae.Disconnected,new te("could not establish PC connection, ".concat(e.message))}})}sendDataPacket(e,t){return f(this,void 0,void 0,function*(){const i=e.toBinary();yield this.ensurePublisherConnected(t);const s=this.dataChannelForKind(t);s&&s.send(i),this.updateAndEmitDCBufferStatus(t)})}ensureDataTransportConnected(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;var i;return f(this,void 0,void 0,function*(){if(!this.pcManager)throw new ue("PC manager is closed");const s=t?this.pcManager.subscriber:this.pcManager.publisher,r=t?"Subscriber":"Publisher";if(!s)throw new te("".concat(r," connection not set"));!t&&!this.pcManager.publisher.isICEConnected&&this.pcManager.publisher.getICEConnectionState()!=="checking"&&this.negotiate();const a=this.dataChannelForKind(e,t);if((a==null?void 0:a.readyState)==="open")return;const o=new Date().getTime()+this.peerConnectionTimeout;for(;new Date().getTime()<o;){if(s.isICEConnected&&((i=this.dataChannelForKind(e,t))===null||i===void 0?void 0:i.readyState)==="open")return;yield tt(50)}throw new te("could not establish ".concat(r," connection, state: ").concat(s.getICEConnectionState()))})}ensurePublisherConnected(e){return f(this,void 0,void 0,function*(){yield this.ensureDataTransportConnected(e,!1)})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==ae.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return f(this,void 0,void 0,function*(){return new Promise((e,t)=>f(this,void 0,void 0,function*(){if(!this.pcManager){t(new es("PC manager is closed"));return}this.pcManager.requirePublisher();const i=new AbortController,s=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(I.Closing,s),this.pcManager.publisher.once(Bt.RTPVideoPayloadTypes,r=>{const a=new Map;r.forEach(o=>{const c=o.codec.toLowerCase();ip(c)&&a.set(o.payload,c)}),this.emit(I.RTPVideoMapUpdate,a)});try{yield this.pcManager.negotiate(i),e()}catch(r){r instanceof es&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Mt.RR_UNKNOWN),t(r)}finally{this.off(I.Closing,s)}}))})}dataChannelForKind(e,t){if(t){if(e===ke.LOSSY)return this.lossyDCSub;if(e===ke.RELIABLE)return this.reliableDCSub}else{if(e===ke.LOSSY)return this.lossyDC;if(e===ke.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,s;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const r=this.pcManager.subscriber.getLocalDescription(),a=this.pcManager.subscriber.getRemoteDescription(),o=(s=(i=this.signalOpts)===null||i===void 0?void 0:i.autoSubscribe)!==null&&s!==void 0?s:!0,c=new Array,d=new Array;e.forEach(l=>{l.isDesired!==o&&c.push(l.trackSid),l.isEnabled||d.push(l.trackSid)}),this.client.sendSyncState(new Wa({answer:r?ii({sdp:r.sdp,type:r.type}):void 0,offer:a?ii({sdp:a.sdp,type:a.type}):void 0,subscription:new ui({trackSids:c,subscribe:!o,participantTracks:[]}),publishTracks:Gh(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:d}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(i,s)=>{(i==null?void 0:i.id)!==void 0&&i.id!==null&&e.push(new Ja({label:i.label,id:i.id,target:s}))};return t(this.dataChannelForKind(ke.LOSSY),Ue.PUBLISHER),t(this.dataChannelForKind(ke.RELIABLE),Ue.PUBLISHER),t(this.dataChannelForKind(ke.LOSSY,!0),Ue.SUBSCRIBER),t(this.dataChannelForKind(ke.RELIABLE,!0),Ue.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&ve.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){_e()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){_e()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class xt extends Error{}class Nr{constructor(e,t){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return os(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return f(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(i=>!this.attemptedRegions.find(s=>s.url===i.url));if(t.length>0){const i=t[0];return this.attemptedRegions.push(i),$.debug("next region: ".concat(i.region)),i.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return f(this,void 0,void 0,function*(){const t=yield fetch("".concat(wp(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(t.ok){const i=yield t.json();return this.lastUpdateAt=Date.now(),i}else throw new te("Could not fetch region settings: ".concat(t.statusText),t.status===401?0:void 0,t.status)})}}function wp(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}const Ds=2e3;function vi(n,e){if(!e)return 0;let t,i;return"bytesReceived"in n?(t=n.bytesReceived,i=e.bytesReceived):"bytesSent"in n&&(t=n.bytesSent,i=e.bytesSent),t===void 0||i===void 0||n.timestamp===void 0||e.timestamp===void 0?0:(t-i)*8*1e3/(n.timestamp-e.timestamp)}class Pe extends Tn{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(e,T.Kind.Audio,t,i,r),this.stopOnMute=!1,this.monitorSender=()=>f(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let a;try{a=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}a&&this.prevStats&&(this._currentBitrate=vi(a,this.prevStats)),this.prevStats=a}),this.audioContext=s,this.checkForSilence()}setDeviceId(e){return f(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===ft(e)?!0:(this._constraints.deviceId=e,this.isMuted||(yield this.restartTrack()),this.isMuted||ft(e)===this._mediaStreamTrack.getSettings().deviceId)})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return f(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===T.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return f(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const i=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==ft(this._constraints.deviceId);return this.source===T.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||i)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return f(this,void 0,void 0,function*(){let t;if(e){const i=mi({audio:e});typeof i.audio!="boolean"&&(t=i.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return f(this,void 0,void 0,function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){_e()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},Ds)))}setProcessor(e){var t;return f(this,void 0,void 0,function*(){const i=yield this.processorLock.lock();try{if(!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());const s={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(s),this.processor=e,this.processor.processedTrack&&(yield(t=this.sender)===null||t===void 0?void 0:t.replaceTrack(this.processor.processedTrack)),this.emit(_.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){var e;return f(this,void 0,void 0,function*(){if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let i;return t.forEach(s=>{s.type==="outbound-rtp"&&(i={type:"audio",streamId:s.id,packetsSent:s.packetsSent,packetsLost:s.packetsLost,bytesSent:s.bytesSent,timestamp:s.timestamp,roundTripTime:s.roundTripTime,jitter:s.jitter})}),i})}checkForSilence(){return f(this,void 0,void 0,function*(){const e=yield $h(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(_.AudioSilenceDetected)),e})}}function nc(n,e,t){switch(n.kind){case"audio":return new Pe(n,e,!1,void 0,t);case"video":return new Ie(n,e,!1,t);default:throw new qe("unsupported track type: ".concat(n.kind))}}const Pp=Object.values(bn),Rp=Object.values(ns),Ip=Object.values(Ms),Op=[bn.h180,bn.h360],Mp=[ns.h180,ns.h360],xp=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var i,s;return new K(Math.floor(n.width/t.scaleResolutionDownBy),Math.floor(n.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(n.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((i=n.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((s=t.fps)!==null&&s!==void 0?s:30))))),t.fps,n.encoding.priority)}),ds=["q","h","f"];function ls(n,e,t,i){var s,r;let a=i==null?void 0:i.videoEncoding;n&&(a=i==null?void 0:i.screenShareEncoding);const o=i==null?void 0:i.simulcast,c=i==null?void 0:i.scalabilityMode,d=i==null?void 0:i.videoCodec;if(!a&&!o&&!c||!e||!t)return[{}];a||(a=Dp(n,e,t,d),$.debug("using video encoding",a));const l=new K(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(c&&ni(d)){const m=new ic(c),k=[];if(m.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const v=st();if(kt()||(v==null?void 0:v.name)==="Chrome"&&gi(v==null?void 0:v.version,"113")<0){for(let S=0;S<m.spatial;S+=1)k.push({rid:ds[2-S],maxBitrate:a.maxBitrate/Math.pow(3,S),maxFramerate:l.encoding.maxFramerate});k[0].scalabilityMode=c}else k.push({maxBitrate:a.maxBitrate,maxFramerate:l.encoding.maxFramerate,scalabilityMode:c});return $.debug("using svc encoding",{encodings:k}),k}if(!o)return[a];let u=[];n?u=(s=Ur(i==null?void 0:i.screenShareSimulcastLayers))!==null&&s!==void 0?s:Lr(n,l):u=(r=Ur(i==null?void 0:i.videoSimulcastLayers))!==null&&r!==void 0?r:Lr(n,l);let p;if(u.length>0){const m=u[0];u.length>1&&([,p]=u);const k=Math.max(e,t);if(k>=960&&p)return Mi(e,t,[m,p,l]);if(k>=480)return Mi(e,t,[m,l])}return Mi(e,t,[l])}function Ap(n,e,t){var i,s,r,a;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&$.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const o=n.mediaStreamTrack.getSettings(),c=(i=o.width)!==null&&i!==void 0?i:(s=n.dimensions)===null||s===void 0?void 0:s.width,d=(r=o.height)!==null&&r!==void 0?r:(a=n.dimensions)===null||a===void 0?void 0:a.height;return ls(n.source===T.Source.ScreenShare,c,d,t)}function Dp(n,e,t,i){const s=Np(n,e,t);let{encoding:r}=s[0];const a=Math.max(e,t);for(let o=0;o<s.length;o+=1){const c=s[o];if(r=c.encoding,c.width>=a)break}if(i)switch(i){case"av1":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.7;break;case"vp9":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.85;break}return r}function Np(n,e,t){if(n)return Ip;const i=e>t?e/t:t/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?Pp:Rp}function Lr(n,e){if(n)return xp(e);const{width:t,height:i}=e,s=t>i?t/i:i/t;return Math.abs(s-16/9)<Math.abs(s-4/3)?Op:Mp}function Mi(n,e,t){const i=[];if(t.forEach((s,r)=>{if(r>=ds.length)return;const a=Math.min(n,e),c={rid:ds[r],scaleResolutionDownBy:Math.max(1,a/Math.min(s.width,s.height)),maxBitrate:s.encoding.maxBitrate};s.encoding.maxFramerate&&(c.maxFramerate=s.encoding.maxFramerate);const d=$t()||r===0;s.encoding.priority&&d&&(c.priority=s.encoding.priority,c.networkPriority=s.encoding.priority),i.push(c)}),yt()&&Ko()==="ios"){let s;i.forEach(a=>{s?a.maxFramerate&&a.maxFramerate>s&&(s=a.maxFramerate):s=a.maxFramerate});let r=!0;i.forEach(a=>{var o;a.maxFramerate!=s&&(r&&(r=!1,$.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),$.info('Setting framerate of encoding "'.concat((o=a.rid)!==null&&o!==void 0?o:"",'" to ').concat(s)),a.maxFramerate=s)})}return i}function Ur(n){if(n)return n.sort((e,t)=>{const{encoding:i}=e,{encoding:s}=t;return i.maxBitrate>s.maxBitrate?1:i.maxBitrate<s.maxBitrate?-1:i.maxBitrate===s.maxBitrate&&i.maxFramerate&&s.maxFramerate?i.maxFramerate>s.maxFramerate?1:-1:0})}class ic{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}const Lp=5e3;class Ie extends Tn{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0;super(e,T.Kind.Video,t,i,s),this.simulcastCodecs=new Map,this.monitorSender=()=>f(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}const a=new Map(r.map(o=>[o.rid,o]));if(this.prevStats){let o=0;a.forEach((c,d)=>{var l;const u=(l=this.prevStats)===null||l===void 0?void 0:l.get(d);o+=vi(c,u)}),this._currentBitrate=o}this.prevStats=a}),this.senderLock=new xe}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!_e())return;const i=(t=this.sender)===null||t===void 0?void 0:t.getParameters();i&&(this.encodings=i.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},Ds))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});var t,i,s,r,a;return f(this,void 0,void 0,function*(){yield e.pauseUpstream.call(this);try{for(var o=!0,c=Dt(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;o=!0)r=d.value,o=!1,yield(a=r.sender)===null||a===void 0?void 0:a.replaceTrack(null)}catch(l){i={error:l}}finally{try{!o&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});var t,i,s,r,a;return f(this,void 0,void 0,function*(){yield e.resumeUpstream.call(this);try{for(var o=!0,c=Dt(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;o=!0){r=d.value,o=!1;const l=r;yield(a=l.sender)===null||a===void 0?void 0:a.replaceTrack(l.mediaStreamTrack)}}catch(l){i={error:l}}finally{try{!o&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(i)throw i.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return f(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===T.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return f(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===T.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){var e;return f(this,void 0,void 0,function*(){if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach(s=>{var r;if(s.type==="outbound-rtp"){const a={type:"video",streamId:s.id,frameHeight:s.frameHeight,frameWidth:s.frameWidth,framesPerSecond:s.framesPerSecond,framesSent:s.framesSent,firCount:s.firCount,pliCount:s.pliCount,nackCount:s.nackCount,packetsSent:s.packetsSent,bytesSent:s.bytesSent,qualityLimitationReason:s.qualityLimitationReason,qualityLimitationDurations:s.qualityLimitationDurations,qualityLimitationResolutionChanges:s.qualityLimitationResolutionChanges,rid:(r=s.rid)!==null&&r!==void 0?r:s.id,retransmittedPacketsSent:s.retransmittedPacketsSent,targetBitrate:s.targetBitrate,timestamp:s.timestamp},o=i.get(s.remoteId);o&&(a.jitter=o.jitter,a.packetsLost=o.packetsLost,a.roundTripTime=o.roundTripTime),t.push(a)}}),t.sort((s,r)=>{var a,o;return((a=r.frameWidth)!==null&&a!==void 0?a:0)-((o=s.frameWidth)!==null&&o!==void 0?o:0)}),t})}setPublishingQuality(e){const t=[];for(let i=Me.LOW;i<=Me.HIGH;i+=1)t.push(new _s({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(t)}setDeviceId(e){return f(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===ft(e)?!0:(this._constraints.deviceId=e,this.isMuted||(yield this.restartTrack()),this.isMuted||ft(e)===this._mediaStreamTrack.getSettings().deviceId)})}restartTrack(e){var t,i,s,r;return f(this,void 0,void 0,function*(){let a;if(e){const l=mi({video:e});typeof l.video!="boolean"&&(a=l.video)}yield this.restart(a);try{for(var o=!0,c=Dt(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;o=!0){r=d.value,o=!1;const l=r;l.sender&&(l.mediaStreamTrack=this.mediaStreamTrack.clone(),yield l.sender.replaceTrack(l.mediaStreamTrack))}}catch(l){i={error:l}}finally{try{!o&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(i)throw i.error}}})}setProcessor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;const i=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});var s,r,a,o,c,d;return f(this,void 0,void 0,function*(){if(yield i.setProcessor.call(this,e,t),!((c=this.processor)===null||c===void 0)&&c.processedTrack)try{for(var l=!0,u=Dt(this.simulcastCodecs.values()),p;p=yield u.next(),s=p.done,!s;l=!0)o=p.value,l=!1,yield(d=o.sender)===null||d===void 0?void 0:d.replaceTrack(this.processor.processedTrack)}catch(m){r={error:m}}finally{try{!l&&!s&&(a=u.return)&&(yield a.call(u))}finally{if(r)throw r.error}}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},Lp))}setPublishingCodecs(e){var t,i,s,r,a,o,c;return f(this,void 0,void 0,function*(){if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(e[0].qualities),[];this.subscribedCodecs=e;const d=[];try{for(t=!0,i=Dt(e);s=yield i.next(),r=s.done,!r;t=!0){c=s.value,t=!1;const l=c;if(!this.codec||this.codec===l.codec)yield this.setPublishingLayers(l.qualities);else{const u=this.simulcastCodecs.get(l.codec);if(this.log.debug("try setPublishingCodec for ".concat(l.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:u})),!u||!u.sender){for(const p of l.qualities)if(p.enabled){d.push(l.codec);break}}else u.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(l.codec),this.logContext),yield jr(u.sender,u.encodings,l.qualities,this.senderLock,this.log,this.logContext))}}}catch(l){a={error:l}}finally{try{!t&&!r&&(o=i.return)&&(yield o.call(i))}finally{if(a)throw a.error}}return d})}setPublishingLayers(e){return f(this,void 0,void 0,function*(){this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:e})),!(!this.sender||!this.encodings)&&(yield jr(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return f(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Wo()&&this.isInBackground&&this.source===T.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function jr(n,e,t,i,s,r){return f(this,void 0,void 0,function*(){const a=yield i.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},r),{sender:n,qualities:t,senderEncodings:e}));try{const o=n.getParameters(),{encodings:c}=o;if(!c)return;if(c.length!==e.length){s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},r),{encodings:c,senderEncodings:e}));return}let d=!1;!1&&c[0].scalabilityMode||c.forEach((u,p)=>{var m;let k=(m=u.rid)!==null&&m!==void 0?m:"";k===""&&(k="q");const v=sc(k),S=t.find(O=>O.quality===v);S&&u.active!==S.enabled&&(d=!0,u.active=S.enabled,s.debug("setting layer ".concat(S.quality," to ").concat(u.active?"enabled":"disabled"),r),$t()&&(S.enabled?(u.scaleResolutionDownBy=e[p].scaleResolutionDownBy,u.maxBitrate=e[p].maxBitrate,u.maxFrameRate=e[p].maxFrameRate):(u.scaleResolutionDownBy=4,u.maxBitrate=10,u.maxFrameRate=2)))}),d&&(o.encodings=c,s.debug("setting encodings",Object.assign(Object.assign({},r),{encodings:o.encodings})),yield n.setParameters(o))}finally{a()}})}function sc(n){switch(n){case"f":return Me.HIGH;case"h":return Me.MEDIUM;case"q":return Me.LOW;default:return Me.HIGH}}function Fr(n,e,t,i){if(!t)return[new ht({quality:Me.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(i){const s=t[0].scalabilityMode,r=new ic(s),a=[];for(let o=0;o<r.spatial;o+=1)a.push(new ht({quality:Me.HIGH-o,width:Math.ceil(n/Math.pow(2,o)),height:Math.ceil(e/Math.pow(2,o)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(3,o)):0,ssrc:0}));return a}return t.map(s=>{var r,a,o;const c=(r=s.scaleResolutionDownBy)!==null&&r!==void 0?r:1;let d=sc((a=s.rid)!==null&&a!==void 0?a:"");return new ht({quality:d,width:Math.ceil(n/c),height:Math.ceil(e/c),bitrate:(o=s.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}class rc extends T{constructor(e,t,i,s,r){super(e,i,r),this.sid=t,this.receiver=s}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?_.Muted:_.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver=void 0,this._currentBitrate=0,this.emit(_.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){var e;return f(this,void 0,void 0,function*(){return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),Ds))}}class pn extends rc{constructor(e,t,i,s,r,a){super(e,t,T.Kind.Audio,i,a),this.monitorReceiver=()=>f(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=vi(o,this.prevStats)),this.prevStats=o}),this.audioContext=s,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):i.volume=e;yt()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(yt())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return f(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(as(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&as(e)&&e.setSinkId(this.sinkId),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(s=>{i.connect(s),i=s}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(_.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(s=>{this.emit(_.AudioPlaybackFailed,s)})}disconnectWebAudio(){var e,t;(e=this.gainNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return f(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(i=>{i.type==="inbound-rtp"&&(t={type:"audio",timestamp:i.timestamp,jitter:i.jitter,bytesReceived:i.bytesReceived,concealedSamples:i.concealedSamples,concealmentEvents:i.concealmentEvents,silentConcealedSamples:i.silentConcealedSamples,silentConcealmentEvents:i.silentConcealmentEvents,totalAudioEnergy:i.totalAudioEnergy,totalSamplesDuration:i.totalSamplesDuration})}),t})}}const xi=100;class fn extends rc{constructor(e,t,i,s,r){super(e,t,T.Kind.Video,i,r),this.elementInfos=[],this.monitorReceiver=()=>f(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=vi(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=Os(()=>{this.updateDimensions()},xi),this.adaptiveStreamSettings=s}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?Ft(this._mediaStreamTrack,t):Nt(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){const t=new Up(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const t=this.elementInfos.filter(i=>i===e);for(const i of t)i.stopObserving();this.elementInfos=this.elementInfos.filter(i=>i!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const i of t)this.stopObservingElement(i);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return f(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",s=new Map;return e.forEach(r=>{r.type==="inbound-rtp"?(i=r.codecId,t={type:"video",framesDecoded:r.framesDecoded,framesDropped:r.framesDropped,framesReceived:r.framesReceived,packetsReceived:r.packetsReceived,packetsLost:r.packetsLost,frameWidth:r.frameWidth,frameHeight:r.frameHeight,pliCount:r.pliCount,firCount:r.firCount,nackCount:r.nackCount,jitter:r.jitter,timestamp:r.timestamp,bytesReceived:r.bytesReceived,decoderImplementation:r.decoderImplementation}):r.type==="codec"&&s.set(r.id,r)}),t&&i!==""&&s.get(i)&&(t.mimeType=s.get(i).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(i=>i.element===e);for(const i of t)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return f(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(){var e,t;const i=this.elementInfos.reduce((o,c)=>Math.max(o,c.visibilityChangedAt||0),0),s=!((t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pauseVideoInBackground)!==null&&t!==void 0)||t?this.isInBackground:!1,r=this.elementInfos.some(o=>o.pictureInPicture),a=this.elementInfos.some(o=>o.visible)&&!s||r;if(this.lastVisible!==a){if(!a&&Date.now()-i<xi){ve.setTimeout(()=>{this.updateVisibility()},xi);return}this.lastVisible=a,this.emit(_.VisibilityChanged,a,this)}}updateDimensions(){var e,t;let i=0,s=0;const r=this.getPixelDensity();for(const a of this.elementInfos){const o=a.width()*r,c=a.height()*r;o+c>i+s&&(i=o,s=c)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===i&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===s||(this.lastDimensions={width:i,height:s},this.emit(_.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?Cr():t||(Cr()>2?2:1)}}class Up{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=i=>{var s;const{target:r,isIntersecting:a}=i;r===this.element&&(this.isIntersecting=a,this.visibilityChangedAt=Date.now(),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this))},this.onEnterPiP=()=>{var i;this.isPiP=!0,(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=!1,(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=t??Br(e),this.isPiP=_e()&&document.pictureInPictureElement===e,this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){this.isIntersecting=Br(this.element),this.isPiP=document.pictureInPictureElement===this.element,this.element.handleResize=()=>{var e;(e=this.handleResize)===null||e===void 0||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,_r().observe(this.element),Sr().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP)}stopObserving(){var e,t;(e=_r())===null||e===void 0||e.unobserve(this.element),(t=Sr())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP)}}function Br(n){let e=n.offsetTop,t=n.offsetLeft;const i=n.offsetWidth,s=n.offsetHeight,{hidden:r}=n,{opacity:a,display:o}=getComputedStyle(n);for(;n.offsetParent;)n=n.offsetParent,e+=n.offsetTop,t+=n.offsetLeft;return e<window.pageYOffset+window.innerHeight&&t<window.pageXOffset+window.innerWidth&&e+s>window.pageYOffset&&t+i>window.pageXOffset&&!r&&(a!==""?parseFloat(a)>0:!0)&&o!=="none"}class Ye extends Ge.EventEmitter{constructor(e,t,i,s){var r;super(),this.metadataMuted=!1,this.encryption=Oe.NONE,this.log=$,this.handleMuted=()=>{this.emit(_.Muted)},this.handleUnmuted=()=>{this.emit(_.Unmuted)},this.log=it((r=s==null?void 0:s.loggerName)!==null&&r!==void 0?r:Fe.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=T.Source.Unknown}setTrack(e){this.track&&(this.track.off(_.Muted,this.handleMuted),this.track.off(_.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(_.Muted,this.handleMuted),e.on(_.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),Z(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==Oe.NONE}get audioTrack(){if(this.track instanceof Pe||this.track instanceof pn)return this.track}get videoTrack(){if(this.track instanceof Ie||this.track instanceof fn)return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=T.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===T.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(n){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(n.SubscriptionStatus||(n.SubscriptionStatus={})),function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"}(n.PermissionStatus||(n.PermissionStatus={}))})(Ye||(Ye={}));class si extends Ye{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,i,s){super(e,t.sid,t.name,s),this.track=void 0,this.handleTrackEnded=()=>{this.emit(_.Ended)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&this.track.off(_.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(_.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 f(this,void 0,void 0,function*(){return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){var e;return f(this,void 0,void 0,function*(){return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){var e;return f(this,void 0,void 0,function*(){yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){var e;return f(this,void 0,void 0,function*(){yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}}var dt;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(dt||(dt={}));function jp(n){switch(n){case sn.EXCELLENT:return dt.Excellent;case sn.GOOD:return dt.Good;case sn.POOR:return dt.Poor;case sn.LOST:return dt.Lost;default:return dt.Unknown}}class ac extends Ge.EventEmitter{get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e,t;return(t=(e=this.permissions)===null||e===void 0?void 0:e.agent)!==null&&t!==void 0?t:!1}constructor(e,t,i,s,r){var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=dt.Unknown,this.log=$,this.log=it((a=r==null?void 0:r.loggerName)!==null&&a!==void 0?a:Fe.Participant),this.loggerOptions=r,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=s,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(T.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(T.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(T.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,this.log.trace("update participant info",Object.assign(Object.assign({},this.logContext),{info:e})),!0)}_setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(M.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(M.ParticipantNameChanged,e)}setPermissions(e){var t,i,s,r,a;const o=this.permissions,c=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((i=this.permissions)===null||i===void 0?void 0:i.canSubscribe)||e.canPublishData!==((s=this.permissions)===null||s===void 0?void 0:s.canPublishData)||e.hidden!==((r=this.permissions)===null||r===void 0?void 0:r.hidden)||e.recorder!==((a=this.permissions)===null||a===void 0?void 0:a.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((d,l)=>{var u;return d!==((u=this.permissions)===null||u===void 0?void 0:u.canPublishSources[l])});return this.permissions=e,c&&this.emit(M.ParticipantPermissionsChanged,o),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(M.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=jp(e),t!==this._connectionQuality&&this.emit(M.ConnectionQualityChanged,this._connectionQuality)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>(t.track instanceof pn||t.track instanceof Pe)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(_.Muted,()=>{this.emit(M.TrackMuted,e)}),e.on(_.Unmuted,()=>{this.emit(M.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case T.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case T.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function Fp(n){var e,t,i;if(!n.participantSid&&!n.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Ga({participantIdentity:(e=n.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=n.participantSid)!==null&&t!==void 0?t:"",allTracks:(i=n.allowAll)!==null&&i!==void 0?i:!1,trackSids:n.allowedTrackSids||[]})}class Vr extends ac{constructor(e,t,i,s){super(e,t,void 0,void 0,{loggerName:s.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=Oe.NONE,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Qo)},this.handleReconnected=()=>{var r,a;(a=(r=this.reconnectFuture)===null||r===void 0?void 0:r.resolve)===null||a===void 0||a.call(r),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var r,a;this.reconnectFuture&&(this.reconnectFuture.promise.catch(o=>this.log.warn(o.message,this.logContext)),(a=(r=this.reconnectFuture)===null||r===void 0?void 0:r.reject)===null||a===void 0||a.call(r,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(r=>Fp(r)))},this.onTrackUnmuted=r=>{this.onTrackMuted(r,r.isUpstreamPaused)},this.onTrackMuted=(r,a)=>{if(a===void 0&&(a=!0),!r.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),Z(r)));return}this.engine.updateMuteStatus(r.sid,a)},this.onTrackUpstreamPaused=r=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),Z(r))),this.onTrackMuted(r,!0)},this.onTrackUpstreamResumed=r=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),Z(r))),this.onTrackMuted(r,r.isMuted)},this.handleSubscribedQualityUpdate=r=>f(this,void 0,void 0,function*(){var a,o,c,d,l,u;if(!(!((l=this.roomOptions)===null||l===void 0)&&l.dynacast))return;const p=this.videoTrackPublications.get(r.trackSid);if(!p){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:r.trackSid}));return}if(r.subscribedCodecs.length>0){if(!p.videoTrack)return;const S=yield p.videoTrack.setPublishingCodecs(r.subscribedCodecs);try{for(var m=!0,k=Dt(S),v;v=yield k.next(),a=v.done,!a;m=!0){d=v.value,m=!1;const O=d;Fh(O)&&(this.log.debug("publish ".concat(O," for ").concat(p.videoTrack.sid),Object.assign(Object.assign({},this.logContext),Z(p))),yield this.publishAdditionalCodecForTrack(p.videoTrack,O,p.options))}}catch(O){o={error:O}}finally{try{!m&&!a&&(c=k.return)&&(yield c.call(k))}finally{if(o)throw o.error}}}else r.subscribedQualities.length>0&&(yield(u=p.videoTrack)===null||u===void 0?void 0:u.setPublishingLayers(r.subscribedQualities))}),this.handleLocalTrackUnpublished=r=>{const a=this.trackPublications.get(r.trackSid);if(!a){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:r.trackSid}));return}this.unpublishTrack(a.track)},this.handleTrackEnded=r=>f(this,void 0,void 0,function*(){if(r.source===T.Source.ScreenShare||r.source===T.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),Z(r))),this.unpublishTrack(r);else if(r.isUserProvided)yield r.mute();else if(r instanceof Pe||r instanceof Ie)try{if(_e())try{const a=yield navigator==null?void 0:navigator.permissions.query({name:r.source===T.Source.Camera?"camera":"microphone"});if(a&&a.state==="denied")throw this.log.warn("user has revoked access to ".concat(r.source),Object.assign(Object.assign({},this.logContext),Z(r))),a.onchange=()=>{a.state!=="denied"&&(r.isMuted||r.restartTrack(),a.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}r.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),Z(r))),yield r.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),Z(r))),yield r.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=s,this.setupEngine(i),this.activeDeviceMap=new Map}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Oe.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){this.engine=e,this.engine.on(I.RemoteMute,(t,i)=>{const s=this.trackPublications.get(t);!s||!s.track||(i?s.mute():s.unmute())}),this.engine.on(I.Connected,this.handleReconnected).on(I.SignalRestarted,this.handleReconnected).on(I.SignalResumed,this.handleReconnected).on(I.Restarting,this.handleReconnecting).on(I.Resuming,this.handleReconnecting).on(I.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(I.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(I.Disconnected,this.handleDisconnected)}setMetadata(e){var t;this.engine.client.sendUpdateLocalMetadata(e,(t=this.name)!==null&&t!==void 0?t:"")}setName(e){var t;this.engine.client.sendUpdateLocalMetadata((t=this.metadata)!==null&&t!==void 0?t:"",e)}setCameraEnabled(e,t,i){return this.setTrackEnabled(T.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(T.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(T.Source.ScreenShare,e,t,i)}setPermissions(e){const t=this.permissions,i=super.setPermissions(e);return i&&t&&this.emit(M.ParticipantPermissionsChanged,t),i}setE2EEEnabled(e){return f(this,void 0,void 0,function*(){this.encryptionType=e?Oe.GCM:Oe.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,i,s){var r,a;return f(this,void 0,void 0,function*(){this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t}));let o=this.getTrackPublication(e);if(t)if(o)yield o.unmute();else{let c;if(this.pendingPublishing.has(e)){this.log.info("skipping duplicate published source",Object.assign(Object.assign({},this.logContext),{source:e}));return}this.pendingPublishing.add(e);try{switch(e){case T.Source.Camera:c=yield this.createTracks({video:(r=i)!==null&&r!==void 0?r:!0});break;case T.Source.Microphone:c=yield this.createTracks({audio:(a=i)!==null&&a!==void 0?a:!0});break;case T.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},i));break;default:throw new qe(e)}const d=[];for(const u of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),Z(u))),d.push(this.publishTrack(u,s));[o]=yield Promise.all(d)}catch(d){throw c==null||c.forEach(l=>{l.stop()}),d instanceof Error&&!(d instanceof qe)&&this.emit(M.MediaDevicesError,d),d}finally{this.pendingPublishing.delete(e)}}else if(o&&o.track)if(e===T.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const c=this.getTrackPublication(T.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return f(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(T.Source.Camera)||this.pendingPublishing.has(T.Source.Microphone))){this.pendingPublishing.add(T.Source.Camera),this.pendingPublishing.add(T.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(t=>this.publishTrack(t)))}finally{this.pendingPublishing.delete(T.Source.Camera),this.pendingPublishing.delete(T.Source.Microphone)}}})}createTracks(e){var t,i;return f(this,void 0,void 0,function*(){const s=qo(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(i=this.roomOptions)===null||i===void 0?void 0:i.videoCaptureDefaults),r=mi(s);let a;try{a=yield navigator.mediaDevices.getUserMedia(r)}catch(o){throw o instanceof Error&&(r.audio&&(this.microphoneError=o),r.video&&(this.cameraError=o)),o}return r.audio&&(this.microphoneError=void 0,this.emit(M.AudioStreamAcquired)),r.video&&(this.cameraError=void 0),a.getTracks().map(o=>{const c=o.kind==="audio";c?e.audio:e.video;let d;const l=c?r.audio:r.video;typeof l!="boolean"&&(d=l);const u=nc(o,d,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return u.kind===T.Kind.Video?u.source=T.Source.Camera:u.kind===T.Kind.Audio&&(u.source=T.Source.Microphone),u.mediaStream=a,u})})}createScreenTracks(e){return f(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Is("getDisplayMedia not supported");e.resolution===void 0&&!Zh()&&(e.resolution=Ms.h1080fps30.resolution);const t=qh(e),i=yield navigator.mediaDevices.getDisplayMedia(t),s=i.getVideoTracks();if(s.length===0)throw new qe("no video track found");const r=new Ie(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=T.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const a=[r];if(i.getAudioTracks().length>0){this.emit(M.AudioStreamAcquired);const o=new Pe(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=T.Source.ScreenShareAudio,a.push(o)}return a})}publishTrack(e,t){var i,s,r,a;return f(this,void 0,void 0,function*(){e instanceof Pe&&e.setAudioContext(this.audioContext),yield(i=this.reconnectFuture)===null||i===void 0?void 0:i.promise,e instanceof Tn&&this.pendingPublishPromises.has(e)&&(yield this.pendingPublishPromises.get(e));let o;if(e instanceof MediaStreamTrack)o=e.getConstraints();else{o=e.constraints;let m;switch(e.source){case T.Source.Microphone:m="audioinput";break;case T.Source.Camera:m="videoinput"}m&&this.activeDeviceMap.has(m)&&(o=Object.assign(Object.assign({},o),{deviceId:this.activeDeviceMap.get(m)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new Pe(e,o,!0,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});break;case"video":e=new Ie(e,o,!0,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});break;default:throw new qe("unsupported MediaStreamTrack kind ".concat(e.kind))}else e.updateLoggerOptions({loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});let c;if(this.trackPublications.forEach(m=>{m.track&&m.track===e&&(c=m)}),c)return this.log.warn("track has already been published, skipping",Object.assign(Object.assign({},this.logContext),Z(c))),c;const d="channelCount"in e.mediaStreamTrack.getSettings()&&e.mediaStreamTrack.getSettings().channelCount===2||e.mediaStreamTrack.getConstraints().channelCount===2,l=(s=t==null?void 0:t.forceStereo)!==null&&s!==void 0?s:d;l&&(t||(t={}),t.dtx===void 0&&this.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},this.logContext),Z(e))),t.red===void 0&&this.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(r=t.dtx)!==null&&r!==void 0||(t.dtx=!1),(a=t.red)!==null&&a!==void 0||(t.red=!1));const u=Object.assign(Object.assign({},this.roomOptions.publishDefaults),t);kt()&&this.roomOptions.e2ee&&(this.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari",Object.assign({},this.logContext)),u.simulcast=!1),u.source&&(e.source=u.source);const p=this.publish(e,u,l);this.pendingPublishPromises.set(e,p);try{return yield p}catch(m){throw m}finally{this.pendingPublishPromises.delete(e)}})}publish(e,t,i){var s,r,a,o,c,d,l,u,p,m,k,v;return f(this,void 0,void 0,function*(){Array.from(this.trackPublications.values()).find(N=>e instanceof Tn&&N.source===e.source)&&e.source!==T.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),Z(e))),t.stopMicTrackOnMute&&e instanceof Pe&&(e.stopOnMute=!0),e.source===T.Source.ScreenShare&&$t()&&(t.simulcast=!1),t.videoCodec==="av1"&&!Jh()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!Kh()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=cs);const O=t.videoCodec;e.on(_.Muted,this.onTrackMuted),e.on(_.Unmuted,this.onTrackUnmuted),e.on(_.Ended,this.handleTrackEnded),e.on(_.UpstreamPaused,this.onTrackUpstreamPaused),e.on(_.UpstreamResumed,this.onTrackUpstreamResumed);const w=new Gi({cid:e.mediaStreamTrack.id,name:t.name,type:T.kindToProto(e.kind),muted:e.isMuted,source:T.sourceToProto(e.source),disableDtx:!(!((s=t.dtx)!==null&&s!==void 0)||s),encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(!((r=t.red)!==null&&r!==void 0)||r),stream:t==null?void 0:t.stream});let F;if(e.kind===T.Kind.Video){let N={width:0,height:0};try{N=yield e.waitForDimensions()}catch{const A=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:bn.h720.resolution;N={width:A.width,height:A.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),Z(e)),{dims:N}))}w.width=N.width,w.height=N.height,e instanceof Ie&&(ni(O)&&(e.source===T.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),Z(e))))),t.scalabilityMode=(c=t.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),w.simulcastCodecs=[new qi({codec:O,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:cs}),t.backupCodec&&O!==t.backupCodec.codec&&w.encryption===Oe.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),w.simulcastCodecs.push(new qi({codec:t.backupCodec.codec,cid:""})))),F=ls(e.source===T.Source.ScreenShare,w.width,w.height,t),w.layers=Fr(w.width,w.height,F,ni(t.videoCodec))}else e.kind===T.Kind.Audio&&(F=[{maxBitrate:(d=t.audioPreset)===null||d===void 0?void 0:d.maxBitrate,priority:(u=(l=t.audioPreset)===null||l===void 0?void 0:l.priority)!==null&&u!==void 0?u:"high",networkPriority:(m=(p=t.audioPreset)===null||p===void 0?void 0:p.priority)!==null&&m!==void 0?m:"high"}]);if(!this.engine||this.engine.isClosed)throw new ue("cannot publish track when not connected");const W=yield this.engine.addTrack(w);let he;if(W.codecs.forEach(N=>{he===void 0&&(he=N.mimeType)}),he&&e.kind===T.Kind.Video){const N=zo(he);N!==O&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),Z(e)),{codec:N})),t.videoCodec=N,F=ls(e.source===T.Source.ScreenShare,w.width,w.height,t))}const de=new si(e.kind,W,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(de.options=t,e.sid=W.sid,!this.engine.pcManager)throw new ue("pcManager is not ready");if(this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:F,trackInfo:W})),e.sender=yield this.engine.createSender(e,t,F),F)if($t()&&e.kind===T.Kind.Audio){let N;for(const X of this.engine.pcManager.publisher.getTransceivers())if(X.sender===e.sender){N=X;break}N&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:N,codec:"opus",maxbr:!((k=F[0])===null||k===void 0)&&k.maxBitrate?F[0].maxBitrate/1e3:0})}else e.codec&&e.codec=="av1"&&(!((v=F[0])===null||v===void 0)&&v.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:w.cid,codec:e.codec,maxbr:F[0].maxBitrate/1e3});if(e.kind===T.Kind.Video&&e.source===T.Source.ScreenShare)try{this.log.debug("setting degradationPreference to maintain-resolution");const N=e.sender.getParameters();N.degradationPreference="maintain-resolution",yield e.sender.setParameters(N)}catch(N){this.log.warn("failed to set degradationPreference: ".concat(N))}return yield this.engine.negotiate(),e instanceof Ie?e.startMonitor(this.engine.client):e instanceof Pe&&e.startMonitor(),this.addTrackPublication(de),this.emit(M.LocalTrackPublished,de),de})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){var s;return f(this,void 0,void 0,function*(){if(this.encryptionType!==Oe.NONE)return;let r;if(this.trackPublications.forEach(u=>{u.track&&u.track===e&&(r=u)}),!r)throw new qe("track is not published");if(!(e instanceof Ie))throw new qe("track is not a video track");const a=Object.assign(Object.assign({},(s=this.roomOptions)===null||s===void 0?void 0:s.publishDefaults),i),o=Ap(e,t,a);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),Z(e)));return}const c=e.addSimulcastTrack(t,o);if(!c)return;const d=new Gi({cid:c.mediaStreamTrack.id,type:T.kindToProto(e.kind),muted:e.isMuted,source:T.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:c.mediaStreamTrack.id}]});if(d.layers=Fr(d.width,d.height,o),!this.engine||this.engine.isClosed)throw new ue("cannot publish track when not connected");const l=yield this.engine.addTrack(d);yield this.engine.createSimulcastSender(e,c,a,o),yield this.engine.negotiate(),this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:l}))})}unpublishTrack(e,t){var i,s;return f(this,void 0,void 0,function*(){const r=this.getPublicationForTrack(e),a=r?Z(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),a)),!r||!r.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),a));return}e=r.track,e.off(_.Muted,this.onTrackMuted),e.off(_.Unmuted,this.onTrackUnmuted),e.off(_.Ended,this.handleTrackEnded),e.off(_.UpstreamPaused,this.onTrackUpstreamPaused),e.off(_.UpstreamResumed,this.onTrackUpstreamResumed),t===void 0&&(t=(s=(i=this.roomOptions)===null||i===void 0?void 0:i.stopLocalTrackOnUnpublish)!==null&&s!==void 0?s:!0),t&&e.stop();let o=!1;const c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<ae.FAILED&&c)try{for(const d of this.engine.pcManager.publisher.getTransceivers())d.sender===c&&(d.direction="inactive",o=!0);if(this.engine.removeTrack(c)&&(o=!0),e instanceof Ie){for(const[,d]of e.simulcastCodecs)d.sender&&(this.engine.removeTrack(d.sender)&&(o=!0),d.sender=void 0);e.simulcastCodecs.clear()}}catch(d){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),a),{error:d}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case T.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case T.Kind.Video:this.videoTrackPublications.delete(r.trackSid);break}return this.emit(M.LocalTrackUnpublished,r),r.setTrack(void 0),o&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return f(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>i instanceof si)})}republishAllTracks(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return f(this,void 0,void 0,function*(){const i=[];this.trackPublications.forEach(s=>{s.track&&(e&&(s.options=Object.assign(Object.assign({},s.options),e)),i.push(s))}),yield Promise.all(i.map(s=>f(this,void 0,void 0,function*(){const r=s.track;yield this.unpublishTrack(r,!1),t&&!r.isMuted&&r.source!==T.Source.ScreenShare&&r.source!==T.Source.ScreenShareAudio&&(r instanceof Pe||r instanceof Ie)&&!r.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:s.trackSid})),yield r.restartTrack()),yield this.publishTrack(r,s.options)})))})}publishData(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return f(this,void 0,void 0,function*(){const i=t.reliable?ke.RELIABLE:ke.LOSSY,s=t.destinationIdentities,r=t.topic,a=new Ia({kind:i,value:{case:"user",value:new Ma({participantIdentity:this.identity,payload:e,destinationIdentities:s,topic:r})}});yield this.engine.sendDataPacket(a,i)})}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}updateInfo(e){return e.sid!==this.sid||!super.updateInfo(e)?!1:(e.tracks.forEach(t=>{var i,s;const r=this.trackPublications.get(t.sid);if(r){const a=r.isMuted||((s=(i=r.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&s!==void 0?s:!1);a!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),Z(r)),{mutedOnServer:a})),this.engine.client.sendMuteTrack(t.sid,a))}}),!0)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{const s=i.track;s&&(e instanceof MediaStreamTrack?(s instanceof Pe||s instanceof Ie)&&s.mediaStreamTrack===e&&(t=i):e===s&&(t=i))}),t}}class oc extends Ye{constructor(e,t,i,s){super(e,t.sid,t.name,s),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=Me.HIGH,this.handleEnded=r=>{this.setTrack(void 0),this.emit(_.Ended,r)},this.handleVisibilityChange=r=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(r),this.logContext),this.disabled=!r,this.emitTrackUpdate()},this.handleVideoDimensionsChange=r=>{this.log.debug("adaptivestream video dimensions ".concat(r.width,"x").concat(r.height),this.logContext),this.videoDimensions=r,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const s=new ui({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new bs({participantSid:"",trackSids:[this.trackSid]})]});this.emit(_.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?Ye.SubscriptionStatus.Unsubscribed:super.isSubscribed?Ye.SubscriptionStatus.Subscribed:Ye.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Ye.PermissionStatus.Allowed:Ye.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}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()&&(((t=this.videoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((i=this.videoDimensions)===null||i===void 0?void 0:i.height)===e.height||(this.track instanceof fn&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&this.track instanceof fn&&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(_.VideoDimensionsChanged,this.handleVideoDimensionsChange),s.off(_.VisibilityChanged,this.handleVisibilityChange),s.off(_.Ended,this.handleEnded),s.detach(),s.stopMonitor(),this.emit(_.Unsubscribed,s)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(_.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(_.VisibilityChanged,this.handleVisibilityChange),e.on(_.Ended,this.handleEnded),this.emit(_.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(_.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?_.Muted:_.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(_.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(_.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.kind===T.Kind.Video&&this.isAdaptiveStream?(this.log.warn("adaptive stream is enabled, cannot change video track settings",this.logContext),!1):this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return this.track instanceof fn&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Va({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(e.width=Math.ceil(this.videoDimensions.width),e.height=Math.ceil(this.videoDimensions.height)):this.currentVideoQuality!==void 0?e.quality=this.currentVideoQuality:e.quality=Me.HIGH,this.emit(_.UpdateSettings,e)}}class ri extends ac{static fromParticipantInfo(e,t){return new ri(e,t.sid,t.identity,t.name,t.metadata)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,s,r,a){super(t,i||"",s,r,a),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(_.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),Z(e))),this.signalClient.sendUpdateTrackSettings(t)}),e.on(_.UpdateSubscription,t=>{t.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(_.SubscriptionPermissionChanged,t=>{this.emit(M.TrackSubscriptionPermissionChanged,e,t)}),e.on(_.SubscriptionStatusChanged,t=>{this.emit(M.TrackSubscriptionStatusChanged,e,t)}),e.on(_.Subscribed,t=>{this.emit(M.TrackSubscribed,t,e)}),e.on(_.Unsubscribed,t=>{this.emit(M.TrackUnsubscribed,t,e)}),e.on(_.SubscriptionFailed,t=>{this.emit(M.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:T.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:T.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,s,r,a){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(l=>{!o&&e.kind===l.kind.toString()&&(o=l)}),!o){if(a===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(M.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,s,r,a-1)},150);return}if(e.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),Z(o))),this.emit(M.TrackSubscriptionFailed,t);return}const c=e.kind==="video";let d;return c?d=new fn(e,t,s,r):d=new pn(e,t,s,this.audioContext,this.audioOutput),d.source=o.source,d.isMuted=o.isMuted,d.setMediaStream(i),d.start(),o.setTrack(d),this.volumeMap.has(o.source)&&d instanceof pn&&d.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,i=new Map;return e.tracks.forEach(s=>{var r,a;let o=this.getTrackPublicationBySid(s.sid);if(o)o.updateInfo(s);else{const c=T.kindFromProto(s.type);if(!c)return;o=new oc(c,s,(r=this.signalClient.connectOptions)===null||r===void 0?void 0:r.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(a=this.loggerOptions)===null||a===void 0?void 0:a.loggerName}),o.updateInfo(s),i.set(s.sid,o);const d=Array.from(this.trackPublications.values()).find(l=>l.source===(o==null?void 0:o.source));d&&o.source!==T.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(o.source),Object.assign(Object.assign({},this.logContext),{oldTrack:Z(d),newTrack:Z(o)})),this.addTrackPublication(o)}t.set(s.sid,o)}),this.trackPublications.forEach(s=>{t.has(s.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),Z(s))),this.unpublishTrack(s.trackSid,!0))}),i.forEach(s=>{this.emit(M.TrackPublished,s)}),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const{track:s}=i;switch(s&&(s.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case T.Kind.Audio:this.audioTrackPublications.delete(e);break;case T.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(M.TrackUnpublished,i)}setAudioOutput(e){return f(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(i=>{var s;i.track instanceof pn&&t.push(i.track.setSinkId((s=e.deviceId)!==null&&s!==void 0?s:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}var J;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting"})(J||(J={}));const Bp=2*1e3;class cc extends Ge.EventEmitter{constructor(e){var t,i,s;super(),t=this,this.state=J.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=$,this.bufferedEvents=[],this.isResuming=!1,this.connect=(r,a,o)=>f(this,void 0,void 0,function*(){var c;if(!Xh())throw yt()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const d=yield this.disconnectLock.lock();if(this.state===J.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),d(),Promise.resolve();if(this.connectFuture)return d(),this.connectFuture.promise;this.setAndEmitConnectionState(J.Connecting),((c=this.regionUrlProvider)===null||c===void 0?void 0:c.getServerUrl().toString())!==r&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),os(new URL(r))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new Nr(r,a):this.regionUrlProvider.updateToken(a),this.regionUrlProvider.fetchRegionSettings().catch(p=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:p}))}));const l=(p,m,k)=>f(this,void 0,void 0,function*(){var v;this.abortController&&this.abortController.abort();const S=new AbortController;this.abortController=S,d==null||d();try{yield this.attemptConnection(k??r,a,o,S),this.abortController=void 0,p()}catch(O){if(this.regionUrlProvider&&O instanceof te&&O.reason!==3&&O.reason!==0){let w=null;try{w=yield this.regionUrlProvider.getNextBestRegionUrl((v=this.abortController)===null||v===void 0?void 0:v.signal)}catch(F){if(F instanceof te&&(F.status===401||F.reason===3)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),m(F);return}}w?(this.log.info("Initial connection failed with ConnectionError: ".concat(O.message,". Retrying with another region: ").concat(w),this.logContext),this.recreateEngine(),yield l(p,m,w)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),m(O))}else this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),m(O)}}),u=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Qo((p,m)=>{l(p,m,u)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(r,a,o,c,d,l)=>f(this,void 0,void 0,function*(){var u,p,m;const k=yield o.join(r,a,{autoSubscribe:c.autoSubscribe,adaptiveStream:typeof d.adaptiveStream=="object"?!0:d.adaptiveStream,maxRetries:c.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:c.websocketTimeout},l.signal);let v=k.serverInfo;if(v||(v={version:k.serverVersion,region:k.serverRegion}),this.log.debug("connected to Livekit Server ".concat(Object.entries(v).map(S=>{let[O,w]=S;return"".concat(O,": ").concat(w)}).join(", ")),{room:(u=k.room)===null||u===void 0?void 0:u.name,roomSid:(p=k.room)===null||p===void 0?void 0:p.sid,identity:(m=k.participant)===null||m===void 0?void 0:m.identity}),!k.serverVersion)throw new xh("unknown server version");return k.serverVersion==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),d.dynacast=!1),k}),this.applyJoinResponse=r=>{const a=r.participant;if(this.localParticipant.sid=a.sid,this.localParticipant.identity=a.identity,this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(r.sifTrailer)}catch(o){this.log.error(o instanceof Error?o.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:o}))}this.handleParticipantUpdates([a,...r.otherParticipants]),r.room&&this.handleRoomUpdate(r.room)},this.attemptConnection=(r,a,o,c)=>f(this,void 0,void 0,function*(){var d,l,u;this.state===J.Reconnecting||this.isResuming||!((d=this.engine)===null||d===void 0)&&d.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((l=this.regionUrlProvider)===null||l===void 0)&&l.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},As),o),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const p=yield this.connectSignal(r,a,this.engine,this.connOptions,this.options,c);this.applyJoinResponse(p),this.setupLocalParticipantEvents(),this.emit(E.SignalConnected)}catch(p){yield this.engine.close(),this.recreateEngine();const m=new te("could not establish signal connection");throw p instanceof Error&&(m.message="".concat(m.message,": ").concat(p.message)),p instanceof te&&(m.reason=p.reason,m.status=p.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:p})),m}if(c.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new te("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,c)}catch(p){throw yield this.engine.close(),this.recreateEngine(),p}_e()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),_e()&&(document.addEventListener("freeze",this.onPageLeave),(u=navigator.mediaDevices)===null||u===void 0||u.addEventListener("devicechange",this.handleDeviceChange)),this.setAndEmitConnectionState(J.Connected),this.emit(E.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){let r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return f(t,void 0,void 0,function*(){var a,o,c,d;const l=yield this.disconnectLock.lock();try{if(this.state===J.Disconnected){this.log.debug("already disconnected",this.logContext);return}this.log.info("disconnect from room",Object.assign({},this.logContext)),(this.state===J.Connecting||this.state===J.Reconnecting||this.isResuming)&&(this.log.warn("abort connection attempt",this.logContext),(a=this.abortController)===null||a===void 0||a.abort(),(c=(o=this.connectFuture)===null||o===void 0?void 0:o.reject)===null||c===void 0||c.call(o,new te("Client initiated disconnect")),this.connectFuture=void 0),!((d=this.engine)===null||d===void 0)&&d.client.isDisconnected||(yield this.engine.client.sendLeave()),this.engine&&(yield this.engine.close()),this.handleDisconnect(r,un.CLIENT_INITIATED),this.engine=void 0}finally{l()}})},this.onPageLeave=()=>f(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>f(this,void 0,void 0,function*(){const r=[],a=st();if(a&&a.os==="iOS"){const o="livekit-dummy-audio-el";let c=document.getElementById(o);if(!c){c=document.createElement("audio"),c.id=o,c.autoplay=!0,c.hidden=!0;const d=Ri();d.enabled=!0;const l=new MediaStream([d]);c.srcObject=l,document.addEventListener("visibilitychange",()=>{c&&(c.srcObject=document.hidden?null:l,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(c),this.once(E.Disconnected,()=>{c==null||c.remove(),c=null})}r.push(c)}this.remoteParticipants.forEach(o=>{o.audioTrackPublications.forEach(c=>{c.track&&c.track.attachedElements.forEach(d=>{r.push(d)})})});try{yield Promise.all([this.acquireAudioContext(),...r.map(o=>(o.muted=!1,o.play()))]),this.handleAudioPlaybackStarted()}catch(o){throw this.handleAudioPlaybackFailed(o),o}}),this.startVideo=()=>f(this,void 0,void 0,function*(){const r=[];for(const a of this.remoteParticipants.values())a.videoTrackPublications.forEach(o=>{var c;(c=o.track)===null||c===void 0||c.attachedElements.forEach(d=>{r.includes(d)||r.push(d)})});yield Promise.all(r.map(a=>a.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(a=>{a.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const r of this.remoteParticipants.values())this.handleParticipantDisconnected(r.identity,r);this.setAndEmitConnectionState(J.Reconnecting)&&this.emit(E.Reconnecting)},this.handleSignalRestarted=r=>f(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(r.serverRegion),Object.assign(Object.assign({},this.logContext),{region:r.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(r);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(a){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:a}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:r.serverRegion}))}catch{return}this.setAndEmitConnectionState(J.Connected),this.emit(E.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=r=>{r.forEach(a=>{var o;if(a.identity===this.localParticipant.identity){this.localParticipant.updateInfo(a);return}a.identity===""&&(a.identity=(o=this.sidToIdentity.get(a.sid))!==null&&o!==void 0?o:"");let c=this.remoteParticipants.get(a.identity);a.state===$i.DISCONNECTED?this.handleParticipantDisconnected(a.identity,c):c=this.getOrCreateParticipant(a.identity,a)})},this.handleActiveSpeakersUpdate=r=>{const a=[],o={};r.forEach(c=>{if(o[c.sid]=!0,c.sid===this.localParticipant.sid)this.localParticipant.audioLevel=c.level,this.localParticipant.setIsSpeaking(!0),a.push(this.localParticipant);else{const d=this.getRemoteParticipantBySid(c.sid);d&&(d.audioLevel=c.level,d.setIsSpeaking(!0),a.push(d))}}),o[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(c=>{o[c.sid]||(c.audioLevel=0,c.setIsSpeaking(!1))}),this.activeSpeakers=a,this.emitWhenConnected(E.ActiveSpeakersChanged,a)},this.handleSpeakersChanged=r=>{const a=new Map;this.activeSpeakers.forEach(c=>{a.set(c.sid,c)}),r.forEach(c=>{let d=this.getRemoteParticipantBySid(c.sid);c.sid===this.localParticipant.sid&&(d=this.localParticipant),d&&(d.audioLevel=c.level,d.setIsSpeaking(c.active),c.active?a.set(c.sid,d):a.delete(c.sid))});const o=Array.from(a.values());o.sort((c,d)=>d.audioLevel-c.audioLevel),this.activeSpeakers=o,this.emitWhenConnected(E.ActiveSpeakersChanged,o)},this.handleStreamStateUpdate=r=>{r.streamStates.forEach(a=>{const o=this.getRemoteParticipantBySid(a.participantSid);if(!o)return;const c=o.getTrackPublicationBySid(a.trackSid);!c||!c.track||(c.track.streamState=T.streamStateFromProto(a.state),o.emit(M.TrackStreamStateChanged,c,c.track.streamState),this.emitWhenConnected(E.TrackStreamStateChanged,c,c.track.streamState,o))})},this.handleSubscriptionPermissionUpdate=r=>{const a=this.getRemoteParticipantBySid(r.participantSid);if(!a)return;const o=a.getTrackPublicationBySid(r.trackSid);o&&o.setAllowed(r.allowed)},this.handleSubscriptionError=r=>{const a=Array.from(this.remoteParticipants.values()).find(c=>c.trackPublications.has(r.trackSid));if(!a)return;const o=a.getTrackPublicationBySid(r.trackSid);o&&o.setSubscriptionError(r.err)},this.handleDataPacket=(r,a)=>{const o=this.remoteParticipants.get(r.participantIdentity);this.emit(E.DataReceived,r.payload,o,a,r.topic),o==null||o.emit(M.DataReceived,r.payload,a)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(E.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=r=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:r})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(E.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(E.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(E.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>f(this,void 0,void 0,function*(){this.emit(E.MediaDevicesChanged)}),this.handleRoomUpdate=r=>{const a=this.roomInfo;this.roomInfo=r,a&&a.metadata!==r.metadata&&this.emitWhenConnected(E.RoomMetadataChanged,r.metadata),(a==null?void 0:a.activeRecording)!==r.activeRecording&&this.emitWhenConnected(E.RecordingStatusChanged,r.activeRecording)},this.handleConnectionQualityUpdate=r=>{r.updates.forEach(a=>{if(a.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(a.quality);return}const o=this.getRemoteParticipantBySid(a.participantSid);o&&o.setConnectionQuality(a.quality)})},this.onLocalParticipantMetadataChanged=r=>{this.emit(E.ParticipantMetadataChanged,r,this.localParticipant)},this.onLocalParticipantNameChanged=r=>{this.emit(E.ParticipantNameChanged,r,this.localParticipant)},this.onLocalTrackMuted=r=>{this.emit(E.TrackMuted,r,this.localParticipant)},this.onLocalTrackUnmuted=r=>{this.emit(E.TrackUnmuted,r,this.localParticipant)},this.onTrackProcessorUpdate=r=>{var a;(a=r==null?void 0:r.onPublish)===null||a===void 0||a.call(r,this)},this.onLocalTrackPublished=r=>f(this,void 0,void 0,function*(){var a,o,c,d,l;(a=r.track)===null||a===void 0||a.on(_.TrackProcessorUpdate,this.onTrackProcessorUpdate),(d=(c=(o=r.track)===null||o===void 0?void 0:o.getProcessor())===null||c===void 0?void 0:c.onPublish)===null||d===void 0||d.call(c,this),this.emit(E.LocalTrackPublished,r,this.localParticipant),r.track instanceof Pe&&(yield r.track.checkForSilence())&&this.emit(E.LocalAudioSilenceDetected,r);const u=yield(l=r.track)===null||l===void 0?void 0:l.getDeviceId(),p=Hh(r.source);p&&u&&u!==this.localParticipant.activeDeviceMap.get(p)&&(this.localParticipant.activeDeviceMap.set(p,u),this.emit(E.ActiveDeviceChanged,p,u))}),this.onLocalTrackUnpublished=r=>{var a;(a=r.track)===null||a===void 0||a.off(_.TrackProcessorUpdate,this.onTrackProcessorUpdate),this.emit(E.LocalTrackUnpublished,r,this.localParticipant)},this.onLocalConnectionQualityChanged=r=>{this.emit(E.ConnectionQualityChanged,r,this.localParticipant)},this.onMediaDevicesError=r=>{this.emit(E.MediaDevicesError,r)},this.onLocalParticipantPermissionsChanged=r=>{this.emit(E.ParticipantPermissionsChanged,r,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Cp),e),this.log=it((i=this.options.loggerName)!==null&&i!==void 0?i:Fe.Room),this.options.audioCaptureDefaults=Object.assign(Object.assign({},ec),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},tc),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Tp),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new xe,this.localParticipant=new Vr("","",this.engine,this.options),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",ft(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",ft(this.options.audioCaptureDefaults.deviceId)),!((s=this.options.audioOutput)===null||s===void 0)&&s.deviceId&&this.switchActiveDevice("audiooutput",ft(this.options.audioOutput.deviceId)).catch(r=>this.log.warn("Could not set audio output: ".concat(r.message),this.logContext)),this.options.e2ee&&this.setupE2EE()}setE2EEEnabled(e){return f(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity);else throw Error("e2ee not configured, please set e2ee settings within the room options")})}setupE2EE(){var e;this.options.e2ee&&(this.e2eeManager=new ap(this.options.e2ee),this.e2eeManager.on(lt.ParticipantEncryptionStatusChanged,(t,i)=>{i instanceof Vr&&(this.isE2EEEnabled=t),this.emit(E.ParticipantEncryptionStatusChanged,t,i)}),this.e2eeManager.on(lt.EncryptionError,t=>this.emit(E.EncryptionError,t)),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&t!==void 0?t:!1}getSid(){return f(this,void 0,void 0,function*(){return this.state===J.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,t)=>{const i=s=>{s.sid!==""&&(this.engine.off(I.RoomUpdate,i),e(s.sid))};this.engine.on(I.RoomUpdate,i),this.once(E.Disconnected,()=>{this.engine.off(I.RoomUpdate,i),t("Room disconnected before room server id was available")})})})}get name(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&t!==void 0?t:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&t!==void 0?t:0}get numPublishers(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&t!==void 0?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new Ep(this.options),this.engine.on(I.ParticipantUpdate,this.handleParticipantUpdates).on(I.RoomUpdate,this.handleRoomUpdate).on(I.SpeakersChanged,this.handleSpeakersChanged).on(I.StreamStateChanged,this.handleStreamStateUpdate).on(I.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(I.SubscriptionError,this.handleSubscriptionError).on(I.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(I.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(I.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(I.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(I.DataPacketReceived,this.handleDataPacket).on(I.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext)}).on(I.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents()}).on(I.SignalResumed,()=>{this.bufferedEvents=[],(this.state===J.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(I.Restarting,this.handleRestarting).on(I.SignalRestarted,this.handleSignalRestarted).on(I.Offline,()=>{this.setAndEmitConnectionState(J.Reconnecting)&&this.emit(E.Reconnecting)}).on(I.DCBufferStatusChanged,(e,t)=>{this.emit(E.DCBufferStatusChanged,e,t)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine))}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return ye.getInstance().getDevices(e,t)}prepareConnection(e,t){return f(this,void 0,void 0,function*(){if(this.state===J.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(os(new URL(e))&&t){this.regionUrlProvider=new Nr(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===J.Disconnected&&(this.regionUrl=i,yield fetch(wr(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(wr(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:i}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return f(this,void 0,void 0,function*(){let i=()=>{},s;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":s=new Ke({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":s=new Ke({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":s=new Ke({scenario:{case:"serverLeave",value:!0}});break;case"migration":s=new Ke({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":i=()=>f(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new Ke({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>f(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new Ke({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":s=new Ke({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>f(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new hi({reason:un.CLIENT_INITIATED,canReconnect:!0}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");s=new Ke({scenario:{case:"subscriberBandwidth",value:BigInt(t)}});break}s&&(yield this.engine.client.sendSimulateScenario(s),yield i())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;var s,r,a,o;return f(this,void 0,void 0,function*(){let c=!1,d=!0;const l=i?{exact:t}:t;if(e==="audioinput"){const u=this.options.audioCaptureDefaults.deviceId;this.options.audioCaptureDefaults.deviceId=l,c=u!==l;const p=Array.from(this.localParticipant.audioTrackPublications.values()).filter(m=>m.source===T.Source.Microphone);try{d=(yield Promise.all(p.map(m=>{var k;return(k=m.audioTrack)===null||k===void 0?void 0:k.setDeviceId(l)}))).every(m=>m===!0)}catch(m){throw this.options.audioCaptureDefaults.deviceId=u,m}}else if(e==="videoinput"){const u=this.options.videoCaptureDefaults.deviceId;this.options.videoCaptureDefaults.deviceId=l,c=u!==l;const p=Array.from(this.localParticipant.videoTrackPublications.values()).filter(m=>m.source===T.Source.Camera);try{d=(yield Promise.all(p.map(m=>{var k;return(k=m.videoTrack)===null||k===void 0?void 0:k.setDeviceId(l)}))).every(m=>m===!0)}catch(m){throw this.options.videoCaptureDefaults.deviceId=u,m}}else if(e==="audiooutput"){if(!as()&&!this.options.webAudioMix||this.options.webAudioMix&&this.audioContext&&!("setSinkId"in this.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");this.options.webAudioMix&&(t=(s=yield ye.getInstance().normalizeDeviceId("audiooutput",t))!==null&&s!==void 0?s:""),(r=(o=this.options).audioOutput)!==null&&r!==void 0||(o.audioOutput={});const u=this.options.audioOutput.deviceId;this.options.audioOutput.deviceId=t,c=u!==l;try{this.options.webAudioMix?(a=this.audioContext)===null||a===void 0||a.setSinkId(t):yield Promise.all(Array.from(this.remoteParticipants.values()).map(p=>p.setAudioOutput({deviceId:t})))}catch(p){throw this.options.audioOutput.deviceId=u,p}}return c&&d&&(this.localParticipant.activeDeviceMap.set(e,t),this.emit(E.ActiveDeviceChanged,e,t)),d})}setupLocalParticipantEvents(){this.localParticipant.on(M.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(M.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(M.TrackMuted,this.onLocalTrackMuted).on(M.TrackUnmuted,this.onLocalTrackUnmuted).on(M.LocalTrackPublished,this.onLocalTrackPublished).on(M.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(M.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(M.MediaDevicesError,this.onMediaDevicesError).on(M.AudioStreamAcquired,this.startAudio).on(M.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,i){if(this.state===J.Connecting||this.state===J.Reconnecting){const l=()=>{this.onTrackAdded(e,t,i),u()},u=()=>{this.off(E.Reconnected,l),this.off(E.Connected,l),this.off(E.Disconnected,u)};this.once(E.Reconnected,l),this.once(E.Connected,l),this.once(E.Disconnected,u);return}if(this.state===J.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}const s=Wh(t.id),r=s[0];let a=s[1],o=e.id;if(a&&a.startsWith("TR")&&(o=a),r===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const c=Array.from(this.remoteParticipants.values()).find(l=>l.sid===r);if(!c){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r),this.logContext);return}let d;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?d=this.options.adaptiveStream:d={}),c.addSubscribedMediaTrack(e,o,t,i,d)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var i;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.state!==J.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(s=>{s.trackPublications.forEach(r=>{s.unpublishTrack(r.trackSid)})}),this.localParticipant.trackPublications.forEach(s=>{var r,a;s.track&&this.localParticipant.unpublishTrack(s.track,e),e&&((r=s.track)===null||r===void 0||r.detach(),(a=s.track)===null||a===void 0||a.stop())}),this.localParticipant.off(M.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(M.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(M.TrackMuted,this.onLocalTrackMuted).off(M.TrackUnmuted,this.onLocalTrackUnmuted).off(M.LocalTrackPublished,this.onLocalTrackPublished).off(M.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(M.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(M.MediaDevicesError,this.onMediaDevicesError).off(M.AudioStreamAcquired,this.startAudio).off(M.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix=="boolean"&&(this.audioContext.close(),this.audioContext=void 0),_e()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(i=navigator.mediaDevices)===null||i===void 0||i.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(J.Disconnected),this.emit(E.Disconnected,t)}}}handleParticipantDisconnected(e,t){this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach(i=>{t.unpublishTrack(i.trackSid,!0)}),this.emit(E.ParticipantDisconnected,t))}acquireAudioContext(){var e,t;return f(this,void 0,void 0,function*(){if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=Go())!==null&&e!==void 0?e:void 0),this.audioContext&&this.audioContext.state==="suspended")try{yield this.audioContext.resume()}catch(s){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:s}))}this.options.webAudioMix&&this.remoteParticipants.forEach(s=>s.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext);const i=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(E.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let s;return t?s=ri.fromParticipantInfo(this.engine.client,t):s=new ri(this.engine.client,"",e,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&s.setAudioContext(this.audioContext),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&s.setAudioOutput(this.options.audioOutput).catch(r=>this.log.warn("Could not set audio output: ".concat(r.message),this.logContext)),s}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const s=this.remoteParticipants.get(e);return t&&s.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),s}const i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(E.ParticipantConnected,i),i.on(M.TrackPublished,s=>{this.emitWhenConnected(E.TrackPublished,s,i)}).on(M.TrackSubscribed,(s,r)=>{s.kind===T.Kind.Audio?(s.on(_.AudioPlaybackStarted,this.handleAudioPlaybackStarted),s.on(_.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):s.kind===T.Kind.Video&&(s.on(_.VideoPlaybackFailed,this.handleVideoPlaybackFailed),s.on(_.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(E.TrackSubscribed,s,r,i)}).on(M.TrackUnpublished,s=>{this.emit(E.TrackUnpublished,s,i)}).on(M.TrackUnsubscribed,(s,r)=>{this.emit(E.TrackUnsubscribed,s,r,i)}).on(M.TrackSubscriptionFailed,s=>{this.emit(E.TrackSubscriptionFailed,s,i)}).on(M.TrackMuted,s=>{this.emitWhenConnected(E.TrackMuted,s,i)}).on(M.TrackUnmuted,s=>{this.emitWhenConnected(E.TrackUnmuted,s,i)}).on(M.ParticipantMetadataChanged,s=>{this.emitWhenConnected(E.ParticipantMetadataChanged,s,i)}).on(M.ParticipantNameChanged,s=>{this.emitWhenConnected(E.ParticipantNameChanged,s,i)}).on(M.ConnectionQualityChanged,s=>{this.emitWhenConnected(E.ConnectionQualityChanged,s,i)}).on(M.ParticipantPermissionsChanged,s=>{this.emitWhenConnected(E.ParticipantPermissionsChanged,s,i)}).on(M.TrackSubscriptionStatusChanged,(s,r)=>{this.emitWhenConnected(E.TrackSubscriptionStatusChanged,s,r,i)}).on(M.TrackSubscriptionFailed,(s,r)=>{this.emit(E.TrackSubscriptionFailed,s,i,r)}).on(M.TrackSubscriptionPermissionChanged,(s,r)=>{this.emitWhenConnected(E.TrackSubscriptionPermissionChanged,s,r,i)}),t&&i.updateInfo(t),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((i,s)=>(i.push(...s.getTrackPublications()),i),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&t instanceof oc&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=ve.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,un.STATE_MISMATCH))):e=0},Bp)}clearConnectionReconcile(){this.connectionReconcileInterval&&ve.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(E.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,i]=e;this.emit(t,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];if(this.state===J.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===J.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){var t,i;return f(this,void 0,void 0,function*(){const s=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),r=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new qt({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:se.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new mt({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(E.SignalConnected),this.emit(E.Connected),this.setAndEmitConnectionState(J.Connected),s.video){const a=new si(T.Kind.Video,new Ze({source:me.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Le.AUDIO,name:"video-dummy"}),new Ie(s.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Er(160*((t=r.aspectRatios[0])!==null&&t!==void 0?t:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(a),this.localParticipant.emit(M.LocalTrackPublished,a)}if(s.audio){const a=new si(T.Kind.Audio,new Ze({source:me.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Le.AUDIO}),new Pe(s.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Ri(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(a),this.localParticipant.emit(M.LocalTrackPublished,a)}for(let a=0;a<r.count-1;a+=1){let o=new mt({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(a),state:$i.ACTIVE,tracks:[],joinedAt:se.parse(Date.now())});const c=this.getOrCreateParticipant(o.identity,o);if(r.video){const d=Er(160*((i=r.aspectRatios[a%r.aspectRatios.length])!==null&&i!==void 0?i:1),160,!1,!0),l=new Ze({source:me.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Le.AUDIO});c.addSubscribedMediaTrack(d,l.sid,new MediaStream([d])),o.tracks=[...o.tracks,l]}if(r.audio){const d=Ri(),l=new Ze({source:me.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Le.AUDIO});c.addSubscribedMediaTrack(d,l.sid,new MediaStream([d])),o.tracks=[...o.tracks,l]}c.updateInfo(o)}})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];if(e!==E.ActiveSpeakersChanged){const r=dc(i).filter(a=>a!==void 0);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r}))}return super.emit(e,...i)}}function dc(n){return n.map(e=>{if(e)return Array.isArray(e)?dc(e):typeof e=="object"?"logContext"in e&&e.logContext:e})}var De;(function(n){n[n.IDLE=0]="IDLE",n[n.RUNNING=1]="RUNNING",n[n.SKIPPED=2]="SKIPPED",n[n.SUCCESS=3]="SUCCESS",n[n.FAILED=4]="FAILED"})(De||(De={}));class zt extends Ge.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=De.IDLE,this.logs=[],this.errorsAsWarnings=!1,this.url=e,this.token=t,this.name=this.constructor.name,this.room=new cc(i.roomOptions),this.connectOptions=i.connectOptions,i.errorsAsWarnings&&(this.errorsAsWarnings=i.errorsAsWarnings)}run(e){return f(this,void 0,void 0,function*(){if(this.status!==De.IDLE)throw Error("check is running already");this.setStatus(De.RUNNING);try{yield this.perform()}catch(t){t instanceof Error&&(this.errorsAsWarnings?this.appendWarning(t.message):this.appendError(t.message))}return yield this.disconnect(),yield new Promise(t=>setTimeout(t,500)),this.status!==De.SKIPPED&&this.setStatus(this.isSuccess()?De.SUCCESS:De.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(){return f(this,void 0,void 0,function*(){return this.room.state===J.Connected?this.room:(yield this.room.connect(this.url,this.token),this.room)})}disconnect(){return f(this,void 0,void 0,function*(){this.room&&this.room.state!==J.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(De.SKIPPED)}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return(e=this.room)===null||e===void 0?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}function lc(n){var e,t;return f(this,void 0,void 0,function*(){n??(n={}),(e=n.audio)!==null&&e!==void 0||(n.audio=!0),(t=n.video)!==null&&t!==void 0||(n.video=!0);const i=qo(n,ec,tc),s=mi(i),r=navigator.mediaDevices.getUserMedia(s);n.audio&&(ye.userMediaPromiseMap.set("audioinput",r),r.catch(()=>ye.userMediaPromiseMap.delete("audioinput"))),n.video&&(ye.userMediaPromiseMap.set("videoinput",r),r.catch(()=>ye.userMediaPromiseMap.delete("videoinput")));const a=yield r;return a.getTracks().map(o=>{const c=o.kind==="audio";c?n.audio:n.video;let d;const l=c?s.audio:s.video;typeof l!="boolean"&&(d=l),d?d.deviceId=o.getSettings().deviceId:d={deviceId:o.getSettings().deviceId};const u=nc(o,d);return u.kind===T.Kind.Video?u.source=T.Source.Camera:u.kind===T.Kind.Audio&&(u.source=T.Source.Microphone),u.mediaStream=a,u})})}function Vp(n){return f(this,void 0,void 0,function*(){return(yield lc({audio:!1,video:n}))[0]})}function $p(n){return f(this,void 0,void 0,function*(){return(yield lc({audio:n,video:!1}))[0]})}class Hp extends zt{get description(){return"Can publish audio"}perform(){var e;return f(this,void 0,void 0,function*(){const t=yield this.connect(),i=yield $p();t.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,3e3));const s=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let r=0;if(s.forEach(a=>{a.type==="outbound-rtp"&&a.mediaType==="audio"&&(r=a.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," audio packets"))})}}class qp extends zt{get description(){return"Can publish video"}perform(){var e;return f(this,void 0,void 0,function*(){const t=yield this.connect(),i=yield Vp();t.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,3e3));const s=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let r=0;if(s.forEach(a=>{a.type==="outbound-rtp"&&a.mediaType==="video"&&(r=a.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))})}}class Gp extends zt{get description(){return"Resuming connection after interruption"}perform(){var e;return f(this,void 0,void 0,function*(){const t=yield this.connect();let i=!1,s=!1,r;const a=new Promise(c=>{setTimeout(c,5e3),r=c});t.on(E.Reconnecting,()=>{i=!0}).on(E.Reconnected,()=>{s=!0,r(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const o=t.engine.client.onClose;if(o&&o(""),yield a,i){if(!s||t.state!==J.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}else throw new Error("Did not attempt to reconnect")})}}class zp extends zt{get description(){return"Can connect via TURN"}perform(){var e,t;return f(this,void 0,void 0,function*(){const i=new xs,s=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let r=!1,a=!1,o=!1;for(let c of s.iceServers)for(let d of c.urls)d.startsWith("turn:")?(a=!0,o=!0):d.startsWith("turns:")&&(a=!0,o=!0,r=!0),d.startsWith("stun:")&&(o=!0);o?a&&!r&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield i.close(),!((t=(e=this.connectOptions)===null||e===void 0?void 0:e.rtcConfig)===null||t===void 0)&&t.iceServers||a?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(c=>setTimeout(c,0)))})}}class Wp extends zt{get description(){return"Establishing WebRTC connection"}perform(){return f(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(E.SignalConnected,()=>{const i=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(s,r)=>{if(s.candidate){const a=new RTCIceCandidate(s);let o="".concat(a.protocol," ").concat(a.address,":").concat(a.port," ").concat(a.type);a.address&&(Jp(a.address)?o+=" (private)":a.protocol==="tcp"&&a.tcpType==="passive"?(e=!0,o+=" (passive)"):a.protocol==="udp"&&(t=!0)),this.appendMessage(o)}i&&i(s,r)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=s=>{s instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(s.errorCode," ").concat(s.errorText," ").concat(s.url))})});try{yield this.connect(),$.info("now the room is connected")}catch(i){throw this.appendWarning("ports need to be open on firewall in order to connect."),i}e||this.appendWarning("Server is not configured for ICE/TCP"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function Jp(n){const e=n.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}class Kp extends zt{get description(){return"Connecting to signal connection via WebSocket"}perform(){var e,t,i;return f(this,void 0,void 0,function*(){(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let s=new xs;const r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(r.serverVersion,".")),((e=r.serverInfo)===null||e===void 0?void 0:e.edition)===xa.Cloud&&(!((t=r.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=r.serverInfo)===null||i===void 0?void 0:i.region)),yield s.close()})}}class sf extends Ge.EventEmitter{constructor(e,t){super(),this.checkResults=new Map,this.url=e,this.token=t}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:De.IDLE,name:"",description:""}),e}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==De.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return f(this,void 0,void 0,function*(){const t=this.getNextCheckId(),i=new e(this.url,this.token),s=a=>{this.updateCheck(t,a)};i.on("update",s);const r=yield i.run();return i.off("update",s),r})}checkWebsocket(){return f(this,void 0,void 0,function*(){return this.createAndRunCheck(Kp)})}checkWebRTC(){return f(this,void 0,void 0,function*(){return this.createAndRunCheck(Wp)})}checkTURN(){return f(this,void 0,void 0,function*(){return this.createAndRunCheck(zp)})}checkReconnect(){return f(this,void 0,void 0,function*(){return this.createAndRunCheck(Gp)})}checkPublishAudio(){return f(this,void 0,void 0,function*(){return this.createAndRunCheck(Hp)})}checkPublishVideo(){return f(this,void 0,void 0,function*(){return this.createAndRunCheck(qp)})}}function Qp(){const n=document.createElement("style");return n.textContent=`
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./constants-X_93hTEi.cjs");var t={mouseDown:1,shift:2,alt:4,block:8,focus:16},n=e=>Math.round(Math.min(100,Math.max(0,e))*100),r=e=>e/100,i=e=>typeof e==`function`?e:function(){return e},a=typeof self<`u`?self:null,o=typeof window<`u`?window:null,s=a||o||globalThis,c=`2.0.0`,l={connecting:0,open:1,closing:2,closed:3},u=100,d=1e4,f=1e3,p={closed:`closed`,errored:`errored`,joined:`joined`,joining:`joining`,leaving:`leaving`},m={close:`phx_close`,error:`phx_error`,join:`phx_join`,reply:`phx_reply`,leave:`phx_leave`},h={longpoll:`longpoll`,websocket:`websocket`},g={complete:4},_=`base64url.bearer.phx.`,v=class{constructor(e,t,n,r){this.channel=e,this.event=t,this.payload=n||function(){return{}},this.receivedResp=null,this.timeout=r,this.timeoutTimer=null,this.recHooks=[],this.sent=!1}resend(e){this.timeout=e,this.reset(),this.send()}send(){this.hasReceived(`timeout`)||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()},this.channel))}receive(e,t){return this.hasReceived(e)&&t(this.receivedResp.response),this.recHooks.push({status:e,callback:t}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}matchReceive({status:e,response:t,_ref:n}){this.recHooks.filter(t=>t.status===e).forEach(e=>e.callback(t))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.cancelRefEvent(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,e=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=e,this.matchReceive(e)}),this.timeoutTimer=setTimeout(()=>{this.trigger(`timeout`,{})},this.timeout)}hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}trigger(e,t){this.channel.trigger(this.refEvent,{status:e,response:t})}},y=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=null,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries+=1,this.callback()},this.timerCalc(this.tries+1))}},b=class{constructor(e,t,n){this.state=p.closed,this.topic=e,this.params=i(t||{}),this.socket=n,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new v(this,m.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new y(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive(`ok`,()=>{this.state=p.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(e=>e.send()),this.pushBuffer=[]}),this.joinPush.receive(`error`,()=>{this.state=p.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log(`channel`,`close ${this.topic} ${this.joinRef()}`),this.state=p.closed,this.socket.remove(this)}),this.onError(e=>{this.socket.hasLogger()&&this.socket.log(`channel`,`error ${this.topic}`,e),this.isJoining()&&this.joinPush.reset(),this.state=p.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive(`timeout`,()=>{this.socket.hasLogger()&&this.socket.log(`channel`,`timeout ${this.topic} (${this.joinRef()})`,this.joinPush.timeout),new v(this,m.leave,i({}),this.timeout).send(),this.state=p.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(m.reply,(e,t)=>{this.trigger(this.replyEventName(t),e)})}join(e=this.timeout){if(this.joinedOnce)throw Error(`tried to join multiple times. 'join' can only be called a single time per channel instance`);return this.timeout=e,this.joinedOnce=!0,this.rejoin(),this.joinPush}onClose(e){this.on(m.close,e)}onError(e){return this.on(m.error,t=>e(t))}on(e,t){let n=this.bindingRef++;return this.bindings.push({event:e,ref:n,callback:t}),n}off(e,t){this.bindings=this.bindings.filter(n=>n.event!==e||t!==void 0&&t!==n.ref)}canPush(){return this.socket.isConnected()&&this.isJoined()}push(e,t,n=this.timeout){if(t||={},!this.joinedOnce)throw Error(`tried to push '${e}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let r=new v(this,e,function(){return t},n);return this.canPush()?r.send():(r.startTimeout(),this.pushBuffer.push(r)),r}leave(e=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=p.leaving;let t=()=>{this.socket.hasLogger()&&this.socket.log(`channel`,`leave ${this.topic}`),this.trigger(m.close,`leave`)},n=new v(this,m.leave,i({}),e);return n.receive(`ok`,()=>t()).receive(`timeout`,()=>t()),n.send(),this.canPush()||n.trigger(`ok`,{}),n}onMessage(e,t,n){return t}isMember(e,t,n,r){return this.topic===e?r&&r!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log(`channel`,`dropping outdated message`,{topic:e,event:t,payload:n,joinRef:r}),!1):!0:!1}joinRef(){return this.joinPush.ref}rejoin(e=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=p.joining,this.joinPush.resend(e))}trigger(e,t,n,r){let i=this.onMessage(e,t,n,r);if(t&&!i)throw Error(`channel onMessage callbacks must return the payload, modified or unmodified`);let a=this.bindings.filter(t=>t.event===e);for(let e=0;e<a.length;e++)a[e].callback(i,n,r||this.joinRef())}replyEventName(e){return`chan_reply_${e}`}isClosed(){return this.state===p.closed}isErrored(){return this.state===p.errored}isJoined(){return this.state===p.joined}isJoining(){return this.state===p.joining}isLeaving(){return this.state===p.leaving}},x=class{static request(e,t,n,r,i,a,o){if(s.XDomainRequest){let n=new s.XDomainRequest;return this.xdomainRequest(n,e,t,r,i,a,o)}if(s.XMLHttpRequest){let c=new s.XMLHttpRequest;return this.xhrRequest(c,e,t,n,r,i,a,o)}if(s.fetch&&s.AbortController)return this.fetchRequest(e,t,n,r,i,a,o);throw Error(`No suitable XMLHttpRequest implementation found`)}static fetchRequest(e,t,n,r,i,a,o){let c={method:e,headers:n,body:r},l=null,u=null;return i&&(l=new AbortController,u=setTimeout(()=>l.abort(),i),c.signal=l.signal),s.fetch(t,c).then(e=>e.text()).then(e=>this.parseJSON(e)).then(e=>{u&&clearTimeout(u),o&&o(e)}).catch(e=>{u&&clearTimeout(u),e.name===`AbortError`&&a?a():o&&o(null)}),l}static xdomainRequest(e,t,n,r,i,a,o){return e.timeout=i,e.open(t,n),e.onload=()=>{let t=this.parseJSON(e.responseText);o&&o(t)},a&&(e.ontimeout=a),e.onprogress=()=>{},e.send(r),e}static xhrRequest(e,t,n,r,i,a,o,s){e.open(t,n,!0),e.timeout=a;for(let[t,n]of Object.entries(r))e.setRequestHeader(t,n);return e.onerror=()=>s&&s(null),e.onreadystatechange=()=>{e.readyState===g.complete&&s&&s(this.parseJSON(e.responseText))},o&&(e.ontimeout=o),e.send(i),e}static parseJSON(e){if(!e||e===``)return null;try{return JSON.parse(e)}catch{return console&&console.log(`failed to parse JSON response`,e),null}}static serialize(e,t){let n=[];for(var r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;let i=t?`${t}[${r}]`:r,a=e[r];typeof a==`object`?n.push(this.serialize(a,i)):n.push(encodeURIComponent(i)+`=`+encodeURIComponent(a))}return n.join(`&`)}static appendParams(e,t){return Object.keys(t).length===0?e:`${e}${e.match(/\?/)?`&`:`?`}${this.serialize(t)}`}},S=e=>{let t=``,n=new Uint8Array(e),r=n.byteLength;for(let e=0;e<r;e++)t+=String.fromCharCode(n[e]);return btoa(t)},C=class{constructor(e,t){t&&t.length===2&&t[1].startsWith(_)&&(this.authToken=atob(t[1].slice(_.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.messageTimers=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(e),this.readyState=l.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(e){return e.replace(`ws://`,`http://`).replace(`wss://`,`https://`).replace(RegExp(`(.*)/`+h.websocket),`$1/`+h.longpoll)}endpointURL(){return x.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(e,t,n,r){this.isActive()&&(this.stop(l.connecting),this.onerror(e),this.isActive()&&this.emitClose(t,n,r))}ontimeout(){this.closeAndRetry(`timeout`,1005,`timeout`,!1)}isActive(){return this.readyState===l.open||this.readyState===l.connecting}poll(){if(!this.isActive())return;let e={Accept:`application/json`};this.authToken&&(e[`X-Phoenix-AuthToken`]=this.authToken),this.ajax(`GET`,e,null,()=>this.ontimeout(),e=>{if(e){var{status:t,token:n,messages:r}=e;if(t===410&&this.token!==null){this.closeAndRetry(410,3410,`session_gone`,!1);return}this.token=n}else t=0;switch(t){case 200:r.forEach(e=>{let t=setTimeout(()=>{this.messageTimers.delete(t),this.onmessage({data:e})},0);this.messageTimers.add(t)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=l.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,`forbidden`,!1);break;case 0:case 500:this.closeAndRetry(500,1011,`internal server error`,!1);break;default:throw Error(`unhandled poll status ${t}`)}})}send(e){typeof e!=`string`&&(e=S(e)),this.currentBatch?this.currentBatch.push(e):this.awaitingBatchAck?this.batchBuffer.push(e):(this.currentBatch=[e],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(e,t=0){this.awaitingBatchAck=!0;let n=t+u,r=e.slice(t,n);this.ajax(`POST`,{"Content-Type":`application/x-ndjson`},r.join(`
|
|
2
|
+
`),()=>this.ontimeout(),t=>{!t||t.status!==200?this.closeAndRetry(t&&t.status,1011,`internal server error`,!1):n<e.length?this.batchSend(e,n):this.batchBuffer.length>0?(this.batchSend(this.batchBuffer),this.batchBuffer=[]):this.awaitingBatchAck=!1})}close(e,t,n){this.stop(l.closed),this.emitClose(e,t,n)}stop(e){this.readyState=e;let t=this.reqs;this.reqs=new Set;for(let{req:e}of t)e&&e.abort();for(let e of this.messageTimers)clearTimeout(e);this.messageTimers.clear(),this.batchBuffer=[],this.awaitingBatchAck=!1,clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,this.currentBatch=null}emitClose(e=1005,t,n=!0){let r={code:e,reason:t,wasClean:n};typeof CloseEvent<`u`?this.onclose(new CloseEvent(`close`,r)):this.onclose(r)}ajax(e,t,n,r,i){let a={req:null};this.reqs.add(a),a.req=x.request(e,this.endpointURL(),t,n,this.timeout,()=>{this.reqs.delete(a)&&r()},e=>{this.reqs.delete(a)&&i(e)})}},w={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(e,t){if(e.payload.constructor===ArrayBuffer)return t(this.binaryEncode(e));{let n=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(n))}},decode(e,t){if(e.constructor===ArrayBuffer)return t(this.binaryDecode(e));{let[n,r,i,a,o]=JSON.parse(e);return t({join_ref:n,ref:r,topic:i,event:a,payload:o})}},binaryEncode(e){let{join_ref:t,ref:n,event:r,topic:i,payload:a}=e,o=new TextEncoder,s=o.encode(t),c=o.encode(n),l=o.encode(i),u=o.encode(r);this.assertFieldSize(s.byteLength,`join_ref`),this.assertFieldSize(c.byteLength,`ref`),this.assertFieldSize(l.byteLength,`topic`),this.assertFieldSize(u.byteLength,`event`);let d=this.META_LENGTH+s.byteLength+c.byteLength+l.byteLength+u.byteLength,f=new ArrayBuffer(this.HEADER_LENGTH+d),p=new Uint8Array(f),m=new DataView(f),h=0;m.setUint8(h++,this.KINDS.push),m.setUint8(h++,s.byteLength),m.setUint8(h++,c.byteLength),m.setUint8(h++,l.byteLength),m.setUint8(h++,u.byteLength),p.set(s,h),h+=s.byteLength,p.set(c,h),h+=c.byteLength,p.set(l,h),h+=l.byteLength,p.set(u,h),h+=u.byteLength;var g=new Uint8Array(f.byteLength+a.byteLength);return g.set(p,0),g.set(new Uint8Array(a),f.byteLength),g.buffer},assertFieldSize(e,t){if(e>255)throw Error(`unable to convert ${t} to binary: must be less than or equal to 255 bytes, but is ${e} bytes`)},binaryDecode(e){let t=new DataView(e),n=t.getUint8(0),r=new TextDecoder;switch(n){case this.KINDS.push:return this.decodePush(e,t,r);case this.KINDS.reply:return this.decodeReply(e,t,r);case this.KINDS.broadcast:return this.decodeBroadcast(e,t,r)}},decodePush(e,t,n){let r=t.getUint8(1),i=t.getUint8(2),a=t.getUint8(3),o=this.HEADER_LENGTH+this.META_LENGTH-1,s=n.decode(e.slice(o,o+r));o+=r;let c=n.decode(e.slice(o,o+i));o+=i;let l=n.decode(e.slice(o,o+a));return o+=a,{join_ref:s,ref:null,topic:c,event:l,payload:e.slice(o,e.byteLength)}},decodeReply(e,t,n){let r=t.getUint8(1),i=t.getUint8(2),a=t.getUint8(3),o=t.getUint8(4),s=this.HEADER_LENGTH+this.META_LENGTH,c=n.decode(e.slice(s,s+r));s+=r;let l=n.decode(e.slice(s,s+i));s+=i;let u=n.decode(e.slice(s,s+a));s+=a;let d=n.decode(e.slice(s,s+o));s+=o;let f={status:d,response:e.slice(s,e.byteLength)};return{join_ref:c,ref:l,topic:u,event:m.reply,payload:f}},decodeBroadcast(e,t,n){let r=t.getUint8(1),i=t.getUint8(2),a=this.HEADER_LENGTH+2,o=n.decode(e.slice(a,a+r));a+=r;let s=n.decode(e.slice(a,a+i));return a+=i,{join_ref:null,ref:null,topic:o,event:s,payload:e.slice(a,e.byteLength)}}},T=class{constructor(e,t){this.socket=e,this.transport=t,this.joins=new WeakMap,this.pings=new Map,this.closing=!1,this.ended=!1,this.channelsErrored=!1,this.closeHandled=!1,t.onopen=()=>{this.isCurrent()&&e.onConnOpen()},t.onerror=t=>{this.isCurrent()&&e.onConnError(t)},t.onmessage=t=>{this.isCurrent()&&e.onConnMessage(t)},t.onclose=t=>{this.isCurrent()&&!this.closeHandled&&(this.closeHandled=!0,e.onConnClose(t))}}isCurrent(){return this.socket.connection===this}isOpen(){return this.transport.readyState===l.open}isConnecting(){return this.transport.readyState===l.connecting}carried(e,t=e.joinRef()){return this.joins.has(e)&&this.joins.get(e)===t}close(e,t){this.closing=!0,this.transport.onerror=function(){},e?this.transport.close(e,t||``):this.transport.close()}},E=class{constructor(e,t={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.fallbackErrorRef=null,this.timeout=t.timeout||d,this.transport=t.transport||s.WebSocket||C,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=t.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=t.sessionStorage||s&&s.sessionStorage,this.establishedConnections=0,this.defaultEncoder=w.encode.bind(w),this.defaultDecoder=w.decode.bind(w),this.closeWasClean=!0,this.binaryType=t.binaryType||`arraybuffer`,this.connection=null,this.connectClock=1,this.visibilityConnection=null,this.transport===C?(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder):(this.encode=t.encode||this.defaultEncoder,this.decode=t.decode||this.defaultDecoder);let n=null;o&&o.addEventListener&&(o.addEventListener(`pagehide`,e=>{this.connection&&!this.connection.ended&&(this.disconnect(),n=this.connectClock)}),o.addEventListener(`pageshow`,e=>{n===this.connectClock&&(n=null,this.connect())}),o.addEventListener(`visibilitychange`,()=>{this.handleVisibilityChange()}),o.document&&o.document.addEventListener(`resume`,()=>{this.handleVisibilityChange()})),this.heartbeatIntervalMs=t.heartbeatIntervalMs||3e4,this.rejoinAfterMs=e=>t.rejoinAfterMs?t.rejoinAfterMs(e):[1e3,2e3,5e3][e-1]||1e4,this.reconnectAfterMs=e=>t.reconnectAfterMs?t.reconnectAfterMs(e):[10,50,100,150,200,250,500,1e3,2e3][e-1]||5e3,this.logger=t.logger||null,!this.logger&&t.debug&&(this.logger=(e,t,n)=>{console.log(`${e}: ${t}`,n)}),this.longpollerTimeout=t.longpollerTimeout||2e4,this.params=i(t.params||{}),this.endPoint=`${e}/${h.websocket}`,this.vsn=t.vsn||c,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new y(()=>{this.pageHidden?(this.log(`Not reconnecting as page is hidden!`),this.teardown()):this.teardownAndReconnect(()=>this.connect())},this.reconnectAfterMs),this.authToken=t.authToken&&i(t.authToken)}get conn(){return this.connection&&this.connection.transport}get pageHidden(){return o&&o.document?o.document.visibilityState===`hidden`:!1}handleVisibilityChange(){if(this.pageHidden){this.visibilityConnection=null;return}let e=this.connection;e&&e===this.visibilityConnection&&e.isConnecting()||!this.isConnected()&&!this.closeWasClean&&(this.reconnectTimer.reset(),this.teardownAndReconnect(()=>{this.connect(),this.visibilityConnection=this.connection}))}getLongPollTransport(){return C}replaceTransport(e){let t=++this.connectClock;this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.transport=e;let n=this.connection;if(n){let e=n.isOpen();this.connection=null,n.ended=!0,n.close(),this.clearHeartbeats(),e&&this.triggerChanError(`connection_closed`,n)}return t}protocol(){return location.protocol.match(/^https/)?`wss`:`ws`}endPointURL(){let e=x.appendParams(x.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return e.charAt(0)===`/`?e.charAt(1)===`/`?`${this.protocol()}:${e}`:`${this.protocol()}://${location.host}${e}`:e}disconnect(e,t,n){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.connection&&(this.connection.ended=!0),this.teardown(e,t,n)}connect(e){e&&(console&&console.log(`passing params to connect is deprecated. Instead pass :params to the Socket constructor`),this.params=i(e)),(!this.connection||this.connection.ended)&&(this.longPollFallbackMs&&this.transport!==C?this.connectWithFallback(C,this.longPollFallbackMs):this.transportConnect())}log(e,t,n){this.logger&&this.logger(e,t,n)}hasLogger(){return this.logger!==null}onOpen(e){let t=this.makeRef();return this.stateChangeCallbacks.open.push([t,e]),t}onClose(e){let t=this.makeRef();return this.stateChangeCallbacks.close.push([t,e]),t}onError(e){let t=this.makeRef();return this.stateChangeCallbacks.error.push([t,e]),t}onMessage(e){let t=this.makeRef();return this.stateChangeCallbacks.message.push([t,e]),t}ping(e){if(!this.isConnected())return!1;let t=this.makeRef(),n=Date.now();return this.connection.pings.set(t,()=>e(Date.now()-n)),this.push({topic:`phoenix`,event:`heartbeat`,payload:{},ref:t}),!0}transportName(e){switch(e){case C:return`LongPoll`;default:return e.name}}transportConnect(){let e=this.connection;this.connectClock++,this.closeWasClean=!1,clearTimeout(this.reconnectTimer.timer);let t;this.authToken&&(t=[`phoenix`,`${_}${btoa(this.authToken()).replace(/=/g,``)}`]);let n=new this.transport(this.endPointURL(),t);n.binaryType=this.binaryType,n.timeout=this.longpollerTimeout,this.connection=new T(this,n),e&&e.isOpen()&&this.triggerChanError(`connection_closed`,e)}getSession(e){return this.sessionStore&&this.sessionStore.getItem(e)}storeSession(e,t){this.sessionStore&&this.sessionStore.setItem(e,t)}connectWithFallback(e,t=2500){this.cancelFallback();let n=!1,r=!0,i,a,o=()=>a===this.connectClock&&!this.closeWasClean,s=this.transportName(e),c=t=>{this.log(`transport`,`falling back to ${s}...`,t),this.off([i]),r=!1,this.replaceTransport(e)===this.connectClock&&this.transportConnect()};if(this.getSession(`phx:fallback:${s}`))return c(`memorized`);this.fallbackTimer=setTimeout(c,t),i=this.fallbackErrorRef=this.onError(e=>{o()&&(this.log(`transport`,`error`,e),r&&!n&&(clearTimeout(this.fallbackTimer),c(e)))}),this.fallbackRef=this.onOpen(()=>{if(!r){if(this.transport!==e||this.closeWasClean)return;let t=this.transportName(e);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${t}`,`true`),this.log(`transport`,`established ${t} fallback`)}o()&&(n=!0,clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(c,t),this.ping(e=>{this.log(`transport`,`connected to primary after`,e),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)}))}),this.transportConnect(),a=this.connectClock}cancelFallback(){clearTimeout(this.fallbackTimer),this.off([this.fallbackRef,this.fallbackErrorRef])}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer),this.pendingHeartbeatRef=null}onConnOpen(){this.hasLogger()&&this.log(`transport`,`${this.transportName(this.transport)} connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.resetHeartbeat(),this.stateChangeCallbacks.open.forEach(([,e])=>e())}heartbeatTimeout(){if(this.pendingHeartbeatRef){let e=this.connection;if(this.pendingHeartbeatRef=null,this.hasLogger()&&this.log(`transport`,`heartbeat timeout. Attempting to re-establish connection`),this.closeWasClean=!1,e&&e.close(f,`heartbeat timeout`),!this.stillUses(e)||(this.triggerChanError(`heartbeat_timeout`),!this.stillUses(e)))return;this.teardownAndReconnect(()=>this.reconnectTimer.scheduleTimeout())}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardownAndReconnect(e){let t=this.connection,n=this.connectClock;this.teardown(()=>{n!==this.connectClock||t&&t.ended||e()})}stillUses(e){return this.connection===e&&!(e&&e.ended)}teardown(e,t,n){let r=this.connection;if(!r)return e&&e();this.clearHeartbeats(),this.waitForBufferDone(r.transport,()=>{if(!r.closing){let e=!r.isConnecting();r.close(t,n),e&&this.triggerChanError(`connection_closed`,r)}this.waitForSocketClosed(r.transport,()=>{this.connection===r&&(this.connection=null),e&&e()})})}waitForBufferDone(e,t,n=1){n===5||!e.bufferedAmount||e.readyState!==l.open?t():setTimeout(()=>{this.waitForBufferDone(e,t,n+1)},150*n)}waitForSocketClosed(e,t,n=1){n===5||e.readyState===l.closed?t():setTimeout(()=>{this.waitForSocketClosed(e,t,n+1)},150*n)}onConnClose(e){let t=this.connection;this.hasLogger()&&this.log(`transport`,`close`,e),this.clearHeartbeats();let n=!!(t&&t.closing);this.triggerChanError(`connection_closed`,t),this.stillUses(t)&&!n&&!this.closeWasClean&&this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(([,t])=>t(e))}onConnError(e){let t=this.connection;this.hasLogger()&&this.log(`transport`,`error`,e);let n=this.transport,r=this.establishedConnections;this.stateChangeCallbacks.error.forEach(([,t])=>{t(e,n,r)}),this.triggerChanError(`connection_error`,t)}triggerChanError(e,t=this.connection){let n=!1;t&&!t.isOpen()&&(n=t.channelsErrored,t.channelsErrored=!0),this.channels.map(e=>[e,e.joinRef()]).forEach(([r,i])=>{r.joinRef()===i&&(!t||!n&&t.isCurrent()||t.carried(r,i))&&(r.isErrored()||r.isLeaving()||r.isClosed()||r.trigger(m.error,{source:`transport`,reason:e}))})}connectionState(){switch(this.conn&&this.conn.readyState){case l.connecting:return`connecting`;case l.open:return`open`;case l.closing:return`closing`;default:return`closed`}}isConnected(){return this.connectionState()===`open`}remove(e){this.off(e.stateChangeRefs),this.channels=this.channels.filter(t=>t!==e)}off(e){for(let t in this.stateChangeCallbacks)this.stateChangeCallbacks[t]=this.stateChangeCallbacks[t].filter(([t])=>e.indexOf(t)===-1)}channel(e,t={}){let n=new b(e,t,this);return this.channels.push(n),n}push(e,t){if(this.hasLogger()){let{topic:t,event:n,payload:r,ref:i,join_ref:a}=e;this.log(`push`,`${t} ${n} (${a}, ${i})`,r)}this.isConnected()?this.send(e,t):this.sendBuffer.push(()=>{this.isOutdated(e,t)||this.send(e,t)})}send(e,t){let n=this.connection;t&&e.event===m.join&&n.joins.set(t,e.join_ref),this.encode(e,r=>{n.isCurrent()&&n.isOpen()&&(e.event!==m.leave&&this.isOutdated(e,t)||n.transport.send(r))})}isOutdated(e,t){return!!t&&(e.join_ref!==t.joinRef()||t.isClosed())}makeRef(){let e=this.ref+1;return this.ref=e===this.ref?0:e,this.ref.toString()}sendHeartbeat(){(!this.pendingHeartbeatRef||this.isConnected())&&(this.pendingHeartbeatRef=this.makeRef(),this.push({topic:`phoenix`,event:`heartbeat`,payload:{},ref:this.pendingHeartbeatRef}),this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs))}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}onConnMessage(e){let t=this.connection,n=t&&t.isOpen();this.decode(e.data,e=>{if(t!==this.connection||n&&!t.isOpen())return;let{topic:r,event:i,payload:a,ref:o,join_ref:s}=e;o&&o===this.pendingHeartbeatRef&&(this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)),this.hasLogger()&&this.log(`receive`,`${a.status||``} ${r} ${i} ${o&&`(`+o+`)`||``}`,a);let c=this.channels;for(let e=0;e<c.length;e++){let t=c[e];t.isMember(r,i,a,s)&&t.trigger(i,a,o,s)}let l=this.stateChangeCallbacks.message;for(let t=0;t<l.length;t++){let[,n]=l[t];n(e)}let u=o&&t.pings.get(o);u&&(t.pings.delete(o),u())})}leaveOpenTopic(e){let t=this.channels.find(t=>t.topic===e&&(t.isJoined()||t.isJoining()));t&&(this.hasLogger()&&this.log(`transport`,`leaving duplicate topic "${e}"`),t.leave())}},D=1e3,O=1e3,k=150,ee=2,te=3e4,ne=1e4,A=60,j=class{probe;onChange;now;quality=`good`;rtt=null;rtts=[];pings=0;stalls=0;stallMs=0;maxStallMs=0;unstableMs=0;offlineMs=0;reconnects=0;everOnline=!1;wasOnline=!1;pingSentAt=null;stallSince=null;lastIssueAt=-1/0;slowAt=[];lastPingAt=-1/0;lastTick;timer=null;constructor(e,t,n=()=>performance.now()){this.probe=e,this.onChange=t,this.now=n,this.lastTick=n()}start(e=250){this.stop(),this.timer=setInterval(()=>this.tick(),e)}stop(){this.timer&&clearInterval(this.timer),this.timer=null}tick(){let e=this.now(),t=e-this.lastTick;this.lastTick=e,this.quality===`unstable`&&(this.unstableMs+=t),this.quality===`offline`&&(this.offlineMs+=t);let n=this.probe.online();n&&!this.wasOnline&&(this.everOnline&&this.reconnects++,this.everOnline=!0),!n&&this.wasOnline&&this.endStall(e),this.wasOnline=n,n?(this.pingSentAt!==null&&this.stallSince===null&&e-this.pingSentAt>=O&&(this.stallSince=this.pingSentAt),this.pingSentAt===null&&e-this.lastPingAt>=D&&this.sendPing(e)):this.pingSentAt=null;let r=n?this.stallSince!==null||e-this.lastIssueAt<ne||this.recentSlow(e)>=ee?`unstable`:`good`:this.everOnline?`offline`:`good`;r!==this.quality&&(this.quality=r,this.onChange(r))}report(){let e=[...this.rtts].sort((e,t)=>e-t),t=t=>Math.round(e[Math.min(e.length-1,Math.floor(t*e.length))]);return{q:this.quality===`good`?`good`:`unstable`,rtt:e.length?[t(.5),t(.95),Math.round(e[e.length-1])]:null,pings:this.pings,stalls:this.stalls,stall_ms:Math.round(this.stallMs),max_stall_ms:Math.round(this.maxStallMs),unstable_ms:Math.round(this.unstableMs),offline_ms:Math.round(this.offlineMs),reconnects:this.reconnects}}sendPing(e){this.lastPingAt=e,this.probe.ping(t=>{if(this.pingSentAt!==e)return;let n=this.now();this.pingSentAt=null,this.pings++,this.rtt=t,this.rtts.push(t),this.rtts.length>A&&this.rtts.shift();let[r,i,a]=this.rtts.slice(-3);a!==void 0&&i>=r+k&&i>=a+k&&this.slowAt.push(n),this.endStall(n),this.tick()})&&(this.pingSentAt=e)}recentSlow(e){for(;this.slowAt.length&&e-this.slowAt[0]>=te;)this.slowAt.shift();return this.slowAt.length}endStall(e){if(this.stallSince===null)return;let t=e-this.stallSince;this.stalls++,this.stallMs+=t,this.maxStallMs=Math.max(this.maxStallMs,t),this.stallSince=null,this.lastIssueAt=e}},M=class{options;participants=new Map;status=`connecting`;you=null;livekit=null;account=null;socket=null;channel=null;bySlot=new Map;listeners=new Map;flags=t.alt;renames=new Map;cursor=null;sentCursor=null;moveScheduled=!1;lastMoveAt=0;localState={};follow=`all`;monitor=null;reportTimer=null;offPageHide=null;tabs=null;constructor(e){this.options=e}on(e,t){let n=this.listeners.get(e);return n||this.listeners.set(e,n=new Set),n.add(t),()=>n.delete(t)}emit(e,t){for(let n of this.listeners.get(e)??[])n(t)}get me(){return this.you?this.participants.get(this.you):void 0}hasFlag(e){return(this.flags&t[e])!==0}connect(){let e=this.options,t=()=>this.reportNet();window.addEventListener(`pagehide`,t),this.offPageHide=()=>window.removeEventListener(`pagehide`,t),this.socket=new E(e.url,{params:e.apiToken?{api_token:e.apiToken}:{},heartbeatIntervalMs:e.heartbeatMs??5e3,reconnectAfterMs:e=>[50,100,250,500,1e3,2e3][e-1]??3e3,rejoinAfterMs:e=>[100,500,1e3,2e3][e-1]??5e3,logger:e.logger}),this.socket.onClose(()=>this.setStatus(`disconnected`)),this.socket.connect();let n=this.socket;this.monitor=new j({ping:e=>n.ping(e),online:()=>n.isConnected()&&this.status===`joined`},e=>{this.emit(`quality`,e),this.reportNet()}),this.monitor.start(),this.reportTimer=setInterval(()=>this.reportNet(),1e4),this.channel=this.socket.channel(`room:${e.roomId}`,()=>this.joinParams()),this.channel.on(`snapshot`,e=>this.onSnapshot(e)),this.channel.on(`presence`,e=>this.onPresence(e)),this.channel.on(`cursors`,e=>this.onCursors(e)),this.channel.on(`state`,e=>this.onState(e)),this.channel.on(`click`,e=>this.emit(`click`,e)),this.channel.on(`wheel`,e=>this.emit(`wheel`,e)),this.channel.on(`account`,({account:e})=>{this.account=e,this.emit(`account`,e)});let r=this.channel;this.whenResumeIsFree(()=>this.join(r)),r.onError(()=>this.setStatus(`disconnected`))}join(e){e===this.channel&&e.join().receive(`ok`,({you:e,resume:t})=>{this.you=e,t&&this.storage?.setItem(this.resumeKey,t)}).receive(`error`,({reason:e,code:t})=>{if(t!==`refused`)return this.setStatus(`disconnected`);this.setStatus(`refused`),this.emit(`refused`,e),this.disconnect()})}whenResumeIsFree(e){if(typeof BroadcastChannel>`u`)return e();let t=this.tabs=new BroadcastChannel(`liveroom:${this.options.roomId}`),n=this.storage?.getItem(this.resumeKey)||null,r=!1;if(t.onmessage=({data:e})=>{let i=this.storage?.getItem(this.resumeKey);e?.type===`who`&&i&&e.resume===i&&this.status===`joined`?t.postMessage({type:`mine`,resume:i}):e?.type===`mine`&&n&&e.resume===n&&(r=!0)},!n)return e();t.postMessage({type:`who`,resume:n}),setTimeout(()=>{r&&this.storage?.setItem(this.resumeKey,``),e()},150)}disconnect(){for(let e of[...this.renames.keys()])this.flushRename(e);this.reportNet(),this.monitor?.stop(),this.reportTimer&&clearInterval(this.reportTimer),this.offPageHide?.(),this.tabs?.close(),this.tabs=null,this.monitor=null,this.reportTimer=null,this.offPageHide=null,this.channel?.leave(),this.socket?.disconnect(),this.channel=null,this.socket=null}get quality(){return this.monitor?.quality??`good`}get rtt(){return this.monitor?.rtt??null}reportNet(){this.monitor&&this.push(`net`,this.monitor.report())}setStatus(e){this.status!==`refused`&&this.status!==e&&(this.status=e,this.emit(`status`,e))}get storage(){if(this.options.storage!==void 0)return this.options.storage;try{return window.sessionStorage}catch{return null}}get resumeKey(){return`liveroom-resume:${this.options.roomId}`}joinParams(){let e=this.options;return F({v:2,room_token:e.roomToken,type:e.type,resume:this.storage?.getItem(this.resumeKey)||void 0,name:e.name??void 0,color:e.color??void 0,viewport:e.viewport?.()??this.localState.viewport,cursor:this.cursor?this.cursor.map(n):void 0,net:this.monitor&&this.monitor.quality!==`good`?`unstable`:void 0,...e.analytics})}onSnapshot(e){this.you=e.you,this.livekit=e.livekit,this.account=e.account,this.participants.clear(),this.bySlot.clear();for(let t of Object.values(e.users))this.put(t);this.setStatus(`joined`),this.sentCursor=null,this.push(`f`,this.flags),Object.keys(this.localState).length&&this.push(`s`,this.localState),this.follow!==`all`&&this.push(`follow`,this.follow),this.reportNet(),this.flushMove(),this.emit(`snapshot`,void 0),this.emit(`account`,this.account)}onPresence(e){let t=Object.values(e.joins).map(e=>(this.put(e),e.id));for(let t of e.leaves){let e=this.participants.get(t);e&&this.bySlot.delete(e.slot),this.participants.delete(t)}let n=[];for(let[t,r]of Object.entries(e.updates)){let e=this.participants.get(t);e&&(Object.assign(e,r),n.push(t))}this.emit(`presence`,{joined:t,left:e.leaves,updated:n})}onCursors({t:e,c:t}){let n=[];for(let i=0;i+3<t.length;i+=4){let a=this.bySlot.get(t[i]),o=a?this.participants.get(a):void 0;o&&(o.x=r(t[i+1]),o.y=r(t[i+2]),o.flags=t[i+3],o.cursorAt=e,n.push(o.id))}n.length&&this.emit(`cursors`,{ids:n,t:e})}onState(e){let t=[];for(let[n,r]of Object.entries(e)){let e=this.participants.get(n);e&&(Object.assign(e,r),t.push(n))}t.length&&this.emit(`state`,{ids:t})}put(e){this.participants.set(e.id,{...e,x:r(e.x),y:r(e.y),cursorAt:0}),this.bySlot.set(e.slot,e.id)}push(e,t){this.channel&&this.status===`joined`&&this.channel.push(e,t)}move(e,t){if(this.cursor=[e,t],this.moveScheduled)return;if(performance.now()-this.lastMoveAt>=15)return this.flushMove();this.moveScheduled=!0;let n=()=>{this.moveScheduled=!1,this.flushMove()};typeof document<`u`&&document.visibilityState===`visible`&&typeof requestAnimationFrame==`function`?requestAnimationFrame(n):setTimeout(n,16)}flushMove(){if(!this.cursor)return;let e=[n(this.cursor[0]),n(this.cursor[1])];this.sentCursor&&e[0]===this.sentCursor[0]&&e[1]===this.sentCursor[1]||this.status===`joined`&&(this.sentCursor=e,this.lastMoveAt=performance.now(),this.push(`m`,e))}setFlag(e,n){let r=n?this.flags|t[e]:this.flags&~t[e];r!==this.flags&&(this.flags=r,this.flushMove(),this.push(`f`,r),this.emit(`flags`,r))}toggleFlag(e){this.setFlag(e,!this.hasFlag(e))}get ownFlags(){return this.flags}setState(e){e.url&&(e={...e,url:P(e.url)}),Object.assign(this.localState,e),this.push(`s`,e)}click(e){this.flushMove(),this.push(`click`,{to:e,...this.cursorPayload()})}wheel(e,t,n){this.flushMove(),this.push(`wheel`,{to:e,dx:Math.round(t),dy:Math.round(n),...this.cursorPayload()})}cursorPayload(){return this.cursor?{x:n(this.cursor[0]),y:n(this.cursor[1])}:{}}rename(e,t){let n=this.renames.get(e);n&&clearTimeout(n.timer);let r=setTimeout(()=>this.flushRename(e),250);this.renames.set(e,{name:t,timer:r})}flushRename(e){let t=this.renames.get(e);t&&(clearTimeout(t.timer),this.renames.delete(e),this.push(`rename`,{id:e,name:t.name}))}cameras(e){this.push(`cameras`,{enabled:e})}presenter(e){this.push(`presenter`,{name:e})}setFollow(e){e===this.follow||Array.isArray(e)&&Array.isArray(this.follow)&&e.length===this.follow.length&&e.every((e,t)=>e===this.follow[t])||(this.follow=e,this.push(`follow`,e))}},N=2048;function P(e){return e.length>2048?e.slice(0,N):e}function F(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,typeof t==`string`?P(t):t]))}var I=`
|
|
3
|
+
.lr-cursors { position: absolute; inset: 0; overflow: hidden; pointer-events: none; z-index: 2147483646; }
|
|
4
|
+
.lr-user { position: absolute; top: 0; left: 0; user-select: none; will-change: transform; transform-origin: 0 0; }
|
|
5
|
+
.lr-user[data-hidden="true"] { display: none; }
|
|
6
|
+
.lr-cursor { position: absolute; top: 0; left: 0; color: var(--color); transform-origin: top left; transform: rotate(6deg); }
|
|
7
|
+
.lr-label { position: absolute; top: 18px; left: 14px; font: 600 12px/1.6 system-ui, sans-serif; color: black;
|
|
8
|
+
background: var(--color); border-radius: 9999px; padding: 0 8px; white-space: nowrap; box-shadow: 0 1px 2px rgb(0 0 0 / 5%);
|
|
9
|
+
display: flex; flex-direction: column; align-items: center; overflow: hidden; max-width: 200px; text-overflow: ellipsis; }
|
|
10
|
+
.lr-label video { display: none; width: 170.6667px; height: 96px; object-fit: cover; margin: 0; }
|
|
11
|
+
/* Keep the same 16:9 video surface. The small bubble is a circular crop. */
|
|
12
|
+
.lr-user[data-live="true"] .lr-label, .lr-user[data-focus-motion="true"] .lr-label {
|
|
13
|
+
padding: 0; border-radius: 0; top: 10px; left: -31.3333px; width: 170.6667px; height: 96px;
|
|
14
|
+
background: transparent; box-shadow: none; overflow: visible;
|
|
15
|
+
}
|
|
16
|
+
.lr-user[data-live="true"] .lr-label video, .lr-user[data-focus-motion="true"] .lr-label video {
|
|
17
|
+
display: block; clip-path: inset(0 37.3333px round 48px);
|
|
18
|
+
transition: clip-path 250ms cubic-bezier(0.77, 0, 0.175, 1);
|
|
19
|
+
}
|
|
20
|
+
.lr-user[data-live="true"] .lr-label > span, .lr-user[data-focus-motion="true"] .lr-label > span {
|
|
21
|
+
position: absolute; top: calc(100% + 2px); left: 50%; padding: 2px 8px; border-radius: 9999px;
|
|
22
|
+
background: var(--color); opacity: 0; visibility: hidden;
|
|
23
|
+
transform: translateX(-50%) scale(calc(1 / var(--focus-scale, 1))); transform-origin: top center;
|
|
24
|
+
transition: opacity 200ms ease, visibility 200ms ease;
|
|
25
|
+
}
|
|
26
|
+
.lr-halo { position: absolute; top: -60px; left: -60px; width: 120px; height: 120px; border-radius: 9999px; z-index: -1;
|
|
27
|
+
border: 1px solid color-mix(in srgb, var(--color) 75%, transparent); background: color-mix(in srgb, var(--color) 25%, transparent);
|
|
28
|
+
transform: scale(0); transition: transform 200ms ease-in-out; }
|
|
29
|
+
.lr-user[data-halo="true"] .lr-halo { transform: scale(1); }
|
|
30
|
+
.lr-user[data-self="true"] .lr-cursor, .lr-user[data-self="true"] .lr-label { display: none; }
|
|
31
|
+
.lr-cursors::before { content: ""; position: absolute; inset: 0; background: rgb(39 39 42 / 25%); backdrop-filter: blur(6px); opacity: 0; transition: opacity 200ms ease; }
|
|
32
|
+
.lr-cursors[data-focus="true"]::before { opacity: 1; }
|
|
33
|
+
.lr-user[data-focus-motion="true"] { transition: transform 250ms cubic-bezier(0.77, 0, 0.175, 1); }
|
|
34
|
+
.lr-user[data-focus="true"] { transform: translate3d(calc(50vw - 54px * var(--focus-scale)), calc(50vh - 58px * var(--focus-scale)), 0) scale(var(--focus-scale)) !important; z-index: 1; }
|
|
35
|
+
.lr-user[data-focus="true"] .lr-label video { clip-path: inset(0 round 4px); }
|
|
36
|
+
.lr-user[data-focus="true"] .lr-label > span { opacity: 1; visibility: visible; }
|
|
37
|
+
.lr-user[data-focus="true"]:not([data-live="true"]) .lr-label { background: #18181b; border-radius: 4px; }
|
|
38
|
+
.lr-user[data-focus="true"] .lr-cursor, .lr-user[data-focus="true"] .lr-halo { opacity: 0; }
|
|
39
|
+
@media (prefers-reduced-motion: reduce) {
|
|
40
|
+
.lr-user[data-focus-motion="true"], .lr-label video { transition: none !important; }
|
|
41
|
+
.lr-cursors::before, .lr-label > span { transition-duration: 100ms; }
|
|
42
|
+
}
|
|
43
|
+
.lr-user[data-blocked="true"] { opacity: 0.4; }
|
|
44
|
+
/* On a bad network: a pulsing dot before the name (its cursor may freeze). */
|
|
45
|
+
.lr-user[data-net="unstable"] .lr-label span::before { content: ""; display: inline-block; width: 6px; height: 6px; margin: 0 5px 1px 0;
|
|
46
|
+
border-radius: 50%; background: #d97706; box-shadow: 0 0 0 1px rgb(255 255 255 / 70%); animation: lr-pulse 1.2s ease-in-out infinite; }
|
|
47
|
+
@keyframes lr-pulse { 50% { opacity: 0.3; } }
|
|
48
|
+
`,L=`<svg width="23" viewBox="0 0 27 24" fill="currentColor" aria-hidden="true" xmlns="http://www.w3.org/2000/svg"><path d="M2.27 0.06L25.43 8.06C25.66 8.13 25.83 8.26 25.95 8.43C26.07 8.59 26.14 8.79 26.14 8.99C26.14 9.2 26.07 9.4 25.95 9.56C25.83 9.73 25.66 9.86 25.46 9.93L15.35 13.77L11.31 23.37C11.23 23.56 11.1 23.72 10.92 23.83C10.75 23.94 10.54 24 10.33 24C10.12 24 9.91 23.94 9.73 23.82C9.55 23.7 9.42 23.53 9.34 23.34L0.92 1.34C0.86 1.16 0.84 0.97 0.89 0.78C0.93 0.6 1.03 0.43 1.17 0.29C1.31 0.16 1.49 0.07 1.68 0.02C1.88 -0.02 2.08 -0.01 2.27 0.06Z"/></svg>`,R=/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i,z=e=>R.test(e)?e:`#a3a3a3`;function B(e,t,n){e.dataset[t]!==n&&(e.dataset[t]=n)}var V=class{root;options;nodes=new Map;frame=0;style;trace;constructor(e){this.options={smooth:!0,minSmoothGapMs:24,maxSmoothMs:80,...e};let t=e.container.ownerDocument;this.style=t.createElement(`style`),this.style.textContent=I,(e.styleRoot.nodeType===9?e.styleRoot.head:e.styleRoot).appendChild(this.style),this.trace=t.documentElement.hasAttribute(`data-liveroom-trace`),this.root=t.createElement(`div`),this.root.className=`lr-cursors`,e.container.appendChild(this.root)}destroy(){cancelAnimationFrame(this.frame),this.root.remove(),this.style.remove();for(let e of this.nodes.values())clearTimeout(e.focusExitTimer);this.nodes.clear()}videoFor(e){return this.nodes.get(e)?.video}sync(e){let t=new Set;for(let n of e)t.add(n.id),this.update(n);for(let[e,n]of this.nodes)t.has(e)||(clearTimeout(n.focusExitTimer),n.el.remove(),this.nodes.delete(e));this.updateFocus()}setFocusScale(e){let t=e.ownerDocument.defaultView,n=Math.min(4,(t?.innerWidth??1e3)*.8/(512/3),(t?.innerHeight??800)*.7/96);e.style.setProperty(`--focus-scale`,String(n))}updateFocus(){B(this.root,`focus`,String(!!this.root.querySelector(`[data-focus="true"]`)))}update(e){let n=this.nodes.get(e.id)??this.create(e),r=n.el,i=z(e.color);r.style.getPropertyValue(`--color`)!==i&&r.style.setProperty(`--color`,i),n.label.firstChild.textContent!==e.name&&(n.label.firstChild.textContent=e.name),n.video.getAttribute(`aria-label`)!==e.name&&n.video.setAttribute(`aria-label`,e.name),B(r,`self`,String(!!e.self)),B(r,`camera`,String((e.camera||e.type===`admin`&&(e.flags&t.focus)!==0)&&!e.self));let a=String(e.type===`admin`&&!e.self&&(e.flags&t.focus)!==0);r.dataset.focus!==a&&(clearTimeout(n.focusExitTimer),(r.dataset.focus!==void 0||a===`true`)&&B(r,`focusMotion`,`true`),this.setFocusScale(r),B(r,`focus`,a),a===`false`&&r.dataset.focusMotion===`true`&&(n.focusExitTimer=setTimeout(()=>{B(r,`focusMotion`,`false`)},300)),this.updateFocus()),B(r,`blocked`,String(!!e.blocked)),B(r,`net`,e.net??`good`),B(r,`halo`,String((e.flags&t.shift)!==0||!e.self&&(e.flags&t.mouseDown)!==0)),this.setTarget(e.id,e.x,e.y)}setTarget(e,t,n,r=!1){let i=this.nodes.get(e);if(!i||!r&&i.target[0]===t&&i.target[1]===n)return;let a=this.options.map(t,n);if(i.target=[t,n],i.arrived=!1,i.el.dataset.hidden=String(!a),!a)return;let o=performance.now();i.fromX=i.x,i.fromY=i.y,i.toX=a.left,i.toY=a.top,i.start=o;let s=i.lastTargetAt===0?0:o-i.lastTargetAt;i.duration=this.options.smooth&&s>=this.options.minSmoothGapMs?Math.min(s,this.options.maxSmoothMs):0,i.lastTargetAt=o,i.duration===0?this.place(i,i.toX,i.toY,!0):this.schedule()}place(e,t,n,r,i=this.options.scale?.()??1){e.x=t,e.y=n,e.el.style.transform=`translate3d(${t}px, ${n}px, 0) scale(${i})`,r&&(e.arrived=!0,this.trace&&(e.el.dataset.x=e.target[0].toFixed(2),e.el.dataset.y=e.target[1].toFixed(2)))}relayout(){for(let[e,t]of this.nodes)t.el.dataset.focus===`true`&&this.setFocusScale(t.el),t.arrived=!1,t.lastTargetAt=0,this.setTarget(e,t.target[0],t.target[1],!0)}create(e){let t=this.root.ownerDocument.createElement(`div`);t.className=`lr-user`,t.id=`user-${e.id}`,t.innerHTML=`${L.replace(`<svg`,`<svg class="lr-cursor"`)}<div class="lr-label"><span></span><video autoplay muted playsinline></video></div><div class="lr-halo"></div>`;let n=t.querySelector(`.lr-label`);n.firstElementChild.textContent=e.name,this.root.appendChild(t);let r={el:t,label:n,video:t.querySelector(`video`),x:0,y:0,fromX:0,fromY:0,toX:0,toY:0,start:0,duration:0,lastTargetAt:0,target:[NaN,NaN],arrived:!1};return this.nodes.set(e.id,r),r}schedule(){this.frame||=requestAnimationFrame(()=>this.render())}render(){this.frame=0;let e=performance.now(),t=this.options.scale?.()??1,n=!1;for(let r of this.nodes.values()){if(r.arrived)continue;let i=r.duration>0?Math.min(1,(e-r.start)/r.duration):1,a=r.fromX+(r.toX-r.fromX)*i,o=r.fromY+(r.toY-r.fromY)*i;this.place(r,a,o,i>=1,t),i<1&&(n=!0)}n&&this.schedule()}};function H(e,t){let n=e?.closest(`.lr-user`);n&&(n.dataset.live=String(t))}var U=(e,n)=>e.type===`admin`&&((e.id===n.you?n.ownFlags:e.flags)&t.focus)!==0,W=(e,t)=>e.camera||U(e,t),G=class{options;room=null;connecting=null;tracks=new Map;stopped=!1;requested=``;wasFocused=!1;focusExitTimer=null;failures=0;retryTimer=null;constructor(e){this.options=e;let{client:t}=e,n=()=>{if(this.stopped)return;let e=[...t.participants.values()],n=e.some(e=>U(e,t)),r=`${e.some(e=>W(e,t))}/${t.me?W(t.me,t):!1}/${n}/${this.warm()}`;r!==this.requested&&(this.requested=r,this.focusExitTimer&&clearTimeout(this.focusExitTimer),this.wasFocused&&!n?this.focusExitTimer=setTimeout(()=>{this.focusExitTimer=null,this.update()},300):this.update(),this.wasFocused=n)};t.on(`snapshot`,n),t.on(`presence`,n),t.on(`cursors`,n),t.on(`flags`,n)}reattach(){for(let[e,t]of this.tracks){let n=this.options.videoFor(e);n&&!t.attachedElements.includes(n)&&t.attach(n);let r=this.options.client.participants.get(e);H(n,!!r&&(W(r,this.options.client)||!!this.focusExitTimer))}}async stop(){this.stopped=!0,this.focusExitTimer&&clearTimeout(this.focusExitTimer),this.focusExitTimer=null,this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=null,await this.room?.disconnect(),this.room=null,this.clearTracks()}warm(){return!!this.options.preconnect&&[...this.options.client.participants.values()].some(e=>e.type===`admin`)}scheduleRetry(){if(this.stopped||this.retryTimer)return;let e=Math.min(1e3*2**this.failures,15e3);this.failures++,this.retryTimer=setTimeout(()=>{this.retryTimer=null,this.update()},e)}clearTracks(){for(let e of this.tracks.keys())H(this.options.videoFor(e),!1);this.tracks.clear()}async update(){if(this.stopped)return;let{client:e}=this.options;if((this.warm()||[...e.participants.values()].some(t=>W(t,e)))&&!this.room&&!this.connecting&&e.livekit&&(this.connecting=this.connect().finally(()=>this.connecting=null)),this.connecting&&await this.connecting,!this.stopped){if(!this.warm()&&![...e.participants.values()].some(t=>W(t,e))&&this.room){let e=this.room;this.room=null,this.clearTracks(),await e.disconnect()}else{if(this.room&&this.options.publish){let t=e.me?W(e.me,e):!1;this.room.localParticipant.isCameraEnabled!==t&&await this.room.localParticipant.setCameraEnabled(t).catch(e=>this.options.log?.(`camera`,e))}this.reattach()}}}async connect(){let{client:e}=this.options,{Room:t,RoomEvent:n,Track:r}=await Promise.resolve().then(()=>require("./livekit-client.esm-DiyxitqE.cjs")),i=new t({dynacast:!0,adaptiveStream:!0});i.on(n.TrackSubscribed,(e,t,n)=>{t.source===r.Source.Camera&&(this.tracks.set(n.identity,e),this.reattach())}),i.on(n.TrackUnsubscribed,(e,t,n)=>{this.tracks.delete(n.identity),H(this.options.videoFor(n.identity),!1)}),i.on(n.Disconnected,()=>{this.room===i&&(this.room=null,this.clearTracks(),this.scheduleRetry())});try{if(await i.connect(e.livekit.url,e.livekit.token,{autoSubscribe:!0}),this.stopped)return void i.disconnect();this.room=i,this.failures=0}catch(e){this.options.log?.(`livekit connect failed`,e),this.scheduleRetry()}}},K=`16px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif`;function q(e){return`:host { all: initial !important; display: block !important; font: ${K} !important; color: #0f172a !important; text-align: left !important; direction: ltr !important; ${e.split(`;`).map(e=>e.trim()).filter(Boolean).map(e=>`${e.replace(/\s*!important$/,``)} !important;`).join(` `)} }`}function J(){let e=document.createElement(`style`);return e.textContent=`
|
|
55
49
|
* {
|
|
56
50
|
cursor: crosshair !important;
|
|
57
51
|
}
|
|
58
|
-
`,
|
|
52
|
+
`,e}function Y(){let e=document.createElement(`style`);return e.textContent=`
|
|
59
53
|
* {
|
|
60
54
|
pointer-events: none !important;
|
|
61
55
|
user-select: none !important;
|
|
62
56
|
}
|
|
63
|
-
`,n}function Xp(n){Ec(n,"svelte-10y2zdk",'#liveroom-client-element.svelte-10y2zdk.svelte-10y2zdk{font-family:Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;line-height:1.5;font-weight:400;font-synthesis:none;text-rendering:optimizeLegibility;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-text-size-adjust:100%}#users-container.svelte-10y2zdk.svelte-10y2zdk{z-index:999999;position:fixed;inset:0;overflow:hidden;pointer-events:none}.user.svelte-10y2zdk.svelte-10y2zdk{z-index:10;position:absolute;top:0;left:0;user-select:none;transform:translate(var(--x), var(--y));transition:transform 100ms linear;will-change:transform}.user[data-isfocusmode="true"].svelte-10y2zdk.svelte-10y2zdk{transform:translate(calc(50vw - 350px), calc(50svh - 200px)) scale(4)}.user.svelte-10y2zdk .cursor.svelte-10y2zdk{position:absolute;top:0;left:0;color:var(--color);transform-origin:top left;transform:rotate(6deg)}.user[data-isself="true"].svelte-10y2zdk .cursor.svelte-10y2zdk{display:none}.user[data-isfocusmode="true"].svelte-10y2zdk .cursor.svelte-10y2zdk{opacity:0}.user-label.svelte-10y2zdk.svelte-10y2zdk{font-weight:600;font-size:12px;color:black;background-color:var(--color);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;border-radius:9999px;box-shadow:0 1px 2px 0 rgb(0 0 0 / 0.05);display:flex;flex-direction:column;align-items:center}.user-label[data-cameraenabled="false"].svelte-10y2zdk.svelte-10y2zdk{position:absolute;top:18px;left:14px}.user-label[data-cameraenabled="true"].svelte-10y2zdk.svelte-10y2zdk{position:absolute;top:10px;left:6px}.user[data-isfocusmode="true"].svelte-10y2zdk .user-label.svelte-10y2zdk{position:absolute;top:0;left:0;background-color:transparent;overflow:visible;box-shadow:none}.user[data-isself="true"].svelte-10y2zdk .user-label.svelte-10y2zdk{display:none}.user-label.svelte-10y2zdk .user-name.svelte-10y2zdk{display:flex;justify-content:center;align-items:center;background-color:var(--color)}.user[data-isfocusmode="false"].svelte-10y2zdk .user-label[data-cameraenabled="false"] .user-name.svelte-10y2zdk{padding:4px 10px}.user[data-isfocusmode="false"].svelte-10y2zdk .user-label[data-cameraenabled="true"] .user-name.svelte-10y2zdk{position:absolute;inset-inline:0;bottom:0;padding:2px 0 4px 0}.user[data-isfocusmode="true"].svelte-10y2zdk .user-label .user-name.svelte-10y2zdk{transform:translate(0, -4px) scale(0.3);border-radius:9999px;padding:4px 16px;width:fit-content}.user-label.svelte-10y2zdk #video-container.svelte-10y2zdk{overflow:hidden;display:flex;justify-content:center;align-items:center}.user[data-isfocusmode="false"].svelte-10y2zdk .user-label #video-container.svelte-10y2zdk{height:100px;width:100px}.user[data-isfocusmode="true"].svelte-10y2zdk .user-label #video-container.svelte-10y2zdk{height:100px;width:auto;border-radius:4px;box-shadow:0 1px 2px 0 rgb(0 0 0 / 0.05)}.user[data-isfocusmode="false"].svelte-10y2zdk .user-label[data-cameraenabled="false"] #video-container.svelte-10y2zdk{display:none}.user-label.svelte-10y2zdk #video-container video.svelte-10y2zdk{height:100%;aspect-ratio:16 / 9;transform:scaleX(-1);margin-bottom:30px}.user[data-isfocusmode="true"].svelte-10y2zdk .user-label #video-container video.svelte-10y2zdk{margin-bottom:0}.user.svelte-10y2zdk .halo.svelte-10y2zdk{transform:scale(0);z-index:-1;position:absolute;top:-60px;left:-60px;width:120px;height:120px;border-radius:9999px;border:1px solid var(--color75);background-color:var(--color25);transition:transform 200ms ease-in-out;box-shadow:0 1px 2px 0 rgb(0 0 0 / 0.05)}.user.svelte-10y2zdk .halo[data-show="true"].svelte-10y2zdk{transform:scale(1)}.user[data-isfocusmode="true"].svelte-10y2zdk .halo.svelte-10y2zdk{transform:scale(0) !important}#focus_mode_dialog.svelte-10y2zdk.svelte-10y2zdk{z-index:999998;position:fixed;inset:0;background-color:rgb(39, 39, 42, 0.25);backdrop-filter:blur(6px)}')}function $r(n,e,t){const i=n.slice();return i[31]=e[t],i[32]=e,i[33]=t,i}function Hr(n){let e,t=[],i=new Map,s=Hs(Object.values(n[2]));const r=a=>a[31].id;for(let a=0;a<s.length;a+=1){let o=$r(n,s,a),c=r(o);i.set(c,t[a]=qr(c,o))}return{c(){e=Ne("div");for(let a=0;a<t.length;a+=1)t[a].c();V(e,"id","users-container"),V(e,"class","svelte-10y2zdk")},m(a,o){Tt(a,e,o);for(let c=0;c<t.length;c+=1)t[c]&&t[c].m(e,null)},p(a,o){o[0]&30&&(s=Hs(Object.values(a[2])),t=Bc(t,o,r,1,a,s,i,e,Fc,qr,null,$r))},d(a){a&&ut(e);for(let o=0;o<t.length;o+=1)t[o].d()}}}function qr(n,e){let t,i,s,r,a,o,c,d,l=e[31],u,p,m=e[31].name+"",k,v,S,O,w,F,W,he,de;const N=()=>e[15](c,l),X=()=>e[15](null,l);return{key:n,first:null,c(){t=Ne("div"),i=Vs("svg"),s=Vs("path"),r=en(),a=Ne("div"),o=Ne("div"),c=Ne("video"),u=en(),p=Ne("div"),k=ps(m),S=en(),O=Ne("div"),F=en(),V(s,"d","M2.2706 0.0593359L25.4277 8.05957H25.45926C25.65896 8.13153 25.83096 8.25952 25.95221 8.42653C26.07357 8.59354 26.13851 8.79166 26.13851 8.99459C26.13851 9.19751 26.07357 9.39564 25.95221 9.56265C25.83096 9.72966 25.65896 9.85765 25.45926 9.92962L15.3543 13.7698L11.3124 23.37C11.2344 23.5561 11.0994 23.7156 10.9248 23.828C10.7503 23.9402 10.5443 24.0002 10.3335 24C10.1172 24 9.9061 23.9365 9.7291 23.8184C9.552 23.7004 9.4176 23.5332 9.344 23.34L0.9233 1.33937C0.8555 1.16076 0.8426 0.967504 0.8861 0.782189C0.9297 0.596873 1.0278 0.427163 1.1691 0.292901C1.3105 0.158639 1.4891 0.0653762 1.6841 0.0240151C1.8792 -0.0173461 2.0826 -0.00509504 2.2706 0.0593359Z"),V(i,"width","23"),V(i,"viewBox","0 0 27 24"),V(i,"fill","currentColor"),V(i,"aria-hidden","true"),V(i,"xmlns","http://www.w3.org/2000/svg"),V(i,"class","cursor svelte-10y2zdk"),V(c,"id",d=`user-video-${e[31].id}`),V(c,"class","svelte-10y2zdk"),V(o,"id","video-container"),V(o,"class","svelte-10y2zdk"),V(p,"class","user-name svelte-10y2zdk"),V(a,"class","user-label svelte-10y2zdk"),V(a,"data-cameraenabled",v=e[31].camera_enabled),V(O,"class","halo svelte-10y2zdk"),V(O,"data-show",w=(e[31].id==e[1].id&&e[31].is_shift_key_down||e[31].id!=e[1].id&&(e[31].is_shift_key_down||e[31].is_mouse_down))&&e[4]>1),V(t,"id",W="user-"+e[31].id),V(t,"class","user svelte-10y2zdk"),V(t,"data-isself",he=e[31].id==e[1].id),V(t,"data-isfocusmode",de=e[31].is_f_key_down),Ve(t,"--color",e[31].color),Ve(t,"--color25",e[31].color+"25"),Ve(t,"--color75",e[31].color+"75"),Ve(t,"--x",parseFloat(e[31].x)+"vw"),Ve(t,"--y",parseFloat(e[31].y)+"vh"),this.first=t},m(A,H){Tt(A,t,H),we(t,i),we(i,s),we(t,r),we(t,a),we(a,o),we(o,c),N(),we(a,u),we(a,p),we(p,k),we(t,S),we(t,O),we(t,F)},p(A,H){e=A,H[0]&4&&d!==(d=`user-video-${e[31].id}`)&&V(c,"id",d),l!==e[31]&&(X(),l=e[31],N()),H[0]&4&&m!==(m=e[31].name+"")&&Oc(k,m),H[0]&4&&v!==(v=e[31].camera_enabled)&&V(a,"data-cameraenabled",v),H[0]&22&&w!==(w=(e[31].id==e[1].id&&e[31].is_shift_key_down||e[31].id!=e[1].id&&(e[31].is_shift_key_down||e[31].is_mouse_down))&&e[4]>1)&&V(O,"data-show",w),H[0]&4&&W!==(W="user-"+e[31].id)&&V(t,"id",W),H[0]&6&&he!==(he=e[31].id==e[1].id)&&V(t,"data-isself",he),H[0]&4&&de!==(de=e[31].is_f_key_down)&&V(t,"data-isfocusmode",de),H[0]&4&&Ve(t,"--color",e[31].color),H[0]&4&&Ve(t,"--color25",e[31].color+"25"),H[0]&4&&Ve(t,"--color75",e[31].color+"75"),H[0]&4&&Ve(t,"--x",parseFloat(e[31].x)+"vw"),H[0]&4&&Ve(t,"--y",parseFloat(e[31].y)+"vh")},d(A){A&&ut(t),X()}}}function Gr(n){let e;return{c(){e=Ne("div"),V(e,"id","focus_mode_dialog"),V(e,"role","dialog"),V(e,"class","svelte-10y2zdk")},m(t,i){Tt(t,e,i)},d(t){t&&ut(e)}}}function Zp(n){let e,t,i,s=n[1]&&n[2]&&Hr(n),r=n[0]&&Gr();return{c(){e=Ne("div"),s&&s.c(),t=en(),r&&r.c(),i=Rc(),V(e,"id","liveroom-client-element"),V(e,"class","svelte-10y2zdk")},m(a,o){Tt(a,e,o),s&&s.m(e,null),Tt(a,t,o),r&&r.m(a,o),Tt(a,i,o)},p(a,o){a[1]&&a[2]?s?s.p(a,o):(s=Hr(a),s.c(),s.m(e,null)):s&&(s.d(1),s=null),a[0]?r||(r=Gr(),r.c(),r.m(i.parentNode,i)):r&&(r.d(1),r=null)},i:mn,o:mn,d(a){a&&(ut(e),ut(t),ut(i)),s&&s.d(),r&&r.d(a)}}}function us(n,e){if(n.tagName==="BODY")return window;if(hs(n))return n;const{overflowY:t,overflowX:i}=getComputedStyle(n);return e==="vertical"&&["auto","scroll"].includes(t)&&n.scrollHeight>n.clientHeight||e==="horizontal"&&["auto","scroll"].includes(i)&&n.scrollWidth>n.clientWidth?n:n.parentElement?us(n.parentElement,e):window}function hs(n){return n.tagName==="ION-CONTENT"&&typeof n.scrollByPoint=="function"}function ef(n,e,t){let{version:i}=e,{url:s}=e,{room_id:r}=e,{room_token:a}=e,{user_name:o=void 0}=e,{user_color:c=void 0}=e,d,l,u=!1,p=!1,m=Qp(),k=Yp(),v,S,O,w,F={},W;xc(async()=>{console.log(`[Liveroom] Starting in room '${r}' (user name: '${o}')... (v${i})`),de()}),Ac(()=>{N(),Jt(),t(0,p=!1)});async function he(){if(console.log("[LiveKit] Beginning setup..."),t(11,l=new cc({dynacast:!0}).on(E.TrackSubscribed,async(R,pe,fe)=>{switch(console.log("[LiveKit] Track Subscribed",R,pe,fe),console.table({identity:fe.identity,source:pe.source}),pe.source){case T.Source.Camera:{const Y=F[fe.identity];Y&&(console.log(`[LiveKit] Attaching user camera (identity ${fe.identity})`),R.attach(Y));break}}})),console.log("[LiveKit] Created room",l.name),!O)throw new Error("LiveKit websocket URL not set");if(!w)throw new Error("LiveKit token not set");console.log(`[LiveKit] Connecting to '${O}'...`),await l.connect(O,w,{autoSubscribe:!0}),console.log("[LiveKit] Connected to room",l.name)}function de(){console.log(`[Liveroom] Starting session on room ${r}`),d=new Wd({url:s,topic:`liveroom-livestate:rooms:${r}`,params:{room_id:r,room_token:a,user_name:o,user_color:c,referrer:document.referrer,current_url:window.location.href,window_inner_width:window.innerWidth,window_inner_height:window.innerHeight,window_outer_width:window.outerWidth,window_outer_height:window.outerHeight,language:window.navigator.language,user_agent:window.navigator.userAgent},socketOptions:{logger:(R,pe,fe)=>{switch(R){case"error":console.error("Error in socket",pe,fe);break}}}}),d.addEventListener("wheel-from-another-user",({detail:{delta_x:R,delta_y:pe,x:fe,y:Y}})=>{const be=parseInt(R),Pt=parseInt(pe),le=new WheelEvent("wheel",{view:window,bubbles:!0,cancelable:!0,clientX:window.innerWidth*parseFloat(fe)/100,clientY:window.innerHeight*parseFloat(Y)/100,deltaX:be,deltaY:Pt,deltaMode:0}),xn=document.head.contains(k);xn&&document.head.removeChild(k);const Rt=document.elementFromPoint(le.clientX,le.clientY);if(xn&&document.head.appendChild(k),Rt instanceof HTMLElement||Rt instanceof SVGElement)if(Math.abs(Pt)>=Math.abs(be)){const We=us(Rt,"vertical");hs(We)?We.scrollByPoint(0,Pt,0):We.scrollBy({top:Pt,left:0,behavior:"instant"})}else{const We=us(Rt,"horizontal");hs(We)?We.scrollByPoint(be,0,0):We.scrollBy({top:0,left:be,behavior:"instant"})}}),d.addEventListener("click-from-another-user",({detail:{x:R,y:pe}})=>{const fe=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!0,clientX:window.innerWidth*parseFloat(R)/100,clientY:window.innerHeight*parseFloat(pe)/100}),Y=document.head.contains(k);Y&&document.head.removeChild(k);const be=document.elementFromPoint(fe.clientX,fe.clientY);be==null||be.dispatchEvent(fe),Y&&document.head.appendChild(k)}),d.addEventListener("livestate-change",({detail:{state:R}})=>{var pe,fe;(pe=R==null?void 0:R.me)!=null&&pe.name&&R.me.name!=(v==null?void 0:v.name)&&(sessionStorage==null||sessionStorage.setItem(Fs.SESSION_STORAGE_KEY_USER_NAME,R.me.name)),(fe=R==null?void 0:R.me)!=null&&fe.color&&R.me.color!=(v==null?void 0:v.color)&&(sessionStorage==null||sessionStorage.setItem(Fs.SESSION_STORAGE_KEY_USER_COLOR,R.me.color)),t(5,r=R.room_id),t(1,v=R.me),t(2,S=R.users),t(13,O=R.livekit_ws_url),t(14,w=R.livekit_token)}),d.connect(),window.addEventListener("mousemove",X),window.addEventListener("mousedown",A),window.addEventListener("mouseup",H),window.addEventListener("keydown",Be),window.addEventListener("keyup",Wt),window.addEventListener("resize",wt)}function N(){window.removeEventListener("resize",wt),window.removeEventListener("keyup",Wt),window.removeEventListener("keydown",Be),window.removeEventListener("mouseup",H),window.removeEventListener("mousedown",A),window.removeEventListener("mousemove",X),d==null||d.disconnect(),d=void 0,l==null||l.disconnect(),t(11,l=void 0)}function X(R){d&&(v!=null&&v.id)&&d.dispatchEvent(new CustomEvent("mouse_move",{detail:{user_id:v.id,x:Number(R.clientX/window.innerWidth*100).toFixed(2),y:Number(R.clientY/window.innerHeight*100).toFixed(2)}}))}function A(){d&&(v!=null&&v.id)&&d.dispatchEvent(new CustomEvent("mouse_down",{detail:{user_id:v.id}}))}function H(){d&&(v!=null&&v.id)&&d.dispatchEvent(new CustomEvent("mouse_up",{detail:{user_id:v.id}}))}const ze=["Shift"];function Be(R){!R.repeat&&ze.includes(R.key)&&d&&(v!=null&&v.id)&&d.dispatchEvent(new CustomEvent("key_down",{detail:{key:R.key,user_id:v.id}}))}function Wt(R){ze.includes(R.key)&&d&&(v!=null&&v.id)&&d.dispatchEvent(new CustomEvent("key_up",{detail:{key:R.key,user_id:v.id}}))}function wt(){setTimeout(()=>{d&&(v!=null&&v.id)&&d.dispatchEvent(new CustomEvent("window_resize",{detail:{window_inner_width:window.innerWidth,window_inner_height:window.innerHeight,window_outer_width:window.outerWidth,window_outer_height:window.outerHeight,user_id:v.id}}))},100)}function On(){document.head.appendChild(m),document.head.appendChild(k),t(12,u=!0)}function Jt(){document.head.removeChild(m),document.head.removeChild(k),t(12,u=!1)}function Mn(R,pe){Ai[R?"unshift":"push"](()=>{F[pe.id]=R,t(3,F)})}return n.$$set=R=>{"version"in R&&t(6,i=R.version),"url"in R&&t(7,s=R.url),"room_id"in R&&t(5,r=R.room_id),"room_token"in R&&t(8,a=R.room_token),"user_name"in R&&t(9,o=R.user_name),"user_color"in R&&t(10,c=R.user_color)},n.$$.update=()=>{n.$$.dirty[0]&26630&&!l&&v&&S&&O&&w&&he(),n.$$.dirty[0]&4&&t(4,W=Object.keys(S||{}).length),n.$$.dirty[0]&4100&&!u&&S&&Object.values(S).some(R=>R.type=="admin"&&R.is_b_key_down)&&On(),n.$$.dirty[0]&4100&&u&&S&&Object.values(S).filter(R=>R.type=="admin").every(R=>!R.is_b_key_down)&&Jt(),n.$$.dirty[0]&5&&!p&&S&&Object.values(S).some(R=>R.type=="admin"&&R.is_f_key_down)&&t(0,p=!0),n.$$.dirty[0]&5&&p&&S&&Object.values(S).filter(R=>R.type=="admin").every(R=>!R.is_f_key_down)&&t(0,p=!1)},[p,v,S,F,W,r,i,s,a,o,c,l,u,O,w,Mn]}class uc extends zc{constructor(e){super(),qc(this,e,ef,Zp,Sc,{version:6,url:7,room_id:5,room_token:8,user_name:9,user_color:10},Xp,[-1,-1])}get version(){return this.$$.ctx[6]}set version(e){this.$$set({version:e}),ct()}get url(){return this.$$.ctx[7]}set url(e){this.$$set({url:e}),ct()}get room_id(){return this.$$.ctx[5]}set room_id(e){this.$$set({room_id:e}),ct()}get room_token(){return this.$$.ctx[8]}set room_token(e){this.$$set({room_token:e}),ct()}get user_name(){return this.$$.ctx[9]}set user_name(e){this.$$set({user_name:e}),ct()}get user_color(){return this.$$.ctx[10]}set user_color(e){this.$$set({user_color:e}),ct()}}customElements.define("liveroom-client-element",Gc(uc,{version:{},url:{},room_id:{},room_token:{},user_name:{},user_color:{}},[],[],!0));module.exports=uc;
|
|
57
|
+
`,e}function X(){let e=document.createElement(`style`);return e.textContent=`
|
|
58
|
+
html { overflow: hidden !important; scrollbar-gutter: stable !important; }
|
|
59
|
+
* { touch-action: none !important; overscroll-behavior: none !important; }
|
|
60
|
+
`,e}var re=q(`position: fixed; inset: 0; pointer-events: none; z-index: 2147483646; width: auto; height: auto`),Z=class extends HTMLElement{client;layer;cameras;cleanup=[];blockMouseStyle=J();blockPointerStyle=Y();blocked=!1;blockScrollStyle=X();pointer=[50,50];shift=!1;connectedCallback(){let t=this.getAttribute(`room_id`),n=this.getAttribute(`room_token`),r=this.getAttribute(`url`)||`wss://liveroom.app/room`;if(!t||!n||this.client)return;console.log(`[Liveroom] Starting in room '${t}'... (v${e.u})`);let i=this.shadowRoot??this.attachShadow({mode:`open`});i.replaceChildren();let a=document.createElement(`style`);a.textContent=re,i.appendChild(a);let o=document.createElement(`div`);o.id=`liveroom-client-element`,o.style.cssText=`position: fixed; inset: 0; pointer-events: none;`,i.appendChild(o);let s=this.client=new M({url:r,roomId:t,roomToken:n,type:`client`,name:this.getAttribute(`user_name`),color:this.getAttribute(`user_color`),viewport:Q,analytics:{url:location.href,referrer:document.referrer,language:navigator.language,user_agent:navigator.userAgent}});this.layer=new V({container:o,styleRoot:i,map:(e,t)=>({left:e/100*innerWidth,top:t/100*innerHeight})}),this.cameras=new G({preconnect:!0,client:s,publish:!1,videoFor:e=>this.layer?.videoFor(e)});let c=()=>this.render();s.on(`snapshot`,()=>{let t=s.me;t?.name&&sessionStorage?.setItem(e.l,t.name),t?.color&&sessionStorage?.setItem(e.c,t.color),c()}),s.on(`presence`,()=>{let t=s.me;t?.name&&sessionStorage?.setItem(e.l,t.name),c(),this.cameras?.reattach()}),s.on(`cursors`,({ids:e})=>{let t=!1;for(let n of e){let e=s.participants.get(n);e&&(this.layer.update(e),e.type===`admin`&&(t=!0))}t&&this.updateBlocked()}),s.on(`click`,({x:e,y:t})=>this.replayClick(e/100,t/100)),s.on(`wheel`,({x:e,y:t,dx:n,dy:r})=>this.replayWheel(e/100,t/100,n,r)),s.on(`refused`,e=>console.error(`[Liveroom] Refused: ${e}`)),this.netPill(i,s),s.connect();let l=e=>{this.blocked&&(e.preventDefault(),e.stopImmediatePropagation())};this.listen(window,`wheel`,l,{capture:!0,passive:!1}),this.listen(window,`touchmove`,l,{capture:!0,passive:!1}),this.listen(window,`keydown`,e=>{[`ArrowUp`,`ArrowDown`,`ArrowLeft`,`ArrowRight`,`PageUp`,`PageDown`,`Home`,`End`,` `].includes(e.key)&&l(e)},{capture:!0}),this.listen(window,`mousemove`,e=>{this.pointer=[e.clientX/innerWidth*100,e.clientY/innerHeight*100],s.move(this.pointer[0],this.pointer[1]),this.shift&&this.renderSelf()}),this.listen(window,`mousedown`,()=>s.setFlag(`mouseDown`,!0)),this.listen(window,`mouseup`,()=>s.setFlag(`mouseDown`,!1)),this.listen(window,`keydown`,e=>{e.key===`Shift`&&!e.repeat&&(this.shift=!0,s.setFlag(`shift`,!0),c())}),this.listen(window,`keyup`,e=>{e.key===`Shift`&&(this.shift=!1,s.setFlag(`shift`,!1),c())});let u;this.listen(window,`resize`,()=>{clearTimeout(u),u=window.setTimeout(()=>{s.setState({viewport:Q()}),this.layer?.relayout()},100)});let d=location.href,f=window.setInterval(()=>{location.href!==d&&s.setState({url:d=location.href})},500);this.cleanup.push(()=>clearInterval(f))}disconnectedCallback(){for(let e of this.cleanup.splice(0))e();this.cameras?.stop(),this.client?.disconnect(),this.layer?.destroy(),this.setBlocked(!1),this.client=this.layer=this.cameras=void 0}netPill(e,t){let n=document.createElement(`style`);n.textContent=`
|
|
61
|
+
.lr-net { position: fixed; left: 12px; bottom: 12px; display: flex; align-items: center; gap: 6px; padding: 4px 10px;
|
|
62
|
+
border-radius: 9999px; background: rgb(15 23 42 / 85%); color: white; font: 500 12px/1.5 system-ui, sans-serif;
|
|
63
|
+
pointer-events: none; opacity: 0; transform: translateY(4px); transition: opacity 200ms, transform 200ms; }
|
|
64
|
+
.lr-net[data-shown="true"] { opacity: 1; transform: none; }
|
|
65
|
+
.lr-net::before { content: ""; width: 7px; height: 7px; border-radius: 50%; background: #f59e0b; }
|
|
66
|
+
.lr-net[data-quality="offline"]::before { background: #ef4444; }`;let r=document.createElement(`div`);r.className=`lr-net`,r.setAttribute(`role`,`status`),e.append(n,r);let i,a=t.on(`quality`,e=>{clearTimeout(i),e===`good`?r.dataset.shown=`false`:i=window.setTimeout(()=>{r.dataset.quality=e,r.textContent=e===`offline`?`Reconnecting…`:`Unstable connection`,r.dataset.shown=`true`},500)});this.cleanup.push(a,()=>clearTimeout(i),()=>(n.remove(),r.remove()))}listen(e,t,n,r){e.addEventListener(t,n,r),this.cleanup.push(()=>e.removeEventListener(t,n,r))}updateBlocked(){let e=[...this.client.participants.values()].filter(e=>e.type===`admin`);this.setBlocked(e.some(e=>(e.flags&(t.block|t.focus))!==0))}render(){let e=this.client;this.updateBlocked();let n=[];for(let r of e.participants.values())r.id===e.you?n.push({...r,self:!0,x:this.pointer[0],y:this.pointer[1],flags:this.shift?t.shift:0}):n.push(r);this.layer.sync(n)}renderSelf(){let e=this.client?.me;e&&this.layer?.update({...e,self:!0,x:this.pointer[0],y:this.pointer[1],flags:this.shift?t.shift:0})}setBlocked(e){if(e!==this.blocked){this.blocked=e;for(let t of[this.blockMouseStyle,this.blockPointerStyle,this.blockScrollStyle])e?document.head.appendChild(t):t.remove()}}elementAt(e,t){let n=this.blocked&&this.blockPointerStyle.isConnected;n&&this.blockPointerStyle.remove();let r=document.elementFromPoint(e,t);return n&&document.head.appendChild(this.blockPointerStyle),r}replayClick(e,t){let n=innerWidth*e/100,r=innerHeight*t/100;this.elementAt(n,r)?.dispatchEvent(new MouseEvent(`click`,{view:window,bubbles:!0,cancelable:!0,clientX:n,clientY:r}))}replayWheel(e,t,n,r){let i=this.elementAt(innerWidth*e/100,innerHeight*t/100);if(!(i instanceof HTMLElement||i instanceof SVGElement))return;let a=Math.abs(r)>=Math.abs(n),o=ie(i,a?`vertical`:`horizontal`);$(o)?o.scrollByPoint(a?0:n,a?r:0,0):o.scrollBy({top:a?r:0,left:a?0:n,behavior:`instant`})}};function Q(){return[innerWidth,innerHeight,outerWidth,outerHeight]}function $(e){return e instanceof HTMLElement&&e.tagName===`ION-CONTENT`&&`scrollByPoint`in e}function ie(e,t){for(let n=e;n&&n!==document.body;n=n.parentElement){if($(n))return n;let{overflowY:e,overflowX:r}=getComputedStyle(n);if((t===`vertical`?[`auto`,`scroll`].includes(e)&&n.scrollHeight>n.clientHeight:[`auto`,`scroll`].includes(r)&&n.scrollWidth>n.clientWidth)&&(n instanceof HTMLElement||n instanceof SVGElement))return n}return window}customElements.get(`liveroom-client-element`)||customElements.define(`liveroom-client-element`,Z),exports.LiveroomClientElement=Z;
|