liveroom-client-element 0.0.50 → 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 -57
- package/dist/liveroom-client-element.js +1543 -19338
- package/dist/main.cjs +1 -1
- package/dist/main.js +37 -59
- package/package.json +14 -14
- package/dist/constants-Bnl9ENcX.js +0 -15
- package/dist/constants-DPiV-x94.cjs +0 -1
|
@@ -1,64 +1,66 @@
|
|
|
1
|
-
"use strict";var Dc=Object.defineProperty;var Nc=(i,e,t)=>e in i?Dc(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var B=(i,e,t)=>(Nc(i,typeof e!="symbol"?e+"":e,t),t);const ar=require("./constants-DPiV-x94.cjs");function Ti(){}function ko(i){return i()}function cr(){return Object.create(null)}function Ri(i){i.forEach(ko)}function To(i){return typeof i=="function"}function Lc(i,e){return i!=i?e==e:i!==e||i&&typeof i=="object"||typeof i=="function"}function Uc(i){return Object.keys(i).length===0}function Ae(i,e){i.appendChild(e)}function jc(i,e,t){const n=Fc(i);if(!n.getElementById(e)){const s=Ve("style");s.id=e,s.textContent=t,Bc(n,s)}}function Fc(i){if(!i)return document;const e=i.getRootNode?i.getRootNode():i.ownerDocument;return e&&e.host?e:i.ownerDocument}function Bc(i,e){return Ae(i.head||i,e),e.sheet}function Ot(i,e,t){i.insertBefore(e,t||null)}function kt(i){i.parentNode&&i.parentNode.removeChild(i)}function Ve(i){return document.createElement(i)}function dr(i){return document.createElementNS("http://www.w3.org/2000/svg",i)}function Ms(i){return document.createTextNode(i)}function ui(){return Ms(" ")}function Vc(){return Ms("")}function K(i,e,t){t==null?i.removeAttribute(e):i.getAttribute(e)!==t&&i.setAttribute(e,t)}function qc(i){return Array.from(i.childNodes)}function $c(i,e){e=""+e,i.data!==e&&(i.data=e)}function We(i,e,t,n){t==null?i.style.removeProperty(e):i.style.setProperty(e,t,"")}function Hc(i){const e={};return i.childNodes.forEach(t=>{e[t.slot||"default"]=!0}),e}let Ci;function pi(i){Ci=i}function Co(){if(!Ci)throw new Error("Function called outside component initialization");return Ci}function zc(i){Co().$$.on_mount.push(i)}function Gc(i){Co().$$.on_destroy.push(i)}const $t=[],zn=[];let Gt=[];const lr=[],Wc=Promise.resolve();let Gn=!1;function Kc(){Gn||(Gn=!0,Wc.then(mt))}function Wn(i){Gt.push(i)}const _n=new Set;let Ft=0;function mt(){if(Ft!==0)return;const i=Ci;do{try{for(;Ft<$t.length;){const e=$t[Ft];Ft++,pi(e),Jc(e.$$)}}catch(e){throw $t.length=0,Ft=0,e}for(pi(null),$t.length=0,Ft=0;zn.length;)zn.pop()();for(let e=0;e<Gt.length;e+=1){const t=Gt[e];_n.has(t)||(_n.add(t),t())}Gt.length=0}while($t.length);for(;lr.length;)lr.pop()();Gn=!1,_n.clear(),pi(i)}function Jc(i){if(i.fragment!==null){i.update(),Ri(i.before_update);const e=i.dirty;i.dirty=[-1],i.fragment&&i.fragment.p(i.ctx,e),i.after_update.forEach(Wn)}}function Qc(i){const e=[],t=[];Gt.forEach(n=>i.indexOf(n)===-1?e.push(n):t.push(n)),t.forEach(n=>n()),Gt=e}const Yc=new Set;function So(i,e){i&&i.i&&(Yc.delete(i),i.i(e))}function ur(i){return(i==null?void 0:i.length)!==void 0?i:Array.from(i)}function Xc(i,e){i.d(1),e.delete(i.key)}function Zc(i,e,t,n,s,r,o,a,c,d,l,u){let h=i.length,f=r.length,m=h;const g={};for(;m--;)g[i[m].key]=m;const T=[],C=new Map,M=new Map,j=[];for(m=f;m--;){const R=u(s,r,m),D=t(R);let F=o.get(D);F?j.push(()=>F.p(R,e)):(F=d(D,R),F.c()),C.set(D,T[m]=F),D in g&&M.set(D,Math.abs(m-g[D]))}const k=new Set,y=new Set;function _(R){So(R,1),R.m(a,l),o.set(R.key,R),l=R.first,f--}for(;h&&f;){const R=T[f-1],D=i[h-1],F=R.key,U=D.key;R===D?(l=R.first,h--,f--):C.has(U)?!o.has(F)||k.has(F)?_(R):y.has(U)?h--:M.get(F)>M.get(U)?(y.add(F),_(R)):(k.add(U),h--):(c(D,o),h--)}for(;h--;){const R=i[h];C.has(R.key)||c(R,o)}for(;f;)_(T[f-1]);return Ri(j),T}function ed(i,e,t){const{fragment:n,after_update:s}=i.$$;n&&n.m(e,t),Wn(()=>{const r=i.$$.on_mount.map(ko).filter(To);i.$$.on_destroy?i.$$.on_destroy.push(...r):Ri(r),i.$$.on_mount=[]}),s.forEach(Wn)}function td(i,e){const t=i.$$;t.fragment!==null&&(Qc(t.after_update),Ri(t.on_destroy),t.fragment&&t.fragment.d(e),t.on_destroy=t.fragment=null,t.ctx=[])}function id(i,e){i.$$.dirty[0]===-1&&($t.push(i),Kc(),i.$$.dirty.fill(0)),i.$$.dirty[e/31|0]|=1<<e%31}function nd(i,e,t,n,s,r,o=null,a=[-1]){const c=Ci;pi(i);const d=i.$$={fragment:null,ctx:[],props:r,update:Ti,not_equal:s,bound:cr(),on_mount:[],on_destroy:[],on_disconnect:[],before_update:[],after_update:[],context:new Map(e.context||(c?c.$$.context:[])),callbacks:cr(),dirty:a,skip_bound:!1,root:e.target||c.$$.root};o&&o(d.root);let l=!1;if(d.ctx=t?t(i,e.props||{},(u,h,...f)=>{const m=f.length?f[0]:h;return d.ctx&&s(d.ctx[u],d.ctx[u]=m)&&(!d.skip_bound&&d.bound[u]&&d.bound[u](m),l&&id(i,u)),h}):[],d.update(),l=!0,Ri(d.before_update),d.fragment=n?n(d.ctx):!1,e.target){if(e.hydrate){const u=qc(e.target);d.fragment&&d.fragment.l(u),u.forEach(kt)}else d.fragment&&d.fragment.c();e.intro&&So(i.$$.fragment),ed(i,e.target,e.anchor),mt()}pi(c)}let Eo;typeof HTMLElement=="function"&&(Eo=class extends HTMLElement{constructor(e,t,n){super();B(this,"$$ctor");B(this,"$$s");B(this,"$$c");B(this,"$$cn",!1);B(this,"$$d",{});B(this,"$$r",!1);B(this,"$$p_d",{});B(this,"$$l",{});B(this,"$$l_u",new Map);this.$$ctor=e,this.$$s=t,n&&this.attachShadow({mode:"open"})}addEventListener(e,t,n){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,n)}removeEventListener(e,t,n){if(super.removeEventListener(e,t,n),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 o;return{c:function(){o=Ve("slot"),r!=="default"&&K(o,"name",r)},m:function(d,l){Ot(d,o,l)},d:function(d){d&&kt(o)}}}};if(await Promise.resolve(),!this.$$cn||this.$$c)return;const t={},n=Hc(this);for(const r of this.$$s)r in n&&(t[r]=[e(r)]);for(const r of this.attributes){const o=this.$$g_p(r.name);o in this.$$d||(this.$$d[o]=Bi(o,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 o=Bi(r,this.$$d[r],this.$$p_d,"toAttribute");o==null?this.removeAttribute(this.$$p_d[r].attribute||r):this.setAttribute(this.$$p_d[r].attribute||r,o)}this.$$r=!1};this.$$c.$$.after_update.push(s),s();for(const r in this.$$l)for(const o of this.$$l[r]){const a=this.$$c.$on(r,o);this.$$l_u.set(o,a)}this.$$l={}}}attributeChangedCallback(e,t,n){var s;this.$$r||(e=this.$$g_p(e),this.$$d[e]=Bi(e,n,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 Bi(i,e,t,n){var r;const s=(r=t[i])==null?void 0:r.type;if(e=s==="Boolean"&&typeof e!="boolean"?e!=null:e,!n||!t[i])return e;if(n==="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 sd(i,e,t,n,s,r){let o=class extends Eo{constructor(){super(i,t,s),this.$$p_d=e}static get observedAttributes(){return Object.keys(e).map(a=>(e[a].attribute||a).toLowerCase())}};return Object.keys(e).forEach(a=>{Object.defineProperty(o.prototype,a,{get(){return this.$$c&&a in this.$$c?this.$$c[a]:this.$$d[a]},set(c){var d;c=Bi(a,c,e),this.$$d[a]=c,(d=this.$$c)==null||d.$set({[a]:c})}})}),n.forEach(a=>{Object.defineProperty(o.prototype,a,{get(){var c;return(c=this.$$c)==null?void 0:c[a]}})}),i.element=o,o}class rd{constructor(){B(this,"$$");B(this,"$$set")}$destroy(){td(this,1),this.$destroy=Ti}$on(e,t){if(!To(t))return Ti;const n=this.$$.callbacks[e]||(this.$$.callbacks[e]=[]);return n.push(t),()=>{const s=n.indexOf(t);s!==-1&&n.splice(s,1)}}$set(e){this.$$set&&!Uc(e)&&(this.$$.skip_bound=!0,this.$$set(e),this.$$.skip_bound=!1)}}const od="4";typeof window<"u"&&(window.__svelte||(window.__svelte={v:new Set})).v.add(od);const{isArray:ad}=Array,cd=Object.keys,Si=i=>{if(!i)return i;if(ad(i)){const e=[],t=i.length;for(let n=0;n<t;n++)e.push(Si(i[n]));return e}else if(typeof i=="object"){const e=cd(i),t=e.length,n={};for(let s=0;s<t;s++){const r=e[s];n[r]=Si(i[r])}return n}return i};class Ne{constructor(e){B(this,"path");B(this,"from");this.path=e}}const dd=/~1/g,ld=/~0/g,ud=/~/g,hd=/\//g;function fd(i){return i.indexOf("~")===-1?i:i.replace(dd,"/").replace(ld,"~")}function pd(i){return i.indexOf("/")===-1&&i.indexOf("~")===-1?i:i.replace(ud,"~0").replace(hd,"~1")}function md(i){return i?i.slice(1).split("/").map(fd):[]}function Z(i){return gd(i)?"":"/"+i.map(e=>pd(String(e))).join("/")}const G=i=>typeof i=="string"?md(i):i,gd=i=>!i.length,vd=Object.prototype.hasOwnProperty;function yd(i,e){return vd.call(i,e)}const{isArray:wo}=Array,oe=(i,e)=>{const t=e.length;if(!t)return{val:i};let n,s;for(let o=0;o<t;o++)if(n=i,s=e[o],wo(n)){const a=n.length;if(s==="-")s=a;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")}i=n[s]}else if(typeof n=="object"&&n)i=yd(n,s)?n[s]:void 0;else throw new Error("NOT_FOUND");return{val:i,obj:n,key:s}},Ii=i=>wo(i.obj)&&typeof i.key=="number",gn=i=>typeof i.obj=="object"&&typeof i.key=="string";class Ds extends Ne{constructor(t,n){super(t);B(this,"value");this.value=n}op(){return"add"}code(){return 0}apply(t){const{val:n,key:s,obj:r}=oe(t,this.path),o=Si(this.value);if(!r)t=o;else if(typeof s=="string")r[s]=o;else{const a=r.length;if(s<a)r.splice(s,0,o);else{if(s>a)throw new Error("INVALID_INDEX");r.push(o)}}return{doc:t,old:n}}toJson(t){return{op:"add",path:Z(this.path),value:this.value}}toCompact(t,n){return[n?"add":0,this.path,this.value]}encode(t){t.encodeArrayHeader(3),t.writer.u8(0),t.encodeArray(this.path),t.encodeAny(this.value)}}class _o extends Ne{constructor(t,n){super(t);B(this,"oldValue");this.oldValue=n}op(){return"remove"}code(){return 1}apply(t){const n=oe(t,this.path);if(n.val===void 0)throw new Error("NOT_FOUND");return gn(n)?delete n.obj[n.key]:Ii(n)?n.val!==void 0&&n.obj.splice(n.key,1):t=null,{doc:t,old:n.val}}toJson(t){const n={op:"remove",path:Z(this.path)};return this.oldValue!==void 0&&(n.oldValue=this.oldValue),n}toCompact(t,n){const s=n?"remove":1;return this.oldValue===void 0?[s,this.path]:[s,this.path,this.oldValue]}encode(t,n){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 bd extends Ne{constructor(t,n,s){super(t);B(this,"value");B(this,"oldValue");this.value=n,this.oldValue=s}op(){return"replace"}code(){return 2}apply(t){const n=oe(t,this.path);if(n.val===void 0)throw new Error("NOT_FOUND");return gn(n)?n.obj[n.key]=this.value:Ii(n)?n.obj[n.key]=this.value:t=this.value,{doc:t,old:n.val}}toJson(t){const n={op:"replace",path:Z(this.path),value:this.value};return this.oldValue!==void 0&&(n.oldValue=this.oldValue),n}toCompact(t,n){const s=n?"replace":2;return this.oldValue===void 0?[s,this.path,this.value]:[s,this.path,this.value,this.oldValue]}encode(t,n){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 kd extends Ne{constructor(t,n){super(t);B(this,"from");this.from=n}op(){return"move"}code(){return 4}apply(t){const n=new _o(G(this.from),void 0).apply(t);return new Ds(this.path,n.old).apply(n.doc)}toJson(t){return{op:"move",path:Z(this.path),from:Z(this.from)}}toCompact(t,n){return[n?"move":4,this.path,this.from]}encode(t,n){t.encodeArrayHeader(3),t.writer.u8(4),t.encodeArray(this.path),t.encodeArray(this.from)}}class Td extends Ne{constructor(t,n){super(t);B(this,"from");this.from=n}op(){return"copy"}code(){return 3}apply(t){const{val:n}=oe(t,this.from);if(n===void 0)throw new Error("NOT_FOUND");return new Ds(this.path,Si(n)).apply(t)}toJson(t){return{op:"copy",path:Z(this.path),from:Z(this.from)}}toCompact(t,n){return[n?"copy":3,this.path,this.from]}encode(t,n){t.encodeArrayHeader(3),t.writer.u8(3),t.encodeArray(this.path),t.encodeArray(this.from)}}class we extends Ne{apply(e){if(!this.test(e))throw new Error("TEST");return{doc:e}}}const sn=(i,e)=>{if(i===e)return!0;if(i&&e&&typeof i=="object"&&typeof e=="object"){if(i.constructor!==e.constructor)return!1;let t,n,s;if(Array.isArray(i)){if(t=i.length,t!==e.length)return!1;for(n=t;n--!==0;)if(!sn(i[n],e[n]))return!1;return!0}if(s=Object.keys(i),t=s.length,t!==Object.keys(e).length)return!1;for(n=t;n--!==0;){const r=s[n];if(!sn(i[r],e[r]))return!1}return!0}return!1};class Cd extends we{constructor(t,n,s){super(t);B(this,"value");B(this,"not");this.value=n,this.not=s}op(){return"test"}code(){return 5}test(t){const{val:n}=oe(t,this.path);if(n===void 0)return!!this.not;const s=sn(n,this.value);return this.not?!s:s}toJson(t){const n={op:"test",path:Z(t?this.path.slice(t.path.length):this.path),value:this.value};return this.not&&(n.not=this.not),n}toCompact(t,n){const s=t?this.path.slice(t.path.length):this.path,r=n?"test":5;return this.not?[r,s,this.value,1]:[r,s,this.value]}encode(t,n){t.encodeArrayHeader(this.not?4:3),t.writer.u8(5),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeAny(this.value),this.not&&t.writer.u8(1)}}class Sd extends Ne{constructor(e){super(e)}op(){return"flip"}code(){return 8}apply(e){const t=oe(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 Ed extends Ne{constructor(t,n){super(t);B(this,"inc");this.inc=n}op(){return"inc"}code(){return 9}apply(t){const n=oe(t,this.path),s=this.inc+Number(n.val);return n.obj?n.obj[n.key]=s:t=s,{doc:t,old:n.val}}toJson(t){return{op:"inc",path:Z(this.path),inc:this.inc}}toCompact(t,n){return[n?"inc":9,this.path,this.inc]}encode(t,n){t.encodeArrayHeader(3),t.writer.u8(9),t.encodeArray(this.path),t.encodeNumber(this.inc)}}class wd extends Ne{constructor(t,n,s){super(t);B(this,"pos");B(this,"str");this.pos=n,this.str=s}op(){return"str_ins"}code(){return 6}apply(t){const{val:n,key:s,obj:r}=oe(t,this.path);if(typeof n!="string"){if(n!==void 0)throw new Error("NOT_A_STRING");if(this.pos!==0)throw new Error("POS")}const o=typeof n=="string"?n:"",a=Math.min(this.pos,o.length),c=o.slice(0,a),d=o.slice(a),l=c+this.str+d;return r?r[s]=l:t=l,{doc:t,old:n}}toJson(t){return{op:"str_ins",path:Z(this.path),pos:this.pos,str:this.str}}toCompact(t,n){return[n?"str_ins":6,this.path,this.pos,this.str]}encode(t,n){t.encodeArrayHeader(4),t.writer.u8(6),t.encodeArray(this.path),t.encodeNumber(this.pos),t.encodeString(this.str)}}class _d extends Ne{constructor(t,n,s,r){super(t);B(this,"pos");B(this,"str");B(this,"len");this.pos=n,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:n,key:s,obj:r}=oe(t,this.path);if(typeof n!="string")throw new Error("NOT_A_STRING");const o=n.length,a=Math.min(this.pos,n.length),c=Math.min(a,o),d=this.str!==void 0?this.str.length:this.len,l=Math.min(a+d,o),u=n.slice(0,c),h=n.substr(l),f=u+h;return r?r[s]=f:t=f,{doc:t,old:n}}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,n){const s=n?"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,n){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:Pd}=Array,Kn=i=>!!i&&typeof i=="object"&&typeof i.text=="string",Jn=i=>!!i&&typeof i=="object"&&Pd(i.children),Rd=(i,e)=>{const t=new RegExp(i,e?"i":void 0);return n=>t.test(n)};class Id extends Ne{constructor(t,n,s){super(t);B(this,"pos");B(this,"props");this.pos=n,this.props=s}op(){return"split"}code(){return 10}apply(t){const n=oe(t,this.path);if(n.val===void 0)throw new Error("NOT_FOUND");const s=this.split(n.val);return gn(n)?n.obj[n.key]=s:Ii(n)?(n.obj[n.key]=s[0],n.obj.splice(n.key+1,0,s[1])):t=s,{doc:t,old:n.val}}split(t){if(typeof t=="string"){const{pos:n,props:s}=this,r=t.slice(0,n),o=t.slice(n);return s?[{...s,text:r},{...s,text:o}]:[r,o]}else if(Kn(t)){const{pos:n,props:s}=this,r=t.text.slice(0,n),o=t.text.slice(n);return[{...t,...s,text:r},{...t,...s,text:o}]}else if(Jn(t)){const{pos:n,props:s}=this,r=t.children.slice(0,n),o=t.children.slice(n);return[{...t,...s,children:r},{...t,...s,children:o}]}else if(typeof t=="number"){const{pos:n}=this;return[n,t-n]}else return[t,t]}toJson(t){const n={op:"split",path:Z(this.path),pos:this.pos};return this.props&&(n.props=this.props),n}toCompact(t,n){const s=n?"split":10;return this.props?[s,this.path,this.pos,this.props]:[s,this.path,this.pos]}encode(t,n){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 Od extends Ne{constructor(t,n,s){super(t);B(this,"pos");B(this,"props");this.pos=n,this.props=s}op(){return"merge"}code(){return 11}apply(t){const n=oe(t,this.path);if(!Ii(n))throw new Error("INVALID_TARGET");if(n.key<=0)throw new Error("INVALID_KEY");const s=n.obj[n.key-1],r=n.obj[n.key],o=this.merge(s,r);return n.obj[n.key-1]=o,n.obj.splice(n.key,1),{doc:t,old:[s,r]}}merge(t,n){return typeof t=="string"&&typeof n=="string"||typeof t=="number"&&typeof n=="number"?t+n:Kn(t)&&Kn(n)?{...t,...n,text:t.text+n.text}:Jn(t)&&Jn(n)?{...t,...n,children:[...t.children,...n.children]}:[t,n]}toJson(t){const n={op:"merge",path:Z(this.path),pos:this.pos};return this.props&&(n.props=this.props),n}toCompact(t,n){const s=n?"merge":11;return this.props?[s,this.path,this.pos,this.props]:[s,this.path,this.pos]}encode(t,n){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:xd}=Array;class Ad extends Ne{constructor(t,n,s){super(t);B(this,"props");B(this,"deleteNull");this.props=n,this.deleteNull=s}op(){return"extend"}code(){return 12}apply(t){const n=oe(t,this.path);return Ii(n)?n.val!==void 0&&(n.obj[n.key]=this.extend(n.val)):gn(n)?n.obj[n.key]=this.extend(n.val):t=this.extend(t),{doc:t}}extend(t){if(xd(t)||typeof t!="object"||!t)return t;for(const[n,s]of Object.entries(this.props)){if(n==="__proto__")throw new Error("NO_PROTO");if(s===null&&this.deleteNull){delete t[n];continue}t[n]=s}return t}toJson(t){const n={op:"extend",path:Z(this.path),props:this.props};return this.deleteNull&&(n.deleteNull=this.deleteNull),n}toCompact(t,n){const s=n?"extend":12;return this.deleteNull?[s,this.path,this.props,1]:[s,this.path,this.props]}encode(t,n){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 Md extends we{constructor(e){super(e)}op(){return"defined"}code(){return 31}test(e){const{val:t}=oe(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 Dd extends we{constructor(e){super(e)}op(){return"undefined"}code(){return 38}test(e){try{const{val:t}=oe(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:Nd}=Array;class Ld extends we{constructor(t,n){super(t);B(this,"type");this.type=n}op(){return"test_type"}code(){return 39}test(t){const{val:n}=oe(t,this.path);return n===null?this.type.indexOf("null")>-1:Nd(n)?this.type.indexOf("array")>-1:this.type.indexOf(typeof n)>-1||typeof n=="number"&&n===Math.round(n)&&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,n){return[n?"test_type":39,t?this.path.slice(t.path.length):this.path,this.type]}encode(t,n){t.encodeArrayHeader(3),t.writer.u8(39),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeArray(this.type)}}class Ud extends we{constructor(t,n,s,r){super(t);B(this,"pos");B(this,"str");B(this,"not");this.pos=n,this.str=s,this.not=r}op(){return"test_string"}code(){return 40}test(t){const{val:n}=oe(t,this.path);if(typeof n!="string")return!1;const s=n.length,r=Math.min(this.pos,s),o=Math.min(this.pos+this.str.length,s),a=n.substring(r,o)===this.str;return this.not?!a:a}toJson(t){const n={op:"test_string",path:Z(t?this.path.slice(t.path.length):this.path),pos:this.pos,str:this.str};return this.not&&(n.not=this.not),n}toCompact(t,n){const s=n?"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,n){t.encodeArrayHeader(this.not?5:4),t.writer.u8(40),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeNumber(this.pos),t.encodeString(this.str),this.not&&t.writer.u8(1)}}class jd extends we{constructor(t,n,s){super(t);B(this,"len");B(this,"not");this.len=n,this.not=s}op(){return"test_string_len"}code(){return 41}test(t){const{val:n}=oe(t,this.path);if(typeof n!="string")return!1;const r=n.length>=this.len;return this.not?!r:r}toJson(t){const n={op:"test_string_len",path:Z(t?this.path.slice(t.path.length):this.path),len:this.len};return this.not&&(n.not=this.not),n}toCompact(t,n){const s=n?"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,n){t.encodeArrayHeader(this.not?4:3),t.writer.u8(41),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeNumber(this.len),this.not&&t.writer.u8(1)}}class Fd extends we{constructor(t,n,s){super(t);B(this,"value");B(this,"ignore_case");this.value=n,this.ignore_case=s}op(){return"contains"}code(){return 30}test(t){const{val:n}=oe(t,this.path);if(typeof n!="string")return!1;const s=this.ignore_case?n.toLowerCase():n,r=this.ignore_case?this.value.toLowerCase():this.value;return s.indexOf(r)>-1}toJson(t){const n={op:"contains",path:Z(t?this.path.slice(t.path.length):this.path),value:this.value};return this.ignore_case&&(n.ignore_case=this.ignore_case),n}toCompact(t,n){const s=n?"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,n){const s=this.ignore_case;t.encodeArrayHeader(s?4:3),t.writer.u8(30),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeString(this.value),s&&t.writer.u8(1)}}class Bd extends we{constructor(t,n,s){super(t);B(this,"value");B(this,"ignore_case");this.value=n,this.ignore_case=s}op(){return"ends"}code(){return 32}test(t){const{val:n}=oe(t,this.path);if(typeof n!="string")return!1;const s=this.ignore_case?n.toLowerCase():n,r=this.ignore_case?this.value.toLowerCase():this.value;return s.endsWith(r)}toJson(t){const n={op:"ends",path:Z(t?this.path.slice(t.path.length):this.path),value:this.value};return this.ignore_case&&(n.ignore_case=this.ignore_case),n}toCompact(t,n){const s=n?"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,n){const s=this.ignore_case;t.encodeArrayHeader(s?4:3),t.writer.u8(32),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeString(this.value),s&&t.writer.u8(1)}}class Vd extends we{constructor(t,n,s){super(t);B(this,"value");B(this,"ignore_case");this.value=n,this.ignore_case=s}op(){return"starts"}code(){return 37}test(t){const{val:n}=oe(t,this.path);if(typeof n!="string")return!1;const s=this.ignore_case?n.toLowerCase():n,r=this.ignore_case?this.value.toLowerCase():this.value;return s.startsWith(r)}toJson(t){const n={op:"starts",path:Z(t?this.path.slice(t.path.length):this.path),value:this.value};return this.ignore_case&&(n.ignore_case=this.ignore_case),n}toCompact(t,n){const s=n?"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,n){const s=this.ignore_case;t.encodeArrayHeader(s?4:3),t.writer.u8(37),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeString(this.value),s&&t.writer.u8(1)}}class qd extends we{constructor(t,n){super(t);B(this,"value");this.value=n}op(){return"in"}code(){return 33}test(t){const{val:n}=oe(t,this.path);for(const s of this.value)if(sn(n,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,n){return[n?"in":33,t?this.path.slice(t.path.length):this.path,this.value]}encode(t,n){t.encodeArrayHeader(3),t.writer.u8(33),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeArray(this.value)}}class $d extends we{constructor(t,n){super(t);B(this,"value");this.value=n}op(){return"less"}code(){return 34}test(t){const{val:n}=oe(t,this.path);return typeof n!="number"?!1:n<this.value}toJson(t){return{op:"less",path:Z(t?this.path.slice(t.path.length):this.path),value:this.value}}toCompact(t,n){return[n?"less":34,t?this.path.slice(t.path.length):this.path,this.value]}encode(t,n){t.encodeArrayHeader(3),t.writer.u8(34),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeNumber(this.value)}}class Hd extends we{constructor(t,n){super(t);B(this,"value");this.value=n}op(){return"more"}code(){return 36}test(t){const{val:n}=oe(t,this.path);return typeof n!="number"?!1:n>this.value}toJson(t){return{op:"more",path:Z(t?this.path.slice(t.path.length):this.path),value:this.value}}toCompact(t,n){return[n?"more":36,t?this.path.slice(t.path.length):this.path,this.value]}encode(t,n){t.encodeArrayHeader(3),t.writer.u8(36),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeNumber(this.value)}}class Ns extends we{constructor(t,n){super(t);B(this,"ops");this.ops=n}}class zd extends Ns{constructor(t,n){super(t,n);B(this,"ops");this.ops=n}op(){return"and"}code(){return 43}test(t){for(const n of this.ops)if(!n.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,n){return[n?"and":43,t?this.path.slice(t.path.length):this.path,this.ops.map(r=>r.toCompact(this,n))]}encode(t,n){const s=n?this.path.slice(n.path.length):this.path;t.encodeArrayHeader(3),t.writer.u8(43),t.encodeArray(s);const r=this.ops.length;t.encodeArrayHeader(r);for(let o=0;o<r;o++)this.ops[o].encode(t,this)}}class Gd extends Ns{constructor(t,n){super(t,n);B(this,"ops");this.ops=n}op(){return"or"}code(){return 45}test(t){for(const n of this.ops)if(n.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,n){return[n?"or":45,t?this.path.slice(t.path.length):this.path,this.ops.map(r=>r.toCompact(this,n))]}encode(t,n){t.encodeArrayHeader(3),t.writer.u8(45),t.encodeArray(n?this.path.slice(n.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 Wd extends Ns{constructor(t,n){super(t,n);B(this,"ops");this.ops=n}op(){return"not"}code(){return 44}test(t){for(const n of this.ops)if(n.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,n){return[n?"not":44,t?this.path.slice(t.path.length):this.path,this.ops.map(r=>r.toCompact(this,n))]}encode(t,n){t.encodeArrayHeader(3),t.writer.u8(44),t.encodeArray(n?this.path.slice(n.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 Kd extends we{constructor(t,n,s,r){super(t);B(this,"value");B(this,"ignore_case");B(this,"matcher");this.value=n,this.ignore_case=s,this.matcher=r(n,s)}op(){return"matches"}code(){return 35}test(t){const{val:n}=oe(t,this.path);return typeof n!="string"?!1:this.matcher(n)}toJson(t){const n={op:"matches",path:Z(t?this.path.slice(t.path.length):this.path),value:this.value};return this.ignore_case&&(n.ignore_case=this.ignore_case),n}toCompact(t,n){const s=n?"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,n){const s=this.ignore_case;t.encodeArrayHeader(s?4:3),t.writer.u8(35),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeString(this.value),s&&t.writer.u8(1)}}const{isArray:Jd}=Array;class Qd extends we{constructor(t,n){super(t);B(this,"value");this.value=n}op(){return"type"}code(){return 42}test(t){const{val:n}=oe(t,this.path);return n===null?this.value==="null":Jd(n)?this.value==="array":typeof n===this.value||typeof n=="number"&&n===Math.round(n)&&this.value==="integer"}toJson(t){return{op:"type",path:Z(t?this.path.slice(t.path.length):this.path),value:this.value}}toCompact(t,n){return[n?"type":42,t?this.path.slice(t.path.length):this.path,this.value]}encode(t,n){t.encodeArrayHeader(3),t.writer.u8(42),t.encodeArray(n?this.path.slice(n.path.length):this.path),t.encodeString(this.value)}}const Yd=(i,e)=>{switch(i.op){case"add":return new Ds(G(i.path),i.value);case"remove":return new _o(G(i.path),i.oldValue);case"replace":return new bd(G(i.path),i.value,i.oldValue);case"move":return new kd(G(i.path),G(i.from));case"copy":return new Td(G(i.path),G(i.from));case"flip":return new Sd(G(i.path));case"inc":return new Ed(G(i.path),i.inc);case"str_ins":return new wd(G(i.path),i.pos,i.str);case"str_del":return new _d(G(i.path),i.pos,i.str,i.len);case"split":return new Id(G(i.path),i.pos,i.props||null);case"merge":return new Od(G(i.path),i.pos,i.props||null);case"extend":return new Ad(G(i.path),i.props,!!i.deleteNull);default:return Vi(i,e)}},Vi=(i,e)=>{switch(i.op){case"test":return new Cd(G(i.path),i.value,!!i.not);case"defined":return new Md(G(i.path));case"undefined":return new Dd(G(i.path));case"type":return new Qd(G(i.path),i.value);case"test_type":return new Ld(G(i.path),i.type);case"test_string":return new Ud(G(i.path),i.pos,i.str,!!i.not);case"test_string_len":return new jd(G(i.path),i.len,!!i.not);case"contains":return new Fd(G(i.path),i.value,!!i.ignore_case);case"ends":return new Bd(G(i.path),i.value,!!i.ignore_case);case"starts":return new Vd(G(i.path),i.value,!!i.ignore_case);case"matches":return new Kd(G(i.path),i.value,!!i.ignore_case,e.createMatcher||Rd);case"in":return new qd(G(i.path),i.value);case"less":return new $d(G(i.path),i.value);case"more":return new Hd(G(i.path),i.value);case"and":{const t=G(i.path);return new zd(t,i.apply.map(n=>Vi({...n,path:[...t,...G(n.path)]},e)))}case"or":{const t=G(i.path);return new Gd(t,i.apply.map(n=>Vi({...n,path:[...t,...G(n.path)]},e)))}case"not":{const t=G(i.path);return new Wd(t,i.apply.map(n=>Vi({...n,path:[...t,...G(n.path)]},e)))}default:throw new Error("OP_UNKNOWN")}};function Xd(i,e,t){i=Si(i);const n=[],s=e.length;for(let r=0;r<s;r++){const a=Yd(e[r],t).apply(i);i=a.doc,n.push(a)}return{doc:i,res:n}}var mi=i=>typeof i=="function"?i:function(){return i},Zd=typeof self<"u"?self:null,hi=typeof window<"u"?window:null,xt=Zd||hi||xt,el="2.0.0",Qe={connecting:0,open:1,closing:2,closed:3},tl=1e4,il=1e3,xe={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},nt={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},Qn={longpoll:"longpoll",websocket:"websocket"},nl={complete:4},Di=class{constructor(i,e,t,n){this.channel=i,this.event=e,this.payload=t||function(){return{}},this.receivedResp=null,this.timeout=n,this.timeoutTimer=null,this.recHooks=[],this.sent=!1}resend(i){this.timeout=i,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(i,e){return this.hasReceived(i)&&e(this.receivedResp.response),this.recHooks.push({status:i,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}matchReceive({status:i,response:e,_ref:t}){this.recHooks.filter(n=>n.status===i).forEach(n=>n.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,i=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=i,this.matchReceive(i)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(i){return this.receivedResp&&this.receivedResp.status===i}trigger(i,e){this.channel.trigger(this.refEvent,{status:i,response:e})}},Po=class{constructor(i,e){this.callback=i,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))}},sl=class{constructor(i,e,t){this.state=xe.closed,this.topic=i,this.params=mi(e||{}),this.socket=t,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new Di(this,nt.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new Po(()=>{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=xe.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(n=>n.send()),this.pushBuffer=[]}),this.joinPush.receive("error",()=>{this.state=xe.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=xe.closed,this.socket.remove(this)}),this.onError(n=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,n),this.isJoining()&&this.joinPush.reset(),this.state=xe.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 Di(this,nt.leave,mi({}),this.timeout).send(),this.state=xe.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(nt.reply,(n,s)=>{this.trigger(this.replyEventName(s),n)})}join(i=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=i,this.joinedOnce=!0,this.rejoin(),this.joinPush}onClose(i){this.on(nt.close,i)}onError(i){return this.on(nt.error,e=>i(e))}on(i,e){let t=this.bindingRef++;return this.bindings.push({event:i,ref:t,callback:e}),t}off(i,e){this.bindings=this.bindings.filter(t=>!(t.event===i&&(typeof e>"u"||e===t.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(i,e,t=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${i}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let n=new Di(this,i,function(){return e},t);return this.canPush()?n.send():(n.startTimeout(),this.pushBuffer.push(n)),n}leave(i=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=xe.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(nt.close,"leave")},t=new Di(this,nt.leave,mi({}),i);return t.receive("ok",()=>e()).receive("timeout",()=>e()),t.send(),this.canPush()||t.trigger("ok",{}),t}onMessage(i,e,t){return e}isMember(i,e,t,n){return this.topic!==i?!1:n&&n!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:i,event:e,payload:t,joinRef:n}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(i=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=xe.joining,this.joinPush.resend(i))}trigger(i,e,t,n){let s=this.onMessage(i,e,t,n);if(e&&!s)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let r=this.bindings.filter(o=>o.event===i);for(let o=0;o<r.length;o++)r[o].callback(s,t,n||this.joinRef())}replyEventName(i){return`chan_reply_${i}`}isClosed(){return this.state===xe.closed}isErrored(){return this.state===xe.errored}isJoined(){return this.state===xe.joined}isJoining(){return this.state===xe.joining}isLeaving(){return this.state===xe.leaving}},rn=class{static request(i,e,t,n,s,r,o){if(xt.XDomainRequest){let a=new xt.XDomainRequest;return this.xdomainRequest(a,i,e,n,s,r,o)}else{let a=new xt.XMLHttpRequest;return this.xhrRequest(a,i,e,t,n,s,r,o)}}static xdomainRequest(i,e,t,n,s,r,o){return i.timeout=s,i.open(e,t),i.onload=()=>{let a=this.parseJSON(i.responseText);o&&o(a)},r&&(i.ontimeout=r),i.onprogress=()=>{},i.send(n),i}static xhrRequest(i,e,t,n,s,r,o,a){return i.open(e,t,!0),i.timeout=r,i.setRequestHeader("Content-Type",n),i.onerror=()=>a&&a(null),i.onreadystatechange=()=>{if(i.readyState===nl.complete&&a){let c=this.parseJSON(i.responseText);a(c)}},o&&(i.ontimeout=o),i.send(s),i}static parseJSON(i){if(!i||i==="")return null;try{return JSON.parse(i)}catch{return console&&console.log("failed to parse JSON response",i),null}}static serialize(i,e){let t=[];for(var n in i){if(!Object.prototype.hasOwnProperty.call(i,n))continue;let s=e?`${e}[${n}]`:n,r=i[n];typeof r=="object"?t.push(this.serialize(r,s)):t.push(encodeURIComponent(s)+"="+encodeURIComponent(r))}return t.join("&")}static appendParams(i,e){if(Object.keys(e).length===0)return i;let t=i.match(/\?/)?"&":"?";return`${i}${t}${this.serialize(e)}`}},rl=i=>{let e="",t=new Uint8Array(i),n=t.byteLength;for(let s=0;s<n;s++)e+=String.fromCharCode(t[s]);return btoa(e)},ri=class{constructor(i){this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=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(i),this.readyState=Qe.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(i){return i.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+Qn.websocket),"$1/"+Qn.longpoll)}endpointURL(){return rn.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(i,e,t){this.close(i,e,t),this.readyState=Qe.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===Qe.open||this.readyState===Qe.connecting}poll(){this.ajax("GET","application/json",null,()=>this.ontimeout(),i=>{if(i){var{status:e,token:t,messages:n}=i;this.token=t}else e=0;switch(e){case 200:n.forEach(s=>{setTimeout(()=>this.onmessage({data:s}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=Qe.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(i){typeof i!="string"&&(i=rl(i)),this.currentBatch?this.currentBatch.push(i):this.awaitingBatchAck?this.batchBuffer.push(i):(this.currentBatch=[i],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(i){this.awaitingBatchAck=!0,this.ajax("POST","application/x-ndjson",i.join(`
|
|
2
|
-
`),()=>this.onerror("timeout"),e=>{this.awaitingBatchAck=!1,!e||e.status!==200?(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",!1)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[])})}close(i,e,t){for(let s of this.reqs)s.abort();this.readyState=Qe.closed;let n=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:i,reason:e,wasClean:t});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",n)):this.onclose(n)}ajax(i,e,t,n,s){let r,o=()=>{this.reqs.delete(r),n()};r=rn.request(i,this.endpointURL(),e,t,this.timeout,o,a=>{this.reqs.delete(r),this.isActive()&&s(a)}),this.reqs.add(r)}},Ni={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(i,e){if(i.payload.constructor===ArrayBuffer)return e(this.binaryEncode(i));{let t=[i.join_ref,i.ref,i.topic,i.event,i.payload];return e(JSON.stringify(t))}},decode(i,e){if(i.constructor===ArrayBuffer)return e(this.binaryDecode(i));{let[t,n,s,r,o]=JSON.parse(i);return e({join_ref:t,ref:n,topic:s,event:r,payload:o})}},binaryEncode(i){let{join_ref:e,ref:t,event:n,topic:s,payload:r}=i,o=this.META_LENGTH+e.length+t.length+s.length+n.length,a=new ArrayBuffer(this.HEADER_LENGTH+o),c=new DataView(a),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++,n.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(n,u=>c.setUint8(d++,u.charCodeAt(0)));var l=new Uint8Array(a.byteLength+r.byteLength);return l.set(new Uint8Array(a),0),l.set(new Uint8Array(r),a.byteLength),l.buffer},binaryDecode(i){let e=new DataView(i),t=e.getUint8(0),n=new TextDecoder;switch(t){case this.KINDS.push:return this.decodePush(i,e,n);case this.KINDS.reply:return this.decodeReply(i,e,n);case this.KINDS.broadcast:return this.decodeBroadcast(i,e,n)}},decodePush(i,e,t){let n=e.getUint8(1),s=e.getUint8(2),r=e.getUint8(3),o=this.HEADER_LENGTH+this.META_LENGTH-1,a=t.decode(i.slice(o,o+n));o=o+n;let c=t.decode(i.slice(o,o+s));o=o+s;let d=t.decode(i.slice(o,o+r));o=o+r;let l=i.slice(o,i.byteLength);return{join_ref:a,ref:null,topic:c,event:d,payload:l}},decodeReply(i,e,t){let n=e.getUint8(1),s=e.getUint8(2),r=e.getUint8(3),o=e.getUint8(4),a=this.HEADER_LENGTH+this.META_LENGTH,c=t.decode(i.slice(a,a+n));a=a+n;let d=t.decode(i.slice(a,a+s));a=a+s;let l=t.decode(i.slice(a,a+r));a=a+r;let u=t.decode(i.slice(a,a+o));a=a+o;let h=i.slice(a,i.byteLength),f={status:u,response:h};return{join_ref:c,ref:d,topic:l,event:nt.reply,payload:f}},decodeBroadcast(i,e,t){let n=e.getUint8(1),s=e.getUint8(2),r=this.HEADER_LENGTH+2,o=t.decode(i.slice(r,r+n));r=r+n;let a=t.decode(i.slice(r,r+s));r=r+s;let c=i.slice(r,i.byteLength);return{join_ref:null,ref:null,topic:o,event:a,payload:c}}},ol=class{constructor(i,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.timeout=e.timeout||tl,this.transport=e.transport||xt.WebSocket||ri,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=e.sessionStorage||xt&&xt.sessionStorage,this.establishedConnections=0,this.defaultEncoder=Ni.encode.bind(Ni),this.defaultDecoder=Ni.decode.bind(Ni),this.closeWasClean=!1,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.transport!==ri?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let t=null;hi&&hi.addEventListener&&(hi.addEventListener("pagehide",n=>{this.conn&&(this.disconnect(),t=this.connectClock)}),hi.addEventListener("pageshow",n=>{t===this.connectClock&&(t=null,this.connect())})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.rejoinAfterMs=n=>e.rejoinAfterMs?e.rejoinAfterMs(n):[1e3,2e3,5e3][n-1]||1e4,this.reconnectAfterMs=n=>e.reconnectAfterMs?e.reconnectAfterMs(n):[10,50,100,150,200,250,500,1e3,2e3][n-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(n,s,r)=>{console.log(`${n}: ${s}`,r)}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=mi(e.params||{}),this.endPoint=`${i}/${Qn.websocket}`,this.vsn=e.vsn||el,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new Po(()=>{this.teardown(()=>this.connect())},this.reconnectAfterMs)}getLongPollTransport(){return ri}replaceTransport(i){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=i}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let i=rn.appendParams(rn.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return i.charAt(0)!=="/"?i:i.charAt(1)==="/"?`${this.protocol()}:${i}`:`${this.protocol()}://${location.host}${i}`}disconnect(i,e,t){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(i,e,t)}connect(i){i&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=mi(i)),!this.conn&&(this.longPollFallbackMs&&this.transport!==ri?this.connectWithFallback(ri,this.longPollFallbackMs):this.transportConnect())}log(i,e,t){this.logger&&this.logger(i,e,t)}hasLogger(){return this.logger!==null}onOpen(i){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,i]),e}onClose(i){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,i]),e}onError(i){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,i]),e}onMessage(i){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,i]),e}ping(i){if(!this.isConnected())return!1;let e=this.makeRef(),t=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let n=this.onMessage(s=>{s.ref===e&&(this.off([n]),i(Date.now()-t))});return!0}transportConnect(){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=i=>this.onConnError(i),this.conn.onmessage=i=>this.onConnMessage(i),this.conn.onclose=i=>this.onConnClose(i)}getSession(i){return this.sessionStore&&this.sessionStore.getItem(i)}storeSession(i,e){this.sessionStore&&this.sessionStore.setItem(i,e)}connectWithFallback(i,e=2500){clearTimeout(this.fallbackTimer);let t=!1,n=!0,s,r,o=a=>{this.log("transport",`falling back to ${i.name}...`,a),this.off([s,r]),n=!1,this.replaceTransport(i),this.transportConnect()};if(this.getSession(`phx:fallback:${i.name}`))return o("memorized");this.fallbackTimer=setTimeout(o,e),r=this.onError(a=>{this.log("transport","error",a),n&&!t&&(clearTimeout(this.fallbackTimer),o(a))}),this.onOpen(()=>{if(t=!0,!n)return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${i.name}`,"true"),this.log("transport",`established ${i.name} fallback`);clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(o,e),this.ping(a=>{this.log("transport","connected to primary after",a),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`${this.transport.name} connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.resetHeartbeat(),this.stateChangeCallbacks.open.forEach(([,i])=>i())}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(),il,"heartbeat timeout"))}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(i,e,t){if(!this.conn)return i&&i();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),i&&i()})})}waitForBufferDone(i,e=1){if(e===5||!this.conn||!this.conn.bufferedAmount){i();return}setTimeout(()=>{this.waitForBufferDone(i,e+1)},150*e)}waitForSocketClosed(i,e=1){if(e===5||!this.conn||this.conn.readyState===Qe.closed){i();return}setTimeout(()=>{this.waitForSocketClosed(i,e+1)},150*e)}onConnClose(i){let e=i&&i.code;this.hasLogger()&&this.log("transport","close",i),this.triggerChanError(),this.clearHeartbeats(),!this.closeWasClean&&e!==1e3&&this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(([,t])=>t(i))}onConnError(i){this.hasLogger()&&this.log("transport",i);let e=this.transport,t=this.establishedConnections;this.stateChangeCallbacks.error.forEach(([,n])=>{n(i,e,t)}),(e===this.transport||t>0)&&this.triggerChanError()}triggerChanError(){this.channels.forEach(i=>{i.isErrored()||i.isLeaving()||i.isClosed()||i.trigger(nt.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case Qe.connecting:return"connecting";case Qe.open:return"open";case Qe.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(i){this.off(i.stateChangeRefs),this.channels=this.channels.filter(e=>e!==i)}off(i){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([t])=>i.indexOf(t)===-1)}channel(i,e={}){let t=new sl(i,e,this);return this.channels.push(t),t}push(i){if(this.hasLogger()){let{topic:e,event:t,payload:n,ref:s,join_ref:r}=i;this.log("push",`${e} ${t} (${r}, ${s})`,n)}this.isConnected()?this.encode(i,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(i,e=>this.conn.send(e)))}makeRef(){let i=this.ref+1;return i===this.ref?this.ref=0:this.ref=i,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(i=>i()),this.sendBuffer=[])}onConnMessage(i){this.decode(i.data,e=>{let{topic:t,event:n,payload:s,ref:r,join_ref:o}=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} ${n} ${r&&"("+r+")"||""}`,s);for(let a=0;a<this.channels.length;a++){const c=this.channels[a];c.isMember(t,n,s,o)&&c.trigger(n,s,r,o)}for(let a=0;a<this.stateChangeCallbacks.message.length;a++){let[,c]=this.stateChangeCallbacks.message[a];c(e)}})}leaveOpenTopic(i){let e=this.channels.find(t=>t.topic===i&&(t.isJoined()||t.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${i}"`),e.leave())}};class al{constructor(e){this.connected=!1,this.config=e,this.socket=new ol(this.config.url,this.config.socketOptions||{logger:(t,n,s)=>{console.debug(`${t}: ${n}`,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,n){var s;this.eventTarget.addEventListener(e,t,n),e.startsWith("livestate-")||(s=this.channel)==null||s.on(e,r=>{this.eventTarget.dispatchEvent(new CustomEvent(e,{detail:r}))})}removeEventListener(e,t,n){return this.eventTarget.removeEventListener(e,t,n)}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(n=>n);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:n}=Xd(this.state,e,{});this.state=n,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 Ro=32;let pe,He,on=i=>(pe=0,He=i,i=lt(),He[pe]?at():i||""),at=(i="Bad syntax",e=He[pe],t=He.slice(0,pe).split(`
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
***************************************************************************** */var pr;(function(i){(function(e){var t=typeof fr=="object"?fr:typeof self=="object"?self:typeof this=="object"?this:Function("return this;")(),n=s(i);typeof t.Reflect>"u"?t.Reflect=i:n=s(t.Reflect,n),e(n);function s(r,o){return function(a,c){typeof r[a]!="function"&&Object.defineProperty(r,a,{configurable:!0,writable:!0,value:c}),o&&o(a,c)}}})(function(e){var t=Object.prototype.hasOwnProperty,n=typeof Symbol=="function",s=n&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",r=n&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",o=typeof Object.create=="function",a={__proto__:[]}instanceof Array,c=!o&&!a,d={create:o?function(){return wn(Object.create(null))}:a?function(){return wn({__proto__:null})}:function(){return wn({})},has:c?function(v,S){return t.call(v,S)}:function(v,S){return S in v},get:c?function(v,S){return t.call(v,S)?v[S]:void 0}:function(v,S){return v[S]}},l=Object.getPrototypeOf(Function),u=typeof process=="object"&&process.env&&process.env.REFLECT_METADATA_USE_MAP_POLYFILL==="true",h=!u&&typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:xc(),f=!u&&typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Ac(),m=!u&&typeof WeakMap=="function"?WeakMap:Mc(),g=new m;function T(v,S,P,N){if(se(P)){if(!nr(v))throw new TypeError;if(!sr(S))throw new TypeError;return U(v,S)}else{if(!nr(v))throw new TypeError;if(!ve(S))throw new TypeError;if(!ve(N)&&!se(N)&&!Ee(N))throw new TypeError;return Ee(N)&&(N=void 0),P=it(P),$(v,S,P,N)}}e("decorate",T);function C(v,S){function P(N,q){if(!ve(N))throw new TypeError;if(!se(q)&&!_c(q))throw new TypeError;xi(v,S,N,q)}return P}e("metadata",C);function M(v,S,P,N){if(!ve(P))throw new TypeError;return se(N)||(N=it(N)),xi(v,S,P,N)}e("defineMetadata",M);function j(v,S,P){if(!ve(S))throw new TypeError;return se(P)||(P=it(P)),Oe(v,S,P)}e("hasMetadata",j);function k(v,S,P){if(!ve(S))throw new TypeError;return se(P)||(P=it(P)),Ue(v,S,P)}e("hasOwnMetadata",k);function y(v,S,P){if(!ve(S))throw new TypeError;return se(P)||(P=it(P)),Lt(v,S,P)}e("getMetadata",y);function _(v,S,P){if(!ve(S))throw new TypeError;return se(P)||(P=it(P)),si(v,S,P)}e("getOwnMetadata",_);function R(v,S){if(!ve(v))throw new TypeError;return se(S)||(S=it(S)),L(v,S)}e("getMetadataKeys",R);function D(v,S){if(!ve(v))throw new TypeError;return se(S)||(S=it(S)),be(v,S)}e("getOwnMetadataKeys",D);function F(v,S,P){if(!ve(S))throw new TypeError;se(P)||(P=it(P));var N=ee(S,P,!1);if(se(N)||!N.delete(v))return!1;if(N.size>0)return!0;var q=g.get(S);return q.delete(P),q.size>0||g.delete(S),!0}e("deleteMetadata",F);function U(v,S){for(var P=v.length-1;P>=0;--P){var N=v[P],q=N(S);if(!se(q)&&!Ee(q)){if(!sr(q))throw new TypeError;S=q}}return S}function $(v,S,P,N){for(var q=v.length-1;q>=0;--q){var Ce=v[q],H=Ce(S,P,N);if(!se(H)&&!Ee(H)){if(!ve(H))throw new TypeError;N=H}}return N}function ee(v,S,P){var N=g.get(v);if(se(N)){if(!P)return;N=new h,g.set(v,N)}var q=N.get(S);if(se(q)){if(!P)return;q=new h,N.set(S,q)}return q}function Oe(v,S,P){var N=Ue(v,S,P);if(N)return!0;var q=En(S);return Ee(q)?!1:Oe(v,q,P)}function Ue(v,S,P){var N=ee(S,P,!1);return se(N)?!1:tt(N.has(v))}function Lt(v,S,P){var N=Ue(v,S,P);if(N)return si(v,S,P);var q=En(S);if(!Ee(q))return Lt(v,q,P)}function si(v,S,P){var N=ee(S,P,!1);if(!se(N))return N.get(v)}function xi(v,S,P,N){var q=ee(P,N,!0);q.set(v,S)}function L(v,S){var P=be(v,S),N=En(v);if(N===null)return P;var q=L(N,S);if(q.length<=0)return P;if(P.length<=0)return q;for(var Ce=new f,H=[],z=0,V=P;z<V.length;z++){var Y=V[z],X=Ce.has(Y);X||(Ce.add(Y),H.push(Y))}for(var ut=0,or=q;ut<or.length;ut++){var Y=or[ut],X=Ce.has(Y);X||(Ce.add(Y),H.push(Y))}return H}function be(v,S){var P=[],N=ee(v,S,!1);if(se(N))return P;for(var q=N.keys(),Ce=Pc(q),H=0;;){var z=Ic(Ce);if(!z)return P.length=H,P;var V=Rc(z);try{P[H]=V}catch(Y){try{Oc(Ce)}finally{throw Y}}H++}}function ke(v){if(v===null)return 1;switch(typeof v){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return v===null?1:6;default:return 6}}function se(v){return v===void 0}function Ee(v){return v===null}function Ut(v){return typeof v=="symbol"}function ve(v){return typeof v=="object"?v!==null:typeof v=="function"}function Ai(v,S){switch(ke(v)){case 0:return v;case 1:return v;case 2:return v;case 3:return v;case 4:return v;case 5:return v}var P="string",N=rr(v,s);if(N!==void 0){var q=N.call(v,P);if(ve(q))throw new TypeError;return q}return jt(v)}function jt(v,S){var P,N,q;{var Ce=v.toString;if(Mi(Ce)){var N=Ce.call(v);if(!ve(N))return N}var P=v.valueOf;if(Mi(P)){var N=P.call(v);if(!ve(N))return N}}throw new TypeError}function tt(v){return!!v}function wc(v){return""+v}function it(v){var S=Ai(v);return Ut(S)?S:wc(S)}function nr(v){return Array.isArray?Array.isArray(v):v instanceof Object?v instanceof Array:Object.prototype.toString.call(v)==="[object Array]"}function Mi(v){return typeof v=="function"}function sr(v){return typeof v=="function"}function _c(v){switch(ke(v)){case 3:return!0;case 4:return!0;default:return!1}}function rr(v,S){var P=v[S];if(P!=null){if(!Mi(P))throw new TypeError;return P}}function Pc(v){var S=rr(v,r);if(!Mi(S))throw new TypeError;var P=S.call(v);if(!ve(P))throw new TypeError;return P}function Rc(v){return v.value}function Ic(v){var S=v.next();return S.done?!1:S}function Oc(v){var S=v.return;S&&S.call(v)}function En(v){var S=Object.getPrototypeOf(v);if(typeof v!="function"||v===l||S!==l)return S;var P=v.prototype,N=P&&Object.getPrototypeOf(P);if(N==null||N===Object.prototype)return S;var q=N.constructor;return typeof q!="function"||q===v?S:q}function xc(){var v={},S=[],P=function(){function H(z,V,Y){this._index=0,this._keys=z,this._values=V,this._selector=Y}return H.prototype["@@iterator"]=function(){return this},H.prototype[r]=function(){return this},H.prototype.next=function(){var z=this._index;if(z>=0&&z<this._keys.length){var V=this._selector(this._keys[z],this._values[z]);return z+1>=this._keys.length?(this._index=-1,this._keys=S,this._values=S):this._index++,{value:V,done:!1}}return{value:void 0,done:!0}},H.prototype.throw=function(z){throw this._index>=0&&(this._index=-1,this._keys=S,this._values=S),z},H.prototype.return=function(z){return this._index>=0&&(this._index=-1,this._keys=S,this._values=S),{value:z,done:!0}},H}();return function(){function H(){this._keys=[],this._values=[],this._cacheKey=v,this._cacheIndex=-2}return Object.defineProperty(H.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),H.prototype.has=function(z){return this._find(z,!1)>=0},H.prototype.get=function(z){var V=this._find(z,!1);return V>=0?this._values[V]:void 0},H.prototype.set=function(z,V){var Y=this._find(z,!0);return this._values[Y]=V,this},H.prototype.delete=function(z){var V=this._find(z,!1);if(V>=0){for(var Y=this._keys.length,X=V+1;X<Y;X++)this._keys[X-1]=this._keys[X],this._values[X-1]=this._values[X];return this._keys.length--,this._values.length--,z===this._cacheKey&&(this._cacheKey=v,this._cacheIndex=-2),!0}return!1},H.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=v,this._cacheIndex=-2},H.prototype.keys=function(){return new P(this._keys,this._values,N)},H.prototype.values=function(){return new P(this._keys,this._values,q)},H.prototype.entries=function(){return new P(this._keys,this._values,Ce)},H.prototype["@@iterator"]=function(){return this.entries()},H.prototype[r]=function(){return this.entries()},H.prototype._find=function(z,V){return this._cacheKey!==z&&(this._cacheIndex=this._keys.indexOf(this._cacheKey=z)),this._cacheIndex<0&&V&&(this._cacheIndex=this._keys.length,this._keys.push(z),this._values.push(void 0)),this._cacheIndex},H}();function N(H,z){return H}function q(H,z){return z}function Ce(H,z){return[H,z]}}function Ac(){return function(){function v(){this._map=new h}return Object.defineProperty(v.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),v.prototype.has=function(S){return this._map.has(S)},v.prototype.add=function(S){return this._map.set(S,S),this},v.prototype.delete=function(S){return this._map.delete(S)},v.prototype.clear=function(){this._map.clear()},v.prototype.keys=function(){return this._map.keys()},v.prototype.values=function(){return this._map.values()},v.prototype.entries=function(){return this._map.entries()},v.prototype["@@iterator"]=function(){return this.keys()},v.prototype[r]=function(){return this.keys()},v}()}function Mc(){var v=16,S=d.create(),P=N();return function(){function V(){this._key=N()}return V.prototype.has=function(Y){var X=q(Y,!1);return X!==void 0?d.has(X,this._key):!1},V.prototype.get=function(Y){var X=q(Y,!1);return X!==void 0?d.get(X,this._key):void 0},V.prototype.set=function(Y,X){var ut=q(Y,!0);return ut[this._key]=X,this},V.prototype.delete=function(Y){var X=q(Y,!1);return X!==void 0?delete X[this._key]:!1},V.prototype.clear=function(){this._key=N()},V}();function N(){var V;do V="@@WeakMap@@"+z();while(d.has(S,V));return S[V]=!0,V}function q(V,Y){if(!t.call(V,P)){if(!Y)return;Object.defineProperty(V,P,{value:d.create()})}return V[P]}function Ce(V,Y){for(var X=0;X<Y;++X)V[X]=Math.random()*255|0;return V}function H(V){return typeof Uint8Array=="function"?typeof crypto<"u"?crypto.getRandomValues(new Uint8Array(V)):typeof msCrypto<"u"?msCrypto.getRandomValues(new Uint8Array(V)):Ce(new Uint8Array(V),V):Ce(new Array(V),V)}function z(){var V=H(v);V[6]=V[6]&79|64,V[8]=V[8]&191|128;for(var Y="",X=0;X<v;++X){var ut=V[X];(X===4||X===6||X===8)&&(Y+="-"),ut<16&&(Y+="0"),Y+=ut.toString(16).toLowerCase()}return Y}}function wn(v){return v.__=void 0,delete v.__,v}})})(pr||(pr={}));function yl(i,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if(n!=="default"&&!(n in i)){var s=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(i,n,s.get?s:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(i)}var bl=Object.defineProperty,kl=(i,e,t)=>e in i?bl(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,mr=(i,e,t)=>kl(i,typeof e!="symbol"?e+"":e,t);class De{constructor(){mr(this,"_locking"),mr(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e;const t=new Promise(s=>e=()=>{this._locks-=1,s()}),n=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),n}}function ue(i,e){if(!i)throw new Error(e)}const Tl=34028234663852886e22,Cl=-34028234663852886e22,Sl=4294967295,El=2147483647,wl=-2147483648;function qi(i){if(typeof i!="number")throw new Error("invalid int 32: "+typeof i);if(!Number.isInteger(i)||i>El||i<wl)throw new Error("invalid int 32: "+i)}function Xn(i){if(typeof i!="number")throw new Error("invalid uint 32: "+typeof i);if(!Number.isInteger(i)||i>Sl||i<0)throw new Error("invalid uint 32: "+i)}function jo(i){if(typeof i!="number")throw new Error("invalid float 32: "+typeof i);if(Number.isFinite(i)&&(i>Tl||i<Cl))throw new Error("invalid float 32: "+i)}const Fo=Symbol("@bufbuild/protobuf/enum-type");function _l(i){const e=i[Fo];return ue(e,"missing enum type on enum object"),e}function Bo(i,e,t,n){i[Fo]=Vo(e,t.map(s=>({no:s.no,name:s.name,localName:i[s.no]})))}function Vo(i,e,t){const n=Object.create(null),s=Object.create(null),r=[];for(const o of e){const a=qo(o);r.push(a),n[o.name]=a,s[o.no]=a}return{typeName:i,values:r,findName(o){return n[o]},findNumber(o){return s[o]}}}function Pl(i,e,t){const n={};for(const s of e){const r=qo(s);n[r.localName]=r.no,n[r.no]=r.localName}return Bo(n,i,e),n}function qo(i){return"localName"in i?i:Object.assign(Object.assign({},i),{localName:i.name})}class js{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const n=this.getType(),s=n.runtime.bin,r=s.makeReadOptions(t);return s.readMessage(this,r.readerFactory(e),e.byteLength,r),this}fromJson(e,t){const n=this.getType(),s=n.runtime.json,r=s.makeReadOptions(t);return s.readMessage(n,e,r,this),this}fromJsonString(e,t){let n;try{n=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(n,t)}toBinary(e){const t=this.getType(),n=t.runtime.bin,s=n.makeWriteOptions(e),r=s.writerFactory();return n.writeMessage(this,r,s),r.finish()}toJson(e){const t=this.getType(),n=t.runtime.json,s=n.makeWriteOptions(e);return n.writeMessage(this,s)}toJsonString(e){var t;const n=this.toJson(e);return JSON.stringify(n,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 Rl(i,e,t,n){var s;const r=(s=n==null?void 0:n.localName)!==null&&s!==void 0?s:e.substring(e.lastIndexOf(".")+1),o={[r]:function(a){i.util.initFields(this),i.util.initPartial(a,this)}}[r];return Object.setPrototypeOf(o.prototype,new js),Object.assign(o,{runtime:i,typeName:e,fields:i.util.newFieldList(t),fromBinary(a,c){return new o().fromBinary(a,c)},fromJson(a,c){return new o().fromJson(a,c)},fromJsonString(a,c){return new o().fromJsonString(a,c)},equals(a,c){return i.util.equals(o,a,c)}}),o}function Il(){let i=0,e=0;for(let n=0;n<28;n+=7){let s=this.buf[this.pos++];if(i|=(s&127)<<n,!(s&128))return this.assertBounds(),[i,e]}let t=this.buf[this.pos++];if(i|=(t&15)<<28,e=(t&112)>>4,!(t&128))return this.assertBounds(),[i,e];for(let n=3;n<=31;n+=7){let s=this.buf[this.pos++];if(e|=(s&127)<<n,!(s&128))return this.assertBounds(),[i,e]}throw new Error("invalid varint")}function Pn(i,e,t){for(let r=0;r<28;r=r+7){const o=i>>>r,a=!(!(o>>>7)&&e==0),c=(a?o|128:o)&255;if(t.push(c),!a)return}const n=i>>>28&15|(e&7)<<4,s=!!(e>>3);if(t.push((s?n|128:n)&255),!!s){for(let r=3;r<31;r=r+7){const o=e>>>r,a=!!(o>>>7),c=(a?o|128:o)&255;if(t.push(c),!a)return}t.push(e>>>31&1)}}const $i=4294967296;function gr(i){const e=i[0]==="-";e&&(i=i.slice(1));const t=1e6;let n=0,s=0;function r(o,a){const c=Number(i.slice(o,a));s*=t,n=n*t+c,n>=$i&&(s=s+(n/$i|0),n=n%$i)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),e?Ho(n,s):Fs(n,s)}function Ol(i,e){let t=Fs(i,e);const n=t.hi&2147483648;n&&(t=Ho(t.lo,t.hi));const s=$o(t.lo,t.hi);return n?"-"+s:s}function $o(i,e){if({lo:i,hi:e}=xl(i,e),e<=2097151)return String($i*e+i);const t=i&16777215,n=(i>>>24|e<<8)&16777215,s=e>>16&65535;let r=t+n*6777216+s*6710656,o=n+s*8147497,a=s*2;const c=1e7;return r>=c&&(o+=Math.floor(r/c),r%=c),o>=c&&(a+=Math.floor(o/c),o%=c),a.toString()+vr(o)+vr(r)}function xl(i,e){return{lo:i>>>0,hi:e>>>0}}function Fs(i,e){return{lo:i|0,hi:e|0}}function Ho(i,e){return e=~e,i?i=~i+1:e+=1,Fs(i,e)}const vr=i=>{const e=String(i);return"0000000".slice(e.length)+e};function yr(i,e){if(i>=0){for(;i>127;)e.push(i&127|128),i=i>>>7;e.push(i)}else{for(let t=0;t<9;t++)e.push(i&127|128),i=i>>7;e.push(1)}}function Al(){let i=this.buf[this.pos++],e=i&127;if(!(i&128))return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<7,!(i&128))return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<14,!(i&128))return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<21,!(i&128))return this.assertBounds(),e;i=this.buf[this.pos++],e|=(i&15)<<28;for(let t=5;i&128&&t<10;t++)i=this.buf[this.pos++];if(i&128)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function Ml(){const i=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof i.getBigInt64=="function"&&typeof i.getBigUint64=="function"&&typeof i.setBigInt64=="function"&&typeof i.setBigUint64=="function"&&(typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){const s=BigInt("-9223372036854775808"),r=BigInt("9223372036854775807"),o=BigInt("0"),a=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>a||d<o)throw new Error("uint64 invalid: ".concat(c));return d},enc(c){return i.setBigInt64(0,this.parse(c),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},uEnc(c){return i.setBigInt64(0,this.uParse(c),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},dec(c,d){return i.setInt32(0,c,!0),i.setInt32(4,d,!0),i.getBigInt64(0,!0)},uDec(c,d){return i.setInt32(0,c,!0),i.setInt32(4,d,!0),i.getBigUint64(0,!0)}}}const t=s=>ue(/^-?[0-9]+$/.test(s),"int64 invalid: ".concat(s)),n=s=>ue(/^[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()),n(s),s},enc(s){return typeof s!="string"&&(s=s.toString()),t(s),gr(s)},uEnc(s){return typeof s!="string"&&(s=s.toString()),n(s),gr(s)},dec(s,r){return Ol(s,r)},uDec(s,r){return $o(s,r)}}}const ce=Ml();var E;(function(i){i[i.DOUBLE=1]="DOUBLE",i[i.FLOAT=2]="FLOAT",i[i.INT64=3]="INT64",i[i.UINT64=4]="UINT64",i[i.INT32=5]="INT32",i[i.FIXED64=6]="FIXED64",i[i.FIXED32=7]="FIXED32",i[i.BOOL=8]="BOOL",i[i.STRING=9]="STRING",i[i.BYTES=12]="BYTES",i[i.UINT32=13]="UINT32",i[i.SFIXED32=15]="SFIXED32",i[i.SFIXED64=16]="SFIXED64",i[i.SINT32=17]="SINT32",i[i.SINT64=18]="SINT64"})(E||(E={}));var St;(function(i){i[i.BIGINT=0]="BIGINT",i[i.STRING=1]="STRING"})(St||(St={}));function ht(i,e,t){if(e===t)return!0;if(i==E.BYTES){if(!(e instanceof Uint8Array)||!(t instanceof Uint8Array)||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}switch(i){case E.UINT64:case E.FIXED64:case E.INT64:case E.SFIXED64:case E.SINT64:return e==t}return!1}function Zt(i,e){switch(i){case E.BOOL:return!1;case E.UINT64:case E.FIXED64:case E.INT64:case E.SFIXED64:case E.SINT64:return e==0?ce.zero:"0";case E.DOUBLE:case E.FLOAT:return 0;case E.BYTES:return new Uint8Array(0);case E.STRING:return"";default:return 0}}function zo(i,e){switch(i){case E.BOOL:return e===!1;case E.STRING:return e==="";case E.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}var me;(function(i){i[i.Varint=0]="Varint",i[i.Bit64=1]="Bit64",i[i.LengthDelimited=2]="LengthDelimited",i[i.StartGroup=3]="StartGroup",i[i.EndGroup=4]="EndGroup",i[i.Bit32=5]="Bit32"})(me||(me={}));class Dl{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),n=0;for(let s=0;s<this.chunks.length;s++)t.set(this.chunks[s],n),n+=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(Xn(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return qi(e),yr(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){jo(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){Xn(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){qi(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return qi(e),e=(e<<1^e>>31)>>>0,yr(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),s=ce.enc(e);return n.setInt32(0,s.lo,!0),n.setInt32(4,s.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),s=ce.uEnc(e);return n.setInt32(0,s.lo,!0),n.setInt32(4,s.hi,!0),this.raw(t)}int64(e){let t=ce.enc(e);return Pn(t.lo,t.hi,this.buf),this}sint64(e){let t=ce.enc(e),n=t.hi>>31,s=t.lo<<1^n,r=(t.hi<<1|t.lo>>>31)^n;return Pn(s,r,this.buf),this}uint64(e){let t=ce.uEnc(e);return Pn(t.lo,t.hi,this.buf),this}}class Nl{constructor(e,t){this.varint64=Il,this.uint32=Al,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,n=e&7;if(t<=0||n<0||n>5)throw new Error("illegal tag: field no "+t+" wire type "+n);return[t,n]}skip(e,t){let n=this.pos;switch(e){case me.Varint:for(;this.buf[this.pos++]&128;);break;case me.Bit64:this.pos+=4;case me.Bit32:this.pos+=4;break;case me.LengthDelimited:let s=this.uint32();this.pos+=s;break;case me.StartGroup:for(;;){const[r,o]=this.tag();if(o===me.EndGroup){if(t!==void 0&&r!==t)throw new Error("invalid end group tag");break}this.skip(o,r)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(n,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 ce.dec(...this.varint64())}uint64(){return ce.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(e&1);return e=(e>>>1|(t&1)<<31)^n,t=t>>>1^n,ce.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 ce.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return ce.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 Ll(i,e,t,n){let s;return{typeName:e,extendee:t,get field(){if(!s){const r=typeof n=="function"?n():n;r.name=e.split(".").pop(),r.jsonName="[".concat(e,"]"),s=i.util.newFieldList([r]).list()[0]}return s},runtime:i}}function Go(i){const e=i.field.localName,t=Object.create(null);return t[e]=Ul(i),[t,()=>t[e]]}function Ul(i){const e=i.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 Zt(e.T,e.L);case"message":const t=e.T,n=new t;return t.fieldWrapper?t.fieldWrapper.unwrapField(n):n;case"map":throw"map fields are not allowed to be extensions"}}function jl(i,e){if(!e.repeated&&(e.kind=="enum"||e.kind=="scalar")){for(let t=i.length-1;t>=0;--t)if(i[t].no==e.no)return[i[t]];return[]}return i.filter(t=>t.no===e.no)}let st="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),yn=[];for(let i=0;i<st.length;i++)yn[st[i].charCodeAt(0)]=i;yn[45]=st.indexOf("+");yn[95]=st.indexOf("/");const Wo={dec(i){let e=i.length*3/4;i[i.length-2]=="="?e-=2:i[i.length-1]=="="&&(e-=1);let t=new Uint8Array(e),n=0,s=0,r,o=0;for(let a=0;a<i.length;a++){if(r=yn[i.charCodeAt(a)],r===void 0)switch(i[a]){case"=":s=0;case`
|
|
19
|
-
`:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(s){case 0:o=r,s=1;break;case 1:t[n++]=o<<2|(r&48)>>4,o=r,s=2;break;case 2:t[n++]=(o&15)<<4|(r&60)>>2,o=r,s=3;break;case 3:t[n++]=(o&3)<<6|r,s=0;break}}if(s==1)throw Error("invalid base64 string.");return t.subarray(0,n)},enc(i){let e="",t=0,n,s=0;for(let r=0;r<i.length;r++)switch(n=i[r],t){case 0:e+=st[n>>2],s=(n&3)<<4,t=1;break;case 1:e+=st[s|n>>4],s=(n&15)<<2,t=2;break;case 2:e+=st[s|n>>6],e+=st[n&63],t=0;break}return t&&(e+=st[s],e+="=",t==1&&(e+="=")),e}};function Fl(i,e,t){Jo(e,i);const n=e.runtime.bin.makeReadOptions(t),s=jl(i.getType().runtime.bin.listUnknownFields(i),e.field),[r,o]=Go(e);for(const a of s)e.runtime.bin.readField(r,n.readerFactory(a.data),e.field,a.wireType,n);return o()}function Bl(i,e,t,n){Jo(e,i);const s=e.runtime.bin.makeReadOptions(n),r=e.runtime.bin.makeWriteOptions(n);if(Ko(i,e)){const d=i.getType().runtime.bin.listUnknownFields(i).filter(l=>l.no!=e.field.no);i.getType().runtime.bin.discardUnknownFields(i);for(const l of d)i.getType().runtime.bin.onUnknownField(i,l.no,l.wireType,l.data)}const o=r.writerFactory();let a=e.field;!a.opt&&!a.repeated&&(a.kind=="enum"||a.kind=="scalar")&&(a=Object.assign(Object.assign({},e.field),{opt:!0})),e.runtime.bin.writeField(a,t,o,r);const c=s.readerFactory(o.finish());for(;c.pos<c.len;){const[d,l]=c.tag(),u=c.skip(l,d);i.getType().runtime.bin.onUnknownField(i,d,l,u)}}function Ko(i,e){const t=i.getType();return e.extendee.typeName===t.typeName&&!!t.runtime.bin.listUnknownFields(i).find(n=>n.no==e.field.no)}function Jo(i,e){ue(i.extendee.typeName==e.getType().typeName,"extension ".concat(i.typeName," can only be applied to message ").concat(i.extendee.typeName))}function Qo(i,e){const t=i.localName;if(i.repeated)return e[t].length>0;if(i.oneof)return e[i.oneof.localName].case===t;switch(i.kind){case"enum":case"scalar":return i.opt||i.req?e[t]!==void 0:i.kind=="enum"?e[t]!==i.T.values[0].no:!zo(i.T,e[t]);case"message":return e[t]!==void 0;case"map":return Object.keys(e[t]).length>0}}function br(i,e){const t=i.localName,n=!i.opt&&!i.req;if(i.repeated)e[t]=[];else if(i.oneof)e[i.oneof.localName]={case:void 0};else switch(i.kind){case"map":e[t]={};break;case"enum":e[t]=n?i.T.values[0].no:void 0;break;case"scalar":e[t]=n?Zt(i.T,i.L):void 0;break;case"message":e[t]=void 0;break}}function At(i,e){if(i===null||typeof i!="object"||!Object.getOwnPropertyNames(js.prototype).every(n=>n in i&&typeof i[n]=="function"))return!1;const t=i.getType();return t===null||typeof t!="function"||!("typeName"in t)||typeof t.typeName!="string"?!1:e===void 0?!0:t.typeName==e.typeName}function Yo(i,e){return At(e)||!i.fieldWrapper?e:i.fieldWrapper.wrapField(e)}E.DOUBLE,E.FLOAT,E.INT64,E.UINT64,E.INT32,E.UINT32,E.BOOL,E.STRING,E.BYTES;const kr={ignoreUnknownFields:!1},Tr={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function Vl(i){return i?Object.assign(Object.assign({},kr),i):kr}function ql(i){return i?Object.assign(Object.assign({},Tr),i):Tr}const an=Symbol(),Hi=Symbol();function $l(){return{makeReadOptions:Vl,makeWriteOptions:ql,readMessage(i,e,t,n){if(e==null||Array.isArray(e)||typeof e!="object")throw new Error("cannot decode message ".concat(i.typeName," from JSON: ").concat(Je(e)));n=n??new i;const s=new Map,r=t.typeRegistry;for(const[o,a]of Object.entries(e)){const c=i.fields.findJsonName(o);if(c){if(c.oneof){if(a===null&&c.kind=="scalar")continue;const d=s.get(c.oneof);if(d!==void 0)throw new Error("cannot decode message ".concat(i.typeName,' from JSON: multiple keys for oneof "').concat(c.oneof.name,'" present: "').concat(d,'", "').concat(o,'"'));s.set(c.oneof,o)}Cr(n,a,c,t,i)}else{let d=!1;if(r!=null&&r.findExtension&&o.startsWith("[")&&o.endsWith("]")){const l=r.findExtension(o.substring(1,o.length-1));if(l&&l.extendee.typeName==i.typeName){d=!0;const[u,h]=Go(l);Cr(u,a,l.field,t,l),Bl(n,l,h(),t)}}if(!d&&!t.ignoreUnknownFields)throw new Error("cannot decode message ".concat(i.typeName,' from JSON: key "').concat(o,'" is unknown'))}}return n},writeMessage(i,e){const t=i.getType(),n={};let s;try{for(s of t.fields.byNumber()){if(!Qo(s,i)){if(s.req)throw"required field not set";if(!e.emitDefaultValues||!zl(s))continue}const o=s.oneof?i[s.oneof.localName].value:i[s.localName],a=Sr(s,o,e);a!==void 0&&(n[e.useProtoFieldName?s.name:s.jsonName]=a)}const r=e.typeRegistry;if(r!=null&&r.findExtensionFor)for(const o of t.runtime.bin.listUnknownFields(i)){const a=r.findExtensionFor(t.typeName,o.no);if(a&&Ko(i,a)){const c=Fl(i,a,e),d=Sr(a.field,c,e);d!==void 0&&(n[a.field.jsonName]=d)}}}catch(r){const o=s?"cannot encode field ".concat(t.typeName,".").concat(s.name," to JSON"):"cannot encode message ".concat(t.typeName," to JSON"),a=r instanceof Error?r.message:String(r);throw new Error(o+(a.length>0?": ".concat(a):""))}return n},readScalar(i,e,t){return vi(i,e,t??St.BIGINT,!0)},writeScalar(i,e,t){if(e!==void 0&&(t||zo(i,e)))return zi(i,e)},debug:Je}}function Je(i){if(i===null)return"null";switch(typeof i){case"object":return Array.isArray(i)?"array":"object";case"string":return i.length>100?"string":'"'.concat(i.split('"').join('\\"'),'"');default:return String(i)}}function Cr(i,e,t,n,s){let r=t.localName;if(t.repeated){if(ue(t.kind!="map"),e===null)return;if(!Array.isArray(e))throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Je(e)));const o=i[r];for(const a of e){if(a===null)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Je(a)));switch(t.kind){case"message":o.push(t.T.fromJson(a,n));break;case"enum":const c=Rn(t.T,a,n.ignoreUnknownFields,!0);c!==Hi&&o.push(c);break;case"scalar":try{o.push(vi(t.T,a,t.L,!0))}catch(d){let l="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Je(a));throw d instanceof Error&&d.message.length>0&&(l+=": ".concat(d.message)),new Error(l)}break}}}else if(t.kind=="map"){if(e===null)return;if(typeof e!="object"||Array.isArray(e))throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Je(e)));const o=i[r];for(const[a,c]of Object.entries(e)){if(c===null)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: map value null"));let d;try{d=Hl(t.K,a)}catch(l){let u="cannot decode map key for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Je(e));throw l instanceof Error&&l.message.length>0&&(u+=": ".concat(l.message)),new Error(u)}switch(t.V.kind){case"message":o[d]=t.V.T.fromJson(c,n);break;case"enum":const l=Rn(t.V.T,c,n.ignoreUnknownFields,!0);l!==Hi&&(o[d]=l);break;case"scalar":try{o[d]=vi(t.V.T,c,St.BIGINT,!0)}catch(u){let h="cannot decode map value for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Je(e));throw u instanceof Error&&u.message.length>0&&(h+=": ".concat(u.message)),new Error(h)}break}}}else switch(t.oneof&&(i=i[t.oneof.localName]={case:r},r="value"),t.kind){case"message":const o=t.T;if(e===null&&o.typeName!="google.protobuf.Value")return;let a=i[r];At(a)?a.fromJson(e,n):(i[r]=a=o.fromJson(e,n),o.fieldWrapper&&!t.oneof&&(i[r]=o.fieldWrapper.unwrapField(a)));break;case"enum":const c=Rn(t.T,e,n.ignoreUnknownFields,!1);switch(c){case an:br(t,i);break;case Hi:break;default:i[r]=c;break}break;case"scalar":try{const d=vi(t.T,e,t.L,!1);switch(d){case an:br(t,i);break;default:i[r]=d;break}}catch(d){let l="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Je(e));throw d instanceof Error&&d.message.length>0&&(l+=": ".concat(d.message)),new Error(l)}break}}function Hl(i,e){if(i===E.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return vi(i,e,St.BIGINT,!0).toString()}function vi(i,e,t,n){if(e===null)return n?Zt(i,t):an;switch(i){case E.DOUBLE:case E.FLOAT:if(e==="NaN")return Number.NaN;if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e===""||typeof e=="string"&&e.trim().length!==e.length||typeof e!="string"&&typeof e!="number")break;const s=Number(e);if(Number.isNaN(s)||!Number.isFinite(s))break;return i==E.FLOAT&&jo(s),s;case E.INT32:case E.FIXED32:case E.SFIXED32:case E.SINT32:case E.UINT32:let r;if(typeof e=="number"?r=e:typeof e=="string"&&e.length>0&&e.trim().length===e.length&&(r=Number(e)),r===void 0)break;return i==E.UINT32||i==E.FIXED32?Xn(r):qi(r),r;case E.INT64:case E.SFIXED64:case E.SINT64:if(typeof e!="number"&&typeof e!="string")break;const o=ce.parse(e);return t?o.toString():o;case E.FIXED64:case E.UINT64:if(typeof e!="number"&&typeof e!="string")break;const a=ce.uParse(e);return t?a.toString():a;case E.BOOL:if(typeof e!="boolean")break;return e;case E.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case E.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return Wo.dec(e)}throw new Error}function Rn(i,e,t,n){if(e===null)return i.typeName=="google.protobuf.NullValue"?0:n?i.values[0].no:an;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":const s=i.findName(e);if(s!==void 0)return s.no;if(t)return Hi;break}throw new Error("cannot decode enum ".concat(i.typeName," from JSON: ").concat(Je(e)))}function zl(i){return i.repeated||i.kind=="map"?!0:!(i.oneof||i.kind=="message"||i.opt||i.req)}function Sr(i,e,t){if(i.kind=="map"){ue(typeof e=="object"&&e!=null);const n={},s=Object.entries(e);switch(i.V.kind){case"scalar":for(const[o,a]of s)n[o.toString()]=zi(i.V.T,a);break;case"message":for(const[o,a]of s)n[o.toString()]=a.toJson(t);break;case"enum":const r=i.V.T;for(const[o,a]of s)n[o.toString()]=In(r,a,t.enumAsInteger);break}return t.emitDefaultValues||s.length>0?n:void 0}if(i.repeated){ue(Array.isArray(e));const n=[];switch(i.kind){case"scalar":for(let s=0;s<e.length;s++)n.push(zi(i.T,e[s]));break;case"enum":for(let s=0;s<e.length;s++)n.push(In(i.T,e[s],t.enumAsInteger));break;case"message":for(let s=0;s<e.length;s++)n.push(e[s].toJson(t));break}return t.emitDefaultValues||n.length>0?n:void 0}switch(i.kind){case"scalar":return zi(i.T,e);case"enum":return In(i.T,e,t.enumAsInteger);case"message":return Yo(i.T,e).toJson(t)}}function In(i,e,t){var n;if(ue(typeof e=="number"),i.typeName=="google.protobuf.NullValue")return null;if(t)return e;const s=i.findNumber(e);return(n=s==null?void 0:s.name)!==null&&n!==void 0?n:e}function zi(i,e){switch(i){case E.INT32:case E.SFIXED32:case E.SINT32:case E.FIXED32:case E.UINT32:return ue(typeof e=="number"),e;case E.FLOAT:case E.DOUBLE:return ue(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case E.STRING:return ue(typeof e=="string"),e;case E.BOOL:return ue(typeof e=="boolean"),e;case E.UINT64:case E.FIXED64:case E.INT64:case E.SFIXED64:case E.SINT64:return ue(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case E.BYTES:return ue(e instanceof Uint8Array),Wo.enc(e)}}const Bt=Symbol("@bufbuild/protobuf/unknown-fields"),Er={readUnknownFields:!0,readerFactory:i=>new Nl(i)},wr={writeUnknownFields:!0,writerFactory:()=>new Dl};function Gl(i){return i?Object.assign(Object.assign({},Er),i):Er}function Wl(i){return i?Object.assign(Object.assign({},wr),i):wr}function Kl(){return{makeReadOptions:Gl,makeWriteOptions:Wl,listUnknownFields(i){var e;return(e=i[Bt])!==null&&e!==void 0?e:[]},discardUnknownFields(i){delete i[Bt]},writeUnknownFields(i,e){const n=i[Bt];if(n)for(const s of n)e.tag(s.no,s.wireType).raw(s.data)},onUnknownField(i,e,t,n){const s=i;Array.isArray(s[Bt])||(s[Bt]=[]),s[Bt].push({no:e,wireType:t,data:n})},readMessage(i,e,t,n,s){const r=i.getType(),o=s?e.len:e.pos+t;let a,c;for(;e.pos<o&&([a,c]=e.tag(),!(s===!0&&c==me.EndGroup));){const d=r.fields.find(a);if(!d){const l=e.skip(c,a);n.readUnknownFields&&this.onUnknownField(i,a,c,l);continue}_r(i,e,d,c,n)}if(s&&(c!=me.EndGroup||a!==t))throw new Error("invalid end group tag")},readField:_r,writeMessage(i,e,t){const n=i.getType();for(const s of n.fields.byNumber()){if(!Qo(s,i)){if(s.req)throw new Error("cannot encode field ".concat(n.typeName,".").concat(s.name," to binary: required field not set"));continue}const r=s.oneof?i[s.oneof.localName].value:i[s.localName];Pr(s,r,e,t)}return t.writeUnknownFields&&this.writeUnknownFields(i,e),e},writeField(i,e,t,n){e!==void 0&&Pr(i,e,t,n)}}}function _r(i,e,t,n,s){let{repeated:r,localName:o}=t;switch(t.oneof&&(i=i[t.oneof.localName],i.case!=o&&delete i.value,i.case=o,o="value"),t.kind){case"scalar":case"enum":const a=t.kind=="enum"?E.INT32:t.T;let c=cn;if(t.kind=="scalar"&&t.L>0&&(c=Ql),r){let h=i[o];if(n==me.LengthDelimited&&a!=E.STRING&&a!=E.BYTES){let m=e.uint32()+e.pos;for(;e.pos<m;)h.push(c(e,a))}else h.push(c(e,a))}else i[o]=c(e,a);break;case"message":const d=t.T;r?i[o].push(Gi(e,new d,s,t)):At(i[o])?Gi(e,i[o],s,t):(i[o]=Gi(e,new d,s,t),d.fieldWrapper&&!t.oneof&&!t.repeated&&(i[o]=d.fieldWrapper.unwrapField(i[o])));break;case"map":let[l,u]=Jl(t,e,s);i[o][l]=u;break}}function Gi(i,e,t,n){const s=e.getType().runtime.bin,r=n==null?void 0:n.delimited;return s.readMessage(e,i,r?n.no:i.uint32(),t,r),e}function Jl(i,e,t){const n=e.uint32(),s=e.pos+n;let r,o;for(;e.pos<s;){const[a]=e.tag();switch(a){case 1:r=cn(e,i.K);break;case 2:switch(i.V.kind){case"scalar":o=cn(e,i.V.T);break;case"enum":o=e.int32();break;case"message":o=Gi(e,new i.V.T,t,void 0);break}break}}if(r===void 0&&(r=Zt(i.K,St.BIGINT)),typeof r!="string"&&typeof r!="number"&&(r=r.toString()),o===void 0)switch(i.V.kind){case"scalar":o=Zt(i.V.T,St.BIGINT);break;case"enum":o=i.V.T.values[0].no;break;case"message":o=new i.V.T;break}return[r,o]}function Ql(i,e){const t=cn(i,e);return typeof t=="bigint"?t.toString():t}function cn(i,e){switch(e){case E.STRING:return i.string();case E.BOOL:return i.bool();case E.DOUBLE:return i.double();case E.FLOAT:return i.float();case E.INT32:return i.int32();case E.INT64:return i.int64();case E.UINT64:return i.uint64();case E.FIXED64:return i.fixed64();case E.BYTES:return i.bytes();case E.FIXED32:return i.fixed32();case E.SFIXED32:return i.sfixed32();case E.SFIXED64:return i.sfixed64();case E.SINT64:return i.sint64();case E.UINT32:return i.uint32();case E.SINT32:return i.sint32()}}function Pr(i,e,t,n){ue(e!==void 0);const s=i.repeated;switch(i.kind){case"scalar":case"enum":let r=i.kind=="enum"?E.INT32:i.T;if(s)if(ue(Array.isArray(e)),i.packed)Xl(t,r,i.no,e);else for(const o of e)yi(t,r,i.no,o);else yi(t,r,i.no,e);break;case"message":if(s){ue(Array.isArray(e));for(const o of e)Rr(t,n,i,o)}else Rr(t,n,i,e);break;case"map":ue(typeof e=="object"&&e!=null);for(const[o,a]of Object.entries(e))Yl(t,n,i,o,a);break}}function Yl(i,e,t,n,s){i.tag(t.no,me.LengthDelimited),i.fork();let r=n;switch(t.K){case E.INT32:case E.FIXED32:case E.UINT32:case E.SFIXED32:case E.SINT32:r=Number.parseInt(n);break;case E.BOOL:ue(n=="true"||n=="false"),r=n=="true";break}switch(yi(i,t.K,1,r),t.V.kind){case"scalar":yi(i,t.V.T,2,s);break;case"enum":yi(i,E.INT32,2,s);break;case"message":ue(s!==void 0),i.tag(2,me.LengthDelimited).bytes(s.toBinary(e));break}i.join()}function Rr(i,e,t,n){const s=Yo(t.T,n);t.delimited?i.tag(t.no,me.StartGroup).raw(s.toBinary(e)).tag(t.no,me.EndGroup):i.tag(t.no,me.LengthDelimited).bytes(s.toBinary(e))}function yi(i,e,t,n){ue(n!==void 0);let[s,r]=Xo(e);i.tag(t,s)[r](n)}function Xl(i,e,t,n){if(!n.length)return;i.tag(t,me.LengthDelimited).fork();let[,s]=Xo(e);for(let r=0;r<n.length;r++)i[s](n[r]);i.join()}function Xo(i){let e=me.Varint;switch(i){case E.BYTES:case E.STRING:e=me.LengthDelimited;break;case E.DOUBLE:case E.FIXED64:case E.SFIXED64:e=me.Bit64;break;case E.FIXED32:case E.SFIXED32:case E.FLOAT:e=me.Bit32;break}const t=E[i].toLowerCase();return[e,t]}function Zl(){return{setEnumType:Bo,initPartial(i,e){if(i===void 0)return;const t=e.getType();for(const n of t.fields.byMember()){const s=n.localName,r=e,o=i;if(o[s]!=null)switch(n.kind){case"oneof":const a=o[s].case;if(a===void 0)continue;const c=n.findField(a);let d=o[s].value;c&&c.kind=="message"&&!At(d,c.T)?d=new c.T(d):c&&c.kind==="scalar"&&c.T===E.BYTES&&(d=oi(d)),r[s]={case:a,value:d};break;case"scalar":case"enum":let l=o[s];n.T===E.BYTES&&(l=n.repeated?l.map(oi):oi(l)),r[s]=l;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===E.BYTES)for(const[f,m]of Object.entries(o[s]))r[s][f]=oi(m);else Object.assign(r[s],o[s]);break;case"message":const h=n.V.T;for(const f of Object.keys(o[s])){let m=o[s][f];h.fieldWrapper||(m=new h(m)),r[s][f]=m}break}break;case"message":const u=n.T;if(n.repeated)r[s]=o[s].map(h=>At(h,u)?h:new u(h));else{const h=o[s];u.fieldWrapper?u.typeName==="google.protobuf.BytesValue"?r[s]=oi(h):r[s]=h:r[s]=At(h,u)?h:new u(h)}break}}},equals(i,e,t){return e===t?!0:!e||!t?!1:i.fields.byMember().every(n=>{const s=e[n.localName],r=t[n.localName];if(n.repeated){if(s.length!==r.length)return!1;switch(n.kind){case"message":return s.every((o,a)=>n.T.equals(o,r[a]));case"scalar":return s.every((o,a)=>ht(n.T,o,r[a]));case"enum":return s.every((o,a)=>ht(E.INT32,o,r[a]))}throw new Error("repeated cannot contain ".concat(n.kind))}switch(n.kind){case"message":return n.T.equals(s,r);case"enum":return ht(E.INT32,s,r);case"scalar":return ht(n.T,s,r);case"oneof":if(s.case!==r.case)return!1;const o=n.findField(s.case);if(o===void 0)return!0;switch(o.kind){case"message":return o.T.equals(s.value,r.value);case"enum":return ht(E.INT32,s.value,r.value);case"scalar":return ht(o.T,s.value,r.value)}throw new Error("oneof cannot contain ".concat(o.kind));case"map":const a=Object.keys(s).concat(Object.keys(r));switch(n.V.kind){case"message":const c=n.V.T;return a.every(l=>c.equals(s[l],r[l]));case"enum":return a.every(l=>ht(E.INT32,s[l],r[l]));case"scalar":const d=n.V.T;return a.every(l=>ht(d,s[l],r[l]))}break}})},clone(i){const e=i.getType(),t=new e,n=t;for(const s of e.fields.byMember()){const r=i[s.localName];let o;if(s.repeated)o=r.map(Li);else if(s.kind=="map"){o=n[s.localName];for(const[a,c]of Object.entries(r))o[a]=Li(c)}else s.kind=="oneof"?o=s.findField(r.case)?{case:r.case,value:Li(r.value)}:{case:void 0}:o=Li(r);n[s.localName]=o}for(const s of e.runtime.bin.listUnknownFields(i))e.runtime.bin.onUnknownField(n,s.no,s.wireType,s.data);return t}}}function Li(i){if(i===void 0)return i;if(At(i))return i.clone();if(i instanceof Uint8Array){const e=new Uint8Array(i.byteLength);return e.set(i),e}return i}function oi(i){return i instanceof Uint8Array?i:new Uint8Array(i)}function eu(i,e,t){return{syntax:i,json:$l(),bin:Kl(),util:Object.assign(Object.assign({},Zl()),{newFieldList:e,initFields:t}),makeMessageType(n,s,r){return Rl(this,n,s,r)},makeEnum:Pl,makeEnumType:Vo,getEnumType:_l,makeExtension(n,s,r){return Ll(this,n,s,r)}}}class tu{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const t={};for(const n of this.list())t[n.jsonName]=t[n.name]=n;this.jsonNames=t}return this.jsonNames[e]}find(e){if(!this.numbers){const t={};for(const n of this.list())t[n.no]=n;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 n of this.list())n.oneof?n.oneof!==t&&(t=n.oneof,e.push(t)):e.push(n)}return this.members}}function Zo(i,e){const t=ea(i);return e?t:au(ou(t))}function iu(i){return Zo(i,!1)}const nu=ea;function ea(i){let e=!1;const t=[];for(let n=0;n<i.length;n++){let s=i.charAt(n);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 su=new Set(["constructor","toString","toJSON","valueOf"]),ru=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),ta=i=>"".concat(i,"$"),ou=i=>ru.has(i)?ta(i):i,au=i=>su.has(i)?ta(i):i;class cu{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=iu(e)}addField(e){ue(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let t=0;t<this.fields.length;t++)this._lookup[this.fields[t].localName]=this.fields[t]}return this._lookup[e]}}function du(i,e){var t,n,s,r,o,a;const c=[];let d;for(const l of typeof i=="function"?i():i){const u=l;if(u.localName=Zo(l.name,l.oneof!==void 0),u.jsonName=(t=l.jsonName)!==null&&t!==void 0?t:nu(l.name),u.repeated=(n=l.repeated)!==null&&n!==void 0?n:!1,l.kind=="scalar"&&(u.L=(s=l.L)!==null&&s!==void 0?s:St.BIGINT),u.delimited=(r=l.delimited)!==null&&r!==void 0?r:!1,u.req=(o=l.req)!==null&&o!==void 0?o:!1,u.opt=(a=l.opt)!==null&&a!==void 0?a:!1,l.packed===void 0&&(u.packed=l.kind=="enum"||l.kind=="scalar"&&l.T!=E.BYTES&&l.T!=E.STRING),l.oneof!==void 0){const h=typeof l.oneof=="string"?l.oneof:l.oneof.name;(!d||d.name!=h)&&(d=new cu(h)),u.oneof=d,d.addField(u)}c.push(u)}return c}const b=eu("proto3",i=>new tu(i,e=>du(e)),i=>{for(const e of i.getType().fields.byMember()){if(e.opt)continue;const t=e.localName,n=i;if(e.repeated){n[t]=[];continue}switch(e.kind){case"oneof":n[t]={case:void 0};break;case"enum":n[t]=0;break;case"map":n[t]={};break;case"scalar":n[t]=Zt(e.T,e.L);break}}});class Pe extends js{constructor(e){super(),this.seconds=ce.zero,this.nanos=0,b.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(b.json.debug(e)));const n=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(!n)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const s=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[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=ce.parse(s/1e3),this.nanos=0,n[7]&&(this.nanos=parseInt("1"+n[7]+"0".repeat(9-n[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 n="Z";if(this.nanos>0){const s=(this.nanos+1e9).toString().substring(1);s.substring(3)==="000000"?n="."+s.substring(0,3)+"Z":s.substring(6)==="000"?n="."+s.substring(0,6)+"Z":n="."+s+"Z"}return new Date(t).toISOString().replace(".000Z",n)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return Pe.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new Pe({seconds:ce.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new Pe().fromBinary(e,t)}static fromJson(e,t){return new Pe().fromJson(e,t)}static fromJsonString(e,t){return new Pe().fromJsonString(e,t)}static equals(e,t){return b.util.equals(Pe,e,t)}}Pe.runtime=b;Pe.typeName="google.protobuf.Timestamp";Pe.fields=b.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const lu=b.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Pe},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:uu,repeated:!0},{no:5,name:"events",kind:"message",T:fu,repeated:!0}]),uu=b.makeMessageType("livekit.TimeSeriesMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"samples",kind:"message",T:hu,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),hu=b.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Pe},{no:3,name:"value",kind:"scalar",T:2}]),fu=b.makeMessageType("livekit.EventMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"start_timestamp_ms",kind:"scalar",T:3},{no:5,name:"end_timestamp_ms",kind:"scalar",T:3,opt:!0},{no:6,name:"normalized_start_timestamp",kind:"message",T:Pe},{no:7,name:"normalized_end_timestamp",kind:"message",T:Pe,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),ia=b.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"REGRESSION"},{no:1,name:"SIMULCAST"}]),qe=b.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),ge=b.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"}]),Bs=b.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),fi=b.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),wi=b.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),ze=b.makeEnum("livekit.DisconnectReason",[{no:0,name:"UNKNOWN_REASON"},{no:1,name:"CLIENT_INITIATED"},{no:2,name:"DUPLICATE_IDENTITY"},{no:3,name:"SERVER_SHUTDOWN"},{no:4,name:"PARTICIPANT_REMOVED"},{no:5,name:"ROOM_DELETED"},{no:6,name:"STATE_MISMATCH"},{no:7,name:"JOIN_FAILURE"},{no:8,name:"MIGRATION"},{no:9,name:"SIGNAL_CLOSE"},{no:10,name:"ROOM_CLOSED"},{no:11,name:"USER_UNAVAILABLE"},{no:12,name:"USER_REJECTED"},{no:13,name:"SIP_TRUNK_FAILURE"}]),Vt=b.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"}]),pu=b.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),Ye=b.makeEnum("livekit.AudioTrackFeature",[{no:0,name:"TF_STEREO"},{no:1,name:"TF_NO_DTX"},{no:2,name:"TF_AUTO_GAIN_CONTROL"},{no:3,name:"TF_ECHO_CANCELLATION"},{no:4,name:"TF_NOISE_SUPPRESSION"},{no:5,name:"TF_ENHANCED_NOISE_CANCELLATION"}]),Vs=b.makeMessageType("livekit.Room",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"empty_timeout",kind:"scalar",T:13},{no:14,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:5,name:"creation_time",kind:"scalar",T:3},{no:15,name:"creation_time_ms",kind:"scalar",T:3},{no:6,name:"turn_password",kind:"scalar",T:9},{no:7,name:"enabled_codecs",kind:"message",T:dn,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:pa}]),dn=b.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),mu=b.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:b.getEnumType(ge),repeated:!0},{no:7,name:"hidden",kind:"scalar",T:8},{no:8,name:"recorder",kind:"scalar",T:8},{no:10,name:"can_update_metadata",kind:"scalar",T:8},{no:11,name:"agent",kind:"scalar",T:8},{no:12,name:"can_subscribe_metrics",kind:"scalar",T:8}]),_i=b.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:b.getEnumType(Zn)},{no:4,name:"tracks",kind:"message",T:Ht,repeated:!0},{no:5,name:"metadata",kind:"scalar",T:9},{no:6,name:"joined_at",kind:"scalar",T:3},{no:17,name:"joined_at_ms",kind:"scalar",T:3},{no:9,name:"name",kind:"scalar",T:9},{no:10,name:"version",kind:"scalar",T:13},{no:11,name:"permission",kind:"message",T:mu},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:b.getEnumType(ln)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:b.getEnumType(ze)}]),Zn=b.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),ln=b.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]),Me=b.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),gu=b.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:Mt,repeated:!0}]),Ht=b.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:b.getEnumType(qe)},{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:b.getEnumType(ge)},{no:10,name:"layers",kind:"message",T:Mt,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:gu,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:b.getEnumType(Me)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:pa},{no:19,name:"audio_features",kind:"enum",T:b.getEnumType(Ye),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:b.getEnumType(ia)}]),Mt=b.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:b.getEnumType(Bs)},{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}]),_e=b.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:b.getEnumType(Q)},{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:sa,oneof:"value"},{no:3,name:"speaker",kind:"message",T:vu,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:ra,oneof:"value"},{no:7,name:"transcription",kind:"message",T:yu,oneof:"value"},{no:8,name:"metrics",kind:"message",T:lu,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:es,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:oa,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:aa,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:ca,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:is,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:ns,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:ss,oneof:"value"}]),Q=b.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),vu=b.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:na,repeated:!0}]),na=b.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}]),sa=b.makeMessageType("livekit.UserPacket",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:5,name:"participant_identity",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"destination_sids",kind:"scalar",T:9,repeated:!0},{no:6,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:4,name:"topic",kind:"scalar",T:9,opt:!0},{no:8,name:"id",kind:"scalar",T:9,opt:!0},{no:9,name:"start_time",kind:"scalar",T:4,opt:!0},{no:10,name:"end_time",kind:"scalar",T:4,opt:!0},{no:11,name:"nonce",kind:"scalar",T:12}]),ra=b.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),yu=b.makeMessageType("livekit.Transcription",()=>[{no:2,name:"transcribed_participant_identity",kind:"scalar",T:9},{no:3,name:"track_id",kind:"scalar",T:9},{no:4,name:"segments",kind:"message",T:bu,repeated:!0}]),bu=b.makeMessageType("livekit.TranscriptionSegment",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}]),es=b.makeMessageType("livekit.ChatMessage",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"edit_timestamp",kind:"scalar",T:3,opt:!0},{no:4,name:"message",kind:"scalar",T:9},{no:5,name:"deleted",kind:"scalar",T:8},{no:6,name:"generated",kind:"scalar",T:8}]),oa=b.makeMessageType("livekit.RpcRequest",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"method",kind:"scalar",T:9},{no:3,name:"payload",kind:"scalar",T:9},{no:4,name:"response_timeout_ms",kind:"scalar",T:13},{no:5,name:"version",kind:"scalar",T:13}]),aa=b.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),ca=b.makeMessageType("livekit.RpcResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:9,oneof:"value"},{no:3,name:"error",kind:"message",T:da,oneof:"value"}]),da=b.makeMessageType("livekit.RpcError",()=>[{no:1,name:"code",kind:"scalar",T:13},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"data",kind:"scalar",T:9}]),la=b.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),ku=b.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:b.getEnumType(ua)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"region",kind:"scalar",T:9},{no:5,name:"node_id",kind:"scalar",T:9},{no:6,name:"debug_info",kind:"scalar",T:9},{no:7,name:"agent_protocol",kind:"scalar",T:5}]),ua=b.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Tu=b.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:b.getEnumType(ha)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"os",kind:"scalar",T:9},{no:5,name:"os_version",kind:"scalar",T:9},{no:6,name:"device_model",kind:"scalar",T:9},{no:7,name:"browser",kind:"scalar",T:9},{no:8,name:"browser_version",kind:"scalar",T:9},{no:9,name:"address",kind:"scalar",T:9},{no:10,name:"network",kind:"scalar",T:9},{no:11,name:"other_sdks",kind:"scalar",T:9}]),ha=b.makeEnum("livekit.ClientInfo.SDK",[{no:0,name:"UNKNOWN"},{no:1,name:"JS"},{no:2,name:"SWIFT"},{no:3,name:"ANDROID"},{no:4,name:"FLUTTER"},{no:5,name:"GO"},{no:6,name:"UNITY"},{no:7,name:"REACT_NATIVE"},{no:8,name:"RUST"},{no:9,name:"PYTHON"},{no:10,name:"CPP"},{no:11,name:"UNITY_WEB"},{no:12,name:"NODE"}]),fa=b.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:Ir},{no:2,name:"screen",kind:"message",T:Ir},{no:3,name:"resume_connection",kind:"enum",T:b.getEnumType(wi)},{no:4,name:"disabled_codecs",kind:"message",T:Cu},{no:5,name:"force_relay",kind:"enum",T:b.getEnumType(wi)}]),Ir=b.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:b.getEnumType(wi)}]),Cu=b.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:dn,repeated:!0},{no:2,name:"publish",kind:"message",T:dn,repeated:!0}]),pa=b.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),ts=b.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),ma=b.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:b.getEnumType(ts)},{no:2,name:"version",kind:"scalar",T:5},{no:3,name:"reply_to_stream_id",kind:"scalar",T:9},{no:4,name:"attached_stream_ids",kind:"scalar",T:9,repeated:!0},{no:5,name:"generated",kind:"scalar",T:8}],{localName:"DataStream_TextHeader"}),ga=b.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),is=b.makeMessageType("livekit.DataStream.Header",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"topic",kind:"scalar",T:9},{no:4,name:"mime_type",kind:"scalar",T:9},{no:5,name:"total_length",kind:"scalar",T:4,opt:!0},{no:7,name:"encryption_type",kind:"enum",T:b.getEnumType(Me)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:ma,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:ga,oneof:"content_header"}],{localName:"DataStream_Header"}),ns=b.makeMessageType("livekit.DataStream.Chunk",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"chunk_index",kind:"scalar",T:4},{no:3,name:"content",kind:"scalar",T:12},{no:4,name:"version",kind:"scalar",T:5},{no:5,name:"iv",kind:"scalar",T:12,opt:!0}],{localName:"DataStream_Chunk"}),ss=b.makeMessageType("livekit.DataStream.Trailer",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"reason",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}],{localName:"DataStream_Trailer"}),$e=b.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),rs=b.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),Su=b.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),Eu=b.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:Dt,oneof:"message"},{no:2,name:"answer",kind:"message",T:Dt,oneof:"message"},{no:3,name:"trickle",kind:"message",T:qs,oneof:"message"},{no:4,name:"add_track",kind:"message",T:as,oneof:"message"},{no:5,name:"mute",kind:"message",T:$s,oneof:"message"},{no:6,name:"subscription",kind:"message",T:bn,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:va,oneof:"message"},{no:8,name:"leave",kind:"message",T:kn,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:ba,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Sa,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Ea,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:ka,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:_a,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:ya,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Iu,oneof:"message"}]),Or=b.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:wu,oneof:"message"},{no:2,name:"answer",kind:"message",T:Dt,oneof:"message"},{no:3,name:"offer",kind:"message",T:Dt,oneof:"message"},{no:4,name:"trickle",kind:"message",T:qs,oneof:"message"},{no:5,name:"update",kind:"message",T:Ru,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Hs,oneof:"message"},{no:8,name:"leave",kind:"message",T:kn,oneof:"message"},{no:9,name:"mute",kind:"message",T:$s,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Ou,oneof:"message"},{no:11,name:"room_update",kind:"message",T:xu,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:Mu,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Nu,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:Uu,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:ju,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Pu,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:_u,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Fu,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:qu,oneof:"message"},{no:22,name:"request_response",kind:"message",T:$u,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Hu,oneof:"message"}]),os=b.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}]),as=b.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:b.getEnumType(qe)},{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:b.getEnumType(ge)},{no:9,name:"layers",kind:"message",T:Mt,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:os,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:b.getEnumType(Me)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:b.getEnumType(ia)}]),qs=b.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:b.getEnumType($e)},{no:3,name:"final",kind:"scalar",T:8}]),$s=b.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),wu=b.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:Vs},{no:2,name:"participant",kind:"message",T:_i},{no:3,name:"other_participants",kind:"message",T:_i,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:Ta,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:fa},{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:ku},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:dn,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),_u=b.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:Ta,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:fa}]),Hs=b.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Ht}]),Pu=b.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),Dt=b.makeMessageType("livekit.SessionDescription",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9}]),Ru=b.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:_i,repeated:!0}]),bn=b.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:la,repeated:!0}]),va=b.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:b.getEnumType(Bs)},{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}]),ya=b.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:b.getEnumType(Ye),repeated:!0}]),Iu=b.makeMessageType("livekit.UpdateLocalVideoTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13}]),kn=b.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:b.getEnumType(ze)},{no:3,name:"action",kind:"enum",T:b.getEnumType(Wt)},{no:4,name:"regions",kind:"message",T:Bu}]),Wt=b.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),ba=b.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:Mt,repeated:!0}]),ka=b.makeMessageType("livekit.UpdateParticipantMetadata",()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:4,name:"request_id",kind:"scalar",T:13}]),Ta=b.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}]),Ou=b.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:na,repeated:!0}]),xu=b.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:Vs}]),Au=b.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:b.getEnumType(fi)},{no:3,name:"score",kind:"scalar",T:2}]),Mu=b.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:Au,repeated:!0}]),Du=b.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:b.getEnumType(rs)}]),Nu=b.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:Du,repeated:!0}]),zs=b.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:b.getEnumType(Bs)},{no:2,name:"enabled",kind:"scalar",T:8}]),Lu=b.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:zs,repeated:!0}]),Uu=b.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:zs,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:Lu,repeated:!0}]),Ca=b.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}]),Sa=b.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Ca,repeated:!0}]),ju=b.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}]),Ea=b.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:Dt},{no:2,name:"subscription",kind:"message",T:bn},{no:3,name:"publish_tracks",kind:"message",T:Hs,repeated:!0},{no:4,name:"data_channels",kind:"message",T:wa,repeated:!0},{no:5,name:"offer",kind:"message",T:Dt},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0}]),wa=b.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:b.getEnumType($e)}]),Ke=b.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:b.getEnumType(Su),oneof:"scenario"},{no:6,name:"subscriber_bandwidth",kind:"scalar",T:3,oneof:"scenario"},{no:7,name:"disconnect_signal_on_resume",kind:"scalar",T:8,oneof:"scenario"},{no:8,name:"disconnect_signal_on_resume_no_messages",kind:"scalar",T:8,oneof:"scenario"},{no:9,name:"leave_request_full_reconnect",kind:"scalar",T:8,oneof:"scenario"}]),_a=b.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),Fu=b.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),Bu=b.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:Vu,repeated:!0}]),Vu=b.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}]),qu=b.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:b.getEnumType(pu)}]),$u=b.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:b.getEnumType(Gs)},{no:3,name:"message",kind:"scalar",T:9}]),Gs=b.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"}]),Hu=b.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]);function zu(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Wi={exports:{}},Gu=Wi.exports,xr;function Wu(){return xr||(xr=1,function(i){(function(e,t){i.exports?i.exports=t():e.log=t()})(Gu,function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],r={},o=null;function a(g,T){var C=g[T];if(typeof C.bind=="function")return C.bind(g);try{return Function.prototype.bind.call(C,g)}catch{return function(){return Function.prototype.apply.apply(C,[g,arguments])}}}function c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function d(g){return g==="debug"&&(g="log"),typeof console===t?!1:g==="trace"&&n?c:console[g]!==void 0?a(console,g):console.log!==void 0?a(console,"log"):e}function l(){for(var g=this.getLevel(),T=0;T<s.length;T++){var C=s[T];this[C]=T<g?e:this.methodFactory(C,g,this.name)}if(this.log=this.debug,typeof console===t&&g<this.levels.SILENT)return"No console available for logging"}function u(g){return function(){typeof console!==t&&(l.call(this),this[g].apply(this,arguments))}}function h(g,T,C){return d(g)||u.apply(this,arguments)}function f(g,T){var C=this,M,j,k,y="loglevel";typeof g=="string"?y+=":"+g:typeof g=="symbol"&&(y=void 0);function _($){var ee=(s[$]||"silent").toUpperCase();if(!(typeof window===t||!y)){try{window.localStorage[y]=ee;return}catch{}try{window.document.cookie=encodeURIComponent(y)+"="+ee+";"}catch{}}}function R(){var $;if(!(typeof window===t||!y)){try{$=window.localStorage[y]}catch{}if(typeof $===t)try{var ee=window.document.cookie,Oe=encodeURIComponent(y),Ue=ee.indexOf(Oe+"=");Ue!==-1&&($=/^([^;]+)/.exec(ee.slice(Ue+Oe.length+1))[1])}catch{}return C.levels[$]===void 0&&($=void 0),$}}function D(){if(!(typeof window===t||!y)){try{window.localStorage.removeItem(y)}catch{}try{window.document.cookie=encodeURIComponent(y)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function F($){var ee=$;if(typeof ee=="string"&&C.levels[ee.toUpperCase()]!==void 0&&(ee=C.levels[ee.toUpperCase()]),typeof ee=="number"&&ee>=0&&ee<=C.levels.SILENT)return ee;throw new TypeError("log.setLevel() called with invalid level: "+$)}C.name=g,C.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},C.methodFactory=T||h,C.getLevel=function(){return k??j??M},C.setLevel=function($,ee){return k=F($),ee!==!1&&_(k),l.call(C)},C.setDefaultLevel=function($){j=F($),R()||C.setLevel($,!1)},C.resetLevel=function(){k=null,D(),l.call(C)},C.enableAll=function($){C.setLevel(C.levels.TRACE,$)},C.disableAll=function($){C.setLevel(C.levels.SILENT,$)},C.rebuild=function(){if(o!==C&&(M=F(o.getLevel())),l.call(C),o===C)for(var $ in r)r[$].rebuild()},M=F(o?o.getLevel():"WARN");var U=R();U!=null&&(k=F(U)),l.call(C)}o=new f,o.getLogger=function(T){if(typeof T!="symbol"&&typeof T!="string"||T==="")throw new TypeError("You must supply a name when creating a logger.");var C=r[T];return C||(C=r[T]=new f(T,o.methodFactory)),C};var m=typeof window!==t?window.log:void 0;return o.noConflict=function(){return typeof window!==t&&window.log===o&&(window.log=m),o},o.getLoggers=function(){return r},o.default=o,o})}(Wi)),Wi.exports}var Tn=Wu(),cs;(function(i){i[i.trace=0]="trace",i[i.debug=1]="debug",i[i.info=2]="info",i[i.warn=3]="warn",i[i.error=4]="error",i[i.silent=5]="silent"})(cs||(cs={}));var Ge;(function(i){i.Default="livekit",i.Room="livekit-room",i.Participant="livekit-participant",i.Track="livekit-track",i.Publication="livekit-track-publication",i.Engine="livekit-engine",i.Signal="livekit-signal",i.PCManager="livekit-pc-manager",i.PCTransport="livekit-pc-transport",i.E2EE="lk-e2ee"})(Ge||(Ge={}));let W=Tn.getLogger("livekit");Object.values(Ge).map(i=>Tn.getLogger(i));W.setDefaultLevel(cs.info);function ct(i){const e=Tn.getLogger(i);return e.setDefaultLevel(W.getLevel()),e}const Ku=Tn.getLogger("lk-e2ee"),ai=7e3,Ju=[0,300,2*2*300,3*3*300,4*4*300,ai,ai,ai,ai,ai];class Qu{constructor(e){this._retryDelays=e!==void 0?[...e]:Ju}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 Yu(i,e){var t={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&e.indexOf(n)<0&&(t[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(i);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(i,n[s])&&(t[n[s]]=i[n[s]]);return t}function p(i,e,t,n){function s(r){return r instanceof t?r:new t(function(o){o(r)})}return new(t||(t=Promise))(function(r,o){function a(l){try{d(n.next(l))}catch(u){o(u)}}function c(l){try{d(n.throw(l))}catch(u){o(u)}}function d(l){l.done?r(l.value):s(l.value).then(a,c)}d((n=n.apply(i,e||[])).next())})}function Ar(i){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&i[e],n=0;if(t)return t.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&n>=i.length&&(i=void 0),{value:i&&i[n++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function vt(i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=i[Symbol.asyncIterator],t;return e?e.call(i):(i=typeof Ar=="function"?Ar(i):i[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=i[r]&&function(o){return new Promise(function(a,c){o=i[r](o),s(a,c,o.done,o.value)})}}function s(r,o,a,c){Promise.resolve(c).then(function(d){r({value:d,done:a})},o)}}var Ui={exports:{}},Mr;function Xu(){if(Mr)return Ui.exports;Mr=1;var i=typeof Reflect=="object"?Reflect:null,e=i&&typeof i.apply=="function"?i.apply:function(y,_,R){return Function.prototype.apply.call(y,_,R)},t;i&&typeof i.ownKeys=="function"?t=i.ownKeys:Object.getOwnPropertySymbols?t=function(y){return Object.getOwnPropertyNames(y).concat(Object.getOwnPropertySymbols(y))}:t=function(y){return Object.getOwnPropertyNames(y)};function n(k){console&&console.warn&&console.warn(k)}var s=Number.isNaN||function(y){return y!==y};function r(){r.init.call(this)}Ui.exports=r,Ui.exports.once=C,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var o=10;function a(k){if(typeof k!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof k)}Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(k){if(typeof k!="number"||k<0||s(k))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+k+".");o=k}}),r.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},r.prototype.setMaxListeners=function(y){if(typeof y!="number"||y<0||s(y))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+y+".");return this._maxListeners=y,this};function c(k){return k._maxListeners===void 0?r.defaultMaxListeners:k._maxListeners}r.prototype.getMaxListeners=function(){return c(this)},r.prototype.emit=function(y){for(var _=[],R=1;R<arguments.length;R++)_.push(arguments[R]);var D=y==="error",F=this._events;if(F!==void 0)D=D&&F.error===void 0;else if(!D)return!1;if(D){var U;if(_.length>0&&(U=_[0]),U instanceof Error)throw U;var $=new Error("Unhandled error."+(U?" ("+U.message+")":""));throw $.context=U,$}var ee=F[y];if(ee===void 0)return!1;if(typeof ee=="function")e(ee,this,_);else for(var Oe=ee.length,Ue=m(ee,Oe),R=0;R<Oe;++R)e(Ue[R],this,_);return!0};function d(k,y,_,R){var D,F,U;if(a(_),F=k._events,F===void 0?(F=k._events=Object.create(null),k._eventsCount=0):(F.newListener!==void 0&&(k.emit("newListener",y,_.listener?_.listener:_),F=k._events),U=F[y]),U===void 0)U=F[y]=_,++k._eventsCount;else if(typeof U=="function"?U=F[y]=R?[_,U]:[U,_]:R?U.unshift(_):U.push(_),D=c(k),D>0&&U.length>D&&!U.warned){U.warned=!0;var $=new Error("Possible EventEmitter memory leak detected. "+U.length+" "+String(y)+" listeners added. Use emitter.setMaxListeners() to increase limit");$.name="MaxListenersExceededWarning",$.emitter=k,$.type=y,$.count=U.length,n($)}return k}r.prototype.addListener=function(y,_){return d(this,y,_,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(y,_){return d(this,y,_,!0)};function l(){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 u(k,y,_){var R={fired:!1,wrapFn:void 0,target:k,type:y,listener:_},D=l.bind(R);return D.listener=_,R.wrapFn=D,D}r.prototype.once=function(y,_){return a(_),this.on(y,u(this,y,_)),this},r.prototype.prependOnceListener=function(y,_){return a(_),this.prependListener(y,u(this,y,_)),this},r.prototype.removeListener=function(y,_){var R,D,F,U,$;if(a(_),D=this._events,D===void 0)return this;if(R=D[y],R===void 0)return this;if(R===_||R.listener===_)--this._eventsCount===0?this._events=Object.create(null):(delete D[y],D.removeListener&&this.emit("removeListener",y,R.listener||_));else if(typeof R!="function"){for(F=-1,U=R.length-1;U>=0;U--)if(R[U]===_||R[U].listener===_){$=R[U].listener,F=U;break}if(F<0)return this;F===0?R.shift():g(R,F),R.length===1&&(D[y]=R[0]),D.removeListener!==void 0&&this.emit("removeListener",y,$||_)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(y){var _,R,D;if(R=this._events,R===void 0)return this;if(R.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):R[y]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete R[y]),this;if(arguments.length===0){var F=Object.keys(R),U;for(D=0;D<F.length;++D)U=F[D],U!=="removeListener"&&this.removeAllListeners(U);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(_=R[y],typeof _=="function")this.removeListener(y,_);else if(_!==void 0)for(D=_.length-1;D>=0;D--)this.removeListener(y,_[D]);return this};function h(k,y,_){var R=k._events;if(R===void 0)return[];var D=R[y];return D===void 0?[]:typeof D=="function"?_?[D.listener||D]:[D]:_?T(D):m(D,D.length)}r.prototype.listeners=function(y){return h(this,y,!0)},r.prototype.rawListeners=function(y){return h(this,y,!1)},r.listenerCount=function(k,y){return typeof k.listenerCount=="function"?k.listenerCount(y):f.call(k,y)},r.prototype.listenerCount=f;function f(k){var y=this._events;if(y!==void 0){var _=y[k];if(typeof _=="function")return 1;if(_!==void 0)return _.length}return 0}r.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function m(k,y){for(var _=new Array(y),R=0;R<y;++R)_[R]=k[R];return _}function g(k,y){for(;y+1<k.length;y++)k[y]=k[y+1];k.pop()}function T(k){for(var y=new Array(k.length),_=0;_<y.length;++_)y[_]=k[_].listener||k[_];return y}function C(k,y){return new Promise(function(_,R){function D(U){k.removeListener(y,F),R(U)}function F(){typeof k.removeListener=="function"&&k.removeListener("error",D),_([].slice.call(arguments))}j(k,y,F,{once:!0}),y!=="error"&&M(k,D,{once:!0})})}function M(k,y,_){typeof k.on=="function"&&j(k,"error",y,_)}function j(k,y,_,R){if(typeof k.on=="function")R.once?k.once(y,_):k.on(y,_);else if(typeof k.addEventListener=="function")k.addEventListener(y,function D(F){R.once&&k.removeEventListener(y,D),_(F)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof k)}return Ui.exports}var et=Xu();let Pa=!0,Ra=!0;function Ki(i,e,t){const n=i.match(e);return n&&n.length>=t&&parseInt(n[t],10)}function Nt(i,e,t){if(!i.RTCPeerConnection)return;const n=i.RTCPeerConnection.prototype,s=n.addEventListener;n.addEventListener=function(o,a){if(o!==e)return s.apply(this,arguments);const c=d=>{const l=t(d);l&&(a.handleEvent?a.handleEvent(l):a(l))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(a,c),s.apply(this,[o,c])};const r=n.removeEventListener;n.removeEventListener=function(o,a){if(o!==e||!this._eventMap||!this._eventMap[e])return r.apply(this,arguments);if(!this._eventMap[e].has(a))return r.apply(this,arguments);const c=this._eventMap[e].get(a);return this._eventMap[e].delete(a),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,r.apply(this,[o,c])},Object.defineProperty(n,"on"+e,{get(){return this["_on"+e]},set(o){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),o&&this.addEventListener(e,this["_on"+e]=o)},enumerable:!0,configurable:!0})}function Zu(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(Pa=i,i?"adapter.js logging disabled":"adapter.js logging enabled")}function eh(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(Ra=!i,"adapter.js deprecation warnings "+(i?"disabled":"enabled"))}function Ia(){if(typeof window=="object"){if(Pa)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Ws(i,e){Ra&&console.warn(i+" is deprecated, please use "+e+" instead.")}function th(i){const e={browser:null,version:null};if(typeof i>"u"||!i.navigator||!i.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:t}=i;if(t.userAgentData&&t.userAgentData.brands){const n=t.userAgentData.brands.find(s=>s.brand==="Chromium");if(n)return{browser:"chrome",version:parseInt(n.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=Ki(t.userAgent,/Firefox\/(\d+)\./,1);else if(t.webkitGetUserMedia||i.isSecureContext===!1&&i.webkitRTCPeerConnection)e.browser="chrome",e.version=Ki(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(i.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=Ki(t.userAgent,/AppleWebKit\/(\d+)\./,1),e.supportsUnifiedPlan=i.RTCRtpTransceiver&&"currentDirection"in i.RTCRtpTransceiver.prototype;else return e.browser="Not a supported browser.",e;return e}function Dr(i){return Object.prototype.toString.call(i)==="[object Object]"}function Oa(i){return Dr(i)?Object.keys(i).reduce(function(e,t){const n=Dr(i[t]),s=n?Oa(i[t]):i[t],r=n&&!Object.keys(s).length;return s===void 0||r?e:Object.assign(e,{[t]:s})},{}):i}function ds(i,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?ds(i,i.get(e[n]),t):n.endsWith("Ids")&&e[n].forEach(s=>{ds(i,i.get(s),t)})}))}function Nr(i,e,t){const n=t?"outbound-rtp":"inbound-rtp",s=new Map;if(e===null)return s;const r=[];return i.forEach(o=>{o.type==="track"&&o.trackIdentifier===e.id&&r.push(o)}),r.forEach(o=>{i.forEach(a=>{a.type===n&&a.trackId===o.id&&ds(i,a,s)})}),s}const Lr=Ia;function xa(i,e){const t=i&&i.navigator;if(!t.mediaDevices)return;const n=function(a){if(typeof a!="object"||a.mandatory||a.optional)return a;const c={};return Object.keys(a).forEach(d=>{if(d==="require"||d==="advanced"||d==="mediaSource")return;const l=typeof a[d]=="object"?a[d]:{ideal:a[d]};l.exact!==void 0&&typeof l.exact=="number"&&(l.min=l.max=l.exact);const u=function(h,f){return h?h+f.charAt(0).toUpperCase()+f.slice(1):f==="deviceId"?"sourceId":f};if(l.ideal!==void 0){c.optional=c.optional||[];let h={};typeof l.ideal=="number"?(h[u("min",d)]=l.ideal,c.optional.push(h),h={},h[u("max",d)]=l.ideal,c.optional.push(h)):(h[u("",d)]=l.ideal,c.optional.push(h))}l.exact!==void 0&&typeof l.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[u("",d)]=l.exact):["min","max"].forEach(h=>{l[h]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[u(h,d)]=l[h])})}),a.advanced&&(c.optional=(c.optional||[]).concat(a.advanced)),c},s=function(a,c){if(e.version>=61)return c(a);if(a=JSON.parse(JSON.stringify(a)),a&&typeof a.audio=="object"){const d=function(l,u,h){u in l&&!(h in l)&&(l[h]=l[u],delete l[u])};a=JSON.parse(JSON.stringify(a)),d(a.audio,"autoGainControl","googAutoGainControl"),d(a.audio,"noiseSuppression","googNoiseSuppression"),a.audio=n(a.audio)}if(a&&typeof a.video=="object"){let d=a.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 a.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(h=>{h=h.filter(m=>m.kind==="videoinput");let f=h.find(m=>u.some(g=>m.label.toLowerCase().includes(g)));return!f&&h.length&&u.includes("back")&&(f=h[h.length-1]),f&&(a.video.deviceId=d.exact?{exact:f.deviceId}:{ideal:f.deviceId}),a.video=n(a.video),Lr("chrome: "+JSON.stringify(a)),c(a)})}a.video=n(a.video)}return Lr("chrome: "+JSON.stringify(a)),c(a)},r=function(a){return e.version>=64?a:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[a.name]||a.name,message:a.message,constraint:a.constraint||a.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},o=function(a,c,d){s(a,l=>{t.webkitGetUserMedia(l,c,u=>{d&&d(r(u))})})};if(t.getUserMedia=o.bind(t),t.mediaDevices.getUserMedia){const a=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(c){return s(c,d=>a(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 Aa(i){i.MediaStream=i.MediaStream||i.webkitMediaStream}function Ma(i){if(typeof i=="object"&&i.RTCPeerConnection&&!("ontrack"in i.RTCPeerConnection.prototype)){Object.defineProperty(i.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=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=n=>{n.stream.addEventListener("addtrack",s=>{let r;i.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(a=>a.track&&a.track.id===s.track.id):r={track:s.track};const o=new Event("track");o.track=s.track,o.receiver=r,o.transceiver={receiver:r},o.streams=[n.stream],this.dispatchEvent(o)}),n.stream.getTracks().forEach(s=>{let r;i.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(a=>a.track&&a.track.id===s.id):r={track:s};const o=new Event("track");o.track=s,o.receiver=r,o.transceiver={receiver:r},o.streams=[n.stream],this.dispatchEvent(o)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else Nt(i,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function Da(i){if(typeof i=="object"&&i.RTCPeerConnection&&!("getSenders"in i.RTCPeerConnection.prototype)&&"createDTMFSender"in i.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(!i.RTCPeerConnection.prototype.getSenders){i.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const s=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(a,c){let d=s.apply(this,arguments);return d||(d=e(this,a),this._senders.push(d)),d};const r=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(a){r.apply(this,arguments);const c=this._senders.indexOf(a);c!==-1&&this._senders.splice(c,1)}}const t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(r){this._senders=this._senders||[],t.apply(this,[r]),r.getTracks().forEach(o=>{this._senders.push(e(this,o))})};const n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(r){this._senders=this._senders||[],n.apply(this,[r]),r.getTracks().forEach(o=>{const a=this._senders.find(c=>c.track===o);a&&this._senders.splice(this._senders.indexOf(a),1)})}}else if(typeof i=="object"&&i.RTCPeerConnection&&"getSenders"in i.RTCPeerConnection.prototype&&"createDTMFSender"in i.RTCPeerConnection.prototype&&i.RTCRtpSender&&!("dtmf"in i.RTCRtpSender.prototype)){const e=i.RTCPeerConnection.prototype.getSenders;i.RTCPeerConnection.prototype.getSenders=function(){const n=e.apply(this,[]);return n.forEach(s=>s._pc=this),n},Object.defineProperty(i.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 Na(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender&&i.RTCRtpReceiver))return;if(!("getStats"in i.RTCRtpSender.prototype)){const t=i.RTCPeerConnection.prototype.getSenders;t&&(i.RTCPeerConnection.prototype.getSenders=function(){const r=t.apply(this,[]);return r.forEach(o=>o._pc=this),r});const n=i.RTCPeerConnection.prototype.addTrack;n&&(i.RTCPeerConnection.prototype.addTrack=function(){const r=n.apply(this,arguments);return r._pc=this,r}),i.RTCRtpSender.prototype.getStats=function(){const r=this;return this._pc.getStats().then(o=>Nr(o,r.track,!0))}}if(!("getStats"in i.RTCRtpReceiver.prototype)){const t=i.RTCPeerConnection.prototype.getReceivers;t&&(i.RTCPeerConnection.prototype.getReceivers=function(){const s=t.apply(this,[]);return s.forEach(r=>r._pc=this),s}),Nt(i,"track",n=>(n.receiver._pc=n.srcElement,n)),i.RTCRtpReceiver.prototype.getStats=function(){const s=this;return this._pc.getStats().then(r=>Nr(r,s.track,!1))}}if(!("getStats"in i.RTCRtpSender.prototype&&"getStats"in i.RTCRtpReceiver.prototype))return;const e=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof i.MediaStreamTrack){const n=arguments[0];let s,r,o;return this.getSenders().forEach(a=>{a.track===n&&(s?o=!0:s=a)}),this.getReceivers().forEach(a=>(a.track===n&&(r?o=!0:r=a),a.track===n)),o||s&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):s?s.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function La(i){i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(o=>this._shimmedLocalStreams[o][0])};const e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(o,a){if(!a)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const c=e.apply(this,arguments);return this._shimmedLocalStreams[a.id]?this._shimmedLocalStreams[a.id].indexOf(c)===-1&&this._shimmedLocalStreams[a.id].push(c):this._shimmedLocalStreams[a.id]=[a,c],c};const t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(o){this._shimmedLocalStreams=this._shimmedLocalStreams||{},o.getTracks().forEach(d=>{if(this.getSenders().find(u=>u.track===d))throw new DOMException("Track already exists.","InvalidAccessError")});const a=this.getSenders();t.apply(this,arguments);const c=this.getSenders().filter(d=>a.indexOf(d)===-1);this._shimmedLocalStreams[o.id]=[o].concat(c)};const n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[o.id],n.apply(this,arguments)};const s=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},o&&Object.keys(this._shimmedLocalStreams).forEach(a=>{const c=this._shimmedLocalStreams[a].indexOf(o);c!==-1&&this._shimmedLocalStreams[a].splice(c,1),this._shimmedLocalStreams[a].length===1&&delete this._shimmedLocalStreams[a]}),s.apply(this,arguments)}}function Ua(i,e){if(!i.RTCPeerConnection)return;if(i.RTCPeerConnection.prototype.addTrack&&e.version>=65)return La(i);const t=i.RTCPeerConnection.prototype.getLocalStreams;i.RTCPeerConnection.prototype.getLocalStreams=function(){const l=t.apply(this);return this._reverseStreams=this._reverseStreams||{},l.map(u=>this._reverseStreams[u.id])};const n=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(l){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},l.getTracks().forEach(u=>{if(this.getSenders().find(f=>f.track===u))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[l.id]){const u=new i.MediaStream(l.getTracks());this._streams[l.id]=u,this._reverseStreams[u.id]=l,l=u}n.apply(this,[l])};const s=i.RTCPeerConnection.prototype.removeStream;i.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]},i.RTCPeerConnection.prototype.addTrack=function(l,u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const h=[].slice.call(arguments,1);if(h.length!==1||!h[0].getTracks().find(g=>g===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(g=>g.track===l))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const m=this._streams[u.id];if(m)m.addTrack(l),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const g=new i.MediaStream([l]);this._streams[u.id]=g,this._reverseStreams[g.id]=u,this.addStream(g)}return this.getSenders().find(g=>g.track===l)};function r(d,l){let u=l.sdp;return Object.keys(d._reverseStreams||[]).forEach(h=>{const f=d._reverseStreams[h],m=d._streams[f.id];u=u.replace(new RegExp(m.id,"g"),f.id)}),new RTCSessionDescription({type:l.type,sdp:u})}function o(d,l){let u=l.sdp;return Object.keys(d._reverseStreams||[]).forEach(h=>{const f=d._reverseStreams[h],m=d._streams[f.id];u=u.replace(new RegExp(f.id,"g"),m.id)}),new RTCSessionDescription({type:l.type,sdp:u})}["createOffer","createAnswer"].forEach(function(d){const l=i.RTCPeerConnection.prototype[d],u={[d](){const h=arguments;return arguments.length&&typeof arguments[0]=="function"?l.apply(this,[m=>{const g=r(this,m);h[0].apply(null,[g])},m=>{h[1]&&h[1].apply(null,m)},arguments[2]]):l.apply(this,arguments).then(m=>r(this,m))}};i.RTCPeerConnection.prototype[d]=u[d]});const a=i.RTCPeerConnection.prototype.setLocalDescription;i.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?a.apply(this,arguments):(arguments[0]=o(this,arguments[0]),a.apply(this,arguments))};const c=Object.getOwnPropertyDescriptor(i.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(i.RTCPeerConnection.prototype,"localDescription",{get(){const d=c.get.apply(this);return d.type===""?d:r(this,d)}}),i.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 h;Object.keys(this._streams).forEach(f=>{this._streams[f].getTracks().find(g=>l.track===g)&&(h=this._streams[f])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.removeTrack(l.track),this.dispatchEvent(new Event("negotiationneeded")))}}function ls(i,e){!i.RTCPeerConnection&&i.webkitRTCPeerConnection&&(i.RTCPeerConnection=i.webkitRTCPeerConnection),i.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const n=i.RTCPeerConnection.prototype[t],s={[t](){return arguments[0]=new(t==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};i.RTCPeerConnection.prototype[t]=s[t]})}function ja(i,e){Nt(i,"negotiationneeded",t=>{const n=t.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return t})}var Ur=Object.freeze({__proto__:null,fixNegotiationNeeded:ja,shimAddTrackRemoveTrack:Ua,shimAddTrackRemoveTrackWithNative:La,shimGetSendersWithDtmf:Da,shimGetUserMedia:xa,shimMediaStream:Aa,shimOnTrack:Ma,shimPeerConnection:ls,shimSenderReceiverGetStats:Na});function Fa(i,e){const t=i&&i.navigator,n=i&&i.MediaStreamTrack;if(t.getUserMedia=function(s,r,o){Ws("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(s).then(r,o)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const s=function(o,a,c){a in o&&!(c in o)&&(o[c]=o[a],delete o[a])},r=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(o){return typeof o=="object"&&typeof o.audio=="object"&&(o=JSON.parse(JSON.stringify(o)),s(o.audio,"autoGainControl","mozAutoGainControl"),s(o.audio,"noiseSuppression","mozNoiseSuppression")),r(o)},n&&n.prototype.getSettings){const o=n.prototype.getSettings;n.prototype.getSettings=function(){const a=o.apply(this,arguments);return s(a,"mozAutoGainControl","autoGainControl"),s(a,"mozNoiseSuppression","noiseSuppression"),a}}if(n&&n.prototype.applyConstraints){const o=n.prototype.applyConstraints;n.prototype.applyConstraints=function(a){return this.kind==="audio"&&typeof a=="object"&&(a=JSON.parse(JSON.stringify(a)),s(a,"autoGainControl","mozAutoGainControl"),s(a,"noiseSuppression","mozNoiseSuppression")),o.apply(this,[a])}}}}function ih(i,e){i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices||i.navigator.mediaDevices&&(i.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){const s=new DOMException("getDisplayMedia without video constraints is undefined");return s.name="NotFoundError",s.code=8,Promise.reject(s)}return n.video===!0?n.video={mediaSource:e}:n.video.mediaSource=e,i.navigator.mediaDevices.getUserMedia(n)})}function Ba(i){typeof i=="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function us(i,e){if(typeof i!="object"||!(i.RTCPeerConnection||i.mozRTCPeerConnection))return;!i.RTCPeerConnection&&i.mozRTCPeerConnection&&(i.RTCPeerConnection=i.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(s){const r=i.RTCPeerConnection.prototype[s],o={[s](){return arguments[0]=new(s==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};i.RTCPeerConnection.prototype[s]=o[s]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){const[r,o,a]=arguments;return n.apply(this,[r||null]).then(c=>{if(e.version<53&&!o)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(o,a)}}function Va(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpSender.prototype)return;const e=i.RTCPeerConnection.prototype.getSenders;e&&(i.RTCPeerConnection.prototype.getSenders=function(){const s=e.apply(this,[]);return s.forEach(r=>r._pc=this),s});const t=i.RTCPeerConnection.prototype.addTrack;t&&(i.RTCPeerConnection.prototype.addTrack=function(){const s=t.apply(this,arguments);return s._pc=this,s}),i.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function qa(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpReceiver.prototype)return;const e=i.RTCPeerConnection.prototype.getReceivers;e&&(i.RTCPeerConnection.prototype.getReceivers=function(){const n=e.apply(this,[]);return n.forEach(s=>s._pc=this),n}),Nt(i,"track",t=>(t.receiver._pc=t.srcElement,t)),i.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function $a(i){!i.RTCPeerConnection||"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(t){Ws("removeStream","removeTrack"),this.getSenders().forEach(n=>{n.track&&t.getTracks().includes(n.track)&&this.removeTrack(n)})})}function Ha(i){i.DataChannel&&!i.RTCDataChannel&&(i.RTCDataChannel=i.DataChannel)}function za(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.addTransceiver;e&&(i.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let n=arguments[1]&&arguments[1].sendEncodings;n===void 0&&(n=[]),n=[...n];const s=n.length>0;s&&n.forEach(o=>{if("rid"in o&&!/^[a-z0-9]{0,16}$/i.test(o.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in o&&!(parseFloat(o.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in o&&!(parseFloat(o.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const r=e.apply(this,arguments);if(s){const{sender:o}=r,a=o.getParameters();(!("encodings"in a)||a.encodings.length===1&&Object.keys(a.encodings[0]).length===0)&&(a.encodings=n,o.sendEncodings=n,this.setParametersPromises.push(o.setParameters(a).then(()=>{delete o.sendEncodings}).catch(()=>{delete o.sendEncodings})))}return r})}function Ga(i){if(!(typeof i=="object"&&i.RTCRtpSender))return;const e=i.RTCRtpSender.prototype.getParameters;e&&(i.RTCRtpSender.prototype.getParameters=function(){const n=e.apply(this,arguments);return"encodings"in n||(n.encodings=[].concat(this.sendEncodings||[{}])),n})}function Wa(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.createOffer;i.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 Ka(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.createAnswer;i.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 jr=Object.freeze({__proto__:null,shimAddTransceiver:za,shimCreateAnswer:Ka,shimCreateOffer:Wa,shimGetDisplayMedia:ih,shimGetParameters:Ga,shimGetUserMedia:Fa,shimOnTrack:Ba,shimPeerConnection:us,shimRTCDataChannel:Ha,shimReceiverGetStats:qa,shimRemoveStream:$a,shimSenderGetStats:Va});function Ja(i){if(!(typeof i!="object"||!i.RTCPeerConnection)){if("getLocalStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in i.RTCPeerConnection.prototype)){const e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addStream=function(n){this._localStreams||(this._localStreams=[]),this._localStreams.includes(n)||this._localStreams.push(n),n.getAudioTracks().forEach(s=>e.call(this,s,n)),n.getVideoTracks().forEach(s=>e.call(this,s,n))},i.RTCPeerConnection.prototype.addTrack=function(n){for(var s=arguments.length,r=new Array(s>1?s-1:0),o=1;o<s;o++)r[o-1]=arguments[o];return r&&r.forEach(a=>{this._localStreams?this._localStreams.includes(a)||this._localStreams.push(a):this._localStreams=[a]}),e.apply(this,arguments)}}"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const n=this._localStreams.indexOf(t);if(n===-1)return;this._localStreams.splice(n,1);const s=t.getTracks();this.getSenders().forEach(r=>{s.includes(r.track)&&this.removeTrack(r)})})}}function Qa(i){if(!(typeof i!="object"||!i.RTCPeerConnection)&&("getRemoteStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in i.RTCPeerConnection.prototype))){Object.defineProperty(i.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=n=>{n.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=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){const n=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(s){s.streams.forEach(r=>{if(n._remoteStreams||(n._remoteStreams=[]),n._remoteStreams.indexOf(r)>=0)return;n._remoteStreams.push(r);const o=new Event("addstream");o.stream=r,n.dispatchEvent(o)})}),e.apply(n,arguments)}}}function Ya(i){if(typeof i!="object"||!i.RTCPeerConnection)return;const e=i.RTCPeerConnection.prototype,t=e.createOffer,n=e.createAnswer,s=e.setLocalDescription,r=e.setRemoteDescription,o=e.addIceCandidate;e.createOffer=function(d,l){const u=arguments.length>=2?arguments[2]:arguments[0],h=t.apply(this,[u]);return l?(h.then(d,l),Promise.resolve()):h},e.createAnswer=function(d,l){const u=arguments.length>=2?arguments[2]:arguments[0],h=n.apply(this,[u]);return l?(h.then(d,l),Promise.resolve()):h};let a=function(c,d,l){const u=s.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u};e.setLocalDescription=a,a=function(c,d,l){const u=r.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u},e.setRemoteDescription=a,a=function(c,d,l){const u=o.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u},e.addIceCandidate=a}function Xa(i){const e=i&&i.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,n=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=s=>n(Za(s))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(n,s,r){e.mediaDevices.getUserMedia(n).then(s,r)}).bind(e))}function Za(i){return i&&i.video!==void 0?Object.assign({},i,{video:Oa(i.video)}):i}function ec(i){if(!i.RTCPeerConnection)return;const e=i.RTCPeerConnection;i.RTCPeerConnection=function(n,s){if(n&&n.iceServers){const r=[];for(let o=0;o<n.iceServers.length;o++){let a=n.iceServers[o];a.urls===void 0&&a.url?(Ws("RTCIceServer.url","RTCIceServer.urls"),a=JSON.parse(JSON.stringify(a)),a.urls=a.url,delete a.url,r.push(a)):r.push(n.iceServers[o])}n.iceServers=r}return new e(n,s)},i.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(i.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function tc(i){typeof i=="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function ic(i){const e=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(n){if(n){typeof n.offerToReceiveAudio<"u"&&(n.offerToReceiveAudio=!!n.offerToReceiveAudio);const s=this.getTransceivers().find(o=>o.receiver.track.kind==="audio");n.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"):n.offerToReceiveAudio===!0&&!s&&this.addTransceiver("audio",{direction:"recvonly"}),typeof n.offerToReceiveVideo<"u"&&(n.offerToReceiveVideo=!!n.offerToReceiveVideo);const r=this.getTransceivers().find(o=>o.receiver.track.kind==="video");n.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"):n.offerToReceiveVideo===!0&&!r&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function nc(i){typeof i!="object"||i.AudioContext||(i.AudioContext=i.webkitAudioContext)}var Fr=Object.freeze({__proto__:null,shimAudioContext:nc,shimCallbacksAPI:Ya,shimConstraints:Za,shimCreateOfferLegacy:ic,shimGetUserMedia:Xa,shimLocalStreamsAPI:Ja,shimRTCIceServerUrls:ec,shimRemoteStreamsAPI:Qa,shimTrackEventTransceiver:tc}),On={exports:{}},Br;function nh(){return Br||(Br=1,function(i){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(`
|
|
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
|
-
s
|
|
49
|
-
t=0 0\r
|
|
50
|
-
`},e.getDirection=function(t,n){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 n?e.getDirection(n):"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 n=e.splitLines(t);for(let s=0;s<n.length;s++)if(n[s].length<2||n[s].charAt(1)!=="=")return!1;return!0},i.exports=e}(On)),On.exports}var sc=nh(),Kt=zu(sc),sh=yl({__proto__:null,default:Kt},[sc]);function Ji(i){if(!i.RTCIceCandidate||i.RTCIceCandidate&&"foundation"in i.RTCIceCandidate.prototype)return;const e=i.RTCIceCandidate;i.RTCIceCandidate=function(n){if(typeof n=="object"&&n.candidate&&n.candidate.indexOf("a=")===0&&(n=JSON.parse(JSON.stringify(n)),n.candidate=n.candidate.substring(2)),n.candidate&&n.candidate.length){const s=new e(n),r=Kt.parseCandidate(n.candidate);for(const o in r)o in s||Object.defineProperty(s,o,{value:r[o]});return s.toJSON=function(){return{candidate:s.candidate,sdpMid:s.sdpMid,sdpMLineIndex:s.sdpMLineIndex,usernameFragment:s.usernameFragment}},s}return new e(n)},i.RTCIceCandidate.prototype=e.prototype,Nt(i,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new i.RTCIceCandidate(t.candidate),writable:"false"}),t))}function hs(i){!i.RTCIceCandidate||i.RTCIceCandidate&&"relayProtocol"in i.RTCIceCandidate.prototype||Nt(i,"icecandidate",e=>{if(e.candidate){const t=Kt.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function Qi(i,e){if(!i.RTCPeerConnection)return;"sctp"in i.RTCPeerConnection.prototype||Object.defineProperty(i.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const t=function(a){if(!a||!a.sdp)return!1;const c=Kt.splitSections(a.sdp);return c.shift(),c.some(d=>{const l=Kt.parseMLine(d);return l&&l.kind==="application"&&l.protocol.indexOf("SCTP")!==-1})},n=function(a){const c=a.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(a){let c=65536;return e.browser==="firefox"&&(e.version<57?a===-1?c=16384:c=2147483637:e.version<60?c=e.version===57?65535:65536:c=2147483637),c},r=function(a,c){let d=65536;e.browser==="firefox"&&e.version===57&&(d=65535);const l=Kt.matchPrefix(a.sdp,"a=max-message-size:");return l.length>0?d=parseInt(l[0].substring(19),10):e.browser==="firefox"&&c!==-1&&(d=2147483637),d},o=i.RTCPeerConnection.prototype.setRemoteDescription;i.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=n(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 h={};Object.defineProperty(h,"maxMessageSize",{get(){return u}}),this._sctp=h}return o.apply(this,arguments)}}function Yi(i){if(!(i.RTCPeerConnection&&"createDataChannel"in i.RTCPeerConnection.prototype))return;function e(n,s){const r=n.send;n.send=function(){const a=arguments[0],c=a.length||a.size||a.byteLength;if(n.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(n,arguments)}}const t=i.RTCPeerConnection.prototype.createDataChannel;i.RTCPeerConnection.prototype.createDataChannel=function(){const s=t.apply(this,arguments);return e(s,this),s},Nt(i,"datachannel",n=>(e(n.channel,n.target),n))}function fs(i){if(!i.RTCPeerConnection||"connectionState"in i.RTCPeerConnection.prototype)return;const e=i.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 n=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=s=>{const r=s.target;if(r._lastConnectionState!==r.connectionState){r._lastConnectionState=r.connectionState;const o=new Event("connectionstatechange",s);r.dispatchEvent(o)}return s},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}})}function ps(i,e){if(!i.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e.version>=605)return;const t=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(s){if(s&&s.sdp&&s.sdp.indexOf(`
|
|
51
|
-
a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
|
|
52
|
-
`).filter(o=>o.trim()!=="a=extmap-allow-mixed").join(`
|
|
53
|
-
`);i.RTCSessionDescription&&s instanceof i.RTCSessionDescription?arguments[0]=new i.RTCSessionDescription({type:s.type,sdp:r}):s.sdp=r}return t.apply(this,arguments)}}function Xi(i,e){if(!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype))return;const t=i.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(i.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 Zi(i,e){if(!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype))return;const t=i.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(i.RTCPeerConnection.prototype.setLocalDescription=function(){let s=arguments[0]||{};if(typeof s!="object"||s.type&&s.sdp)return t.apply(this,arguments);if(s={type:s.type,sdp:s.sdp},!s.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":s.type="offer";break;default:s.type="answer";break}return s.sdp||s.type!=="offer"&&s.type!=="answer"?t.apply(this,[s]):(s.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(o=>t.apply(this,[o]))})}var rh=Object.freeze({__proto__:null,removeExtmapAllowMixed:ps,shimAddIceCandidateNullOrEmpty:Xi,shimConnectionState:fs,shimMaxMessageSize:Qi,shimParameterlessSetLocalDescription:Zi,shimRTCIceCandidate:Ji,shimRTCIceCandidateRelayProtocol:hs,shimSendThrowTypeError:Yi});function oh(){let{window:i}=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=Ia,n=th(i),s={browserDetails:n,commonShim:rh,extractVersion:Ki,disableLog:Zu,disableWarnings:eh,sdp:sh};switch(n.browser){case"chrome":if(!Ur||!ls||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),s;if(n.version===null)return t("Chrome shim can not determine version, not shimming."),s;t("adapter.js shimming chrome."),s.browserShim=Ur,Xi(i,n),Zi(i),xa(i,n),Aa(i),ls(i,n),Ma(i),Ua(i,n),Da(i),Na(i),ja(i,n),Ji(i),hs(i),fs(i),Qi(i,n),Yi(i),ps(i,n);break;case"firefox":if(!jr||!us||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),s;t("adapter.js shimming firefox."),s.browserShim=jr,Xi(i,n),Zi(i),Fa(i,n),us(i,n),Ba(i),$a(i),Va(i),qa(i),Ha(i),za(i),Ga(i),Wa(i),Ka(i),Ji(i),fs(i),Qi(i,n),Yi(i);break;case"safari":if(!Fr||!e.shimSafari)return t("Safari shim is not included in this adapter release."),s;t("adapter.js shimming safari."),s.browserShim=Fr,Xi(i,n),Zi(i),ec(i),ic(i),Ya(i),Ja(i),Qa(i),tc(i),Xa(i),nc(i),Ji(i),hs(i),Qi(i,n),Yi(i),ps(i,n);break;default:t("Unsupported browser!");break}return s}oh({window:typeof window>"u"?void 0:window});const ah=10,ji="lk_e2ee",ch="LKFrameEncryptionKey",dh={sharedKey:!1,ratchetSalt:ch,ratchetWindowSize:8,failureTolerance:ah,keyringSize:16};var Tt;(function(i){i.SetKey="setKey",i.RatchetRequest="ratchetRequest",i.KeyRatcheted="keyRatcheted"})(Tt||(Tt={}));var Vr;(function(i){i.KeyRatcheted="keyRatcheted"})(Vr||(Vr={}));var bt;(function(i){i.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",i.EncryptionError="encryptionError"})(bt||(bt={}));var qr;(function(i){i.Error="cryptorError"})(qr||(qr={}));function lh(){return uh()||ms()}function ms(){return typeof window.RTCRtpScriptTransform<"u"}function uh(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class Zf extends et.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,n)=>{W.debug("key ratcheted event received",{material:t,keyIndex:n})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},dh),e),this.on(Tt.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,n){const s={key:e,participantIdentity:t,keyIndex:n};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(n??0),s),this.emit(Tt.SetKey,s)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(Tt.RatchetRequest,e,t)}}class _t extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var J;(function(i){i[i.NotAllowed=0]="NotAllowed",i[i.ServerUnreachable=1]="ServerUnreachable",i[i.InternalError=2]="InternalError",i[i.Cancelled=3]="Cancelled",i[i.LeaveRequest=4]="LeaveRequest"})(J||(J={}));class re extends _t{constructor(e,t,n,s){super(1,e),this.name="ConnectionError",this.status=n,this.reason=t,this.context=s,this.reasonName=J[t]}}class Ks extends _t{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class rt extends _t{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class hh extends _t{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class ye extends _t{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class gs extends _t{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class fh extends _t{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class $r extends _t{constructor(e,t){super(15,e),this.reason=t,this.reasonName=typeof t=="string"?t:Gs[t]}}var un;(function(i){i.PermissionDenied="PermissionDenied",i.NotFound="NotFound",i.DeviceInUse="DeviceInUse",i.Other="Other"})(un||(un={}));(function(i){function e(t){if(t&&"name"in t)return t.name==="NotFoundError"||t.name==="DevicesNotFoundError"?i.NotFound:t.name==="NotAllowedError"||t.name==="PermissionDeniedError"?i.PermissionDenied:t.name==="NotReadableError"||t.name==="TrackStartError"?i.DeviceInUse:i.Other}i.getFailure=e})(un||(un={}));var Hr;(function(i){i[i.InvalidKey=0]="InvalidKey",i[i.MissingKey=1]="MissingKey",i[i.InternalError=2]="InternalError"})(Hr||(Hr={}));var I;(function(i){i.Connected="connected",i.Reconnecting="reconnecting",i.SignalReconnecting="signalReconnecting",i.Reconnected="reconnected",i.Disconnected="disconnected",i.ConnectionStateChanged="connectionStateChanged",i.MediaDevicesChanged="mediaDevicesChanged",i.ParticipantConnected="participantConnected",i.ParticipantDisconnected="participantDisconnected",i.TrackPublished="trackPublished",i.TrackSubscribed="trackSubscribed",i.TrackSubscriptionFailed="trackSubscriptionFailed",i.TrackUnpublished="trackUnpublished",i.TrackUnsubscribed="trackUnsubscribed",i.TrackMuted="trackMuted",i.TrackUnmuted="trackUnmuted",i.LocalTrackPublished="localTrackPublished",i.LocalTrackUnpublished="localTrackUnpublished",i.LocalAudioSilenceDetected="localAudioSilenceDetected",i.ActiveSpeakersChanged="activeSpeakersChanged",i.ParticipantMetadataChanged="participantMetadataChanged",i.ParticipantNameChanged="participantNameChanged",i.ParticipantAttributesChanged="participantAttributesChanged",i.RoomMetadataChanged="roomMetadataChanged",i.DataReceived="dataReceived",i.SipDTMFReceived="sipDTMFReceived",i.TranscriptionReceived="transcriptionReceived",i.ConnectionQualityChanged="connectionQualityChanged",i.TrackStreamStateChanged="trackStreamStateChanged",i.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",i.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",i.AudioPlaybackStatusChanged="audioPlaybackChanged",i.VideoPlaybackStatusChanged="videoPlaybackChanged",i.MediaDevicesError="mediaDevicesError",i.ParticipantPermissionsChanged="participantPermissionsChanged",i.SignalConnected="signalConnected",i.RecordingStatusChanged="recordingStatusChanged",i.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",i.EncryptionError="encryptionError",i.DCBufferStatusChanged="dcBufferStatusChanged",i.ActiveDeviceChanged="activeDeviceChanged",i.ChatMessage="chatMessage",i.LocalTrackSubscribed="localTrackSubscribed",i.MetricsReceived="metricsReceived"})(I||(I={}));var A;(function(i){i.TrackPublished="trackPublished",i.TrackSubscribed="trackSubscribed",i.TrackSubscriptionFailed="trackSubscriptionFailed",i.TrackUnpublished="trackUnpublished",i.TrackUnsubscribed="trackUnsubscribed",i.TrackMuted="trackMuted",i.TrackUnmuted="trackUnmuted",i.LocalTrackPublished="localTrackPublished",i.LocalTrackUnpublished="localTrackUnpublished",i.ParticipantMetadataChanged="participantMetadataChanged",i.ParticipantNameChanged="participantNameChanged",i.DataReceived="dataReceived",i.SipDTMFReceived="sipDTMFReceived",i.TranscriptionReceived="transcriptionReceived",i.IsSpeakingChanged="isSpeakingChanged",i.ConnectionQualityChanged="connectionQualityChanged",i.TrackStreamStateChanged="trackStreamStateChanged",i.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",i.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",i.MediaDevicesError="mediaDevicesError",i.AudioStreamAcquired="audioStreamAcquired",i.ParticipantPermissionsChanged="participantPermissionsChanged",i.PCTrackAdded="pcTrackAdded",i.AttributesChanged="attributesChanged",i.LocalTrackSubscribed="localTrackSubscribed",i.ChatMessage="chatMessage"})(A||(A={}));var x;(function(i){i.TransportsCreated="transportsCreated",i.Connected="connected",i.Disconnected="disconnected",i.Resuming="resuming",i.Resumed="resumed",i.Restarting="restarting",i.Restarted="restarted",i.SignalResumed="signalResumed",i.SignalRestarted="signalRestarted",i.Closing="closing",i.MediaTrackAdded="mediaTrackAdded",i.ActiveSpeakersUpdate="activeSpeakersUpdate",i.DataPacketReceived="dataPacketReceived",i.RTPVideoMapUpdate="rtpVideoMapUpdate",i.DCBufferStatusChanged="dcBufferStatusChanged",i.ParticipantUpdate="participantUpdate",i.RoomUpdate="roomUpdate",i.SpeakersChanged="speakersChanged",i.StreamStateChanged="streamStateChanged",i.ConnectionQualityUpdate="connectionQualityUpdate",i.SubscriptionError="subscriptionError",i.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",i.RemoteMute="remoteMute",i.SubscribedQualityUpdate="subscribedQualityUpdate",i.LocalTrackUnpublished="localTrackUnpublished",i.LocalTrackSubscribed="localTrackSubscribed",i.Offline="offline",i.SignalRequestResponse="signalRequestResponse"})(x||(x={}));var O;(function(i){i.Message="message",i.Muted="muted",i.Unmuted="unmuted",i.Restarted="restarted",i.Ended="ended",i.Subscribed="subscribed",i.Unsubscribed="unsubscribed",i.UpdateSettings="updateSettings",i.UpdateSubscription="updateSubscription",i.AudioPlaybackStarted="audioPlaybackStarted",i.AudioPlaybackFailed="audioPlaybackFailed",i.AudioSilenceDetected="audioSilenceDetected",i.VisibilityChanged="visibilityChanged",i.VideoDimensionsChanged="videoDimensionsChanged",i.VideoPlaybackStarted="videoPlaybackStarted",i.VideoPlaybackFailed="videoPlaybackFailed",i.ElementAttached="elementAttached",i.ElementDetached="elementDetached",i.UpstreamPaused="upstreamPaused",i.UpstreamResumed="upstreamResumed",i.SubscriptionPermissionChanged="subscriptionPermissionChanged",i.SubscriptionStatusChanged="subscriptionStatusChanged",i.SubscriptionFailed="subscriptionFailed",i.TrackProcessorUpdate="trackProcessorUpdate",i.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",i.TranscriptionReceived="transcriptionReceived",i.TimeSyncUpdate="timeSyncUpdate"})(O||(O={}));function ph(i){if(!(typeof i>"u"))return typeof structuredClone=="function"?structuredClone(i):JSON.parse(JSON.stringify(i))}const mh=/version\/(\d+(\.?_?\d+)+)/i;let xn;function Xe(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const t=navigator.userAgent.toLowerCase();if(xn===void 0||e){const n=gh.find(s=>{let{test:r}=s;return r.test(t)});xn=n==null?void 0:n.describe(t)}return xn}const gh=[{test:/firefox|iceweasel|fxios/i,describe(i){return{name:"Firefox",version:en(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:An(i)}}},{test:/chrom|crios|crmo/i,describe(i){return{name:"Chrome",version:en(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("crios")?"iOS":void 0,osVersion:An(i)}}},{test:/safari|applewebkit/i,describe(i){return{name:"Safari",version:en(mh,i),os:i.includes("mobile/")?"iOS":"macOS",osVersion:An(i)}}}];function en(i,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const n=e.match(i);return n&&n.length>=t&&n[t]||""}function An(i){return i.includes("mac os")?en(/\(.+?(\d+_\d+(:?_\d+)?)/,i,1).replace(/_/g,"."):void 0}var vh="2.9.8";const yh=vh,bh=15;class Se{}Se.setTimeout=function(){return setTimeout(...arguments)};Se.setInterval=function(){return setInterval(...arguments)};Se.clearTimeout=function(){return clearTimeout(...arguments)};Se.clearInterval=function(){return clearInterval(...arguments)};const kh=5e3,ci=[];var Le;(function(i){i[i.LOW=0]="LOW",i[i.MEDIUM=1]="MEDIUM",i[i.HIGH=2]="HIGH"})(Le||(Le={}));class w extends et.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var s;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=w.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=W,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),kh):this.handleAppVisibilityChanged()},this.log=ct((s=n.loggerName)!==null&&s!==void 0?s:Ge.Track),this.loggerContextCb=n.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=w.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),ie(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===w.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===w.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(ci.forEach(r=>{r.parentElement===null&&!e&&(e=r)}),e&&ci.splice(ci.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),zt(this.mediaStreamTrack,e);const n=e.srcObject.getTracks(),s=n.some(r=>r.kind==="audio");return e.play().then(()=>{this.emit(s?O.AudioPlaybackStarted:O.VideoPlaybackStarted)}).catch(r=>{r.name==="NotAllowedError"?this.emit(s?O.AudioPlaybackFailed:O.VideoPlaybackFailed,r):r.name==="AbortError"?W.debug("".concat(s?"audio":"video"," playback aborted, likely due to new play request")):W.warn("could not playback ".concat(s?"audio":"video"),r),s&&e&&n.some(o=>o.kind==="video")&&r.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(O.ElementAttached,e),e}detach(e){try{if(e){Jt(this.mediaStreamTrack,e);const n=this.attachedElements.indexOf(e);return n>=0&&(this.attachedElements.splice(n,1),this.recycleElement(e),this.emit(O.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(n=>{Jt(this.mediaStreamTrack,n),t.push(n),this.recycleElement(n),this.emit(O.ElementDetached,n)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=ct(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),ci.forEach(n=>{n.parentElement||(t=!1)}),t&&ci.push(e)}}handleAppVisibilityChanged(){return p(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===w.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){Re()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Re()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function zt(i,e){let t;e.srcObject instanceof MediaStream?t=e.srcObject:t=new MediaStream;let n;i.kind==="audio"?n=t.getAudioTracks():n=t.getVideoTracks(),n.includes(i)||(n.forEach(s=>{t.removeTrack(s)}),t.addTrack(i)),(!Et()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(Et()||ei())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function Jt(i,e){if(e.srcObject instanceof MediaStream){const t=e.srcObject;t.removeTrack(i),t.getTracks().length>0?e.srcObject=t:e.srcObject=null}}(function(i){let e;(function(d){d.Audio="audio",d.Video="video",d.Unknown="unknown"})(e=i.Kind||(i.Kind={}));let t;(function(d){d.Camera="camera",d.Microphone="microphone",d.ScreenShare="screen_share",d.ScreenShareAudio="screen_share_audio",d.Unknown="unknown"})(t=i.Source||(i.Source={}));let n;(function(d){d.Active="active",d.Paused="paused",d.Unknown="unknown"})(n=i.StreamState||(i.StreamState={}));function s(d){switch(d){case e.Audio:return qe.AUDIO;case e.Video:return qe.VIDEO;default:return qe.DATA}}i.kindToProto=s;function r(d){switch(d){case qe.AUDIO:return e.Audio;case qe.VIDEO:return e.Video;default:return e.Unknown}}i.kindFromProto=r;function o(d){switch(d){case t.Camera:return ge.CAMERA;case t.Microphone:return ge.MICROPHONE;case t.ScreenShare:return ge.SCREEN_SHARE;case t.ScreenShareAudio:return ge.SCREEN_SHARE_AUDIO;default:return ge.UNKNOWN}}i.sourceToProto=o;function a(d){switch(d){case ge.CAMERA:return t.Camera;case ge.MICROPHONE:return t.Microphone;case ge.SCREEN_SHARE:return t.ScreenShare;case ge.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}i.sourceFromProto=a;function c(d){switch(d){case rs.ACTIVE:return n.Active;case rs.PAUSED:return n.Paused;default:return n.Unknown}}i.streamStateFromProto=c})(w);class ne{constructor(e,t,n,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&&n!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:n,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 Th=["vp8","h264"],Ch=["vp8","h264","vp9","av1"];function Sh(i){return!!Th.find(e=>e===i)}var zr;(function(i){i[i.REGRESSION=0]="REGRESSION",i[i.SIMULCAST=1]="SIMULCAST"})(zr||(zr={}));var vs;(function(i){i.telephone={maxBitrate:12e3},i.speech={maxBitrate:24e3},i.music={maxBitrate:48e3},i.musicStereo={maxBitrate:64e3},i.musicHighQuality={maxBitrate:96e3},i.musicHighQualityStereo={maxBitrate:128e3}})(vs||(vs={}));const Pi={h90:new ne(160,90,9e4,20),h180:new ne(320,180,16e4,20),h216:new ne(384,216,18e4,20),h360:new ne(640,360,45e4,20),h540:new ne(960,540,8e5,25),h720:new ne(1280,720,17e5,30),h1080:new ne(1920,1080,3e6,30),h1440:new ne(2560,1440,5e6,30),h2160:new ne(3840,2160,8e6,30)},ys={h120:new ne(160,120,7e4,20),h180:new ne(240,180,125e3,20),h240:new ne(320,240,14e4,20),h360:new ne(480,360,33e4,20),h480:new ne(640,480,5e5,20),h540:new ne(720,540,6e5,25),h720:new ne(960,720,13e5,30),h1080:new ne(1440,1080,23e5,30),h1440:new ne(1920,1440,38e5,30)},Js={h360fps3:new ne(640,360,2e5,3,"medium"),h360fps15:new ne(640,360,4e5,15,"medium"),h720fps5:new ne(1280,720,8e5,5,"medium"),h720fps15:new ne(1280,720,15e5,15,"medium"),h720fps30:new ne(1280,720,2e6,30,"medium"),h1080fps15:new ne(1920,1080,25e5,15,"medium"),h1080fps30:new ne(1920,1080,5e6,30,"medium"),original:new ne(0,0,7e6,30,"medium")},Eh="|",Gr="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function wh(i){const e=i.split(Eh);return e.length>1?[e[0],i.substr(e[0].length+1)]:[i,""]}function Ie(i){return p(this,void 0,void 0,function*(){return new Promise(e=>Se.setTimeout(e,i))})}function bs(){return"addTransceiver"in RTCPeerConnection.prototype}function ks(){return"addTrack"in RTCPeerConnection.prototype}function _h(){if(!("getCapabilities"in RTCRtpSender)||Et())return!1;const i=RTCRtpSender.getCapabilities("video");let e=!1;if(i){for(const t of i.codecs)if(t.mimeType==="video/AV1"){e=!0;break}}return e}function Ph(){if(!("getCapabilities"in RTCRtpSender)||ei())return!1;if(Et()){const t=Xe();if(t!=null&&t.version&&ti(t.version,"16")<0)return!1}const i=RTCRtpSender.getCapabilities("video");let e=!1;if(i){for(const t of i.codecs)if(t.mimeType==="video/VP9"){e=!0;break}}return e}function bi(i){return i==="av1"||i==="vp9"}function Ts(i){return document?(i||(i=document.createElement("audio")),"setSinkId"in i):!1}function Rh(){return typeof RTCPeerConnection>"u"?!1:bs()||ks()}function ei(){var i;return((i=Xe())===null||i===void 0?void 0:i.name)==="Firefox"}function Et(){var i;return((i=Xe())===null||i===void 0?void 0:i.name)==="Safari"}function Ih(){const i=Xe();return(i==null?void 0:i.name)==="Safari"&&i.version.startsWith("17.")}function rc(){var i,e;return Re()?(e=(i=navigator.userAgentData)===null||i===void 0?void 0:i.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function Oh(){const i=Xe(),e="17.2";if(i)return i.name!=="Safari"&&i.os!=="iOS"||i.os==="iOS"&&i.osVersion&&ti(e,i.osVersion)>=0?!0:i.name==="Safari"&&ti(e,i.version)>=0}function Re(){return typeof document<"u"}function Ze(){return navigator.product=="ReactNative"}function Cs(i){return i.hostname.endsWith(".livekit.cloud")||i.hostname.endsWith(".livekit.run")}function oc(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function ac(){if(!Ze())return;let i=oc();if(i)return i.platform}function Wr(){if(Re())return window.devicePixelRatio;if(Ze()){let i=oc();if(i)return i.devicePixelRatio}return 1}function ti(i,e){const t=i.split("."),n=e.split("."),s=Math.min(t.length,n.length);for(let r=0;r<s;++r){const o=parseInt(t[r],10),a=parseInt(n[r],10);if(o>a)return 1;if(o<a)return-1;if(r===s-1&&o===a)return 0}return i===""&&e!==""?-1:e===""?1:t.length==n.length?0:t.length<n.length?-1:1}function xh(i){for(const e of i)e.target.handleResize(e)}function Ah(i){for(const e of i)e.target.handleVisibilityChanged(e)}let Mn=null;const Kr=()=>(Mn||(Mn=new ResizeObserver(xh)),Mn);let Dn=null;const Jr=()=>(Dn||(Dn=new IntersectionObserver(Ah,{root:null,rootMargin:"0px"})),Dn);function Mh(){var i;const e=new Tu({sdk:ha.JS,protocol:bh,version:yh});return Ze()&&(e.os=(i=ac())!==null&&i!==void 0?i:""),e}function Qr(){let i=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,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const s=document.createElement("canvas");s.width=i,s.height=e;const r=s.getContext("2d");r==null||r.fillRect(0,0,s.width,s.height),n&&r&&(r.beginPath(),r.arc(i/2,e/2,50,0,Math.PI*2,!0),r.closePath(),r.fillStyle="grey",r.fill());const o=s.captureStream(),[a]=o.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=t,a}let di;function Nn(){if(!di){const i=new AudioContext,e=i.createOscillator(),t=i.createGain();t.gain.setValueAtTime(0,0);const n=i.createMediaStreamDestination();if(e.connect(t),t.connect(n),e.start(),[di]=n.stream.getAudioTracks(),!di)throw Error("Could not get empty media stream audio track");di.enabled=!1}return di.clone()}class cc{constructor(e,t){this.onFinally=t,this.promise=new Promise((n,s)=>p(this,void 0,void 0,function*(){this.resolve=n,this.reject=s,e&&(yield e(n,s))})).finally(()=>{var n;return(n=this.onFinally)===null||n===void 0?void 0:n.call(this)})}}function Dh(i){return Ch.includes(i)}function Ct(i){if(typeof i=="string"||typeof i=="number")return i;if(Array.isArray(i))return i[0];if(i.exact)return Array.isArray(i.exact)?i.exact[0]:i.exact;if(i.ideal)return Array.isArray(i.ideal)?i.ideal[0]:i.ideal;throw Error("could not unwrap constraint")}function Nh(i){return i.startsWith("http")?i.replace(/^(http)/,"ws"):i}function Yr(i){return i.startsWith("ws")?i.replace(/^(ws)/,"http"):i}function Lh(i,e){return i.segments.map(t=>{let{id:n,text:s,language:r,startTime:o,endTime:a,final:c}=t;var d;const l=(d=e.get(n))!==null&&d!==void 0?d:Date.now(),u=Date.now();return c?e.delete(n):e.set(n,l),{id:n,text:s,startTime:Number.parseInt(o.toString()),endTime:Number.parseInt(a.toString()),final:c,language:r,firstReceivedTime:l,lastReceivedTime:u}})}function Uh(i){const{id:e,timestamp:t,message:n,editTimestamp:s}=i;return{id:e,timestamp:Number.parseInt(t.toString()),editTimestamp:s?Number.parseInt(s.toString()):void 0,message:n}}function Xr(i){switch(i.reason){case J.LeaveRequest:return i.context;case J.Cancelled:return ze.CLIENT_INITIATED;case J.NotAllowed:return ze.USER_REJECTED;case J.ServerUnreachable:return ze.JOIN_FAILURE;default:return ze.UNKNOWN_REASON}}function tn(i){return i!==void 0?Number(i):void 0}function Rt(i){return i!==void 0?BigInt(i):void 0}function Qt(i){return!!i&&!(i instanceof MediaStreamTrack)&&i.isLocal}function dt(i){return!!i&&i.kind==w.Kind.Audio}function ni(i){return!!i&&i.kind==w.Kind.Video}function ft(i){return Qt(i)&&ni(i)}function It(i){return Qt(i)&&dt(i)}function Ss(i){return!!i&&!i.isLocal}function jh(i){return!!i&&!i.isLocal}function Ln(i){return Ss(i)&&ni(i)}function Fh(i){return i.isLocal}function Bh(i,e){const t=[];let n=new TextEncoder().encode(i);for(;n.length>e;){let s=e;for(;s>0;){const r=n[s];if(r!==void 0&&(r&192)!==128)break;s--}t.push(n.slice(0,s)),n=n.slice(s)}return n.length>0&&t.push(n),t}function dc(i,e,t){var n,s,r,o,a;const{optionsWithoutProcessor:c,audioProcessor:d,videoProcessor:l}=Qs(i??{}),u=e==null?void 0:e.processor,h=t==null?void 0:t.processor,f=(n=ph(c))!==null&&n!==void 0?n:{};return f.audio===!0&&(f.audio={}),f.video===!0&&(f.video={}),f.audio&&(Es(f.audio,e),(s=(o=f.audio).deviceId)!==null&&s!==void 0||(o.deviceId="default"),(d||u)&&(f.audio.processor=d??u)),f.video&&(Es(f.video,t),(r=(a=f.video).deviceId)!==null&&r!==void 0||(a.deviceId="default"),(l||h)&&(f.video.processor=l??h)),f}function Es(i,e){return Object.keys(e).forEach(t=>{i[t]===void 0&&(i[t]=e[t])}),i}function Cn(i){var e,t,n,s;const r={};if(i.video)if(typeof i.video=="object"){const o={},a=o,c=i.video;Object.keys(c).forEach(d=>{switch(d){case"resolution":Es(a,c.resolution);break;default:a[d]=c[d]}}),r.video=o,(e=(n=r.video).deviceId)!==null&&e!==void 0||(n.deviceId="default")}else r.video=i.video?{deviceId:"default"}:!1;else r.video=!1;return i.audio?typeof i.audio=="object"?(r.audio=i.audio,(t=(s=r.audio).deviceId)!==null&&t!==void 0||(s.deviceId="default")):r.audio={deviceId:"default"}:r.audio=!1,r}function lc(i){return p(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){const n=uc();if(n){const s=n.createAnalyser();s.fftSize=2048;const r=s.frequencyBinCount,o=new Uint8Array(r);n.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(s),yield Ie(t),s.getByteTimeDomainData(o);const c=o.some(d=>d!==128&&d!==0);return n.close(),!c}return!1}()})}function uc(){var i;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const t=new e({latencyHint:"interactive"});if(t.state==="suspended"&&typeof window<"u"&&(!((i=window.document)===null||i===void 0)&&i.body)){const n=()=>{t.resume().then(()=>{var s;(s=window.document.body)===null||s===void 0||s.removeEventListener("click",n)})};window.document.body.addEventListener("click",n)}return t}}function Zr(i){return i===w.Source.Microphone?"audioinput":i===w.Source.Camera?"videoinput":void 0}function Vh(i){var e,t;let n=(e=i.video)!==null&&e!==void 0?e:!0;return i.resolution&&i.resolution.width>0&&i.resolution.height>0&&(n=typeof n=="boolean"?{}:n,Et()?n=Object.assign(Object.assign({},n),{width:{max:i.resolution.width},height:{max:i.resolution.height},frameRate:i.resolution.frameRate}):n=Object.assign(Object.assign({},n),{width:{ideal:i.resolution.width},height:{ideal:i.resolution.height},frameRate:i.resolution.frameRate})),{audio:(t=i.audio)!==null&&t!==void 0?t:!1,video:n,controller:i.controller,selfBrowserSurface:i.selfBrowserSurface,surfaceSwitching:i.surfaceSwitching,systemAudio:i.systemAudio,preferCurrentTab:i.preferCurrentTab}}function nn(i){return i.split("/")[1].toLowerCase()}function qh(i){const e=[];return i.forEach(t=>{t.track!==void 0&&e.push(new Hs({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function ie(i){return"mediaStreamTrack"in i?{trackID:i.sid,source:i.source,muted:i.isMuted,enabled:i.mediaStreamTrack.enabled,kind:i.kind,streamID:i.mediaStreamID,streamTrackID:i.mediaStreamTrack.id}:{trackID:i.trackSid,enabled:i.isEnabled,muted:i.isMuted,trackInfo:Object.assign({mimeType:i.mimeType,name:i.trackName,encrypted:i.isEncrypted,kind:i.kind,source:i.source},i.track?ie(i.track):{})}}function $h(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function Hh(i,e){var t;i===void 0&&(i={}),e===void 0&&(e={});const n=[...Object.keys(e),...Object.keys(i)],s={};for(const r of n)i[r]!==e[r]&&(s[r]=(t=e[r])!==null&&t!==void 0?t:"");return s}function Qs(i){const e=Object.assign({},i);let t,n;return typeof e.audio=="object"&&e.audio.processor&&(t=e.audio.processor,e.audio=Object.assign(Object.assign({},e.audio),{processor:void 0})),typeof e.video=="object"&&e.video.processor&&(n=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:t,videoProcessor:n,optionsWithoutProcessor:e}}function zh(i){switch(i){case ge.CAMERA:return w.Source.Camera;case ge.MICROPHONE:return w.Source.Microphone;case ge.SCREEN_SHARE:return w.Source.ScreenShare;case ge.SCREEN_SHARE_AUDIO:return w.Source.ScreenShareAudio;default:return w.Source.Unknown}}class Gh extends et.EventEmitter{constructor(e){super(),this.onWorkerMessage=t=>{var n,s;const{kind:r,data:o}=t.data;switch(r){case"error":W.error(o.error.message),this.emit(bt.EncryptionError,o.error);break;case"initAck":o.enabled&&this.keyProvider.getKeys().forEach(a=>{this.postKey(a)});break;case"enable":if(o.enabled&&this.keyProvider.getKeys().forEach(a=>{this.postKey(a)}),this.encryptionEnabled!==o.enabled&&o.participantIdentity===((n=this.room)===null||n===void 0?void 0:n.localParticipant.identity))this.emit(bt.ParticipantEncryptionStatusChanged,o.enabled,this.room.localParticipant),this.encryptionEnabled=o.enabled;else if(o.participantIdentity){const a=(s=this.room)===null||s===void 0?void 0:s.getParticipantByIdentity(o.participantIdentity);if(!a)throw TypeError("couldn't set encryption status, participant not found".concat(o.participantIdentity));this.emit(bt.ParticipantEncryptionStatusChanged,o.enabled,a)}break;case"ratchetKey":this.keyProvider.emit(Tt.KeyRatcheted,o.material,o.keyIndex);break}},this.onWorkerError=t=>{W.error("e2ee worker encountered an error:",{error:t.error}),this.emit(bt.EncryptionError,t.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!lh())throw new Ks("tried to setup end-to-end encryption on an unsupported browser");if(W.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:Ku.getLevel()}};this.worker&&(W.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){W.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?W.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(x.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(I.TrackPublished,(n,s)=>this.setParticipantCryptorEnabled(n.trackInfo.encryption!==Me.NONE,s.identity)),e.on(I.ConnectionStateChanged,n=>{n===te.Connected&&e.remoteParticipants.forEach(s=>{s.trackPublications.forEach(r=>{this.setParticipantCryptorEnabled(r.trackInfo.encryption!==Me.NONE,s.identity)})})}).on(I.TrackUnsubscribed,(n,s,r)=>{var o;const a={kind:"removeTransform",data:{participantIdentity:r.identity,trackId:n.mediaStreamID}};(o=this.worker)===null||o===void 0||o.postMessage(a)}).on(I.TrackSubscribed,(n,s,r)=>{this.setupE2EEReceiver(n,r.identity,s.trackInfo)}).on(I.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach(n=>{this.postKey(n)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(A.LocalTrackPublished,n=>p(this,void 0,void 0,function*(){this.setupE2EESender(n.track,n.track.sender)})),t.on(Tt.SetKey,n=>this.postKey(n)).on(Tt.RatchetRequest,(n,s)=>this.postRatchetRequest(n,s))}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const n={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(n)}postKey(e){let{key:t,participantIdentity:n,keyIndex:s}=e;var r;if(!this.worker)throw Error("could not set key, worker is missing");const o={kind:"setKey",data:{participantIdentity:n,isPublisher:n===((r=this.room)===null||r===void 0?void 0:r.localParticipant.identity),key:t,keyIndex:s}};this.worker.postMessage(o)}postEnable(e,t){if(this.worker){const n={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(n)}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 n={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(n)}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,n){if(e.receiver){if(!(n!=null&&n.mimeType)||n.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?nn(n.mimeType):void 0)}}setupE2EESender(e,t){if(!Qt(e)||!t){t||W.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,n,s){return p(this,void 0,void 0,function*(){if(this.worker){if(ms()){const r={kind:"decode",participantIdentity:n,trackId:t,codec:s};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{if(ji in e&&s){const c={kind:"updateCodec",data:{trackId:t,codec:s,participantIdentity:n}};this.worker.postMessage(c);return}let r=e.writableStream,o=e.readableStream;if(!r||!o){const c=e.createEncodedStreams();e.writableStream=c.writable,r=c.writable,e.readableStream=c.readable,o=c.readable}const a={kind:"decode",data:{readableStream:o,writableStream:r,trackId:t,codec:s,participantIdentity:n}};this.worker.postMessage(a,[o,r])}e[ji]=!0}})}handleSender(e,t,n){var s;if(!(ji 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(ms()){W.info("initialize script transform");const r={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{W.info("initialize encoded streams");const r=e.createEncodedStreams(),o={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(o,[r.readable,r.writable])}e[ji]=!0}}}const Un="default";class Te{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new Te),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return p(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var r;if(((r=Te.userMediaPromiseMap)===null||r===void 0?void 0:r.size)>0){W.debug("awaiting getUserMedia promise");try{t?yield Te.userMediaPromiseMap.get(t):yield Promise.all(Te.userMediaPromiseMap.values())}catch{W.warn("error waiting for media permissons")}}let o=yield navigator.mediaDevices.enumerateDevices();if(s&&!(Et()&&n.hasDeviceInUse(t))&&(o.filter(c=>c.kind===t).length===0||o.some(c=>{const d=c.label==="",l=t?c.kind===t:!0;return d&&l}))){const c={video:t!=="audioinput"&&t!=="audiooutput",audio:t!=="videoinput"&&{deviceId:"default"}},d=yield navigator.mediaDevices.getUserMedia(c);o=yield navigator.mediaDevices.enumerateDevices(),d.getTracks().forEach(l=>{l.stop()})}return n._previousDevices=o,t&&(o=o.filter(a=>a.kind===t)),o}()})}normalizeDeviceId(e,t,n){return p(this,void 0,void 0,function*(){if(t!==Un)return t;const s=yield this.getDevices(e),r=s.find(a=>a.deviceId===Un);if(!r){W.warn("could not reliably determine default device");return}const o=s.find(a=>a.deviceId!==Un&&a.groupId===(n??r.groupId));if(!o){W.warn("could not reliably determine default device");return}return o==null?void 0:o.deviceId})}hasDeviceInUse(e){return e?Te.userMediaPromiseMap.has(e):Te.userMediaPromiseMap.size>0}}Te.mediaDeviceKinds=["audioinput","audiooutput","videoinput"];Te.userMediaPromiseMap=new Map;var ki;(function(i){i[i.WAITING=0]="WAITING",i[i.RUNNING=1]="RUNNING",i[i.COMPLETED=2]="COMPLETED"})(ki||(ki={}));class Wh{constructor(){this.pendingTasks=new Map,this.taskMutex=new De,this.nextTaskIndex=0}run(e){return p(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:ki.WAITING};this.pendingTasks.set(t.id,t);const n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=ki.RUNNING,yield e()}finally{t.status=ki.COMPLETED,this.pendingTasks.delete(t.id),n()}})}flush(){return p(this,void 0,void 0,function*(){return this.run(()=>p(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}const Kh=["syncState","trickle","offer","answer","simulate","leave"];function Jh(i){const e=Kh.indexOf(i.case)>=0;return W.trace("request allowed to bypass queue:",{canPass:e,req:i}),e}var ae;(function(i){i[i.CONNECTING=0]="CONNECTING",i[i.CONNECTED=1]="CONNECTED",i[i.RECONNECTING=2]="RECONNECTING",i[i.DISCONNECTING=3]="DISCONNECTING",i[i.DISCONNECTED=4]="DISCONNECTED"})(ae||(ae={}));class Ys{get currentState(){return this.state}get isDisconnected(){return this.state===ae.DISCONNECTING||this.state===ae.DISCONNECTED}get isEstablishingConnection(){return this.state===ae.CONNECTING||this.state===ae.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var n;this.rtt=0,this.state=ae.DISCONNECTED,this.log=W,this._requestId=0,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=ct((n=t.loggerName)!==null&&n!==void 0?n:Ge.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new Wh,this.queuedRequests=[],this.closingLock=new De,this.connectionLock=new De,this.state=ae.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,n,s){return p(this,void 0,void 0,function*(){return this.state=ae.CONNECTING,this.options=n,yield this.connect(e,t,n,s)})}reconnect(e,t,n,s){return p(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=ae.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:s}))})}connect(e,t,n,s){this.connectOptions=n;const r=new URL(Nh(e));r.pathname=r.pathname.replace(/\/$/,""),r.pathname+="/rtc";const o=Mh(),a=Qh(t,o,n);for(const[c,d]of a)r.searchParams.set(c,d);return new Promise((c,d)=>p(this,void 0,void 0,function*(){const l=yield this.connectionLock.lock();try{const u=()=>p(this,void 0,void 0,function*(){this.close(),clearTimeout(h),d(new re("room connection has been cancelled (signal)",J.Cancelled))}),h=setTimeout(()=>{this.close(),d(new re("room connection has timed out (signal)",J.ServerUnreachable))},n.websocketTimeout);s!=null&&s.aborted&&u(),s==null||s.addEventListener("abort",u);const f=new URL(r.toString());f.searchParams.has("access_token")&&f.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(f),Object.assign({reconnect:n.reconnect,reconnectReason:n.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(r.toString()),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(h)},this.ws.onerror=m=>p(this,void 0,void 0,function*(){if(this.state!==ae.CONNECTED){this.state=ae.DISCONNECTED,clearTimeout(h);try{const g=new URL(r.toString());g.protocol="http".concat(g.protocol.substring(2)),g.pathname+="/validate";const T=yield fetch(g);if(T.status.toFixed(0).startsWith("4")){const C=yield T.text();d(new re(C,J.NotAllowed,T.status))}else d(new re("Internal error",J.InternalError,T.status))}catch(g){d(new re(g instanceof Error?g.message:"server was not reachable",J.ServerUnreachable))}return}this.handleWSError(m)}),this.ws.onmessage=m=>p(this,void 0,void 0,function*(){var g,T,C;let M;if(typeof m.data=="string"){const j=JSON.parse(m.data);M=Or.fromJson(j,{ignoreUnknownFields:!0})}else if(m.data instanceof ArrayBuffer)M=Or.fromBinary(new Uint8Array(m.data));else{this.log.error("could not decode websocket message: ".concat(typeof m.data),this.logContext);return}if(this.state!==ae.CONNECTED){let j=!1;if(((g=M.message)===null||g===void 0?void 0:g.case)==="join"?(this.state=ae.CONNECTED,s==null||s.removeEventListener("abort",u),this.pingTimeoutDuration=M.message.value.pingTimeout,this.pingIntervalDuration=M.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()),c(M.message.value)):this.state===ae.RECONNECTING&&M.message.case!=="leave"?(this.state=ae.CONNECTED,s==null||s.removeEventListener("abort",u),this.startPingInterval(),((T=M.message)===null||T===void 0?void 0:T.case)==="reconnect"?c(M.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),c(void 0),j=!0)):this.isEstablishingConnection&&M.message.case==="leave"?d(new re("Received leave request while trying to (re)connect",J.LeaveRequest,void 0,M.message.value.reason)):n.reconnect||d(new re("did not receive join response, got ".concat((C=M.message)===null||C===void 0?void 0:C.case," instead"),J.InternalError)),!j)return}this.signalLatency&&(yield Ie(this.signalLatency)),this.handleSignalResponse(M)}),this.ws.onclose=m=>{this.isEstablishingConnection&&d(new re("Websocket got closed during a (re)connection attempt",J.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:m.reason,code:m.code,wasClean:m.wasClean,state:this.state})),this.handleOnClose(m.reason)}}finally{l()}}))}close(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){const n=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=ae.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;const s=new Promise(r=>{e.ws?e.ws.onclose=()=>{r()}:r()});e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([s,Ie(250)])),e.ws=void 0}}finally{t&&(e.state=ae.DISCONNECTED),n()}}()})}sendOffer(e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:hn(e)})}sendAnswer(e){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:hn(e)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new qs({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new $s({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return p(this,arguments,void 0,function(n,s){var r=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return function*(){const a=r.getNextRequestId();return yield r.sendRequest({case:"updateMetadata",value:new ka({requestId:a,metadata:n,name:s,attributes:o})}),a}()})}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:"updateLayers",value:new ba({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Sa({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:ce.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new _a({timestamp:ce.parse(Date.now()),rtt:ce.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new ya({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new kn({reason:ze.CLIENT_INITIATED,action:Wt.DISCONNECT})})}sendRequest(e){return p(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return function*(){if(!s&&!Jh(t)&&n.state===ae.RECONNECTING){n.queuedRequests.push(()=>p(n,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(s||(yield n.requestQueue.flush()),n.signalLatency&&(yield Ie(n.signalLatency)),!n.ws||n.ws.readyState!==n.ws.OPEN){n.log.error("cannot send signal request before connected, type: ".concat(t==null?void 0:t.case),n.logContext);return}const o=new Eu({message:t});try{n.useJSON?n.ws.send(o.toJsonString()):n.ws.send(o.toBinary())}catch(a){n.log.error("error sending signal message",Object.assign(Object.assign({},n.logContext),{error:a}))}}()})}handleSignalResponse(e){var t,n;const s=e.message;if(s==null){this.log.debug("received unsupported message",this.logContext);return}let r=!1;if(s.case==="answer"){const o=eo(s.value);this.onAnswer&&this.onAnswer(o)}else if(s.case==="offer"){const o=eo(s.value);this.onOffer&&this.onOffer(o)}else if(s.case==="trickle"){const o=JSON.parse(s.value.candidateInit);this.onTrickle&&this.onTrickle(o,s.value.target)}else s.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((t=s.value.participants)!==null&&t!==void 0?t:[]):s.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(s.value):s.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((n=s.value.speakers)!==null&&n!==void 0?n:[]):s.case==="leave"?this.onLeave&&this.onLeave(s.value):s.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(s.value.sid,s.value.muted):s.case==="roomUpdate"?this.onRoomUpdate&&s.value.room&&this.onRoomUpdate(s.value.room):s.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(s.value):s.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(s.value):s.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(s.value):s.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(s.value):s.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(s.value):s.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(s.value):s.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(s.value):s.case==="pong"||(s.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(s.value.lastPingTimestamp.toString()),this.resetPingTimeout(),r=!0):s.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(s.value):s.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(s.value.trackSid):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 p(this,void 0,void 0,function*(){if(this.state===ae.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=Se.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&&Se.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=Se.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&Se.clearInterval(this.pingInterval)}}function eo(i){const e={type:"offer",sdp:i.sdp};switch(i.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=i.type;break}return e}function hn(i){return new Dt({sdp:i.sdp,type:i.type})}function Qh(i,e,t){var n;const s=new URLSearchParams;return s.set("access_token",i),t.reconnect&&(s.set("reconnect","1"),t.sid&&s.set("sid",t.sid)),s.set("auto_subscribe",t.autoSubscribe?"1":"0"),s.set("sdk",Ze()?"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()),!((n=navigator.connection)===null||n===void 0)&&n.type&&s.set("network",navigator.connection.type),s}var je={},jn={},Fn={exports:{}},to;function Xs(){if(to)return Fn.exports;to=1;var i=Fn.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return e.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return e.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return e.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=e.raddr!=null?" raddr %s rport %d":"%v%v",t+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(t+=" generation %d"),t+=e["network-id"]!=null?" network-id %d":"%v",t+=e["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return e.attribute!=null&&(t+=" %s",e.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return e.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(e.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=e.id!=null?"id=%s %s":"%v%s",t+=e.mediaClockValue!=null?"=%s":"",t+=e.rateNumerator!=null?" rate=%s":"",t+=e.rateDenominator!=null?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(i).forEach(function(e){var t=i[e];t.forEach(function(n){n.reg||(n.reg=/(.*)/),n.format||(n.format="%s")})}),Fn.exports}var io;function Yh(){return io||(io=1,function(i){var e=function(a){return String(Number(a))===a?Number(a):a},t=function(a,c,d,l){if(l&&!d)c[l]=e(a[1]);else for(var u=0;u<d.length;u+=1)a[u+1]!=null&&(c[d[u]]=e(a[u+1]))},n=function(a,c,d){var l=a.name&&a.names;a.push&&!c[a.push]?c[a.push]=[]:l&&!c[a.name]&&(c[a.name]={});var u=a.push?{}:l?c[a.name]:c;t(d.match(a.reg),u,a.names,a.name),a.push&&c[a.push].push(u)},s=Xs(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);i.parse=function(a){var c={},d=[],l=c;return a.split(/(\r\n|\r|\n)/).filter(r).forEach(function(u){var h=u[0],f=u.slice(2);h==="m"&&(d.push({rtp:[],fmtp:[]}),l=d[d.length-1]);for(var m=0;m<(s[h]||[]).length;m+=1){var g=s[h][m];if(g.reg.test(f))return n(g,l,f)}}),c.media=d,c};var o=function(a,c){var d=c.split(/=(.+)/,2);return d.length===2?a[d[0]]=e(d[1]):d.length===1&&c.length>1&&(a[d[0]]=void 0),a};i.parseParams=function(a){return a.split(/;\s?/).reduce(o,{})},i.parseFmtpConfig=i.parseParams,i.parsePayloads=function(a){return a.toString().split(" ").map(Number)},i.parseRemoteCandidates=function(a){for(var c=[],d=a.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},i.parseImageAttributes=function(a){return a.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(o,{})})},i.parseSimulcastStreamList=function(a){return a.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}})})}}(jn)),jn}var Bn,no;function Xh(){if(no)return Bn;no=1;var i=Xs(),e=/%[sdv%]/g,t=function(o){var a=1,c=arguments,d=c.length;return o.replace(e,function(l){if(a>=d)return l;var u=c[a];switch(a+=1,l){case"%%":return"%";case"%s":return String(u);case"%d":return Number(u);case"%v":return""}})},n=function(o,a,c){var d=a.format instanceof Function?a.format(a.push?c:c[a.name]):a.format,l=[o+"="+d];if(a.names)for(var u=0;u<a.names.length;u+=1){var h=a.names[u];a.name?l.push(c[a.name][h]):l.push(c[a.names[u]])}else l.push(c[a.name]);return t.apply(null,l)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r=["i","c","b","a"];return Bn=function(o,a){a=a||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(u){u.payloads==null&&(u.payloads="")});var c=a.outerOrder||s,d=a.innerOrder||r,l=[];return c.forEach(function(u){i[u].forEach(function(h){h.name in o&&o[h.name]!=null?l.push(n(u,h,o)):h.push in o&&o[h.push]!=null&&o[h.push].forEach(function(f){l.push(n(u,h,f))})})}),o.media.forEach(function(u){l.push(n("m",i.m[0],u)),d.forEach(function(h){i[h].forEach(function(f){f.name in u&&u[f.name]!=null?l.push(n(h,f,u)):f.push in u&&u[f.push]!=null&&u[f.push].forEach(function(m){l.push(n(h,f,m))})})})}),l.join(`\r
|
|
54
|
-
`)+`\r
|
|
55
|
-
`},Bn}var so;function Zh(){if(so)return je;so=1;var i=Yh(),e=Xh(),t=Xs();return je.grammar=t,je.write=e,je.parse=i.parse,je.parseParams=i.parseParams,je.parseFmtpConfig=i.parseFmtpConfig,je.parsePayloads=i.parsePayloads,je.parseRemoteCandidates=i.parseRemoteCandidates,je.parseImageAttributes=i.parseImageAttributes,je.parseSimulcastStreamList=i.parseSimulcastStreamList,je}var pt=Zh();function Zs(i,e,t){var n,s,r;e===void 0&&(e=50),t===void 0&&(t={});var o=(n=t.isImmediate)!=null&&n,a=(s=t.callback)!=null&&s,c=t.maxWait,d=Date.now(),l=[];function u(){if(c!==void 0){var f=Date.now()-d;if(f+e>=c)return c-f}return e}var h=function(){var f=[].slice.call(arguments),m=this;return new Promise(function(g,T){var C=o&&r===void 0;if(r!==void 0&&clearTimeout(r),r=setTimeout(function(){if(r=void 0,d=Date.now(),!o){var j=i.apply(m,f);a&&a(j),l.forEach(function(k){return(0,k.resolve)(j)}),l=[]}},u()),C){var M=i.apply(m,f);return a&&a(M),g(M)}l.push({resolve:g,reject:T})})};return h.cancel=function(f){r!==void 0&&clearTimeout(r),l.forEach(function(m){return(0,m.reject)(f)}),l=[]},h}const ef=.7,tf=20,Yt={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class ro extends et.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 n;super(),this.log=W,this.ddExtID=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Zs(s=>p(this,void 0,void 0,function*(){this.emit(Yt.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(s)s(r);else throw r}}),tf),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=ct((n=t.loggerName)!==null&&n!==void 0?n:Ge.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC()}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var n;t.candidate&&((n=this.onIceCandidate)===null||n===void 0||n.call(this,t.candidate))},e.onicecandidateerror=t=>{var n;(n=this.onIceCandidateError)===null||n===void 0||n.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 n;(n=this.onDataChannel)===null||n===void 0||n.call(this,t)},e.ontrack=t=>{var n;(n=this.onTrack)===null||n===void 0||n.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 p(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e){return p(this,void 0,void 0,function*(){var t;let n;if(e.type==="offer"){let{stereoMids:s,nackMids:r}=nf(e);this.remoteStereoMids=s,this.remoteNackMids=r}else if(e.type==="answer"){const s=pt.parse((t=e.sdp)!==null&&t!==void 0?t:"");s.media.forEach(r=>{r.type==="audio"&&this.trackBitrates.some(o=>{if(!o.transceiver||r.mid!=o.transceiver.mid)return!1;let a=0;if(r.rtp.some(d=>d.codec.toUpperCase()===o.codec.toUpperCase()?(a=d.payload,!0):!1),a===0)return!0;let c=!1;for(const d of r.fmtp)if(d.payload===a){d.config=d.config.split(";").filter(l=>!l.includes("maxaveragebitrate")).join(";"),o.maxbr>0&&(d.config+=";maxaveragebitrate=".concat(o.maxbr*1e3)),c=!0;break}return c||o.maxbr>0&&r.fmtp.push({payload:a,config:"maxaveragebitrate=".concat(o.maxbr*1e3)}),!0})}),n=pt.write(s)}yield this.setMungedSDP(e,n,!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(Yt.NegotiationComplete),e.sdp&&pt.parse(e.sdp).media.forEach(r=>{r.type==="video"&&this.emit(Yt.RTPVideoPayloadTypes,r.rtp)}))})}createAndSendOffer(e){return p(this,void 0,void 0,function*(){var t;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 n=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:n.sdp},this.logContext));const s=pt.parse((t=n.sdp)!==null&&t!==void 0?t:"");s.media.forEach(r=>{ao(r),r.type==="audio"?oo(r,[],[]):r.type==="video"&&this.trackBitrates.some(o=>{if(!r.msid||!o.cid||!r.msid.includes(o.cid))return!1;let a=0;if(r.rtp.some(d=>d.codec.toUpperCase()===o.codec.toUpperCase()?(a=d.payload,!0):!1),a===0||(bi(o.codec)&&this.ensureVideoDDExtensionForSVC(r,s),o.codec!=="av1"))return!0;const c=Math.round(o.maxbr*ef);for(const d of r.fmtp)if(d.payload===a){d.config.includes("x-google-start-bitrate")||(d.config+=";x-google-start-bitrate=".concat(c));break}return!0})}),yield this.setMungedSDP(n,pt.write(s)),this.onOffer(n)})}createAndSetAnswer(){return p(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),n=pt.parse((e=t.sdp)!==null&&e!==void 0?e:"");return n.media.forEach(s=>{ao(s),s.type==="audio"&&oo(s,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,pt.write(n)),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 ye("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 ye("PC closed, cannot configure");return(t=this._pc)===null||t===void 0?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var t;return(t=this._pc)===null||t===void 0?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&t!==void 0?t:"closed"}getICEConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&t!==void 0?t:"closed"}getSignallingState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&t!==void 0?t:"closed"}getTransceivers(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[]}getSenders(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&t!==void 0?t:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return p(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const n=new Map,s=new Map;if((yield this._pc.getStats()).forEach(a=>{switch(a.type){case"transport":t=a.selectedCandidatePairId;break;case"candidate-pair":t===""&&a.selected&&(t=a.id),n.set(a.id,a);break;case"remote-candidate":s.set(a.id,"".concat(a.address,":").concat(a.port));break}}),t==="")return;const o=(e=n.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(o!==void 0)return s.get(o)})}setMungedSDP(e,t,n){return p(this,void 0,void 0,function*(){if(t){const s=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(n?"remote":"local"," description"),this.logContext),n?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{n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(s){let r="unknown error";s instanceof Error?r=s.message:typeof s=="string"&&(r=s);const o={error:r,sdp:e.sdp};throw!n&&this.pc.remoteDescription&&(o.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:o})),new gs(r)}})}ensureVideoDDExtensionForSVC(e,t){var n,s;if(!((n=e.ext)===null||n===void 0?void 0:n.some(o=>o.uri===Gr))){if(this.ddExtID===0){let o=0;t.media.forEach(a=>{var c;a.type==="video"&&((c=a.ext)===null||c===void 0||c.forEach(d=>{d.value>o&&(o=d.value)}))}),this.ddExtID=o+1}(s=e.ext)===null||s===void 0||s.push({value:this.ddExtID,uri:Gr})}}}function oo(i,e,t){let n=0;i.rtp.some(s=>s.codec==="opus"?(n=s.payload,!0):!1),n>0&&(i.rtcpFb||(i.rtcpFb=[]),t.includes(i.mid)&&!i.rtcpFb.some(s=>s.payload===n&&s.type==="nack")&&i.rtcpFb.push({payload:n,type:"nack"}),e.includes(i.mid)&&i.fmtp.some(s=>s.payload===n?(s.config.includes("stereo=1")||(s.config+=";stereo=1"),!0):!1))}function nf(i){var e;const t=[],n=[],s=pt.parse((e=i.sdp)!==null&&e!==void 0?e:"");let r=0;return s.media.forEach(o=>{var a;o.type==="audio"&&(o.rtp.some(c=>c.codec==="opus"?(r=c.payload,!0):!1),!((a=o.rtcpFb)===null||a===void 0)&&a.some(c=>c.payload===r&&c.type==="nack")&&n.push(o.mid),o.fmtp.some(c=>c.payload===r?(c.config.includes("sprop-stereo=1")&&t.push(o.mid),!0):!1))}),{stereoMids:t,nackMids:n}}function ao(i){if(i.connection){const e=i.connection.ip.indexOf(":")>=0;(i.connection.version===4&&e||i.connection.version===6&&!e)&&(i.connection.ip="0.0.0.0",i.connection.version=4)}}const ws="vp8",sf={audioPreset:vs.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Js.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:ws,backupCodec:!0},hc={deviceId:"default",autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},fc={deviceId:"default",resolution:Pi.h720.resolution},rf={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Qu,disconnectOnPageLeave:!0,webAudioMix:!1},er={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var le;(function(i){i[i.NEW=0]="NEW",i[i.CONNECTING=1]="CONNECTING",i[i.CONNECTED=2]="CONNECTED",i[i.FAILED=3]="FAILED",i[i.CLOSING=4]="CLOSING",i[i.CLOSED=5]="CLOSED"})(le||(le={}));class of{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,n){var s;this.peerConnectionTimeout=er.peerConnectionTimeout,this.log=W,this.updateState=()=>{var r;const o=this.state,a=this.requiredTransports.map(c=>c.getConnectionState());a.every(c=>c==="connected")?this.state=le.CONNECTED:a.some(c=>c==="failed")?this.state=le.FAILED:a.some(c=>c==="connecting")?this.state=le.CONNECTING:a.every(c=>c==="closed")?this.state=le.CLOSED:a.some(c=>c==="closed")?this.state=le.CLOSING:a.every(c=>c==="new")&&(this.state=le.NEW),o!==this.state&&(this.log.debug("pc state change: from ".concat(le[o]," to ").concat(le[this.state]),this.logContext),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=ct((s=n.loggerName)!==null&&s!==void 0?s:Ge.PCManager),this.loggerOptions=n,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new ro(e,n),this.subscriber=new ro(e,n),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 o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,r,$e.PUBLISHER)},this.subscriber.onIceCandidate=r=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,r,$e.SUBSCRIBER)},this.subscriber.onDataChannel=r=>{var o;(o=this.onDataChannel)===null||o===void 0||o.call(this,r)},this.subscriber.onTrack=r=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,r)},this.publisher.onOffer=r=>{var o;(o=this.onPublisherOffer)===null||o===void 0||o.call(this,r)},this.state=le.NEW,this.connectionLock=new De,this.remoteOfferLock=new De}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 p(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(n){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:n}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return p(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return p(this,void 0,void 0,function*(){t===$e.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e){return p(this,void 0,void 0,function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber.getSignallingState().toString()}));const t=yield this.remoteOfferLock.lock();try{return yield this.subscriber.setRemoteDescription(e),yield this.subscriber.createAndSetAnswer()}finally{t()}})}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return p(this,void 0,void 0,function*(){var n;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((n=this.requiredTransports)===null||n===void 0?void 0:n.map(r=>this.ensureTransportConnected(r,e,t)))}finally{s()}})}negotiate(e){return p(this,void 0,void 0,function*(){return new Promise((t,n)=>p(this,void 0,void 0,function*(){const s=setTimeout(()=>{n("negotiation timed out")},this.peerConnectionTimeout),r=()=>{clearTimeout(s),n("negotiation aborted")};e.signal.addEventListener("abort",r),this.publisher.once(Yt.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Yt.NegotiationComplete,()=>{clearTimeout(s),t()})}),yield this.publisher.negotiate(o=>{clearTimeout(s),n(o)})}))})}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===$e.PUBLISHER?this.publisher.getConnectedAddress():e===$e.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){return p(this,arguments,void 0,function(n,s){var r=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(n.getConnectionState()!=="connected")return new Promise((c,d)=>p(r,void 0,void 0,function*(){const l=()=>{this.log.warn("abort transport connection",this.logContext),Se.clearTimeout(u),d(new re("room connection has been cancelled",J.Cancelled))};s!=null&&s.signal.aborted&&l(),s==null||s.signal.addEventListener("abort",l);const u=Se.setTimeout(()=>{s==null||s.signal.removeEventListener("abort",l),d(new re("could not establish pc connection",J.InternalError))},o);for(;this.state!==le.CONNECTED;)if(yield Ie(50),s!=null&&s.signal.aborted){d(new re("room connection has been cancelled",J.Cancelled));return}Se.clearTimeout(u),s==null||s.signal.removeEventListener("abort",l),c()}))}()})}}class he extends Error{constructor(e,t,n){super(t),this.code=e,this.message=co(t,he.MAX_MESSAGE_BYTES),this.data=n?co(n,he.MAX_DATA_BYTES):void 0}static fromProto(e){return new he(e.code,e.message,e.data)}toProto(){return new da({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new he(he.ErrorCode[e],he.ErrorMessage[e],t)}}he.MAX_MESSAGE_BYTES=256;he.MAX_DATA_BYTES=15360;he.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404};he.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};const pc=15360;function tr(i){return new TextEncoder().encode(i).length}function co(i,e){if(tr(i)<=e)return i;let t=0,n=i.length;const s=new TextEncoder;for(;t<n;){const r=Math.floor((t+n+1)/2);s.encode(i.slice(0,r)).length<=e?t=r:n=r-1}return i.slice(0,t)}const ir=2e3;function Sn(i,e){if(!e)return 0;let t,n;return"bytesReceived"in i?(t=i.bytesReceived,n=e.bytesReceived):"bytesSent"in i&&(t=i.bytesSent,n=e.bytesSent),t===void 0||n===void 0||i.timestamp===void 0||e.timestamp===void 0?0:(t-n)*8*1e3/(i.timestamp-e.timestamp)}const af=1e3;class mc extends w{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}constructor(e,t,n){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,r=arguments.length>4?arguments[4]:void 0;super(e,t,r),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=Zs(()=>p(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>p(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(O.Ended,this)},this.reacquireTrack=!1,this.providedByUser=s,this.muteLock=new De,this.pauseUpstreamLock=new De,this.processorLock=new De,this.restartLock=new De,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==w.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return(t=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&t!==void 0?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return p(this,void 0,void 0,function*(){var n;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(r=>{Jt(this._mediaStreamTrack,r)}),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 s;if(this.processor&&e){const r=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&&(zt(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),s=this.processor.processedTrack}finally{r()}}this.sender&&((n=this.sender.transport)===null||n===void 0?void 0:n.state)!=="closed"&&(yield this.sender.replaceTrack(s??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(r=>{zt(s??e,r)}))})}waitForDimensions(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:af;return function*(){var n;if(e.kind===w.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((n=Xe())===null||n===void 0?void 0:n.os)==="iOS"&&(yield Ie(10));const s=Date.now();for(;Date.now()-s<t;){const r=e.dimensions;if(r)return r;yield Ie(50)}throw new rt("unable to get track dimensions after timeout")}()})}setDeviceId(e){return p(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Ct(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),Ct(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){if(e.source===w.Source.ScreenShare)return;const{deviceId:n,groupId:s}=e._mediaStreamTrack.getSettings(),r=e.kind===w.Kind.Audio?"audioinput":"videoinput";return t?Te.getInstance().normalizeDeviceId(r,n,s):n}()})}mute(){return p(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return p(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return p(this,void 0,void 0,function*(){if(!this.sender)throw new rt("unable to replace an unpublished track");let n,s;return typeof t=="boolean"?n=t:t!==void 0&&(n=t.userProvidedTrack,s=t.stopProcessor),this.providedByUser=n??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),s&&this.processor&&(yield this.stopProcessor()),this})}restart(e){return p(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.restartLock.lock();try{e||(e=this._constraints);const{deviceId:n}=e,s=Yu(e,["deviceId"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const r={audio:!1,video:!1};this.kind===w.Kind.Video?r.video=n?{deviceId:n}:!0:r.audio=n?{deviceId:n}:!0,this.attachedElements.forEach(c=>{Jt(this.mediaStreamTrack,c)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const a=(yield navigator.mediaDevices.getUserMedia(r)).getTracks()[0];return yield a.applyConstraints(s),a.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(a),this._constraints=e,this.emit(O.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),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?O.Muted:O.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 p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),rc()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(e=this.processor)===null||e===void 0||e.destroy(),this.processor=void 0}pauseUpstream(){return p(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(O.UpstreamPaused,this);const n=Xe();if((n==null?void 0:n.name)==="Safari"&&ti(n.version,"12.0")<0)throw new Ks("pauseUpstream is not supported on Safari < 12.");((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return p(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(O.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return p(this,void 0,void 0,function*(){var e;return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){return p(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var r;const o=yield n.processorLock.lock();try{n.log.debug("setting up processor",n.logContext);const a=document.createElement(n.kind),c={kind:n.kind,track:n._mediaStreamTrack,element:a,audioContext:n.audioContext};if(yield t.init(c),n.log.debug("processor initialized",n.logContext),n.processor&&(yield n.stopProcessor()),n.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(zt(n._mediaStreamTrack,a),a.muted=!0,a.play().catch(d=>n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{error:d}))),n.processor=t,n.processorElement=a,n.processor.processedTrack){for(const d of n.attachedElements)d!==n.processorElement&&s&&(Jt(n._mediaStreamTrack,d),zt(n.processor.processedTrack,d));yield(r=n.sender)===null||r===void 0?void 0:r.replaceTrack(n.processor.processedTrack)}n.emit(O.TrackProcessorUpdate,n.processor)}finally{o()}}()})}getProcessor(){return this.processor}stopProcessor(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var n,s;e.processor&&(e.log.debug("stopping processor",e.logContext),(n=e.processor.processedTrack)===null||n===void 0||n.stop(),yield e.processor.destroy(),e.processor=void 0,t||((s=e.processorElement)===null||s===void 0||s.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(O.TrackProcessorUpdate))}()})}}class fn extends mc{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let n=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,w.Kind.Audio,t,n,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>p(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let o;try{o=yield this.getSenderStats()}catch(a){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:a}));return}o&&this.prevStats&&(this._currentBitrate=Sn(o,this.prevStats)),this.prevStats=o}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(O.AudioTrackFeatureUpdate,this,Ye.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(O.AudioTrackFeatureUpdate,this,Ye.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=s,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return p(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===w.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 p(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 n=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Ct(this._constraints.deviceId);return this.source===w.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||n)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return p(this,void 0,void 0,function*(){let t;if(e){const n=Cn({audio:e});typeof n.audio!="boolean"&&(t=n.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return p(this,void 0,void 0,function*(){const n=yield t.restart.call(this,e);return this.checkForSilence(),n})}startMonitor(){Re()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},ir)))}setProcessor(e){return p(this,void 0,void 0,function*(){var t;const n=yield this.processorLock.lock();try{if(!Ze()&&!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.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(O.TrackProcessorUpdate,this.processor)}finally{n()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return p(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let n;return t.forEach(s=>{s.type==="outbound-rtp"&&(n={type:"audio",streamId:s.id,packetsSent:s.packetsSent,packetsLost:s.packetsLost,bytesSent:s.bytesSent,timestamp:s.timestamp,roundTripTime:s.roundTripTime,jitter:s.jitter})}),n})}checkForSilence(){return p(this,void 0,void 0,function*(){const e=yield lc(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(O.AudioSilenceDetected)),e})}}function gc(i,e,t){switch(i.kind){case"audio":return new fn(i,e,!1,void 0,t);case"video":return new pn(i,e,!1,t);default:throw new rt("unsupported track type: ".concat(i.kind))}}const cf=Object.values(Pi),df=Object.values(ys),lf=Object.values(Js),uf=[Pi.h180,Pi.h360],hf=[ys.h180,ys.h360],ff=i=>[{scaleResolutionDownBy:2,fps:i.encoding.maxFramerate}].map(t=>{var n,s;return new ne(Math.floor(i.width/t.scaleResolutionDownBy),Math.floor(i.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(i.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((n=i.encoding.maxFramerate)!==null&&n!==void 0?n:30)/((s=t.fps)!==null&&s!==void 0?s:30))))),t.fps,i.encoding.priority)}),_s=["q","h","f"];function Ps(i,e,t,n){var s,r;let o=n==null?void 0:n.videoEncoding;i&&(o=n==null?void 0:n.screenShareEncoding);const a=n==null?void 0:n.simulcast,c=n==null?void 0:n.scalabilityMode,d=n==null?void 0:n.videoCodec;if(!o&&!a&&!c||!e||!t)return[{}];o||(o=mf(i,e,t,d),W.debug("using video encoding",o));const l=o.maxFramerate,u=new ne(e,t,o.maxBitrate,o.maxFramerate,o.priority);if(c&&bi(d)){const m=new vc(c),g=[];if(m.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const T=Xe();if(Et()||Ze()||(T==null?void 0:T.name)==="Chrome"&&ti(T==null?void 0:T.version,"113")<0){const C=m.suffix=="h"?2:3;for(let M=0;M<m.spatial;M+=1)g.push({rid:_s[2-M],maxBitrate:o.maxBitrate/Math.pow(C,M),maxFramerate:u.encoding.maxFramerate});g[0].scalabilityMode=c}else g.push({maxBitrate:o.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(g[0].priority=u.encoding.priority,g[0].networkPriority=u.encoding.priority),W.debug("using svc encoding",{encodings:g}),g}if(!a)return[o];let h=[];i?h=(s=uo(n==null?void 0:n.screenShareSimulcastLayers))!==null&&s!==void 0?s:lo(i,u):h=(r=uo(n==null?void 0:n.videoSimulcastLayers))!==null&&r!==void 0?r:lo(i,u);let f;if(h.length>0){const m=h[0];h.length>1&&([,f]=h);const g=Math.max(e,t);if(g>=960&&f)return Vn(e,t,[m,f,u],l);if(g>=480)return Vn(e,t,[m,u],l)}return Vn(e,t,[u])}function pf(i,e,t){var n,s,r,o;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&W.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const a=i.mediaStreamTrack.getSettings(),c=(n=a.width)!==null&&n!==void 0?n:(s=i.dimensions)===null||s===void 0?void 0:s.width,d=(r=a.height)!==null&&r!==void 0?r:(o=i.dimensions)===null||o===void 0?void 0:o.height;return i.source===w.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),Ps(i.source===w.Source.ScreenShare,c,d,t)}function mf(i,e,t,n){const s=gf(i,e,t);let{encoding:r}=s[0];const o=Math.max(e,t);for(let a=0;a<s.length;a+=1){const c=s[a];if(r=c.encoding,c.width>=o)break}if(n)switch(n){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 gf(i,e,t){if(i)return lf;const n=e>t?e/t:t/e;return Math.abs(n-16/9)<Math.abs(n-4/3)?cf:df}function lo(i,e){if(i)return ff(e);const{width:t,height:n}=e,s=t>n?t/n:n/t;return Math.abs(s-16/9)<Math.abs(s-4/3)?uf:hf}function Vn(i,e,t,n){const s=[];if(t.forEach((r,o)=>{if(o>=_s.length)return;const a=Math.min(i,e),d={rid:_s[o],scaleResolutionDownBy:Math.max(1,a/Math.min(r.width,r.height)),maxBitrate:r.encoding.maxBitrate},l=n&&r.encoding.maxFramerate?Math.min(n,r.encoding.maxFramerate):r.encoding.maxFramerate;l&&(d.maxFramerate=l);const u=ei()||o===0;r.encoding.priority&&u&&(d.priority=r.encoding.priority,d.networkPriority=r.encoding.priority),s.push(d)}),Ze()&&ac()==="ios"){let r;s.forEach(a=>{r?a.maxFramerate&&a.maxFramerate>r&&(r=a.maxFramerate):r=a.maxFramerate});let o=!0;s.forEach(a=>{var c;a.maxFramerate!=r&&(o&&(o=!1,W.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),W.info('Setting framerate of encoding "'.concat((c=a.rid)!==null&&c!==void 0?c:"",'" to ').concat(r)),a.maxFramerate=r)})}return s}function uo(i){if(i)return i.sort((e,t)=>{const{encoding:n}=e,{encoding:s}=t;return n.maxBitrate>s.maxBitrate?1:n.maxBitrate<s.maxBitrate?-1:n.maxBitrate===s.maxBitrate&&n.maxFramerate&&s.maxFramerate?n.maxFramerate>s.maxFramerate?1:-1:0})}class vc{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function vf(i){return i.source===w.Source.ScreenShare||i.constraints.height&&Ct(i.constraints.height)>=1080?"maintain-resolution":"balanced"}const yf=5e3;class pn extends mc{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0;super(e,w.Kind.Video,t,n,s),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>p(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=yield this.getSenderStats()}catch(a){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:a}));return}const o=new Map(r.map(a=>[a.rid,a]));if(this.prevStats){let a=0;o.forEach((c,d)=>{var l;const u=(l=this.prevStats)===null||l===void 0?void 0:l.get(d);a+=Sn(c,u)}),this._currentBitrate=a}this.prevStats=o}),this.senderLock=new De}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!Re())return;const n=(t=this.sender)===null||t===void 0?void 0:t.getParameters();n&&(this.encodings=n.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},ir))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return p(this,void 0,void 0,function*(){var t,n,s,r,o;yield e.pauseUpstream.call(this);try{for(var a=!0,c=vt(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;a=!0)r=d.value,a=!1,yield(o=r.sender)===null||o===void 0?void 0:o.replaceTrack(null)}catch(l){n={error:l}}finally{try{!a&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(n)throw n.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return p(this,void 0,void 0,function*(){var t,n,s,r,o;yield e.resumeUpstream.call(this);try{for(var a=!0,c=vt(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;a=!0){r=d.value,a=!1;const l=r;yield(o=l.sender)===null||o===void 0?void 0:o.replaceTrack(l.mediaStreamTrack)}}catch(l){n={error:l}}finally{try{!a&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(n)throw n.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return p(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===w.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 p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===w.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(){return p(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],n=yield this.sender.getStats();return n.forEach(s=>{var r;if(s.type==="outbound-rtp"){const o={type:"video",streamId:s.id,frameHeight:s.frameHeight,frameWidth:s.frameWidth,framesPerSecond:s.framesPerSecond,framesSent:s.framesSent,firCount:s.firCount,pliCount:s.pliCount,nackCount:s.nackCount,packetsSent:s.packetsSent,bytesSent:s.bytesSent,qualityLimitationReason:s.qualityLimitationReason,qualityLimitationDurations:s.qualityLimitationDurations,qualityLimitationResolutionChanges:s.qualityLimitationResolutionChanges,rid:(r=s.rid)!==null&&r!==void 0?r:s.id,retransmittedPacketsSent:s.retransmittedPacketsSent,targetBitrate:s.targetBitrate,timestamp:s.timestamp},a=n.get(s.remoteId);a&&(o.jitter=a.jitter,o.packetsLost=a.packetsLost,o.roundTripTime=a.roundTripTime),t.push(o)}}),t.sort((s,r)=>{var o,a;return((o=r.frameWidth)!==null&&o!==void 0?o:0)-((a=s.frameWidth)!==null&&a!==void 0?a:0)}),t})}setPublishingQuality(e){const t=[];for(let n=Le.LOW;n<=Le.HIGH;n+=1)t.push(new zs({quality:n,enabled:n<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(t)}restartTrack(e){return p(this,void 0,void 0,function*(){var t,n,s,r,o;let a;if(e){const u=Cn({video:e});typeof u.video!="boolean"&&(a=u.video)}yield this.restart(a);try{for(var c=!0,d=vt(this.simulcastCodecs.values()),l;l=yield d.next(),t=l.done,!t;c=!0){r=l.value,c=!1;const u=r;u.sender&&((o=u.sender.transport)===null||o===void 0?void 0:o.state)!=="closed"&&(u.mediaStreamTrack=this.mediaStreamTrack.clone(),yield u.sender.replaceTrack(u.mediaStreamTrack))}}catch(u){n={error:u}}finally{try{!c&&!t&&(s=d.return)&&(yield s.call(d))}finally{if(n)throw n.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return p(this,arguments,void 0,function(n){var s=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var o,a,c,d,l,u;if(yield t.setProcessor.call(s,n,r),!((l=s.processor)===null||l===void 0)&&l.processedTrack)try{for(var h=!0,f=vt(s.simulcastCodecs.values()),m;m=yield f.next(),o=m.done,!o;h=!0)d=m.value,h=!1,yield(u=d.sender)===null||u===void 0?void 0:u.replaceTrack(s.processor.processedTrack)}catch(g){a={error:g}}finally{try{!h&&!o&&(c=f.return)&&(yield c.call(f))}finally{if(a)throw a.error}}}()})}setDegradationPreference(e){return p(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){const n=this.simulcastCodecs.get(e);n&&(n.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},yf))}setPublishingCodecs(e){return p(this,void 0,void 0,function*(){var t,n,s,r,o,a,c;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,n=vt(e);s=yield n.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 h of l.qualities)if(h.enabled){d.push(l.codec);break}}else u.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(l.codec),this.logContext),yield ho(u.sender,u.encodings,l.qualities,this.senderLock,this.log,this.logContext))}}}catch(l){o={error:l}}finally{try{!t&&!r&&(a=n.return)&&(yield a.call(n))}finally{if(o)throw o.error}}return d})}setPublishingLayers(e){return p(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 ho(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),rc()&&this.isInBackground&&this.source===w.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function ho(i,e,t,n,s,r){return p(this,void 0,void 0,function*(){const o=yield n.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},r),{sender:i,qualities:t,senderEncodings:e}));try{const a=i.getParameters(),{encodings:c}=a;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,h)=>{var f;let m=(f=u.rid)!==null&&f!==void 0?f:"";m===""&&(m="q");const g=yc(m),T=t.find(C=>C.quality===g);T&&u.active!==T.enabled&&(d=!0,u.active=T.enabled,s.debug("setting layer ".concat(T.quality," to ").concat(u.active?"enabled":"disabled"),r),ei()&&(T.enabled?(u.scaleResolutionDownBy=e[h].scaleResolutionDownBy,u.maxBitrate=e[h].maxBitrate,u.maxFrameRate=e[h].maxFrameRate):(u.scaleResolutionDownBy=4,u.maxBitrate=10,u.maxFrameRate=2)))}),d&&(a.encodings=c,s.debug("setting encodings",Object.assign(Object.assign({},r),{encodings:a.encodings})),yield i.setParameters(a))}finally{o()}})}function yc(i){switch(i){case"f":return Le.HIGH;case"h":return Le.MEDIUM;case"q":return Le.LOW;default:return Le.HIGH}}function fo(i,e,t,n){if(!t)return[new Mt({quality:Le.HIGH,width:i,height:e,bitrate:0,ssrc:0})];if(n){const s=t[0].scalabilityMode,r=new vc(s),o=[],a=r.suffix=="h"?1.5:2,c=r.suffix=="h"?2:3;for(let d=0;d<r.spatial;d+=1)o.push(new Mt({quality:Math.min(Le.HIGH,r.spatial-1)-d,width:Math.ceil(i/Math.pow(a,d)),height:Math.ceil(e/Math.pow(a,d)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(c,d)):0,ssrc:0}));return o}return t.map(s=>{var r,o,a;const c=(r=s.scaleResolutionDownBy)!==null&&r!==void 0?r:1;let d=yc((o=s.rid)!==null&&o!==void 0?o:"");return new Mt({quality:d,width:Math.ceil(i/c),height:Math.ceil(e/c),bitrate:(a=s.maxBitrate)!==null&&a!==void 0?a:0,ssrc:0})})}const po="_lossy",mo="_reliable",bf=2*1e3,qn="leave-reconnect";var Fe;(function(i){i[i.New=0]="New",i[i.Connected=1]="Connected",i[i.Disconnected=2]="Disconnected",i[i.Reconnecting=3]="Reconnecting",i[i.Closed=4]="Closed"})(Fe||(Fe={}));class kf extends et.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=er.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=Fe.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=W,this.handleDataChannel=n=>p(this,[n],void 0,function(s){var r=this;let{channel:o}=s;return function*(){if(o){if(o.label===mo)r.reliableDCSub=o;else if(o.label===po)r.lossyDCSub=o;else return;r.log.debug("on data channel ".concat(o.id,", ").concat(o.label),r.logContext),o.onmessage=r.handleDataMessage}}()}),this.handleDataMessage=n=>p(this,void 0,void 0,function*(){var s,r;const o=yield this.dataProcessLock.lock();try{let a;if(n.data instanceof ArrayBuffer)a=n.data;else if(n.data instanceof Blob)a=yield n.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:n.data}));return}const c=_e.fromBinary(new Uint8Array(a));((s=c.value)===null||s===void 0?void 0:s.case)==="speaker"?this.emit(x.ActiveSpeakersUpdate,c.value.value.speakers):(((r=c.value)===null||r===void 0?void 0:r.case)==="user"&&Cf(c,c.value.value),this.emit(x.DataPacketReceived,c))}finally{o()}}),this.handleDataError=n=>{const r=n.currentTarget.maxRetransmits===0?"lossy":"reliable";if(n instanceof ErrorEvent&&n.error){const{error:o}=n.error;this.log.error("DataChannel error on ".concat(r,": ").concat(n.message),Object.assign(Object.assign({},this.logContext),{error:o}))}else this.log.error("Unknown DataChannel error on ".concat(r),Object.assign(Object.assign({},this.logContext),{event:n}))},this.handleBufferedAmountLow=n=>{const r=n.currentTarget.maxRetransmits===0?Q.LOSSY:Q.RELIABLE;this.updateAndEmitDCBufferStatus(r)},this.handleDisconnect=(n,s)=>{if(this._isClosed)return;this.log.warn("".concat(n," 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(x.Disconnected),this.close()},o=Date.now()-this.reconnectStart;let a=this.getNextRetryDelay({elapsedMs:o,retryCount:this.reconnectAttempts});if(a===null){r(o);return}n===qn&&(a=0),this.log.debug("reconnecting in ".concat(a,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Se.setTimeout(()=>this.attemptReconnect(s).finally(()=>this.reconnectTimeout=void 0),a)},this.waitForRestarted=()=>new Promise((n,s)=>{this.pcState===Fe.Connected&&n();const r=()=>{this.off(x.Disconnected,o),n()},o=()=>{this.off(x.Restarted,r),s()};this.once(x.Restarted,r),this.once(x.Disconnected,o)}),this.updateAndEmitDCBufferStatus=n=>{const s=this.isBufferStatusLow(n);typeof s<"u"&&s!==this.dcBufferStatus.get(n)&&(this.dcBufferStatus.set(n,s),this.emit(x.DCBufferStatusChanged,s,n))},this.isBufferStatusLow=n=>{const s=this.dataChannelForKind(n);if(s)return s.bufferedAmount<=s.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===ae.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(Vt.RR_SIGNAL_DISCONNECTED))},this.log=ct((t=e.loggerName)!==null&&t!==void 0?t:Ge.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new Ys(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new De,this.dataProcessLock=new De,this.dcBufferStatus=new Map([[Q.LOSSY,!0],[Q.RELIABLE,!0]]),this.client.onParticipantUpdate=n=>this.emit(x.ParticipantUpdate,n),this.client.onConnectionQuality=n=>this.emit(x.ConnectionQualityUpdate,n),this.client.onRoomUpdate=n=>this.emit(x.RoomUpdate,n),this.client.onSubscriptionError=n=>this.emit(x.SubscriptionError,n),this.client.onSubscriptionPermissionUpdate=n=>this.emit(x.SubscriptionPermissionUpdate,n),this.client.onSpeakersChanged=n=>this.emit(x.SpeakersChanged,n),this.client.onStreamStateUpdate=n=>this.emit(x.StreamStateChanged,n),this.client.onRequestResponse=n=>this.emit(x.SignalRequestResponse,n)}get logContext(){var e,t,n,s,r,o,a,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=(n=this.latestJoinResponse)===null||n===void 0?void 0:n.room)===null||s===void 0?void 0:s.sid,participant:(o=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.participant)===null||o===void 0?void 0:o.identity,pID:(c=(a=this.latestJoinResponse)===null||a===void 0?void 0:a.participant)===null||c===void 0?void 0:c.sid}}join(e,t,n,s){return p(this,void 0,void 0,function*(){this.url=e,this.token=t,this.signalOpts=n,this.maxJoinAttempts=n.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const r=yield this.client.join(e,t,n,s);return this._isClosed=!1,this.latestJoinResponse=r,this.subscriberPrimary=r.subscriberPrimary,this.pcManager||(yield this.configure(r)),(!this.subscriberPrimary||r.fastPublish)&&this.negotiate(),this.clientConfiguration=r.clientConfiguration,r}catch(r){if(r instanceof re&&r.reason===J.ServerUnreachable&&(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,n,s);throw r}})}close(){return p(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(x.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return p(this,void 0,void 0,function*(){var e;yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0;const t=n=>{n&&(n.close(),n.onbufferedamountlow=null,n.onclose=null,n.onclosing=null,n.onerror=null,n.onmessage=null,n.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 p(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new rt("a track with the same ID has already been published");return new Promise((t,n)=>{const s=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(new re("publication of local track timed out, no response from server",J.InternalError))},1e4);this.pendingTrackResolvers[e.cid]={resolve:r=>{clearTimeout(s),t(r)},reject:()=>{clearTimeout(s),n(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return p(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){return p(this,void 0,void 0,function*(){var t,n;if(this.pcManager&&this.pcManager.currentState!==le.NEW)return;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid;const s=this.makeRTCConfiguration(e);this.pcManager=new of(s,e.subscriberPrimary,this.loggerOptions),this.emit(x.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(r,o)=>{this.client.sendIceCandidate(r,o)},this.pcManager.onPublisherOffer=r=>{this.client.sendOffer(r)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(r,o,a)=>p(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(r),this.logContext),["closed","disconnected","failed"].includes(o)&&(this.publisherConnectionPromise=void 0),r===le.CONNECTED){const l=this.pcState===Fe.New;this.pcState=Fe.Connected,l&&this.emit(x.Connected,e)}else r===le.FAILED&&this.pcState===Fe.Connected&&(this.pcState=Fe.Disconnected,this.handleDisconnect("peerconnection failed",a==="failed"?Vt.RR_SUBSCRIBER_FAILED:Vt.RR_PUBLISHER_FAILED));const c=this.client.isDisconnected||this.client.currentState===ae.RECONNECTING,d=[le.FAILED,le.CLOSING,le.CLOSED].includes(r);c&&d&&!this._isClosed&&this.emit(x.Offline)}),this.pcManager.onTrack=r=>{this.emit(x.MediaTrackAdded,r.track,r.streams[0],r.receiver)},Tf((n=e.serverInfo)===null||n===void 0?void 0:n.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=e=>p(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.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=e=>p(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:n}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],n(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(x.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(x.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(x.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(x.SubscribedQualityUpdate,e)},this.client.onClose=()=>{this.handleDisconnect("signal",Vt.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e==null?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(e.regions)),e.action){case Wt.DISCONNECT:this.emit(x.Disconnected,e==null?void 0:e.reason),this.close();break;case Wt.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(qn);break;case Wt.RESUME:this.handleDisconnect(qn)}}}makeRTCConfiguration(e){var t;const n=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),n.encodedInsertableStreams=!0),e.iceServers&&!n.iceServers){const s=[];e.iceServers.forEach(r=>{const o={urls:r.urls};r.username&&(o.username=r.username),r.credential&&(o.credential=r.credential),s.push(o)}),n.iceServers=s}return e.clientConfiguration&&e.clientConfiguration.forceRelay===wi.ENABLED&&(n.iceTransportPolicy="relay"),n.sdpSemantics="unified-plan",n.continualGatheringPolicy="gather_continually",n}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(po,{ordered:!0,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(mo,{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)}createSender(e,t,n){return p(this,void 0,void 0,function*(){if(bs())return yield this.createTransceiverRTCRtpSender(e,t,n);if(ks())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new ye("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,n,s){return p(this,void 0,void 0,function*(){if(bs())return this.createSimulcastTransceiverSender(e,t,n,s);if(ks())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new ye("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,n){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new ye("publisher is closed");const s=[];e.mediaStream&&s.push(e.mediaStream),ni(e)&&(e.codec=t.videoCodec);const r={direction:"sendonly",streams:s};return n&&(r.sendEncodings=n),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender})}createSimulcastTransceiverSender(e,t,n,s){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new ye("publisher is closed");const r={direction:"sendonly"};s&&(r.sendEncodings=s);const o=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(n.videoCodec)return e.setSimulcastTrackSender(n.videoCodec,o.sender),o.sender})}createRTCRtpSender(e){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new ye("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return p(this,void 0,void 0,function*(){var t,n,s;if(!this._isClosed){if(this.attemptingReconnect){W.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===wi.DISABLED||((s=(n=this.pcManager)===null||n===void 0?void 0:n.currentState)!==null&&s!==void 0?s:le.NEW)===le.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(r){this.reconnectAttempts+=1;let o=!0;r instanceof ye?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:r})),o=!1):r instanceof qt||(this.fullReconnectOnNext=!0),o?this.handleDisconnect("reconnect",Vt.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(x.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(e){return p(this,void 0,void 0,function*(){var t,n,s;try{if(!this.url||!this.token)throw new ye("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(x.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 qt;r=yield this.join(e??this.url,this.token,this.signalOpts)}catch(o){throw o instanceof re&&o.reason===J.NotAllowed?new ye("could not reconnect, token might be expired"):new qt}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(x.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==ae.CONNECTED)throw new qt("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(x.Restarted)}catch(r){const o=yield(n=this.regionUrlProvider)===null||n===void 0?void 0:n.getNextBestRegionUrl();if(o){yield this.restartConnection(o);return}else throw(s=this.regionUrlProvider)===null||s===void 0||s.resetAttempts(),r}})}resumeConnection(e){return p(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new ye("could not reconnect, url or token not saved");if(!this.pcManager)throw new ye("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(x.Resuming);let n;try{this.setupSignalClientCallbacks(),n=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 re&&s.reason===J.NotAllowed?new ye("could not reconnect, token might be expired"):s instanceof re&&s.reason===J.LeaveRequest?s:new qt(r)}if(this.emit(x.SignalResumed),n){const s=this.makeRTCConfiguration(n);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!==ae.CONNECTED)throw new qt("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(x.Resumed)})}waitForPCInitialConnection(e,t){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new ye("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return p(this,void 0,void 0,function*(){this.pcState=Fe.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Ie(bf),!this.pcManager)throw new ye("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Fe.Connected}catch(e){throw this.pcState=Fe.Disconnected,new re("could not establish PC connection, ".concat(e.message),J.InternalError)}})}publishRpcResponse(e,t,n,s){return p(this,void 0,void 0,function*(){const r=new _e({destinationIdentities:[e],kind:Q.RELIABLE,value:{case:"rpcResponse",value:new ca({requestId:t,value:s?{case:"error",value:s.toProto()}:{case:"payload",value:n??""}})}});yield this.sendDataPacket(r,Q.RELIABLE)})}publishRpcAck(e,t){return p(this,void 0,void 0,function*(){const n=new _e({destinationIdentities:[e],kind:Q.RELIABLE,value:{case:"rpcAck",value:new aa({requestId:t})}});yield this.sendDataPacket(n,Q.RELIABLE)})}sendDataPacket(e,t){return p(this,void 0,void 0,function*(){const n=e.toBinary();yield this.ensurePublisherConnected(t);const s=this.dataChannelForKind(t);s&&s.send(n),this.updateAndEmitDCBufferStatus(t)})}waitForBufferStatusLow(e){return new Promise((t,n)=>p(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const s=()=>n("Engine closed");for(this.once(x.Closing,s);!this.dcBufferStatus.get(e);)yield Ie(10);this.off(x.Closing,s),t()}}))}ensureDataTransportConnected(e){return p(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){var r;if(!n.pcManager)throw new ye("PC manager is closed");const o=s?n.pcManager.subscriber:n.pcManager.publisher,a=s?"Subscriber":"Publisher";if(!o)throw new re("".concat(a," connection not set"),J.InternalError);let c=!1;!s&&!n.dataChannelForKind(t,s)&&(n.createDataChannels(),c=!0),!c&&!s&&!n.pcManager.publisher.isICEConnected&&n.pcManager.publisher.getICEConnectionState()!=="checking"&&(c=!0),c&&n.negotiate();const d=n.dataChannelForKind(t,s);if((d==null?void 0:d.readyState)==="open")return;const l=new Date().getTime()+n.peerConnectionTimeout;for(;new Date().getTime()<l;){if(o.isICEConnected&&((r=n.dataChannelForKind(t,s))===null||r===void 0?void 0:r.readyState)==="open")return;yield Ie(50)}throw new re("could not establish ".concat(a," connection, state: ").concat(o.getICEConnectionState()),J.InternalError)}()})}ensurePublisherConnected(e){return p(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==le.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return p(this,void 0,void 0,function*(){return new Promise((e,t)=>p(this,void 0,void 0,function*(){if(!this.pcManager){t(new gs("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const n=new AbortController,s=()=>{n.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(x.Closing,s),this.pcManager.publisher.once(Yt.RTPVideoPayloadTypes,r=>{const o=new Map;r.forEach(a=>{const c=a.codec.toLowerCase();Dh(c)&&o.set(a.payload,c)}),this.emit(x.RTPVideoMapUpdate,o)});try{yield this.pcManager.negotiate(n),e()}catch(r){r instanceof gs&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Vt.RR_UNKNOWN),t(r)}finally{this.off(x.Closing,s)}}))})}dataChannelForKind(e,t){if(t){if(e===Q.LOSSY)return this.lossyDCSub;if(e===Q.RELIABLE)return this.reliableDCSub}else{if(e===Q.LOSSY)return this.lossyDC;if(e===Q.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var n,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(),o=this.pcManager.subscriber.getRemoteDescription(),a=(s=(n=this.signalOpts)===null||n===void 0?void 0:n.autoSubscribe)!==null&&s!==void 0?s:!0,c=new Array,d=new Array;e.forEach(l=>{l.isDesired!==a&&c.push(l.trackSid),l.isEnabled||d.push(l.trackSid)}),this.client.sendSyncState(new Ea({answer:r?hn({sdp:r.sdp,type:r.type}):void 0,offer:o?hn({sdp:o.sdp,type:o.type}):void 0,subscription:new bn({trackSids:c,subscribe:!a,participantTracks:[]}),publishTracks:qh(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:d}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(n,s)=>{(n==null?void 0:n.id)!==void 0&&n.id!==null&&e.push(new wa({label:n.label,id:n.id,target:s}))};return t(this.dataChannelForKind(Q.LOSSY),$e.PUBLISHER),t(this.dataChannelForKind(Q.RELIABLE),$e.PUBLISHER),t(this.dataChannelForKind(Q.LOSSY,!0),$e.SUBSCRIBER),t(this.dataChannelForKind(Q.RELIABLE,!0),$e.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Se.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Re()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){Re()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class qt extends Error{}function Tf(i){return i!==void 0&&i>13}function Cf(i,e){const t=i.participantIdentity?i.participantIdentity:e.participantIdentity;i.participantIdentity=t,e.participantIdentity=t;const n=i.destinationIdentities.length!==0?i.destinationIdentities:e.destinationIdentities;i.destinationIdentities=n,e.destinationIdentities=n}class Rs{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 Cs(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return p(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(n=>!this.attemptedRegions.find(s=>s.url===n.url));if(t.length>0){const n=t[0];return this.attemptedRegions.push(n),W.debug("next region: ".concat(n.region)),n.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return p(this,void 0,void 0,function*(){const t=yield fetch("".concat(Sf(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(t.ok){const n=yield t.json();return this.lastUpdateAt=Date.now(),n}else throw new re("Could not fetch region settings: ".concat(t.statusText),t.status===401?J.NotAllowed:J.InternalError,t.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function Sf(i){return"".concat(i.protocol.replace("ws","http"),"//").concat(i.host,"/settings")}class bc{get info(){return this._info}constructor(e,t,n){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0}}class Ef extends bc{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength;const n=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,n)}[Symbol.asyncIterator](){const e=this.reader.getReader();return{next:()=>p(this,void 0,void 0,function*(){try{const{done:t,value:n}=yield e.read();return t?{done:!0,value:void 0}:(this.handleChunkReceived(n),{done:!1,value:n.content})}catch{return{done:!0,value:void 0}}}),return(){return p(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return p(this,void 0,void 0,function*(){var e,t,n,s;let r=new Set;try{for(var o=!0,a=vt(this),c;c=yield a.next(),e=c.done,!e;o=!0){s=c.value,o=!1;const d=s;r.add(d)}}catch(d){t={error:d}}finally{try{!o&&!e&&(n=a.return)&&(yield n.call(a))}finally{if(t)throw t.error}}return Array.from(r)})}}class wf extends bc{constructor(e,t,n){super(e,t,n),this.receivedChunks=new Map}handleChunkReceived(e){var t;const n=tn(e.chunkIndex),s=this.receivedChunks.get(n);if(s&&s.version>e.version)return;this.receivedChunks.set(n,e),this.bytesReceived+=e.content.byteLength;const r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,r)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder;return{next:()=>p(this,void 0,void 0,function*(){try{const{done:n,value:s}=yield e.read();return n?{done:!0,value:void 0}:(this.handleChunkReceived(s),{done:!1,value:t.decode(s.content)})}catch{return{done:!0,value:void 0}}}),return(){return p(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return p(this,void 0,void 0,function*(){var e,t,n,s;let r="";try{for(var o=!0,a=vt(this),c;c=yield a.next(),e=c.done,!e;o=!0)s=c.value,o=!1,r+=s}catch(d){t={error:d}}finally{try{!o&&!e&&(n=a.return)&&(yield n.call(a))}finally{if(t)throw t.error}}return r})}}class _f{constructor(e,t,n){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=n,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return p(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)===null||e===void 0||e.call(this)})}}class Pf extends _f{}class kc extends w{constructor(e,t,n,s,r){super(e,n,r),this.sid=t,this.receiver=s}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?O.Muted:O.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=n=>{n.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(O.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return p(this,void 0,void 0,function*(){var e;return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),ir)),$h()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const n=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(n){const{timestamp:s,rtpTimestamp:r}=n;r&&this.rtpTimestamp!==r&&(this.emit(O.TimeSyncUpdate,{timestamp:s,rtpTimestamp:r}),this.rtpTimestamp=r)}};e()}}class Rf extends kc{constructor(e,t,n,s,r,o){super(e,t,w.Kind.Audio,n,o),this.monitorReceiver=()=>p(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=Sn(a,this.prevStats)),this.prevStats=a}),this.audioContext=s,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(const n of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):n.volume=e;Ze()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Ze())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return p(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(Ts(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&Ts(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 n=this.sourceNode;this.webAudioPluginNodes.forEach(s=>{n.connect(s),n=s}),this.gainNode=e.createGain(),n.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(O.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(s=>{this.emit(O.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 p(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(n=>{n.type==="inbound-rtp"&&(t={type:"audio",streamId:n.id,timestamp:n.timestamp,jitter:n.jitter,bytesReceived:n.bytesReceived,concealedSamples:n.concealedSamples,concealmentEvents:n.concealmentEvents,silentConcealedSamples:n.silentConcealedSamples,silentConcealmentEvents:n.silentConcealmentEvents,totalAudioEnergy:n.totalAudioEnergy,totalSamplesDuration:n.totalSamplesDuration})}),t})}}const $n=100;class If extends kc{constructor(e,t,n,s,r){super(e,t,w.Kind.Video,n,r),this.elementInfos=[],this.monitorReceiver=()=>p(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=Sn(o,this.prevStats)),this.prevStats=o}),this.debouncedHandleResize=Zs(()=>{this.updateDimensions()},$n),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?Jt(this._mediaStreamTrack,t):zt(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 Of(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(n=>n===e);for(const n of t)n.stopObserving();this.elementInfos=this.elementInfos.filter(n=>n!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const n of t)this.stopObservingElement(n);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return p(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,n="",s=new Map;return e.forEach(r=>{r.type==="inbound-rtp"?(n=r.codecId,t={type:"video",streamId:r.id,framesDecoded:r.framesDecoded,framesDropped:r.framesDropped,framesReceived:r.framesReceived,packetsReceived:r.packetsReceived,packetsLost:r.packetsLost,frameWidth:r.frameWidth,frameHeight:r.frameHeight,pliCount:r.pliCount,firCount:r.firCount,nackCount:r.nackCount,jitter:r.jitter,timestamp:r.timestamp,bytesReceived:r.bytesReceived,decoderImplementation:r.decoderImplementation}):r.type==="codec"&&s.set(r.id,r)}),t&&n!==""&&s.get(n)&&(t.mimeType=s.get(n).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(n=>n.element===e);for(const n of t)this.stopObservingElementInfo(n)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(){var e,t;const n=this.elementInfos.reduce((a,c)=>Math.max(a,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(a=>a.pictureInPicture),o=this.elementInfos.some(a=>a.visible)&&!s||r;if(this.lastVisible!==o){if(!o&&Date.now()-n<$n){Se.setTimeout(()=>{this.updateVisibility()},$n);return}this.lastVisible=o,this.emit(O.VisibilityChanged,o,this)}}updateDimensions(){var e,t;let n=0,s=0;const r=this.getPixelDensity();for(const o of this.elementInfos){const a=o.width()*r,c=o.height()*r;a+c>n+s&&(n=a,s=c)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===n&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===s||(this.lastDimensions={width:n,height:s},this.emit(O.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?Wr():t||(Wr()>2?2:1)}}class Of{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=n=>{var s;const{target:r,isIntersecting:o}=n;r===this.element&&(this.isIntersecting=o,this.isPiP=li(this.element),this.visibilityChangedAt=Date.now(),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this))},this.onEnterPiP=()=>{var n,s,r;(s=(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window)===null||s===void 0||s.addEventListener("pagehide",this.onLeavePiP),this.isPiP=li(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.onLeavePiP=()=>{var n;this.isPiP=li(this.element),(n=this.handleVisibilityChanged)===null||n===void 0||n.call(this)},this.element=e,this.isIntersecting=t??Is(e),this.isPiP=Re()&&li(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,n;this.isIntersecting=Is(this.element),this.isPiP=li(this.element),this.element.handleResize=()=>{var s;(s=this.handleResize)===null||s===void 0||s.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Jr().observe(this.element),Kr().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(n=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||n===void 0||n.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,n,s,r;(e=Jr())===null||e===void 0||e.unobserve(this.element),(t=Kr())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(n=window.documentPictureInPicture)===null||n===void 0||n.removeEventListener("enter",this.onEnterPiP),(r=(s=window.documentPictureInPicture)===null||s===void 0?void 0:s.window)===null||r===void 0||r.removeEventListener("pagehide",this.onLeavePiP)}}function li(i){var e,t;return document.pictureInPictureElement===i?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?Is(i,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function Is(i,e){const t=e||window;let n=i.offsetTop,s=i.offsetLeft;const r=i.offsetWidth,o=i.offsetHeight,{hidden:a}=i,{display:c}=getComputedStyle(i);for(;i.offsetParent;)i=i.offsetParent,n+=i.offsetTop,s+=i.offsetLeft;return n<t.pageYOffset+t.innerHeight&&s<t.pageXOffset+t.innerWidth&&n+o>t.pageYOffset&&s+r>t.pageXOffset&&!a&&c!=="none"}class gt extends et.EventEmitter{constructor(e,t,n,s){var r;super(),this.metadataMuted=!1,this.encryption=Me.NONE,this.log=W,this.handleMuted=()=>{this.emit(O.Muted)},this.handleUnmuted=()=>{this.emit(O.Unmuted)},this.log=ct((r=s==null?void 0:s.loggerName)!==null&&r!==void 0?r:Ge.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=n,this.source=w.Source.Unknown}setTrack(e){this.track&&(this.track.off(O.Muted,this.handleMuted),this.track.off(O.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(O.Muted,this.handleMuted),e.on(O.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),ie(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==Me.NONE}get audioTrack(){if(dt(this.track))return this.track}get videoTrack(){if(ni(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=w.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===w.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(i){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(i.SubscriptionStatus||(i.SubscriptionStatus={})),function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"}(i.PermissionStatus||(i.PermissionStatus={}))})(gt);class Os extends gt{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,n,s){super(e,t.sid,t.name,s),this.track=void 0,this.handleTrackEnded=()=>{this.emit(O.Ended)},this.updateInfo(t),this.setTrack(n)}setTrack(e){this.track&&this.track.off(O.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(O.Ended,this.handleTrackEnded)}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return p(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return p(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return p(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return p(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(dt(this.track)){const t=this.track.getSourceTrackSettings(),n=new Set;return t.autoGainControl&&n.add(Ye.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&n.add(Ye.TF_ECHO_CANCELLATION),t.noiseSuppression&&n.add(Ye.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&n.add(Ye.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||n.add(Ye.TF_NO_DTX),this.track.enhancedNoiseCancellation&&n.add(Ye.TF_ENHANCED_NOISE_CANCELLATION),Array.from(n.values())}else return[]}}var yt;(function(i){i.Excellent="excellent",i.Good="good",i.Poor="poor",i.Lost="lost",i.Unknown="unknown"})(yt||(yt={}));function xf(i){switch(i){case fi.EXCELLENT:return yt.Excellent;case fi.GOOD:return yt.Good;case fi.POOR:return yt.Poor;case fi.LOST:return yt.Lost;default:return yt.Unknown}}class Tc extends et.EventEmitter{get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return((e=this.permissions)===null||e===void 0?void 0:e.agent)||this.kind===ln.AGENT}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,n,s,r,o){let a=arguments.length>6&&arguments[6]!==void 0?arguments[6]:ln.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=yt.Unknown,this.log=W,this.log=ct((c=o==null?void 0:o.loggerName)!==null&&c!==void 0?c:Ge.Participant),this.loggerOptions=o,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=n,this.metadata=s,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=a,this._attributes=r??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(w.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(w.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(w.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),this._setAttributes(e.attributes),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,n=this.metadata;this.metadata=e,t&&this.emit(A.ParticipantMetadataChanged,n)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(A.ParticipantNameChanged,e)}_setAttributes(e){const t=Hh(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(A.AttributesChanged,t)}setPermissions(e){var t,n,s,r,o,a;const c=this.permissions,d=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((n=this.permissions)===null||n===void 0?void 0:n.canSubscribe)||e.canPublishData!==((s=this.permissions)===null||s===void 0?void 0:s.canPublishData)||e.hidden!==((r=this.permissions)===null||r===void 0?void 0:r.hidden)||e.recorder!==((o=this.permissions)===null||o===void 0?void 0:o.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((l,u)=>{var h;return l!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[u])})||e.canSubscribeMetrics!==((a=this.permissions)===null||a===void 0?void 0:a.canSubscribeMetrics);return this.permissions=e,d&&this.emit(A.ParticipantPermissionsChanged,c),d}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(A.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=xf(e),t!==this._connectionQuality&&this.emit(A.ConnectionQualityChanged,this._connectionQuality)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>dt(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(O.Muted,()=>{this.emit(A.TrackMuted,e)}),e.on(O.Unmuted,()=>{this.emit(A.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case w.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case w.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function Af(i){var e,t,n;if(!i.participantSid&&!i.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Ca({participantIdentity:(e=i.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=i.participantSid)!==null&&t!==void 0?t:"",allTracks:(n=i.allowAll)!==null&&n!==void 0?n:!1,trackSids:i.allowedTrackSids||[]})}const Fi=15e3;class Mf extends Tc{constructor(e,t,n,s,r){super(e,t,void 0,void 0,void 0,{loggerName:s.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=Me.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new cc)},this.handleReconnected=()=>{var o,a;(a=(o=this.reconnectFuture)===null||o===void 0?void 0:o.resolve)===null||a===void 0||a.call(o),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var o,a;this.reconnectFuture&&(this.reconnectFuture.promise.catch(c=>this.log.warn(c.message,this.logContext)),(a=(o=this.reconnectFuture)===null||o===void 0?void 0:o.reject)===null||a===void 0||a.call(o,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.handleSignalRequestResponse=o=>{const{requestId:a,reason:c,message:d}=o,l=this.pendingSignalRequests.get(a);l&&(c!==Gs.OK&&l.reject(new $r(d,c)),this.pendingSignalRequests.delete(a))},this.handleDataPacket=o=>{switch(o.value.case){case"rpcResponse":let a=o.value.value,c=null,d=null;a.value.case==="payload"?c=a.value.value:a.value.case==="error"&&(d=he.fromProto(a.value.value)),this.handleIncomingRpcResponse(a.requestId,c,d);break;case"rpcAck":let l=o.value.value;this.handleIncomingRpcAck(l.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(o=>Af(o)))},this.onTrackUnmuted=o=>{this.onTrackMuted(o,o.isUpstreamPaused)},this.onTrackMuted=(o,a)=>{if(a===void 0&&(a=!0),!o.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),ie(o)));return}this.engine.updateMuteStatus(o.sid,a)},this.onTrackUpstreamPaused=o=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),ie(o))),this.onTrackMuted(o,!0)},this.onTrackUpstreamResumed=o=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),ie(o))),this.onTrackMuted(o,o.isMuted)},this.onTrackFeatureUpdate=o=>{const a=this.audioTrackPublications.get(o.sid);if(!a){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(o.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(a.trackSid,a.getTrackFeatures())},this.handleSubscribedQualityUpdate=o=>p(this,void 0,void 0,function*(){var a,c,d,l,u,h;if(!(!((u=this.roomOptions)===null||u===void 0)&&u.dynacast))return;const f=this.videoTrackPublications.get(o.trackSid);if(!f){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:o.trackSid}));return}if(o.subscribedCodecs.length>0){if(!f.videoTrack)return;const C=yield f.videoTrack.setPublishingCodecs(o.subscribedCodecs);try{for(var m=!0,g=vt(C),T;T=yield g.next(),a=T.done,!a;m=!0){l=T.value,m=!1;const M=l;Sh(M)&&(this.log.debug("publish ".concat(M," for ").concat(f.videoTrack.sid),Object.assign(Object.assign({},this.logContext),ie(f))),yield this.publishAdditionalCodecForTrack(f.videoTrack,M,f.options))}}catch(M){c={error:M}}finally{try{!m&&!a&&(d=g.return)&&(yield d.call(g))}finally{if(c)throw c.error}}}else o.subscribedQualities.length>0&&(yield(h=f.videoTrack)===null||h===void 0?void 0:h.setPublishingLayers(o.subscribedQualities))}),this.handleLocalTrackUnpublished=o=>{const a=this.trackPublications.get(o.trackSid);if(!a){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:o.trackSid}));return}this.unpublishTrack(a.track)},this.handleTrackEnded=o=>p(this,void 0,void 0,function*(){if(o.source===w.Source.ScreenShare||o.source===w.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),ie(o))),this.unpublishTrack(o);else if(o.isUserProvided)yield o.mute();else if(It(o)||ft(o))try{if(Re())try{const a=yield navigator==null?void 0:navigator.permissions.query({name:o.source===w.Source.Camera?"camera":"microphone"});if(a&&a.state==="denied")throw this.log.warn("user has revoked access to ".concat(o.source),Object.assign(Object.assign({},this.logContext),ie(o))),a.onchange=()=>{a.state!=="denied"&&(o.isMuted||o.restartTrack(),a.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}o.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),ie(o))),It(o)?yield o.restartTrack({deviceId:"default"}):yield o.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),ie(o))),yield o.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=n,this.roomOptions=s,this.setupEngine(n),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=r}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Me.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(x.RemoteMute,(t,n)=>{const s=this.trackPublications.get(t);!s||!s.track||(n?s.mute():s.unmute())}),this.engine.on(x.Connected,this.handleReconnected).on(x.SignalRestarted,this.handleReconnected).on(x.SignalResumed,this.handleReconnected).on(x.Restarting,this.handleReconnecting).on(x.Resuming,this.handleReconnecting).on(x.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(x.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(x.Disconnected,this.handleDisconnected).on(x.SignalRequestResponse,this.handleSignalRequestResponse).on(x.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return p(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return p(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return p(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return p(this,arguments,void 0,function(t){var n=this;let{metadata:s,name:r,attributes:o}=t;return function*(){return new Promise((a,c)=>p(n,void 0,void 0,function*(){var d,l;try{let u=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((d=s??this.metadata)!==null&&d!==void 0?d:"",(l=r??this.name)!==null&&l!==void 0?l:"",o),f=performance.now();for(this.pendingSignalRequests.set(h,{resolve:a,reject:m=>{c(m),u=!0},values:{name:r,metadata:s,attributes:o}});performance.now()-f<5e3&&!u;){if((!r||this.name===r)&&(!s||this.metadata===s)&&(!o||Object.entries(o).every(m=>{let[g,T]=m;return this.attributes[g]===T||T===""&&!this.attributes[g]}))){this.pendingSignalRequests.delete(h),a();return}yield Ie(50)}c(new $r("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error&&c(u)}}))}()})}setCameraEnabled(e,t,n){return this.setTrackEnabled(w.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(w.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(w.Source.ScreenShare,e,t,n)}setPermissions(e){const t=this.permissions,n=super.setPermissions(e);return n&&t&&this.emit(A.ParticipantPermissionsChanged,t),n}setE2EEEnabled(e){return p(this,void 0,void 0,function*(){this.encryptionType=e?Me.GCM:Me.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,n,s){return p(this,void 0,void 0,function*(){var r,o;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let a=this.getTrackPublication(e);if(t)if(a)yield a.unmute();else{let c;if(this.pendingPublishing.has(e)){const d=yield this.waitForPendingPublicationOfSource(e);return d||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield d==null?void 0:d.unmute(),d}this.pendingPublishing.add(e);try{switch(e){case w.Source.Camera:c=yield this.createTracks({video:(r=n)!==null&&r!==void 0?r:!0});break;case w.Source.Microphone:c=yield this.createTracks({audio:(o=n)!==null&&o!==void 0?o:!0});break;case w.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},n));break;default:throw new rt(e)}}catch(d){throw c==null||c.forEach(l=>{l.stop()}),d instanceof Error&&this.emit(A.MediaDevicesError,d),this.pendingPublishing.delete(e),d}try{const d=[];for(const u of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),ie(u))),d.push(this.publishTrack(u,s));[a]=yield Promise.all(d)}catch(d){throw c==null||c.forEach(l=>{l.stop()}),d}finally{this.pendingPublishing.delete(e)}}else if(!(a!=null&&a.track)&&this.pendingPublishing.has(e)&&(a=yield this.waitForPendingPublicationOfSource(e),a||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),a&&a.track)if(e===w.Source.ScreenShare){a=yield this.unpublishTrack(a.track);const c=this.getTrackPublication(w.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield a.mute();return a})}enableCameraAndMicrophone(){return p(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(w.Source.Camera)||this.pendingPublishing.has(w.Source.Microphone))){this.pendingPublishing.add(w.Source.Camera),this.pendingPublishing.add(w.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(w.Source.Camera),this.pendingPublishing.delete(w.Source.Microphone)}}})}createTracks(e){return p(this,void 0,void 0,function*(){var t,n;e??(e={});const s=dc(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(n=this.roomOptions)===null||n===void 0?void 0:n.videoCaptureDefaults),{audioProcessor:r,videoProcessor:o,optionsWithoutProcessor:a}=Qs(s),c=Cn(a);let d;try{d=yield navigator.mediaDevices.getUserMedia(c)}catch(l){throw l instanceof Error&&(c.audio&&(this.microphoneError=l),c.video&&(this.cameraError=l)),l}return c.audio&&(this.microphoneError=void 0,this.emit(A.AudioStreamAcquired)),c.video&&(this.cameraError=void 0),Promise.all(d.getTracks().map(l=>p(this,void 0,void 0,function*(){const u=l.kind==="audio";let h;const f=u?c.audio:c.video;typeof f!="boolean"&&(h=f);const m=gc(l,h,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return m.kind===w.Kind.Video?m.source=w.Source.Camera:m.kind===w.Kind.Audio&&(m.source=w.Source.Microphone,m.setAudioContext(this.audioContext)),m.mediaStream=d,dt(m)&&r?yield m.setProcessor(r):ni(m)&&o&&(yield m.setProcessor(o)),m})))})}createScreenTracks(e){return p(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Ks("getDisplayMedia not supported");e.resolution===void 0&&!Ih()&&(e.resolution=Js.h1080fps30.resolution);const t=Vh(e),n=yield navigator.mediaDevices.getDisplayMedia(t),s=n.getVideoTracks();if(s.length===0)throw new rt("no video track found");const r=new pn(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=w.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const o=[r];if(n.getAudioTracks().length>0){this.emit(A.AudioStreamAcquired);const a=new fn(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});a.source=w.Source.ScreenShareAudio,o.push(a)}return o})}publishTrack(e,t){return p(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return p(this,arguments,void 0,function(n,s){var r=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var a,c,d,l;It(n)&&n.setAudioContext(r.audioContext),yield(a=r.reconnectFuture)===null||a===void 0?void 0:a.promise,r.republishPromise&&!o&&(yield r.republishPromise),Qt(n)&&r.pendingPublishPromises.has(n)&&(yield r.pendingPublishPromises.get(n));let u;if(n instanceof MediaStreamTrack)u=n.getConstraints();else{u=n.constraints;let C;switch(n.source){case w.Source.Microphone:C="audioinput";break;case w.Source.Camera:C="videoinput"}C&&r.activeDeviceMap.has(C)&&(u=Object.assign(Object.assign({},u),{deviceId:r.activeDeviceMap.get(C)}))}if(n instanceof MediaStreamTrack)switch(n.kind){case"audio":n=new fn(n,u,!0,r.audioContext,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;case"video":n=new pn(n,u,!0,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;default:throw new rt("unsupported MediaStreamTrack kind ".concat(n.kind))}else n.updateLoggerOptions({loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});let h;if(r.trackPublications.forEach(C=>{C.track&&C.track===n&&(h=C)}),h)return r.log.warn("track has already been published, skipping",Object.assign(Object.assign({},r.logContext),ie(h))),h;const f="channelCount"in n.mediaStreamTrack.getSettings()&&n.mediaStreamTrack.getSettings().channelCount===2||n.mediaStreamTrack.getConstraints().channelCount===2,m=(c=s==null?void 0:s.forceStereo)!==null&&c!==void 0?c:f;m&&(s||(s={}),s.dtx===void 0&&r.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},r.logContext),ie(n))),s.red===void 0&&r.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(d=s.dtx)!==null&&d!==void 0||(s.dtx=!1),(l=s.red)!==null&&l!==void 0||(s.red=!1));const g=Object.assign(Object.assign({},r.roomOptions.publishDefaults),s);!Oh()&&r.roomOptions.e2ee&&(r.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},r.logContext)),g.simulcast=!1),g.source&&(n.source=g.source);const T=r.publish(n,g,m);r.pendingPublishPromises.set(n,T);try{return yield T}catch(C){throw C}finally{r.pendingPublishPromises.delete(n)}}()})}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),ie(e))),!1;const{canPublish:t,canPublishSources:n}=this.permissions;return t&&(n.length===0||n.map(s=>zh(s)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),ie(e))),!1)}publish(e,t,n){return p(this,void 0,void 0,function*(){var s,r,o,a,c,d,l,u,h,f;if(!this.hasPermissionsToPublish(e))throw new fh("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(y=>Qt(e)&&y.source===e.source)&&e.source!==w.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),ie(e))),t.stopMicTrackOnMute&&dt(e)&&(e.stopOnMute=!0),e.source===w.Source.ScreenShare&&ei()&&(t.simulcast=!1),t.videoCodec==="av1"&&!_h()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!Ph()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=ws),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(y=>t.videoCodec===nn(y.mime))||(t.videoCodec=nn(this.enabledPublishVideoCodecs[0].mime)));const g=t.videoCodec;e.on(O.Muted,this.onTrackMuted),e.on(O.Unmuted,this.onTrackUnmuted),e.on(O.Ended,this.handleTrackEnded),e.on(O.UpstreamPaused,this.onTrackUpstreamPaused),e.on(O.UpstreamResumed,this.onTrackUpstreamResumed),e.on(O.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const T=new as({cid:e.mediaStreamTrack.id,name:t.name,type:w.kindToProto(e.kind),muted:e.isMuted,source:w.sourceToProto(e.source),disableDtx:!(!((s=t.dtx)!==null&&s!==void 0)||s),encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(!((r=t.red)!==null&&r!==void 0)||r),stream:t==null?void 0:t.stream,backupCodecPolicy:t==null?void 0:t.backupCodecPolicy});let C;if(e.kind===w.Kind.Video){let y={width:0,height:0};try{y=yield e.waitForDimensions()}catch{const R=(a=(o=this.roomOptions.videoCaptureDefaults)===null||o===void 0?void 0:o.resolution)!==null&&a!==void 0?a:Pi.h720.resolution;y={width:R.width,height:R.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),ie(e)),{dims:y}))}T.width=y.width,T.height=y.height,ft(e)&&(bi(g)&&(e.source===w.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),ie(e))))),t.scalabilityMode=(c=t.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),T.simulcastCodecs=[new os({codec:g,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:ws}),t.backupCodec&&g!==t.backupCodec.codec&&T.encryption===Me.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),T.simulcastCodecs.push(new os({codec:t.backupCodec.codec,cid:""})))),C=Ps(e.source===w.Source.ScreenShare,T.width,T.height,t),T.layers=fo(T.width,T.height,C,bi(t.videoCodec))}else e.kind===w.Kind.Audio&&(C=[{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:(f=(h=t.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&f!==void 0?f:"high"}]);if(!this.engine||this.engine.isClosed)throw new ye("cannot publish track when not connected");const M=()=>p(this,void 0,void 0,function*(){var y,_,R;if(!this.engine.pcManager)throw new ye("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,C),ft(e)&&((y=t.degradationPreference)!==null&&y!==void 0||(t.degradationPreference=vf(e)),e.setDegradationPreference(t.degradationPreference)),C)if(ei()&&e.kind===w.Kind.Audio){let D;for(const F of this.engine.pcManager.publisher.getTransceivers())if(F.sender===e.sender){D=F;break}D&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:D,codec:"opus",maxbr:!((_=C[0])===null||_===void 0)&&_.maxBitrate?C[0].maxBitrate/1e3:0})}else e.codec&&bi(e.codec)&&(!((R=C[0])===null||R===void 0)&&R.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:T.cid,codec:e.codec,maxbr:C[0].maxBitrate/1e3});yield this.engine.negotiate()});let j;if(this.enabledPublishVideoCodecs.length>0)j=(yield Promise.all([this.engine.addTrack(T),M()]))[0];else{j=yield this.engine.addTrack(T);let y;if(j.codecs.forEach(_=>{y===void 0&&(y=_.mimeType)}),y&&e.kind===w.Kind.Video){const _=nn(y);_!==g&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),ie(e)),{codec:_})),t.videoCodec=_,C=Ps(e.source===w.Source.ScreenShare,T.width,T.height,t))}yield M()}const k=new Os(e.kind,j,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return k.options=t,e.sid=j.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:C,trackInfo:j})),ft(e)?e.startMonitor(this.engine.client):It(e)&&e.startMonitor(),this.addTrackPublication(k),this.emit(A.LocalTrackPublished,k),k})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return p(this,void 0,void 0,function*(){var s;if(this.encryptionType!==Me.NONE)return;let r;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(r=f)}),!r)throw new rt("track is not published");if(!ft(e))throw new rt("track is not a video track");const o=Object.assign(Object.assign({},(s=this.roomOptions)===null||s===void 0?void 0:s.publishDefaults),n),a=pf(e,t,o);if(!a){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),ie(e)));return}const c=e.addSimulcastTrack(t,a);if(!c)return;const d=new as({cid:c.mediaStreamTrack.id,type:w.kindToProto(e.kind),muted:e.isMuted,source:w.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:o.videoCodec,cid:c.mediaStreamTrack.id}]});if(d.layers=fo(d.width,d.height,a),!this.engine||this.engine.isClosed)throw new ye("cannot publish track when not connected");const l=()=>p(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,c,o,a),yield this.engine.negotiate()}),h=(yield Promise.all([this.engine.addTrack(d),l()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:a,trackInfo:h}))})}unpublishTrack(e,t){return p(this,void 0,void 0,function*(){var n,s;if(Qt(e)){const d=this.pendingPublishPromises.get(e);d&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),ie(e))),yield d)}const r=this.getPublicationForTrack(e),o=r?ie(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),o)),!r||!r.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),o));return}e=r.track,e.off(O.Muted,this.onTrackMuted),e.off(O.Unmuted,this.onTrackUnmuted),e.off(O.Ended,this.handleTrackEnded),e.off(O.UpstreamPaused,this.onTrackUpstreamPaused),e.off(O.UpstreamResumed,this.onTrackUpstreamResumed),e.off(O.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(s=(n=this.roomOptions)===null||n===void 0?void 0:n.stopLocalTrackOnUnpublish)!==null&&s!==void 0?s:!0),t?e.stop():e.stopMonitor();let a=!1;const c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<le.FAILED&&c)try{for(const d of this.engine.pcManager.publisher.getTransceivers())d.sender===c&&(d.direction="inactive",a=!0);if(this.engine.removeTrack(c)&&(a=!0),ft(e)){for(const[,d]of e.simulcastCodecs)d.sender&&(this.engine.removeTrack(d.sender)&&(a=!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),o),{error:d}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case w.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case w.Kind.Video:this.videoTrackPublications.delete(r.trackSid);break}return this.emit(A.LocalTrackUnpublished,r),r.setTrack(void 0),a&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return p(this,void 0,void 0,function*(){return(yield Promise.all(e.map(n=>this.unpublishTrack(n)))).filter(n=>!!n)})}republishAllTracks(e){return p(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){n.republishPromise&&(yield n.republishPromise),n.republishPromise=new Promise((r,o)=>p(n,void 0,void 0,function*(){try{const a=[];this.trackPublications.forEach(c=>{c.track&&(t&&(c.options=Object.assign(Object.assign({},c.options),t)),a.push(c))}),yield Promise.all(a.map(c=>p(this,void 0,void 0,function*(){const d=c.track;yield this.unpublishTrack(d,!1),s&&!d.isMuted&&d.source!==w.Source.ScreenShare&&d.source!==w.Source.ScreenShareAudio&&(It(d)||ft(d))&&!d.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:c.trackSid})),yield d.restartTrack()),yield this.publishOrRepublishTrack(d,c.options,!0)}))),r()}catch(a){o(a)}finally{this.republishPromise=void 0}})),yield n.republishPromise}()})}publishData(e){return p(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){const r=s.reliable?Q.RELIABLE:Q.LOSSY,o=s.destinationIdentities,a=s.topic,c=new _e({kind:r,value:{case:"user",value:new sa({participantIdentity:n.identity,payload:t,destinationIdentities:o,topic:a})}});yield n.engine.sendDataPacket(c,r)}()})}publishDtmf(e,t){return p(this,void 0,void 0,function*(){const n=new _e({kind:Q.RELIABLE,value:{case:"sipDtmf",value:new ra({code:e,digit:t})}});yield this.engine.sendDataPacket(n,Q.RELIABLE)})}sendChatMessage(e,t){return p(this,void 0,void 0,function*(){const n={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t==null?void 0:t.attachments},s=new _e({value:{case:"chatMessage",value:new es(Object.assign(Object.assign({},n),{timestamp:ce.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(s,Q.RELIABLE),this.emit(A.ChatMessage,n),n})}editChatMessage(e,t){return p(this,void 0,void 0,function*(){const n=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),s=new _e({value:{case:"chatMessage",value:new es(Object.assign(Object.assign({},n),{timestamp:ce.parse(n.timestamp),editTimestamp:ce.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(s,Q.RELIABLE),this.emit(A.ChatMessage,n),n})}sendText(e,t){return p(this,void 0,void 0,function*(){var n;const s=crypto.randomUUID(),o=new TextEncoder().encode(e).byteLength,a=(n=t==null?void 0:t.attachments)===null||n===void 0?void 0:n.map(()=>crypto.randomUUID()),c=new Array(a?a.length+1:1).fill(0),d=(u,h)=>{var f;c[h]=u;const m=c.reduce((g,T)=>g+T,0);(f=t==null?void 0:t.onProgress)===null||f===void 0||f.call(t,m)},l=yield this.streamText({streamId:s,totalSize:o,destinationIdentities:t==null?void 0:t.destinationIdentities,topic:t==null?void 0:t.topic,attachedStreamIds:a,attributes:t==null?void 0:t.attributes});return yield l.write(e),d(1,0),yield l.close(),t!=null&&t.attachments&&a&&(yield Promise.all(t.attachments.map((u,h)=>p(this,void 0,void 0,function*(){return this._sendFile(a[h],u,{topic:t.topic,mimeType:u.type,onProgress:f=>{d(f,h+1)}})})))),l.info})}streamText(e){return p(this,void 0,void 0,function*(){var t,n;const s=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),r={id:s,mimeType:"text/plain",timestamp:Date.now(),topic:(n=e==null?void 0:e.topic)!==null&&n!==void 0?n:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes},o=new is({streamId:s,mimeType:r.mimeType,topic:r.topic,timestamp:Rt(r.timestamp),totalLength:Rt(e==null?void 0:e.totalSize),attributes:r.attributes,contentHeader:{case:"textHeader",value:new ma({version:e==null?void 0:e.version,attachedStreamIds:e==null?void 0:e.attachedStreamIds,replyToStreamId:e==null?void 0:e.replyToStreamId,operationType:(e==null?void 0:e.type)==="update"?ts.UPDATE:ts.CREATE})}}),a=e==null?void 0:e.destinationIdentities,c=new _e({destinationIdentities:a,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(c,Q.RELIABLE);let d=0;const l=this,u=new WritableStream({write(m){return p(this,void 0,void 0,function*(){for(const g of Bh(m,Fi)){yield l.engine.waitForBufferStatusLow(Q.RELIABLE);const T=new ns({content:g,streamId:s,chunkIndex:Rt(d)}),C=new _e({destinationIdentities:a,value:{case:"streamChunk",value:T}});yield l.engine.sendDataPacket(C,Q.RELIABLE),d+=1}})},close(){return p(this,void 0,void 0,function*(){const m=new ss({streamId:s}),g=new _e({destinationIdentities:a,value:{case:"streamTrailer",value:m}});yield l.engine.sendDataPacket(g,Q.RELIABLE)})},abort(m){console.log("Sink error:",m)}});let h=()=>p(this,void 0,void 0,function*(){yield f.close()});l.engine.once(x.Closing,h);const f=new Pf(u,r,()=>this.engine.off(x.Closing,h));return f})}sendFile(e,t){return p(this,void 0,void 0,function*(){const n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}})}_sendFile(e,t,n){return p(this,void 0,void 0,function*(){var s,r;const o=t.size,a=new is({totalLength:Rt(o),mimeType:(s=n==null?void 0:n.mimeType)!==null&&s!==void 0?s:t.type,streamId:e,topic:n==null?void 0:n.topic,encryptionType:n==null?void 0:n.encryptionType,timestamp:Rt(Date.now()),contentHeader:{case:"byteHeader",value:new ga({name:t.name})}}),c=n==null?void 0:n.destinationIdentities,d=new _e({destinationIdentities:c,value:{case:"streamHeader",value:a}});yield this.engine.sendDataPacket(d,Q.RELIABLE);function l(m){return new Promise(g=>{const T=new FileReader;T.onload=()=>{g(new Uint8Array(T.result))},T.readAsArrayBuffer(m)})}const u=Math.ceil(o/Fi);for(let m=0;m<u;m++){const g=yield l(t.slice(m*Fi,Math.min((m+1)*Fi,o)));yield this.engine.waitForBufferStatusLow(Q.RELIABLE);const T=new ns({content:g,streamId:e,chunkIndex:Rt(m)}),C=new _e({destinationIdentities:c,value:{case:"streamChunk",value:T}});yield this.engine.sendDataPacket(C,Q.RELIABLE),(r=n==null?void 0:n.onProgress)===null||r===void 0||r.call(n,(m+1)/u)}const h=new ss({streamId:e}),f=new _e({destinationIdentities:c,value:{case:"streamTrailer",value:h}});yield this.engine.sendDataPacket(f,Q.RELIABLE)})}performRpc(e){return p(this,arguments,void 0,function(t){var n=this;let{destinationIdentity:s,method:r,payload:o,responseTimeout:a=1e4}=t;return function*(){return new Promise((d,l)=>p(n,void 0,void 0,function*(){var u,h,f,m;if(tr(o)>pc){l(he.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((h=(u=this.engine.latestJoinResponse)===null||u===void 0?void 0:u.serverInfo)===null||h===void 0)&&h.version&&ti((m=(f=this.engine.latestJoinResponse)===null||f===void 0?void 0:f.serverInfo)===null||m===void 0?void 0:m.version,"1.8.0")<0){l(he.builtIn("UNSUPPORTED_SERVER"));return}const g=crypto.randomUUID();yield this.publishRpcRequest(s,g,r,o,a-2e3);const T=setTimeout(()=>{this.pendingAcks.delete(g),l(he.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(g),clearTimeout(C)},2e3);this.pendingAcks.set(g,{resolve:()=>{clearTimeout(T)},participantIdentity:s});const C=setTimeout(()=>{this.pendingResponses.delete(g),l(he.builtIn("RESPONSE_TIMEOUT"))},a);this.pendingResponses.set(g,{resolve:(M,j)=>{clearTimeout(C),this.pendingAcks.has(g)&&(console.warn("RPC response received before ack",g),this.pendingAcks.delete(g),clearTimeout(T)),j?l(j):d(M??"")},participantIdentity:s})}))}()})}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,n){const s=this.pendingResponses.get(e);s?(s.resolve(t,n),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,n,s,r){return p(this,void 0,void 0,function*(){const o=new _e({destinationIdentities:[e],kind:Q.RELIABLE,value:{case:"rpcRequest",value:new oa({id:t,method:n,payload:s,responseTimeoutMs:r,version:1})}});yield this.engine.sendDataPacket(o,Q.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:n}]of this.pendingAcks)n===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:n,resolve:s}]of this.pendingResponses)n===e&&(s(null,he.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return e.sid!==this.sid||!super.updateInfo(e)?!1:(e.tracks.forEach(t=>{var n,s;const r=this.trackPublications.get(t.sid);if(r){const o=r.isMuted||((s=(n=r.track)===null||n===void 0?void 0:n.isUpstreamPaused)!==null&&s!==void 0?s:!1);o!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),ie(r)),{mutedOnServer:o})),this.engine.client.sendMuteTrack(t.sid,o))}}),!0)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(n=>{const s=n.track;s&&(e instanceof MediaStreamTrack?(It(s)||ft(s))&&s.mediaStreamTrack===e&&(t=n):e===s&&(t=n))}),t}waitForPendingPublicationOfSource(e){return p(this,void 0,void 0,function*(){const n=Date.now();for(;Date.now()<n+1e4;){const s=Array.from(this.pendingPublishPromises.entries()).find(r=>{let[o]=r;return o.source===e});if(s)return s[1];yield Ie(20)}})}}class Df extends gt{constructor(e,t,n,s){super(e,t.sid,t.name,s),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=Le.HIGH,this.handleEnded=r=>{this.setTrack(void 0),this.emit(O.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=n,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const s=new bn({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new la({participantSid:"",trackSids:[this.trackSid]})]});this.emit(O.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?gt.SubscriptionStatus.Unsubscribed:super.isSubscribed?gt.SubscriptionStatus.Subscribed:gt.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?gt.PermissionStatus.Allowed:gt.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return!this.disabled}get isLocal(){return!1}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,n;this.isManualOperationAllowed()&&(((t=this.videoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((n=this.videoDimensions)===null||n===void 0?void 0:n.height)===e.height||(Ln(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Ln(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const t=this.subscriptionStatus,n=this.permissionStatus,s=this.track;s!==e&&(s&&(s.off(O.VideoDimensionsChanged,this.handleVideoDimensionsChange),s.off(O.VisibilityChanged,this.handleVisibilityChange),s.off(O.Ended,this.handleEnded),s.detach(),s.stopMonitor(),this.emit(O.Unsubscribed,s)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(O.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(O.VisibilityChanged,this.handleVisibilityChange),e.on(O.Ended,this.handleEnded),this.emit(O.Subscribed,e)),this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(O.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?O.Muted:O.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(O.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(O.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.kind===w.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 Ln(this.track)&&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=Le.HIGH,this.emit(O.UpdateSettings,e)}}class mn extends Tc{static fromParticipantInfo(e,t,n){return new mn(e,t.sid,t.identity,t.name,t.metadata,t.attributes,n,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,s,r,o,a){let c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:ln.STANDARD;super(t,n||"",s,r,o,a,c),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(O.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),ie(e))),this.signalClient.sendUpdateTrackSettings(t)}),e.on(O.UpdateSubscription,t=>{t.participantTracks.forEach(n=>{n.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(O.SubscriptionPermissionChanged,t=>{this.emit(A.TrackSubscriptionPermissionChanged,e,t)}),e.on(O.SubscriptionStatusChanged,t=>{this.emit(A.TrackSubscriptionStatusChanged,e,t)}),e.on(O.Subscribed,t=>{this.emit(A.TrackSubscribed,t,e)}),e.on(O.Unsubscribed,t=>{this.emit(A.TrackUnsubscribed,t,e)}),e.on(O.SubscriptionFailed,t=>{this.emit(A.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]:w.Source.Microphone;this.volumeMap.set(t,e);const n=this.getTrackPublication(t);n&&n.track&&n.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:w.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,n,s,r,o){let a=this.getTrackPublicationBySid(t);if(a||t.startsWith("TR")||this.trackPublications.forEach(l=>{!a&&e.kind===l.kind.toString()&&(a=l)}),!a){if(o===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(A.TrackSubscriptionFailed,t);return}o===void 0&&(o=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,n,s,r,o-1)},150);return}if(e.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),ie(a))),this.emit(A.TrackSubscriptionFailed,t);return}const c=e.kind==="video";let d;return c?d=new If(e,t,s,r):d=new Rf(e,t,s,this.audioContext,this.audioOutput),d.source=a.source,d.isMuted=a.isMuted,d.setMediaStream(n),d.start(),a.setTrack(d),this.volumeMap.has(a.source)&&Ss(d)&&dt(d)&&d.setVolume(this.volumeMap.get(a.source)),a}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,n=new Map;return e.tracks.forEach(s=>{var r,o;let a=this.getTrackPublicationBySid(s.sid);if(a)a.updateInfo(s);else{const c=w.kindFromProto(s.type);if(!c)return;a=new Df(c,s,(r=this.signalClient.connectOptions)===null||r===void 0?void 0:r.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(o=this.loggerOptions)===null||o===void 0?void 0:o.loggerName}),a.updateInfo(s),n.set(s.sid,a);const d=Array.from(this.trackPublications.values()).find(l=>l.source===(a==null?void 0:a.source));d&&a.source!==w.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(a.source),Object.assign(Object.assign({},this.logContext),{oldTrack:ie(d),newTrack:ie(a)})),this.addTrackPublication(a)}t.set(s.sid,a)}),this.trackPublications.forEach(s=>{t.has(s.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),ie(s))),this.unpublishTrack(s.trackSid,!0))}),n.forEach(s=>{this.emit(A.TrackPublished,s)}),!0}unpublishTrack(e,t){const n=this.trackPublications.get(e);if(!n)return;const{track:s}=n;switch(s&&(s.stop(),n.setTrack(void 0)),this.trackPublications.delete(e),n.kind){case w.Kind.Audio:this.audioTrackPublications.delete(e);break;case w.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(A.TrackUnpublished,n)}setAudioOutput(e){return p(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(n=>{var s;dt(n.track)&&Ss(n.track)&&t.push(n.track.setSinkId((s=e.deviceId)!==null&&s!==void 0?s:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:n})),super.emit(e,...n)}}var te;(function(i){i.Disconnected="disconnected",i.Connecting="connecting",i.Connected="connected",i.Reconnecting="reconnecting",i.SignalReconnecting="signalReconnecting"})(te||(te={}));const Nf=4*1e3;class ii extends et.EventEmitter{constructor(e){var t,n,s,r;if(super(),t=this,this.state=te.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=W,this.bufferedEvents=[],this.isResuming=!1,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.rpcHandlers=new Map,this.connect=(o,a,c)=>p(this,void 0,void 0,function*(){var d;if(!Rh())throw Ze()?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 l=yield this.disconnectLock.lock();if(this.state===te.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),l(),Promise.resolve();if(this.connectFuture)return l(),this.connectFuture.promise;this.setAndEmitConnectionState(te.Connecting),((d=this.regionUrlProvider)===null||d===void 0?void 0:d.getServerUrl().toString())!==o&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Cs(new URL(o))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new Rs(o,a):this.regionUrlProvider.updateToken(a),this.regionUrlProvider.fetchRegionSettings().then(f=>{var m;(m=this.regionUrlProvider)===null||m===void 0||m.setServerReportedRegions(f)}).catch(f=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:f}))}));const u=(f,m,g)=>p(this,void 0,void 0,function*(){var T,C;this.abortController&&this.abortController.abort();const M=new AbortController;this.abortController=M,l==null||l();try{yield this.attemptConnection(g??o,a,c,M),this.abortController=void 0,f()}catch(j){if(this.regionUrlProvider&&j instanceof re&&j.reason!==J.Cancelled&&j.reason!==J.NotAllowed){let k=null;try{k=yield this.regionUrlProvider.getNextBestRegionUrl((T=this.abortController)===null||T===void 0?void 0:T.signal)}catch(y){if(y instanceof re&&(y.status===401||y.reason===J.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),m(y);return}}k&&!(!((C=this.abortController)===null||C===void 0)&&C.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(j.message,". Retrying with another region: ").concat(k),this.logContext),this.recreateEngine(),yield u(f,m,k)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Xr(j)),m(j))}else{let k=ze.UNKNOWN_REASON;j instanceof re&&(k=Xr(j)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,k),m(j)}}}),h=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new cc((f,m)=>{u(f,m,h)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(o,a,c,d,l,u)=>p(this,void 0,void 0,function*(){var h,f,m;const g=yield c.join(o,a,{autoSubscribe:d.autoSubscribe,adaptiveStream:typeof l.adaptiveStream=="object"?!0:l.adaptiveStream,maxRetries:d.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:d.websocketTimeout},u.signal);let T=g.serverInfo;if(T||(T={version:g.serverVersion,region:g.serverRegion}),this.serverInfo=T,this.log.debug("connected to Livekit Server ".concat(Object.entries(T).map(C=>{let[M,j]=C;return"".concat(M,": ").concat(j)}).join(", ")),{room:(h=g.room)===null||h===void 0?void 0:h.name,roomSid:(f=g.room)===null||f===void 0?void 0:f.sid,identity:(m=g.participant)===null||m===void 0?void 0:m.identity}),!T.version)throw new hh("unknown server version");return T.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),l.dynacast=!1),g}),this.applyJoinResponse=o=>{const a=o.participant;if(this.localParticipant.sid=a.sid,this.localParticipant.identity=a.identity,this.localParticipant.setEnabledPublishCodecs(o.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(o.sifTrailer)}catch(c){this.log.error(c instanceof Error?c.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:c}))}this.handleParticipantUpdates([a,...o.otherParticipants]),o.room&&this.handleRoomUpdate(o.room)},this.attemptConnection=(o,a,c,d)=>p(this,void 0,void 0,function*(){var l,u;this.state===te.Reconnecting||this.isResuming||!((l=this.engine)===null||l===void 0)&&l.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((u=this.regionUrlProvider)===null||u===void 0)&&u.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},er),c),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const h=yield this.connectSignal(o,a,this.engine,this.connOptions,this.options,d);this.applyJoinResponse(h),this.setupLocalParticipantEvents(),this.emit(I.SignalConnected)}catch(h){yield this.engine.close(),this.recreateEngine();const f=new re("could not establish signal connection",J.ServerUnreachable);throw h instanceof Error&&(f.message="".concat(f.message,": ").concat(h.message)),h instanceof re&&(f.reason=h.reason,f.status=h.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:h})),f}if(d.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new re("Connection attempt aborted",J.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,d)}catch(h){throw yield this.engine.close(),this.recreateEngine(),h}Re()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Re()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(te.Connected),this.emit(I.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var o=arguments.length,a=new Array(o),c=0;c<o;c++)a[c]=arguments[c];return p(t,[...a],void 0,function(){var d=this;let l=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var u,h,f,m;const g=yield d.disconnectLock.lock();try{if(d.state===te.Disconnected){d.log.debug("already disconnected",d.logContext);return}d.log.info("disconnect from room",Object.assign({},d.logContext)),(d.state===te.Connecting||d.state===te.Reconnecting||d.isResuming)&&(d.log.warn("abort connection attempt",d.logContext),(u=d.abortController)===null||u===void 0||u.abort(),(f=(h=d.connectFuture)===null||h===void 0?void 0:h.reject)===null||f===void 0||f.call(h,new re("Client initiated disconnect",J.Cancelled)),d.connectFuture=void 0),!((m=d.engine)===null||m===void 0)&&m.client.isDisconnected||(yield d.engine.client.sendLeave()),d.engine&&(yield d.engine.close()),d.handleDisconnect(l,ze.CLIENT_INITIATED),d.engine=void 0}finally{g()}}()})},this.onPageLeave=()=>p(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>p(this,void 0,void 0,function*(){const o=[],a=Xe();if(a&&a.os==="iOS"){const c="livekit-dummy-audio-el";let d=document.getElementById(c);if(!d){d=document.createElement("audio"),d.id=c,d.autoplay=!0,d.hidden=!0;const l=Nn();l.enabled=!0;const u=new MediaStream([l]);d.srcObject=u,document.addEventListener("visibilitychange",()=>{d&&(d.srcObject=document.hidden?null:u,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(d),this.once(I.Disconnected,()=>{d==null||d.remove(),d=null})}o.push(d)}this.remoteParticipants.forEach(c=>{c.audioTrackPublications.forEach(d=>{d.track&&d.track.attachedElements.forEach(l=>{o.push(l)})})});try{yield Promise.all([this.acquireAudioContext(),...o.map(c=>(c.muted=!1,c.play()))]),this.handleAudioPlaybackStarted()}catch(c){throw this.handleAudioPlaybackFailed(c),c}}),this.startVideo=()=>p(this,void 0,void 0,function*(){const o=[];for(const a of this.remoteParticipants.values())a.videoTrackPublications.forEach(c=>{var d;(d=c.track)===null||d===void 0||d.attachedElements.forEach(l=>{o.includes(l)||o.push(l)})});yield Promise.all(o.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 o of this.remoteParticipants.values())this.handleParticipantDisconnected(o.identity,o);this.setAndEmitConnectionState(te.Reconnecting)&&this.emit(I.Reconnecting)},this.handleSignalRestarted=o=>p(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(o.serverRegion),Object.assign(Object.assign({},this.logContext),{region:o.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(o);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:o.serverRegion}))}catch{return}this.setAndEmitConnectionState(te.Connected),this.emit(I.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=o=>{o.forEach(a=>{var c;if(a.identity===this.localParticipant.identity){this.localParticipant.updateInfo(a);return}a.identity===""&&(a.identity=(c=this.sidToIdentity.get(a.sid))!==null&&c!==void 0?c:"");let d=this.remoteParticipants.get(a.identity);a.state===Zn.DISCONNECTED?this.handleParticipantDisconnected(a.identity,d):d=this.getOrCreateParticipant(a.identity,a)})},this.handleActiveSpeakersUpdate=o=>{const a=[],c={};o.forEach(d=>{if(c[d.sid]=!0,d.sid===this.localParticipant.sid)this.localParticipant.audioLevel=d.level,this.localParticipant.setIsSpeaking(!0),a.push(this.localParticipant);else{const l=this.getRemoteParticipantBySid(d.sid);l&&(l.audioLevel=d.level,l.setIsSpeaking(!0),a.push(l))}}),c[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(d=>{c[d.sid]||(d.audioLevel=0,d.setIsSpeaking(!1))}),this.activeSpeakers=a,this.emitWhenConnected(I.ActiveSpeakersChanged,a)},this.handleSpeakersChanged=o=>{const a=new Map;this.activeSpeakers.forEach(d=>{const l=this.remoteParticipants.get(d.identity);l&&l.sid!==d.sid||a.set(d.sid,d)}),o.forEach(d=>{let l=this.getRemoteParticipantBySid(d.sid);d.sid===this.localParticipant.sid&&(l=this.localParticipant),l&&(l.audioLevel=d.level,l.setIsSpeaking(d.active),d.active?a.set(d.sid,l):a.delete(d.sid))});const c=Array.from(a.values());c.sort((d,l)=>l.audioLevel-d.audioLevel),this.activeSpeakers=c,this.emitWhenConnected(I.ActiveSpeakersChanged,c)},this.handleStreamStateUpdate=o=>{o.streamStates.forEach(a=>{const c=this.getRemoteParticipantBySid(a.participantSid);if(!c)return;const d=c.getTrackPublicationBySid(a.trackSid);if(!d||!d.track)return;const l=w.streamStateFromProto(a.state);l!==d.track.streamState&&(d.track.streamState=l,c.emit(A.TrackStreamStateChanged,d,d.track.streamState),this.emitWhenConnected(I.TrackStreamStateChanged,d,d.track.streamState,c))})},this.handleSubscriptionPermissionUpdate=o=>{const a=this.getRemoteParticipantBySid(o.participantSid);if(!a)return;const c=a.getTrackPublicationBySid(o.trackSid);c&&c.setAllowed(o.allowed)},this.handleSubscriptionError=o=>{const a=Array.from(this.remoteParticipants.values()).find(d=>d.trackPublications.has(o.trackSid));if(!a)return;const c=a.getTrackPublicationBySid(o.trackSid);c&&c.setSubscriptionError(o.err)},this.handleDataPacket=o=>{const a=this.remoteParticipants.get(o.participantIdentity);if(o.value.case==="user")this.handleUserPacket(a,o.value.value,o.kind);else if(o.value.case==="transcription")this.handleTranscription(a,o.value.value);else if(o.value.case==="sipDtmf")this.handleSipDtmf(a,o.value.value);else if(o.value.case==="chatMessage")this.handleChatMessage(a,o.value.value);else if(o.value.case==="metrics")this.handleMetrics(o.value.value,a);else if(o.value.case==="streamHeader")this.handleStreamHeader(o.value.value,o.participantIdentity);else if(o.value.case==="streamChunk")this.handleStreamChunk(o.value.value);else if(o.value.case==="streamTrailer")this.handleStreamTrailer(o.value.value);else if(o.value.case==="rpcRequest"){const c=o.value.value;this.handleIncomingRpcRequest(o.participantIdentity,c.id,c.method,c.payload,c.responseTimeoutMs,c.version)}},this.handleUserPacket=(o,a,c)=>{this.emit(I.DataReceived,a.payload,o,c,a.topic),o==null||o.emit(A.DataReceived,a.payload,c)},this.handleSipDtmf=(o,a)=>{this.emit(I.SipDTMFReceived,a,o),o==null||o.emit(A.SipDTMFReceived,a)},this.bufferedSegments=new Map,this.handleTranscription=(o,a)=>{const c=a.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(a.transcribedParticipantIdentity),d=c==null?void 0:c.trackPublications.get(a.trackId),l=Lh(a,this.transcriptionReceivedTimes);d==null||d.emit(O.TranscriptionReceived,l),c==null||c.emit(A.TranscriptionReceived,l,d),this.emit(I.TranscriptionReceived,l,c,d)},this.handleChatMessage=(o,a)=>{const c=Uh(a);this.emit(I.ChatMessage,c,o)},this.handleMetrics=(o,a)=>{this.emit(I.MetricsReceived,o,a)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(I.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=o=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:o})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(I.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(I.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(I.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>p(this,void 0,void 0,function*(){var o,a;const c=Te.getInstance().previousDevices,d=yield Te.getInstance().getDevices(void 0,!1),l=Xe();if((l==null?void 0:l.name)==="Chrome"&&l.os!=="iOS")for(let h of d){const f=c.find(m=>m.deviceId===h.deviceId);f&&f.label!==""&&f.kind===h.kind&&f.label!==h.label&&this.getActiveDevice(h.kind)==="default"&&this.emit(I.ActiveDeviceChanged,h.kind,h.deviceId)}const u=["audiooutput","audioinput","videoinput"];for(let h of u){const f=d.filter(g=>g.kind===h),m=this.getActiveDevice(h);if(m===((o=c.filter(g=>g.kind===h)[0])===null||o===void 0?void 0:o.deviceId)&&f.length>0&&((a=f[0])===null||a===void 0?void 0:a.deviceId)!==m){yield this.switchActiveDevice(h,f[0].deviceId);continue}h==="audioinput"&&!Et()||h==="videoinput"||f.length>0&&!f.find(g=>g.deviceId===this.getActiveDevice(h))&&(yield this.switchActiveDevice(h,f[0].deviceId))}this.emit(I.MediaDevicesChanged)}),this.handleRoomUpdate=o=>{const a=this.roomInfo;this.roomInfo=o,a&&a.metadata!==o.metadata&&this.emitWhenConnected(I.RoomMetadataChanged,o.metadata),(a==null?void 0:a.activeRecording)!==o.activeRecording&&this.emitWhenConnected(I.RecordingStatusChanged,o.activeRecording)},this.handleConnectionQualityUpdate=o=>{o.updates.forEach(a=>{if(a.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(a.quality);return}const c=this.getRemoteParticipantBySid(a.participantSid);c&&c.setConnectionQuality(a.quality)})},this.onLocalParticipantMetadataChanged=o=>{this.emit(I.ParticipantMetadataChanged,o,this.localParticipant)},this.onLocalParticipantNameChanged=o=>{this.emit(I.ParticipantNameChanged,o,this.localParticipant)},this.onLocalAttributesChanged=o=>{this.emit(I.ParticipantAttributesChanged,o,this.localParticipant)},this.onLocalTrackMuted=o=>{this.emit(I.TrackMuted,o,this.localParticipant)},this.onLocalTrackUnmuted=o=>{this.emit(I.TrackUnmuted,o,this.localParticipant)},this.onTrackProcessorUpdate=o=>{var a;(a=o==null?void 0:o.onPublish)===null||a===void 0||a.call(o,this)},this.onLocalTrackPublished=o=>p(this,void 0,void 0,function*(){var a,c,d,l,u,h;(a=o.track)===null||a===void 0||a.on(O.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=o.track)===null||c===void 0||c.on(O.Restarted,this.onLocalTrackRestarted),(u=(l=(d=o.track)===null||d===void 0?void 0:d.getProcessor())===null||l===void 0?void 0:l.onPublish)===null||u===void 0||u.call(l,this),this.emit(I.LocalTrackPublished,o,this.localParticipant),It(o.track)&&(yield o.track.checkForSilence())&&this.emit(I.LocalAudioSilenceDetected,o);const f=yield(h=o.track)===null||h===void 0?void 0:h.getDeviceId(!1),m=Zr(o.source);m&&f&&f!==this.localParticipant.activeDeviceMap.get(m)&&(this.localParticipant.activeDeviceMap.set(m,f),this.emit(I.ActiveDeviceChanged,m,f))}),this.onLocalTrackUnpublished=o=>{var a,c;(a=o.track)===null||a===void 0||a.off(O.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=o.track)===null||c===void 0||c.off(O.Restarted,this.onLocalTrackRestarted),this.emit(I.LocalTrackUnpublished,o,this.localParticipant)},this.onLocalTrackRestarted=o=>p(this,void 0,void 0,function*(){const a=yield o.getDeviceId(!1),c=Zr(o.source);c&&a&&a!==this.localParticipant.activeDeviceMap.get(c)&&(this.log.debug("local track restarted, setting ".concat(c," ").concat(a," active"),this.logContext),this.localParticipant.activeDeviceMap.set(c,a),this.emit(I.ActiveDeviceChanged,c,a))}),this.onLocalConnectionQualityChanged=o=>{this.emit(I.ConnectionQualityChanged,o,this.localParticipant)},this.onMediaDevicesError=o=>{this.emit(I.MediaDevicesError,o)},this.onLocalParticipantPermissionsChanged=o=>{this.emit(I.ParticipantPermissionsChanged,o,this.localParticipant)},this.onLocalChatMessageSent=o=>{this.emit(I.ChatMessage,o,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},rf),e),this.log=ct((n=this.options.loggerName)!==null&&n!==void 0?n:Ge.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},hc),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},fc),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},sf),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new De,this.localParticipant=new Mf("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Ct(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Ct(this.options.audioCaptureDefaults.deviceId)),!((s=this.options.audioOutput)===null||s===void 0)&&s.deviceId&&this.switchActiveDevice("audiooutput",Ct(this.options.audioOutput.deviceId)).catch(o=>this.log.warn("Could not set audio output: ".concat(o.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),Re()){const o=new AbortController;(r=navigator.mediaDevices)===null||r===void 0||r.addEventListener("devicechange",this.handleDeviceChange,{signal:o.signal}),ii.cleanupRegistry&&ii.cleanupRegistry.register(this,()=>{o.abort()})}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new TypeError('A text stream handler for topic "'.concat(e,'" has already been set.'));this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new TypeError('A byte stream handler for topic "'.concat(e,'" has already been set.'));this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}handleIncomingRpcRequest(e,t,n,s,r,o){return p(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),o!==1){yield this.engine.publishRpcResponse(e,t,null,he.builtIn("UNSUPPORTED_VERSION"));return}const a=this.rpcHandlers.get(n);if(!a){yield this.engine.publishRpcResponse(e,t,null,he.builtIn("UNSUPPORTED_METHOD"));return}let c=null,d=null;try{const l=yield a({requestId:t,callerIdentity:e,payload:s,responseTimeout:r});tr(l)>pc?(c=he.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(n))):d=l}catch(l){l instanceof he?c=l:(console.warn("Uncaught error returned by RPC handler for ".concat(n,". Returning APPLICATION_ERROR instead."),l),c=he.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,d,c)})}setE2EEEnabled(e){return p(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&&("e2eeManager"in this.options.e2ee?this.e2eeManager=this.options.e2ee.e2eeManager:this.e2eeManager=new Gh(this.options.e2ee),this.e2eeManager.on(bt.ParticipantEncryptionStatusChanged,(t,n)=>{Fh(n)&&(this.isE2EEEnabled=t),this.emit(I.ParticipantEncryptionStatusChanged,t,n)}),this.e2eeManager.on(bt.EncryptionError,t=>this.emit(I.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 p(this,void 0,void 0,function*(){return this.state===te.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,t)=>{const n=s=>{s.sid!==""&&(this.engine.off(x.RoomUpdate,n),e(s.sid))};this.engine.on(x.RoomUpdate,n),this.once(I.Disconnected,()=>{this.engine.off(x.RoomUpdate,n),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 kf(this.options),this.engine.on(x.ParticipantUpdate,this.handleParticipantUpdates).on(x.RoomUpdate,this.handleRoomUpdate).on(x.SpeakersChanged,this.handleSpeakersChanged).on(x.StreamStateChanged,this.handleStreamStateUpdate).on(x.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(x.SubscriptionError,this.handleSubscriptionError).on(x.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(x.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(x.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(x.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(x.DataPacketReceived,this.handleDataPacket).on(x.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(te.SignalReconnecting)&&this.emit(I.SignalReconnecting)}).on(x.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(te.Connected)&&this.emit(I.Reconnected)}).on(x.SignalResumed,()=>{this.bufferedEvents=[],(this.state===te.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(x.Restarting,this.handleRestarting).on(x.SignalRestarted,this.handleSignalRestarted).on(x.Offline,()=>{this.setAndEmitConnectionState(te.Reconnecting)&&this.emit(I.Reconnecting)}).on(x.DCBufferStatusChanged,(e,t)=>{this.emit(I.DCBufferStatusChanged,e,t)}).on(x.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(n=>{let{trackSid:s}=n;return s===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(A.LocalTrackSubscribed,t),this.emitWhenConnected(I.LocalTrackSubscribed,t,this.localParticipant)}),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 Te.getInstance().getDevices(e,t)}prepareConnection(e,t){return p(this,void 0,void 0,function*(){if(this.state===te.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Cs(new URL(e))&&t){this.regionUrlProvider=new Rs(e,t);const n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===te.Disconnected&&(this.regionUrl=n,yield fetch(Yr(n),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(n),this.logContext))}else yield fetch(Yr(e),{method:"HEAD"})}catch(n){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:n}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return p(this,void 0,void 0,function*(){let n=()=>{},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":n=()=>p(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":n=()=>p(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}}),n=()=>p(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new kn({reason:ze.CLIENT_INITIATED,action:Wt.RECONNECT}))});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:Rt(t)}});break;case"leave-full-reconnect":s=new Ke({scenario:{case:"leaveRequestFullReconnect",value:!0}})}s&&(yield this.engine.client.sendSimulateScenario(s),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return p(this,arguments,void 0,function(n,s){var r=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var a,c,d,l,u,h,f,m;let g=!0,T=!1;const C=o?{exact:s}:s;if(n==="audioinput"){T=r.localParticipant.audioTrackPublications.size===0;const M=(a=r.getActiveDevice(n))!==null&&a!==void 0?a:r.options.audioCaptureDefaults.deviceId;r.options.audioCaptureDefaults.deviceId=C;const j=Array.from(r.localParticipant.audioTrackPublications.values()).filter(k=>k.source===w.Source.Microphone);try{g=(yield Promise.all(j.map(k=>{var y;return(y=k.audioTrack)===null||y===void 0?void 0:y.setDeviceId(C)}))).every(k=>k===!0)}catch(k){throw r.options.audioCaptureDefaults.deviceId=M,k}}else if(n==="videoinput"){T=r.localParticipant.videoTrackPublications.size===0;const M=(c=r.getActiveDevice(n))!==null&&c!==void 0?c:r.options.videoCaptureDefaults.deviceId;r.options.videoCaptureDefaults.deviceId=C;const j=Array.from(r.localParticipant.videoTrackPublications.values()).filter(k=>k.source===w.Source.Camera);try{g=(yield Promise.all(j.map(k=>{var y;return(y=k.videoTrack)===null||y===void 0?void 0:y.setDeviceId(C)}))).every(k=>k===!0)}catch(k){throw r.options.videoCaptureDefaults.deviceId=M,k}}else if(n==="audiooutput"){if(!Ts()&&!r.options.webAudioMix||r.options.webAudioMix&&r.audioContext&&!("setSinkId"in r.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");r.options.webAudioMix&&(s=(d=yield Te.getInstance().normalizeDeviceId("audiooutput",s))!==null&&d!==void 0?d:""),(l=(m=r.options).audioOutput)!==null&&l!==void 0||(m.audioOutput={});const M=(u=r.getActiveDevice(n))!==null&&u!==void 0?u:r.options.audioOutput.deviceId;r.options.audioOutput.deviceId=s;try{r.options.webAudioMix&&((h=r.audioContext)===null||h===void 0||h.setSinkId(s)),yield Promise.all(Array.from(r.remoteParticipants.values()).map(j=>j.setAudioOutput({deviceId:s})))}catch(j){throw r.options.audioOutput.deviceId=M,j}}return(T||n==="audiooutput")&&(r.localParticipant.activeDeviceMap.set(n,n==="audiooutput"&&((f=r.options.audioOutput)===null||f===void 0?void 0:f.deviceId)||s),r.emit(I.ActiveDeviceChanged,n,s)),g}()})}setupLocalParticipantEvents(){this.localParticipant.on(A.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(A.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(A.AttributesChanged,this.onLocalAttributesChanged).on(A.TrackMuted,this.onLocalTrackMuted).on(A.TrackUnmuted,this.onLocalTrackUnmuted).on(A.LocalTrackPublished,this.onLocalTrackPublished).on(A.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(A.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(A.MediaDevicesError,this.onMediaDevicesError).on(A.AudioStreamAcquired,this.startAudio).on(A.ChatMessage,this.onLocalChatMessageSent).on(A.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,n){if(this.state===te.Connecting||this.state===te.Reconnecting){const l=()=>{this.onTrackAdded(e,t,n),u()},u=()=>{this.off(I.Reconnected,l),this.off(I.Connected,l),this.off(I.Disconnected,u)};this.once(I.Reconnected,l),this.once(I.Connected,l),this.once(I.Disconnected,u);return}if(this.state===te.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}const s=wh(t.id),r=s[0];let o=s[1],a=e.id;if(o&&o.startsWith("TR")&&(a=o),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,a,t,n,d)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var n;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==te.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,o,a;s.track&&this.localParticipant.unpublishTrack(s.track,e),e?((r=s.track)===null||r===void 0||r.detach(),(o=s.track)===null||o===void 0||o.stop()):(a=s.track)===null||a===void 0||a.stopMonitor()}),this.localParticipant.off(A.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(A.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(A.AttributesChanged,this.onLocalAttributesChanged).off(A.TrackMuted,this.onLocalTrackMuted).off(A.TrackUnmuted,this.onLocalTrackUnmuted).off(A.LocalTrackPublished,this.onLocalTrackPublished).off(A.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(A.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(A.MediaDevicesError,this.onMediaDevicesError).off(A.AudioStreamAcquired,this.startAudio).off(A.ChatMessage,this.onLocalChatMessageSent).off(A.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),Re()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(n=navigator.mediaDevices)===null||n===void 0||n.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(te.Disconnected),this.emit(I.Disconnected,t)}}}handleParticipantDisconnected(e,t){var n;this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach(s=>{t.unpublishTrack(s.trackSid,!0)}),this.emit(I.ParticipantDisconnected,t),(n=this.localParticipant)===null||n===void 0||n.handleParticipantDisconnected(t.identity))}handleStreamHeader(e,t){return p(this,void 0,void 0,function*(){var n;if(e.contentHeader.case==="byteHeader"){const s=this.byteStreamHandlers.get(e.topic);if(!s){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let r;const o={id:e.streamId,name:(n=e.contentHeader.value.name)!==null&&n!==void 0?n:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:tn(e.timestamp),attributes:e.attributes},a=new ReadableStream({start:c=>{r=c,this.byteStreamControllers.set(e.streamId,{info:o,controller:r,startTime:Date.now()})}});s(new Ef(o,a,tn(e.totalLength)),{identity:t})}else if(e.contentHeader.case==="textHeader"){const s=this.textStreamHandlers.get(e.topic);if(!s){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let r;const o={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes},a=new ReadableStream({start:c=>{r=c,this.textStreamControllers.set(e.streamId,{info:o,controller:r,startTime:Date.now()})}});s(new wf(o,a,tn(e.totalLength)),{identity:t})}})}handleStreamChunk(e){const t=this.byteStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e);const n=this.textStreamControllers.get(e.streamId);n&&e.content.length>0&&n.controller.enqueue(e)}handleStreamTrailer(e){const t=this.textStreamControllers.get(e.streamId);t&&(t.info.attributes=Object.assign(Object.assign({},t.info.attributes),e.attributes),t.controller.close(),this.textStreamControllers.delete(e.streamId));const n=this.byteStreamControllers.get(e.streamId);n&&(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close(),this.byteStreamControllers.delete(e.streamId))}acquireAudioContext(){return p(this,void 0,void 0,function*(){var e,t;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=uc())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(s=>s.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),Ie(200)])}catch(s){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:s}))}const n=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";n!==this.canPlaybackAudio&&(this.audioEnabled=n,this.emit(I.AudioPlaybackStatusChanged,n))})}createParticipant(e,t){var n;let s;return t?s=mn.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):s=new mn(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&s.setAudioContext(this.audioContext),!((n=this.options.audioOutput)===null||n===void 0)&&n.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 n=this.createParticipant(e,t);return this.remoteParticipants.set(e,n),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(I.ParticipantConnected,n),n.on(A.TrackPublished,s=>{this.emitWhenConnected(I.TrackPublished,s,n)}).on(A.TrackSubscribed,(s,r)=>{s.kind===w.Kind.Audio?(s.on(O.AudioPlaybackStarted,this.handleAudioPlaybackStarted),s.on(O.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):s.kind===w.Kind.Video&&(s.on(O.VideoPlaybackFailed,this.handleVideoPlaybackFailed),s.on(O.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(I.TrackSubscribed,s,r,n)}).on(A.TrackUnpublished,s=>{this.emit(I.TrackUnpublished,s,n)}).on(A.TrackUnsubscribed,(s,r)=>{this.emit(I.TrackUnsubscribed,s,r,n)}).on(A.TrackMuted,s=>{this.emitWhenConnected(I.TrackMuted,s,n)}).on(A.TrackUnmuted,s=>{this.emitWhenConnected(I.TrackUnmuted,s,n)}).on(A.ParticipantMetadataChanged,s=>{this.emitWhenConnected(I.ParticipantMetadataChanged,s,n)}).on(A.ParticipantNameChanged,s=>{this.emitWhenConnected(I.ParticipantNameChanged,s,n)}).on(A.AttributesChanged,s=>{this.emitWhenConnected(I.ParticipantAttributesChanged,s,n)}).on(A.ConnectionQualityChanged,s=>{this.emitWhenConnected(I.ConnectionQualityChanged,s,n)}).on(A.ParticipantPermissionsChanged,s=>{this.emitWhenConnected(I.ParticipantPermissionsChanged,s,n)}).on(A.TrackSubscriptionStatusChanged,(s,r)=>{this.emitWhenConnected(I.TrackSubscriptionStatusChanged,s,r,n)}).on(A.TrackSubscriptionFailed,(s,r)=>{this.emit(I.TrackSubscriptionFailed,s,n,r)}).on(A.TrackSubscriptionPermissionChanged,(s,r)=>{this.emitWhenConnected(I.TrackSubscriptionPermissionChanged,s,r,n)}),t&&n.updateInfo(t),n}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((n,s)=>(n.push(...s.getTrackPublications()),n),[]),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&&jh(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Se.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,ze.STATE_MISMATCH))):e=0},Nf)}clearConnectionReconcile(){this.connectionReconcileInterval&&Se.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(I.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,n]=e;this.emit(t,...n)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];if(this.state===te.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,n]);else if(this.state===te.Connected)return this.emit(e,...n);return!1}simulateParticipants(e){return p(this,void 0,void 0,function*(){var t,n;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 Vs({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:ce.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new _i({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(I.SignalConnected),this.emit(I.Connected),this.setAndEmitConnectionState(te.Connected),s.video){const o=new Os(w.Kind.Video,new Ht({source:ge.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:qe.AUDIO,name:"video-dummy"}),new pn(s.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Qr(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(o),this.localParticipant.emit(A.LocalTrackPublished,o)}if(s.audio){const o=new Os(w.Kind.Audio,new Ht({source:ge.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:qe.AUDIO}),new fn(s.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Nn(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(o),this.localParticipant.emit(A.LocalTrackPublished,o)}for(let o=0;o<r.count-1;o+=1){let a=new _i({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(o),state:Zn.ACTIVE,tracks:[],joinedAt:ce.parse(Date.now())});const c=this.getOrCreateParticipant(a.identity,a);if(r.video){const d=Qr(160*((n=r.aspectRatios[o%r.aspectRatios.length])!==null&&n!==void 0?n:1),160,!1,!0),l=new Ht({source:ge.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:qe.AUDIO});c.addSubscribedMediaTrack(d,l.sid,new MediaStream([d]),new RTCRtpReceiver),a.tracks=[...a.tracks,l]}if(r.audio){const d=Nn(),l=new Ht({source:ge.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:qe.AUDIO});c.addSubscribedMediaTrack(d,l.sid,new MediaStream([d]),new RTCRtpReceiver),a.tracks=[...a.tracks,l]}c.updateInfo(a)}})}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];if(e!==I.ActiveSpeakersChanged){const r=Cc(n).filter(o=>o!==void 0);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r}))}return super.emit(e,...n)}}ii.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(i=>{i()});function Cc(i){return i.map(e=>{if(e)return Array.isArray(e)?Cc(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Be;(function(i){i[i.IDLE=0]="IDLE",i[i.RUNNING=1]="RUNNING",i[i.SKIPPED=2]="SKIPPED",i[i.SUCCESS=3]="SUCCESS",i[i.FAILED=4]="FAILED"})(Be||(Be={}));class Pt extends et.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Be.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new ii(n.roomOptions),this.connectOptions=n.connectOptions,this.options=n}run(e){return p(this,void 0,void 0,function*(){if(this.status!==Be.IDLE)throw Error("check is running already");this.setStatus(Be.RUNNING);try{yield this.perform()}catch(t){t instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(t.message):this.appendError(t.message))}return yield this.disconnect(),yield new Promise(t=>setTimeout(t,500)),this.status!==Be.SKIPPED&&this.setStatus(this.isSuccess()?Be.SUCCESS:Be.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return p(this,void 0,void 0,function*(){return this.room.state===te.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return p(this,void 0,void 0,function*(){this.room&&this.room.state!==te.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Be.SKIPPED)}switchProtocol(e){return p(this,void 0,void 0,function*(){let t=!1,n=!1;if(this.room.on(I.Reconnecting,()=>{t=!0}),this.room.once(I.Reconnected,()=>{n=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(r=>setTimeout(r,1e3)),!t)return;const s=Date.now()+1e4;for(;Date.now()<s;){if(n)return;yield Ie(100)}throw new Error("Could not reconnect using ".concat(e," protocol after 10 seconds"))})}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return(e=this.room)===null||e===void 0?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class Lf extends Pt{get description(){return"Cloud regions"}perform(){return p(this,void 0,void 0,function*(){const e=new Rs(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],n=new Set;for(let r=0;r<3;r++){const o=yield e.getNextBestRegionUrl();if(!o)break;if(n.has(o))continue;n.add(o);const a=yield this.checkCloudRegion(o);this.appendMessage("".concat(a.region," RTT: ").concat(a.rtt,"ms, duration: ").concat(a.duration,"ms")),t.push(a)}t.sort((r,o)=>(r.duration-o.duration)*.5+(r.rtt-o.rtt)*.5);const s=t[0];this.bestStats=s,this.appendMessage("best Cloud region: ".concat(s.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return p(this,void 0,void 0,function*(){var t,n;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const s=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!s)throw new Error("Region not found");const r=yield this.room.localParticipant.streamText({topic:"test"}),o=1e3,c=1e6/o,d="A".repeat(o),l=Date.now();for(let m=0;m<c;m++)yield r.write(d);yield r.close();const u=Date.now(),h=yield(n=this.room.engine.pcManager)===null||n===void 0?void 0:n.publisher.getStats(),f={region:s,rtt:1e4,duration:u-l};return h==null||h.forEach(m=>{m.type==="candidate-pair"&&m.nominated&&(f.rtt=m.currentRoundTripTime*1e3)}),yield this.disconnect(),f})}}const Hn=1e4;class Uf extends Pt{get description(){return"Connection via UDP vs TCP"}perform(){return p(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):this.appendMessage("best connection quality via udp");const n=this.bestStats;this.appendMessage("upstream bitrate: ".concat((n.bitrateTotal/n.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((n.rttTotal/n.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((n.jitterTotal/n.count*1e3).toFixed(2)," ms")),n.packetsLost>0&&this.appendWarning("packets lost: ".concat((n.packetsLost/n.packetsSent*100).toFixed(2),"%")),n.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((n.qualityLimitationDurations.bandwidth/(Hn/1e3)*100).toFixed(2),"%")),n.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((n.qualityLimitationDurations.cpu/(Hn/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return p(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const n=t.getContext("2d");if(!n)throw new Error("Could not get canvas context");let s=0;const r=()=>{s=(s+1)%360,n.fillStyle="hsl(".concat(s,", 100%, 50%)"),n.fillRect(0,0,t.width,t.height),requestAnimationFrame(r)};r();const a=t.captureStream(30).getVideoTracks()[0],d=(yield this.room.localParticipant.publishTrack(a,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,l={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},u=setInterval(()=>p(this,void 0,void 0,function*(){const h=yield d.getRTCStatsReport();h==null||h.forEach(f=>{f.type==="outbound-rtp"?(l.packetsSent=f.packetsSent,l.qualityLimitationDurations=f.qualityLimitationDurations,l.bitrateTotal+=f.targetBitrate,l.count++):f.type==="remote-inbound-rtp"&&(l.packetsLost=f.packetsLost,l.rttTotal+=f.roundTripTime,l.jitterTotal+=f.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,Hn)),clearInterval(u),a.stop(),t.remove(),yield this.disconnect(),l})}}function Sc(i){return p(this,void 0,void 0,function*(){var e,t;i??(i={}),(e=i.audio)!==null&&e!==void 0||(i.audio={deviceId:"default"}),(t=i.video)!==null&&t!==void 0||(i.video={deviceId:"default"});const{audioProcessor:n,videoProcessor:s}=Qs(i),r=dc(i,hc,fc),o=Cn(r),a=navigator.mediaDevices.getUserMedia(o);i.audio&&(Te.userMediaPromiseMap.set("audioinput",a),a.catch(()=>Te.userMediaPromiseMap.delete("audioinput"))),i.video&&(Te.userMediaPromiseMap.set("videoinput",a),a.catch(()=>Te.userMediaPromiseMap.delete("videoinput")));const c=yield a;return Promise.all(c.getTracks().map(d=>p(this,void 0,void 0,function*(){const l=d.kind==="audio";l?r.audio:r.video;let u;const h=l?o.audio:o.video;typeof h!="boolean"&&(u=h);const f=d.getSettings().deviceId;u!=null&&u.deviceId&&Ct(u.deviceId)!==f?u.deviceId=f:u||(u={deviceId:f});const m=gc(d,u);return m.kind===w.Kind.Video?m.source=w.Source.Camera:m.kind===w.Kind.Audio&&(m.source=w.Source.Microphone),m.mediaStream=c,dt(m)&&n?yield m.setProcessor(n):ni(m)&&s&&(yield m.setProcessor(s)),m})))})}function jf(i){return p(this,void 0,void 0,function*(){return(yield Sc({audio:!1,video:i}))[0]})}function Ff(i){return p(this,void 0,void 0,function*(){return(yield Sc({audio:i,video:!1}))[0]})}class Bf extends Pt{get description(){return"Can publish audio"}perform(){return p(this,void 0,void 0,function*(){var e;const t=yield this.connect(),n=yield Ff();if(yield lc(n,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(n),yield new Promise(a=>setTimeout(a,3e3));const r=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let o=0;if(r.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="audio"||!a.kind&&a.mediaType==="audio")&&(o=a.packetsSent)}),o===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(o," audio packets"))})}}class Vf extends Pt{get description(){return"Can publish video"}perform(){return p(this,void 0,void 0,function*(){var e;const t=yield this.connect(),n=yield jf();yield this.checkForVideo(n.mediaStreamTrack),t.localParticipant.publishTrack(n),yield new Promise(o=>setTimeout(o,5e3));const s=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let r=0;if(s.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="video"||!o.kind&&o.mediaType==="video")&&(r+=o.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))})}checkForVideo(e){return p(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const n=document.createElement("video");n.srcObject=t,n.muted=!0,yield new Promise(s=>{n.onplay=()=>{setTimeout(()=>{var r,o,a,c;const d=document.createElement("canvas"),l=e.getSettings(),u=(o=(r=l.width)!==null&&r!==void 0?r:n.videoWidth)!==null&&o!==void 0?o:1280,h=(c=(a=l.height)!==null&&a!==void 0?a:n.videoHeight)!==null&&c!==void 0?c:720;d.width=u,d.height=h;const f=d.getContext("2d");f.drawImage(n,0,0);const g=f.getImageData(0,0,d.width,d.height).data;let T=!0;for(let C=0;C<g.length;C+=4)if(g[C]!==0||g[C+1]!==0||g[C+2]!==0){T=!1;break}T?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),s()},1e3)},n.play()}),n.remove()})}}class qf extends Pt{get description(){return"Resuming connection after interruption"}perform(){return p(this,void 0,void 0,function*(){var e;const t=yield this.connect();let n=!1,s=!1,r;const o=new Promise(d=>{setTimeout(d,5e3),r=d}),a=()=>{n=!0};t.on(I.SignalReconnecting,a).on(I.Reconnecting,a).on(I.Reconnected,()=>{s=!0,r(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const c=t.engine.client.onClose;if(c&&c(""),yield o,n){if(!s||t.state!==te.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 $f extends Pt{get description(){return"Can connect via TURN"}perform(){return p(this,void 0,void 0,function*(){var e,t;const n=new Ys,s=yield n.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let r=!1,o=!1,a=!1;for(let c of s.iceServers)for(let d of c.urls)d.startsWith("turn:")?(o=!0,a=!0):d.startsWith("turns:")&&(o=!0,a=!0,r=!0),d.startsWith("stun:")&&(a=!0);a?o&&!r&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield n.close(),!((t=(e=this.connectOptions)===null||e===void 0?void 0:e.rtcConfig)===null||t===void 0)&&t.iceServers||o?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 Hf extends Pt{get description(){return"Establishing WebRTC connection"}perform(){return p(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(I.SignalConnected,()=>{const n=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(s,r)=>{if(s.candidate){const o=new RTCIceCandidate(s);let a="".concat(o.protocol," ").concat(o.address,":").concat(o.port," ").concat(o.type);o.address&&(zf(o.address)?a+=" (private)":o.protocol==="tcp"&&o.tcpType==="passive"?(e=!0,a+=" (passive)"):o.protocol==="udp"&&(t=!0)),this.appendMessage(a)}n&&n(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(),W.info("now the room is connected")}catch(n){throw this.appendWarning("ports need to be open on firewall in order to connect."),n}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 zf(i){const e=i.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 Gf extends Pt{get description(){return"Connecting to signal connection via WebSocket"}perform(){return p(this,void 0,void 0,function*(){var e,t,n;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let s=new Ys;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)===ua.Cloud&&(!((t=r.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((n=r.serverInfo)===null||n===void 0?void 0:n.region)),yield s.close()})}}class ep extends et.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=n}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:Be.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!==Be.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return p(this,void 0,void 0,function*(){const t=this.getNextCheckId(),n=new e(this.url,this.token,this.options),s=o=>{this.updateCheck(t,o)};n.on("update",s);const r=yield n.run();return n.off("update",s),r})}checkWebsocket(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Gf)})}checkWebRTC(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Hf)})}checkTURN(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck($f)})}checkReconnect(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(qf)})}checkPublishAudio(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Bf)})}checkPublishVideo(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Vf)})}checkConnectionProtocol(){return p(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(Uf);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Lf)})}}function Wf(){const i=document.createElement("style");return i.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=`
|
|
56
49
|
* {
|
|
57
50
|
cursor: crosshair !important;
|
|
58
51
|
}
|
|
59
|
-
`,
|
|
52
|
+
`,e}function Y(){let e=document.createElement(`style`);return e.textContent=`
|
|
60
53
|
* {
|
|
61
54
|
pointer-events: none !important;
|
|
62
55
|
user-select: none !important;
|
|
63
56
|
}
|
|
64
|
-
`,i}function Jf(i){jc(i,"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 go(i,e,t){const n=i.slice();return n[31]=e[t],n[32]=e,n[33]=t,n}function vo(i){let e,t=[],n=new Map,s=ur(Object.values(i[2]));const r=o=>o[31].id;for(let o=0;o<s.length;o+=1){let a=go(i,s,o),c=r(a);n.set(c,t[o]=yo(c,a))}return{c(){e=Ve("div");for(let o=0;o<t.length;o+=1)t[o].c();K(e,"id","users-container"),K(e,"class","svelte-10y2zdk")},m(o,a){Ot(o,e,a);for(let c=0;c<t.length;c+=1)t[c]&&t[c].m(e,null)},p(o,a){a[0]&30&&(s=ur(Object.values(o[2])),t=Zc(t,a,r,1,o,s,n,e,Xc,yo,null,go))},d(o){o&&kt(e);for(let a=0;a<t.length;a+=1)t[a].d()}}}function yo(i,e){let t,n,s,r,o,a,c,d,l=e[31],u,h,f=e[31].name+"",m,g,T,C,M,j,k,y,_;const R=()=>e[15](c,l),D=()=>e[15](null,l);return{key:i,first:null,c(){t=Ve("div"),n=dr("svg"),s=dr("path"),r=ui(),o=Ve("div"),a=Ve("div"),c=Ve("video"),u=ui(),h=Ve("div"),m=Ms(f),T=ui(),C=Ve("div"),j=ui(),K(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"),K(n,"width","23"),K(n,"viewBox","0 0 27 24"),K(n,"fill","currentColor"),K(n,"aria-hidden","true"),K(n,"xmlns","http://www.w3.org/2000/svg"),K(n,"class","cursor svelte-10y2zdk"),K(c,"id",d=`user-video-${e[31].id}`),K(c,"class","svelte-10y2zdk"),K(a,"id","video-container"),K(a,"class","svelte-10y2zdk"),K(h,"class","user-name svelte-10y2zdk"),K(o,"class","user-label svelte-10y2zdk"),K(o,"data-cameraenabled",g=e[31].camera_enabled),K(C,"class","halo svelte-10y2zdk"),K(C,"data-show",M=(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),K(t,"id",k="user-"+e[31].id),K(t,"class","user svelte-10y2zdk"),K(t,"data-isself",y=e[31].id==e[1].id),K(t,"data-isfocusmode",_=e[31].is_f_key_down),We(t,"--color",e[31].color),We(t,"--color25",e[31].color+"25"),We(t,"--color75",e[31].color+"75"),We(t,"--x",parseFloat(e[31].x)+"vw"),We(t,"--y",parseFloat(e[31].y)+"vh"),this.first=t},m(F,U){Ot(F,t,U),Ae(t,n),Ae(n,s),Ae(t,r),Ae(t,o),Ae(o,a),Ae(a,c),R(),Ae(o,u),Ae(o,h),Ae(h,m),Ae(t,T),Ae(t,C),Ae(t,j)},p(F,U){e=F,U[0]&4&&d!==(d=`user-video-${e[31].id}`)&&K(c,"id",d),l!==e[31]&&(D(),l=e[31],R()),U[0]&4&&f!==(f=e[31].name+"")&&$c(m,f),U[0]&4&&g!==(g=e[31].camera_enabled)&&K(o,"data-cameraenabled",g),U[0]&22&&M!==(M=(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)&&K(C,"data-show",M),U[0]&4&&k!==(k="user-"+e[31].id)&&K(t,"id",k),U[0]&6&&y!==(y=e[31].id==e[1].id)&&K(t,"data-isself",y),U[0]&4&&_!==(_=e[31].is_f_key_down)&&K(t,"data-isfocusmode",_),U[0]&4&&We(t,"--color",e[31].color),U[0]&4&&We(t,"--color25",e[31].color+"25"),U[0]&4&&We(t,"--color75",e[31].color+"75"),U[0]&4&&We(t,"--x",parseFloat(e[31].x)+"vw"),U[0]&4&&We(t,"--y",parseFloat(e[31].y)+"vh")},d(F){F&&kt(t),D()}}}function bo(i){let e;return{c(){e=Ve("div"),K(e,"id","focus_mode_dialog"),K(e,"role","dialog"),K(e,"class","svelte-10y2zdk")},m(t,n){Ot(t,e,n)},d(t){t&&kt(e)}}}function Qf(i){let e,t,n,s=i[1]&&i[2]&&vo(i),r=i[0]&&bo();return{c(){e=Ve("div"),s&&s.c(),t=ui(),r&&r.c(),n=Vc(),K(e,"id","liveroom-client-element"),K(e,"class","svelte-10y2zdk")},m(o,a){Ot(o,e,a),s&&s.m(e,null),Ot(o,t,a),r&&r.m(o,a),Ot(o,n,a)},p(o,a){o[1]&&o[2]?s?s.p(o,a):(s=vo(o),s.c(),s.m(e,null)):s&&(s.d(1),s=null),o[0]?r||(r=bo(),r.c(),r.m(n.parentNode,n)):r&&(r.d(1),r=null)},i:Ti,o:Ti,d(o){o&&(kt(e),kt(t),kt(n)),s&&s.d(),r&&r.d(o)}}}function xs(i,e){if(i.tagName==="BODY")return window;if(As(i))return i;const{overflowY:t,overflowX:n}=getComputedStyle(i);return e==="vertical"&&["auto","scroll"].includes(t)&&i.scrollHeight>i.clientHeight||e==="horizontal"&&["auto","scroll"].includes(n)&&i.scrollWidth>i.clientWidth?i:i.parentElement?xs(i.parentElement,e):window}function As(i){return i.tagName==="ION-CONTENT"&&typeof i.scrollByPoint=="function"}function Yf(i,e,t){let{version:n}=e,{url:s}=e,{room_id:r}=e,{room_token:o}=e,{user_name:a=void 0}=e,{user_color:c=void 0}=e,d,l,u=!1,h=!1,f=Wf(),m=Kf(),g,T,C,M,j={},k;zc(async()=>{console.log(`[Liveroom] Starting in room '${r}' (user name: '${a}')... (v${n})`),_()}),Gc(()=>{R(),si(),t(0,h=!1)});async function y(){if(console.log("[LiveKit] Beginning setup..."),t(11,l=new ii({dynacast:!0}).on(I.TrackSubscribed,async(L,be,ke)=>{switch(console.log("[LiveKit] Track Subscribed",L,be,ke),console.table({identity:ke.identity,source:be.source}),be.source){case w.Source.Camera:{const se=j[ke.identity];se&&(console.log(`[LiveKit] Attaching user camera (identity ${ke.identity})`),L.attach(se));break}}})),console.log("[LiveKit] Created room",l.name),!C)throw new Error("LiveKit websocket URL not set");if(!M)throw new Error("LiveKit token not set");console.log(`[LiveKit] Connecting to '${C}'...`),await l.connect(C,M,{autoSubscribe:!0}),console.log("[LiveKit] Connected to room",l.name)}function _(){console.log(`[Liveroom] Starting session on room ${r}`),d=new al({url:s,topic:`liveroom-livestate:rooms:${r}`,params:{room_id:r,room_token:o,user_name:a,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:(L,be,ke)=>{switch(L){case"error":console.error("Error in socket",be,ke);break}}}}),d.addEventListener("wheel-from-another-user",({detail:{delta_x:L,delta_y:be,x:ke,y:se}})=>{const Ee=parseInt(L),Ut=parseInt(be),ve=new WheelEvent("wheel",{view:window,bubbles:!0,cancelable:!0,clientX:window.innerWidth*parseFloat(ke)/100,clientY:window.innerHeight*parseFloat(se)/100,deltaX:Ee,deltaY:Ut,deltaMode:0}),Ai=document.head.contains(m);Ai&&document.head.removeChild(m);const jt=document.elementFromPoint(ve.clientX,ve.clientY);if(Ai&&document.head.appendChild(m),jt instanceof HTMLElement||jt instanceof SVGElement)if(Math.abs(Ut)>=Math.abs(Ee)){const tt=xs(jt,"vertical");As(tt)?tt.scrollByPoint(0,Ut,0):tt.scrollBy({top:Ut,left:0,behavior:"instant"})}else{const tt=xs(jt,"horizontal");As(tt)?tt.scrollByPoint(Ee,0,0):tt.scrollBy({top:0,left:Ee,behavior:"instant"})}}),d.addEventListener("click-from-another-user",({detail:{x:L,y:be}})=>{const ke=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!0,clientX:window.innerWidth*parseFloat(L)/100,clientY:window.innerHeight*parseFloat(be)/100}),se=document.head.contains(m);se&&document.head.removeChild(m);const Ee=document.elementFromPoint(ke.clientX,ke.clientY);Ee==null||Ee.dispatchEvent(ke),se&&document.head.appendChild(m)}),d.addEventListener("livestate-change",({detail:{state:L}})=>{var be,ke;(be=L==null?void 0:L.me)!=null&&be.name&&L.me.name!=(g==null?void 0:g.name)&&(sessionStorage==null||sessionStorage.setItem(ar.SESSION_STORAGE_KEY_USER_NAME,L.me.name)),(ke=L==null?void 0:L.me)!=null&&ke.color&&L.me.color!=(g==null?void 0:g.color)&&(sessionStorage==null||sessionStorage.setItem(ar.SESSION_STORAGE_KEY_USER_COLOR,L.me.color)),t(5,r=L.room_id),t(1,g=L.me),t(2,T=L.users),t(13,C=L.livekit_ws_url),t(14,M=L.livekit_token)}),d.connect(),window.addEventListener("mousemove",D),window.addEventListener("mousedown",F),window.addEventListener("mouseup",U),window.addEventListener("keydown",ee),window.addEventListener("keyup",Oe),window.addEventListener("resize",Ue)}function R(){window.removeEventListener("resize",Ue),window.removeEventListener("keyup",Oe),window.removeEventListener("keydown",ee),window.removeEventListener("mouseup",U),window.removeEventListener("mousedown",F),window.removeEventListener("mousemove",D),d==null||d.disconnect(),d=void 0,l==null||l.disconnect(),t(11,l=void 0)}function D(L){d&&(g!=null&&g.id)&&d.dispatchEvent(new CustomEvent("mouse_move",{detail:{user_id:g.id,x:Number(L.clientX/window.innerWidth*100).toFixed(2),y:Number(L.clientY/window.innerHeight*100).toFixed(2)}}))}function F(){d&&(g!=null&&g.id)&&d.dispatchEvent(new CustomEvent("mouse_down",{detail:{user_id:g.id}}))}function U(){d&&(g!=null&&g.id)&&d.dispatchEvent(new CustomEvent("mouse_up",{detail:{user_id:g.id}}))}const $=["Shift"];function ee(L){!L.repeat&&$.includes(L.key)&&d&&(g!=null&&g.id)&&d.dispatchEvent(new CustomEvent("key_down",{detail:{key:L.key,user_id:g.id}}))}function Oe(L){$.includes(L.key)&&d&&(g!=null&&g.id)&&d.dispatchEvent(new CustomEvent("key_up",{detail:{key:L.key,user_id:g.id}}))}function Ue(){setTimeout(()=>{d&&(g!=null&&g.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:g.id}}))},100)}function Lt(){document.head.appendChild(f),document.head.appendChild(m),t(12,u=!0)}function si(){document.head.removeChild(f),document.head.removeChild(m),t(12,u=!1)}function xi(L,be){zn[L?"unshift":"push"](()=>{j[be.id]=L,t(3,j)})}return i.$$set=L=>{"version"in L&&t(6,n=L.version),"url"in L&&t(7,s=L.url),"room_id"in L&&t(5,r=L.room_id),"room_token"in L&&t(8,o=L.room_token),"user_name"in L&&t(9,a=L.user_name),"user_color"in L&&t(10,c=L.user_color)},i.$$.update=()=>{i.$$.dirty[0]&26630&&!l&&g&&T&&C&&M&&y(),i.$$.dirty[0]&4&&t(4,k=Object.keys(T||{}).length),i.$$.dirty[0]&4100&&!u&&T&&Object.values(T).some(L=>L.type=="admin"&&L.is_b_key_down)&&Lt(),i.$$.dirty[0]&4100&&u&&T&&Object.values(T).filter(L=>L.type=="admin").every(L=>!L.is_b_key_down)&&si(),i.$$.dirty[0]&5&&!h&&T&&Object.values(T).some(L=>L.type=="admin"&&L.is_f_key_down)&&t(0,h=!0),i.$$.dirty[0]&5&&h&&T&&Object.values(T).filter(L=>L.type=="admin").every(L=>!L.is_f_key_down)&&t(0,h=!1)},[h,g,T,j,k,r,n,s,o,a,c,l,u,C,M,xi]}class Ec extends rd{constructor(e){super(),nd(this,e,Yf,Qf,Lc,{version:6,url:7,room_id:5,room_token:8,user_name:9,user_color:10},Jf,[-1,-1])}get version(){return this.$$.ctx[6]}set version(e){this.$$set({version:e}),mt()}get url(){return this.$$.ctx[7]}set url(e){this.$$set({url:e}),mt()}get room_id(){return this.$$.ctx[5]}set room_id(e){this.$$set({room_id:e}),mt()}get room_token(){return this.$$.ctx[8]}set room_token(e){this.$$set({room_token:e}),mt()}get user_name(){return this.$$.ctx[9]}set user_name(e){this.$$set({user_name:e}),mt()}get user_color(){return this.$$.ctx[10]}set user_color(e){this.$$set({user_color:e}),mt()}}customElements.define("liveroom-client-element",sd(Ec,{version:{},url:{},room_id:{},room_token:{},user_name:{},user_color:{}},[],[],!0));module.exports=Ec;
|
|
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;
|