openclaw-liveavatar 1.0.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.
Files changed (122) hide show
  1. package/.next/BUILD_ID +1 -0
  2. package/.next/app-build-manifest.json +42 -0
  3. package/.next/app-path-routes-manifest.json +6 -0
  4. package/.next/build-manifest.json +33 -0
  5. package/.next/cache/.previewinfo +1 -0
  6. package/.next/cache/.rscinfo +1 -0
  7. package/.next/cache/.tsbuildinfo +1 -0
  8. package/.next/cache/chrome-devtools-workspace-uuid +1 -0
  9. package/.next/cache/next-devtools-config.json +1 -0
  10. package/.next/cache/webpack/client-production/0.pack +0 -0
  11. package/.next/cache/webpack/client-production/1.pack +0 -0
  12. package/.next/cache/webpack/client-production/2.pack +0 -0
  13. package/.next/cache/webpack/client-production/3.pack +0 -0
  14. package/.next/cache/webpack/client-production/4.pack +0 -0
  15. package/.next/cache/webpack/client-production/index.pack +0 -0
  16. package/.next/cache/webpack/client-production/index.pack.old +0 -0
  17. package/.next/cache/webpack/edge-server-production/0.pack +0 -0
  18. package/.next/cache/webpack/edge-server-production/index.pack +0 -0
  19. package/.next/cache/webpack/server-production/0.pack +0 -0
  20. package/.next/cache/webpack/server-production/index.pack +0 -0
  21. package/.next/diagnostics/build-diagnostics.json +6 -0
  22. package/.next/diagnostics/framework.json +1 -0
  23. package/.next/export-marker.json +6 -0
  24. package/.next/images-manifest.json +58 -0
  25. package/.next/next-minimal-server.js.nft.json +1 -0
  26. package/.next/next-server.js.nft.json +1 -0
  27. package/.next/package.json +1 -0
  28. package/.next/prerender-manifest.json +61 -0
  29. package/.next/react-loadable-manifest.json +1 -0
  30. package/.next/required-server-files.json +320 -0
  31. package/.next/routes-manifest.json +53 -0
  32. package/.next/server/app/_not-found/page.js +5 -0
  33. package/.next/server/app/_not-found/page.js.nft.json +1 -0
  34. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -0
  35. package/.next/server/app/_not-found.html +4 -0
  36. package/.next/server/app/_not-found.meta +8 -0
  37. package/.next/server/app/_not-found.rsc +15 -0
  38. package/.next/server/app/api/get-avatars/route.js +1 -0
  39. package/.next/server/app/api/get-avatars/route.js.nft.json +1 -0
  40. package/.next/server/app/api/get-avatars/route_client-reference-manifest.js +1 -0
  41. package/.next/server/app/api/start-session/route.js +1 -0
  42. package/.next/server/app/api/start-session/route.js.nft.json +1 -0
  43. package/.next/server/app/api/start-session/route_client-reference-manifest.js +1 -0
  44. package/.next/server/app/index.html +4 -0
  45. package/.next/server/app/index.meta +7 -0
  46. package/.next/server/app/index.rsc +16 -0
  47. package/.next/server/app/page.js +9 -0
  48. package/.next/server/app/page.js.nft.json +1 -0
  49. package/.next/server/app/page_client-reference-manifest.js +1 -0
  50. package/.next/server/app-paths-manifest.json +6 -0
  51. package/.next/server/chunks/361.js +9 -0
  52. package/.next/server/chunks/611.js +6 -0
  53. package/.next/server/chunks/873.js +22 -0
  54. package/.next/server/functions-config-manifest.json +4 -0
  55. package/.next/server/interception-route-rewrite-manifest.js +1 -0
  56. package/.next/server/middleware-build-manifest.js +1 -0
  57. package/.next/server/middleware-manifest.json +6 -0
  58. package/.next/server/middleware-react-loadable-manifest.js +1 -0
  59. package/.next/server/next-font-manifest.js +1 -0
  60. package/.next/server/next-font-manifest.json +1 -0
  61. package/.next/server/pages/404.html +4 -0
  62. package/.next/server/pages/500.html +1 -0
  63. package/.next/server/pages/_app.js +1 -0
  64. package/.next/server/pages/_app.js.nft.json +1 -0
  65. package/.next/server/pages/_document.js +1 -0
  66. package/.next/server/pages/_document.js.nft.json +1 -0
  67. package/.next/server/pages/_error.js +19 -0
  68. package/.next/server/pages/_error.js.nft.json +1 -0
  69. package/.next/server/pages-manifest.json +6 -0
  70. package/.next/server/server-reference-manifest.js +1 -0
  71. package/.next/server/server-reference-manifest.json +1 -0
  72. package/.next/server/webpack-runtime.js +1 -0
  73. package/.next/static/chunks/144d3bae-37bcc55d23f188ee.js +1 -0
  74. package/.next/static/chunks/255-35bf8c00c5dde345.js +1 -0
  75. package/.next/static/chunks/336-a66237a0a1db954a.js +1 -0
  76. package/.next/static/chunks/4bd1b696-c023c6e3521b1417.js +1 -0
  77. package/.next/static/chunks/app/_not-found/page-dfc6e5d8e6c6203c.js +1 -0
  78. package/.next/static/chunks/app/api/get-avatars/route-8017e1cff542d5d0.js +1 -0
  79. package/.next/static/chunks/app/api/start-session/route-8017e1cff542d5d0.js +1 -0
  80. package/.next/static/chunks/app/layout-ff675313cc8f8fcf.js +1 -0
  81. package/.next/static/chunks/app/page-9e4b703722bef650.js +1 -0
  82. package/.next/static/chunks/framework-de98b93a850cfc71.js +1 -0
  83. package/.next/static/chunks/main-1a0dcce460eb61ce.js +1 -0
  84. package/.next/static/chunks/main-app-e7f1007edc7ad7e1.js +1 -0
  85. package/.next/static/chunks/pages/_app-7d307437aca18ad4.js +1 -0
  86. package/.next/static/chunks/pages/_error-cb2a52f75f2162e2.js +1 -0
  87. package/.next/static/chunks/polyfills-42372ed130431b0a.js +1 -0
  88. package/.next/static/chunks/webpack-4a462cecab786e93.js +1 -0
  89. package/.next/static/css/bfd73afa11897439.css +3 -0
  90. package/.next/static/v_GdCj8lVweDVhmIhhEcM/_buildManifest.js +1 -0
  91. package/.next/static/v_GdCj8lVweDVhmIhhEcM/_ssgManifest.js +1 -0
  92. package/.next/trace +2 -0
  93. package/.next/types/app/api/get-avatars/route.ts +347 -0
  94. package/.next/types/app/api/start-session/route.ts +347 -0
  95. package/.next/types/app/layout.ts +84 -0
  96. package/.next/types/app/page.ts +84 -0
  97. package/.next/types/cache-life.d.ts +141 -0
  98. package/.next/types/package.json +1 -0
  99. package/.next/types/routes.d.ts +74 -0
  100. package/.next/types/validator.ts +88 -0
  101. package/README.md +241 -0
  102. package/app/api/config.ts +18 -0
  103. package/app/api/get-avatars/route.ts +117 -0
  104. package/app/api/start-session/route.ts +95 -0
  105. package/app/globals.css +3 -0
  106. package/app/layout.tsx +37 -0
  107. package/app/page.tsx +9 -0
  108. package/bin/cli.js +100 -0
  109. package/package.json +66 -0
  110. package/src/components/LiveAvatarSession.tsx +825 -0
  111. package/src/components/OpenClawDemo.tsx +399 -0
  112. package/src/gateway/client.ts +522 -0
  113. package/src/gateway/types.ts +83 -0
  114. package/src/liveavatar/context.tsx +750 -0
  115. package/src/liveavatar/index.ts +6 -0
  116. package/src/liveavatar/types.ts +10 -0
  117. package/src/liveavatar/useAvatarActions.ts +41 -0
  118. package/src/liveavatar/useChatHistory.ts +7 -0
  119. package/src/liveavatar/useSession.ts +37 -0
  120. package/src/liveavatar/useTextChat.ts +32 -0
  121. package/src/liveavatar/useVoiceChat.ts +70 -0
  122. package/tsconfig.json +40 -0
@@ -0,0 +1 @@
1
+ "use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[501],{3094:(e,t,i)=>{let n,r;i.d(t,{CC:()=>n9,GI:()=>P,KN:()=>B,P6:()=>rl,Wv:()=>ac,YI:()=>w,_N:()=>F,gF:()=>ri,qi:()=>rd,rV:()=>an,u9:()=>S});var s,a,o,c,l,d,u,h,p,m,g,f,v,b,k,y,T,C,S,w,E,P,R,I,O,D,x,_,M,A,N,L,U,j,F,B,V,q=i(5704),H=Object.defineProperty,G=(e,t,i)=>((e,t,i)=>t in e?H(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class W{constructor(){G(this,"_locking"),G(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;let t=new Promise(t=>e=()=>{this._locks-=1,t()}),i=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),i}}function K(e,t){if(!e)throw Error(t)}function z(e){if("number"!=typeof e)throw Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>0x7fffffff||e<-0x80000000)throw Error("invalid int 32: "+e)}function J(e){if("number"!=typeof e)throw Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>0xffffffff||e<0)throw Error("invalid uint 32: "+e)}function Q(e){if("number"!=typeof e)throw Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>34028234663852886e22||e<-34028234663852886e22))throw Error("invalid float 32: "+e)}let Y=Symbol("@bufbuild/protobuf/enum-type");function X(e,t,i,n){e[Y]=Z(t,i.map(t=>({no:t.no,name:t.name,localName:e[t.no]})))}function Z(e,t,i){let n=Object.create(null),r=Object.create(null),s=[];for(let e of t){let t=$(e);s.push(t),n[e.name]=t,r[e.no]=t}return{typeName:e,values:s,findName:e=>n[e],findNumber:e=>r[e]}}function $(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class ee{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){let i=this.getType().runtime.bin,n=i.makeReadOptions(t);return i.readMessage(this,n.readerFactory(e),e.byteLength,n),this}fromJson(e,t){let i=this.getType(),n=i.runtime.json,r=n.makeReadOptions(t);return n.readMessage(i,e,r,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(e){throw Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(e instanceof Error?e.message:String(e)))}return this.fromJson(i,t)}toBinary(e){let t=this.getType().runtime.bin,i=t.makeWriteOptions(e),n=i.writerFactory();return t.writeMessage(this,n,i),n.finish()}toJson(e){let t=this.getType().runtime.json,i=t.makeWriteOptions(e);return t.writeMessage(this,i)}toJsonString(e){var t;return JSON.stringify(this.toJson(e),null,null!=(t=null==e?void 0:e.prettySpaces)?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function et(){let e=0,t=0;for(let i=0;i<28;i+=7){let n=this.buf[this.pos++];if(e|=(127&n)<<i,(128&n)==0)return this.assertBounds(),[e,t]}let i=this.buf[this.pos++];if(e|=(15&i)<<28,t=(112&i)>>4,(128&i)==0)return this.assertBounds(),[e,t];for(let i=3;i<=31;i+=7){let n=this.buf[this.pos++];if(t|=(127&n)<<i,(128&n)==0)return this.assertBounds(),[e,t]}throw Error("invalid varint")}function ei(e,t,i){for(let n=0;n<28;n+=7){let r=e>>>n,s=r>>>7!=0||0!=t,a=(s?128|r:r)&255;if(i.push(a),!s)return}let n=e>>>28&15|(7&t)<<4,r=t>>3!=0;if(i.push((r?128|n:n)&255),r){for(let e=3;e<31;e+=7){let n=t>>>e,r=n>>>7!=0,s=(r?128|n:n)&255;if(i.push(s),!r)return}i.push(t>>>31&1)}}function en(e){let t="-"===e[0];t&&(e=e.slice(1));let i=0,n=0;function r(t,r){let s=Number(e.slice(t,r));n*=1e6,(i=1e6*i+s)>=0x100000000&&(n+=i/0x100000000|0,i%=0x100000000)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),t?ea(i,n):es(i,n)}function er(e,t){if({lo:e,hi:t}={lo:e>>>0,hi:t>>>0},t<=2097151)return String(0x100000000*t+e);let i=0xffffff&e,n=(e>>>24|t<<8)&0xffffff,r=t>>16&65535,s=i+6777216*n+6710656*r,a=n+8147497*r,o=2*r;return s>=1e7&&(a+=Math.floor(s/1e7),s%=1e7),a>=1e7&&(o+=Math.floor(a/1e7),a%=1e7),o.toString()+eo(a)+eo(s)}function es(e,t){return{lo:0|e,hi:0|t}}function ea(e,t){return t=~t,e?e=~e+1:t+=1,es(e,t)}let eo=e=>{let t=String(e);return"0000000".slice(t.length)+t};function ec(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let i=0;i<9;i++)t.push(127&e|128),e>>=7;t.push(1)}}function el(){let e=this.buf[this.pos++],t=127&e;if((128&e)==0||(t|=(127&(e=this.buf[this.pos++]))<<7,(128&e)==0)||(t|=(127&(e=this.buf[this.pos++]))<<14,(128&e)==0)||(t|=(127&(e=this.buf[this.pos++]))<<21,(128&e)==0))return this.assertBounds(),t;t|=(15&(e=this.buf[this.pos++]))<<28;for(let t=5;(128&e)!=0&&t<10;t++)e=this.buf[this.pos++];if((128&e)!=0)throw Error("invalid varint");return this.assertBounds(),t>>>0}let ed=function(){let e=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64&&("object"!=typeof q||"object"!=typeof q.env||"1"!==q.env.BUF_BIGINT_DISABLE)){let t=BigInt("-9223372036854775808"),i=BigInt("9223372036854775807"),n=BigInt("0"),r=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){let n="bigint"==typeof e?e:BigInt(e);if(n>i||n<t)throw Error("int64 invalid: ".concat(e));return n},uParse(e){let t="bigint"==typeof e?e:BigInt(e);if(t>r||t<n)throw Error("uint64 invalid: ".concat(e));return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigInt64(0,!0)),uDec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigUint64(0,!0))}}let t=e=>K(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),i=e=>K(/^[0-9]+$/.test(e),"uint64 invalid: ".concat(e));return{zero:"0",supported:!1,parse:e=>("string"!=typeof e&&(e=e.toString()),t(e),e),uParse:e=>("string"!=typeof e&&(e=e.toString()),i(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),t(e),en(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),i(e),en(e)),dec:(e,t)=>(function(e,t){let i=es(e,t),n=0x80000000&i.hi;n&&(i=ea(i.lo,i.hi));let r=er(i.lo,i.hi);return n?"-"+r:r})(e,t),uDec:(e,t)=>er(e,t)}}();function eu(e,t,i){if(t===i)return!0;if(e==o.BYTES){if(!(t instanceof Uint8Array)||!(i instanceof Uint8Array)||t.length!==i.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==i[e])return!1;return!0}switch(e){case o.UINT64:case o.FIXED64:case o.INT64:case o.SFIXED64:case o.SINT64:return t==i}return!1}function eh(e,t){switch(e){case o.BOOL:return!1;case o.UINT64:case o.FIXED64:case o.INT64:case o.SFIXED64:case o.SINT64:return 0==t?ed.zero:"0";case o.DOUBLE:case o.FLOAT:return 0;case o.BYTES:return new Uint8Array(0);case o.STRING:return"";default:return 0}}function ep(e,t){switch(e){case o.BOOL:return!1===t;case o.STRING:return""===t;case o.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}!function(e){e[e.DOUBLE=1]="DOUBLE",e[e.FLOAT=2]="FLOAT",e[e.INT64=3]="INT64",e[e.UINT64=4]="UINT64",e[e.INT32=5]="INT32",e[e.FIXED64=6]="FIXED64",e[e.FIXED32=7]="FIXED32",e[e.BOOL=8]="BOOL",e[e.STRING=9]="STRING",e[e.BYTES=12]="BYTES",e[e.UINT32=13]="UINT32",e[e.SFIXED32=15]="SFIXED32",e[e.SFIXED64=16]="SFIXED64",e[e.SINT32=17]="SINT32",e[e.SINT64=18]="SINT64"}(o||(o={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"}(c||(c={})),function(e){e[e.Varint=0]="Varint",e[e.Bit64=1]="Bit64",e[e.LengthDelimited=2]="LengthDelimited",e[e.StartGroup=3]="StartGroup",e[e.EndGroup=4]="EndGroup",e[e.Bit32=5]="Bit32"}(l||(l={}));class em{constructor(e){this.stack=[],this.textEncoder=null!=e?e:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),i=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],i),i+=this.chunks[e].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 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(J(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return z(e),ec(e,this.buf),this}bool(e){return this.buf.push(+!!e),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){Q(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){J(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){z(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return z(e),ec(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=ed.enc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=ed.uEnc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=ed.enc(e);return ei(t.lo,t.hi,this.buf),this}sint64(e){let t=ed.enc(e),i=t.hi>>31;return ei(t.lo<<1^i,(t.hi<<1|t.lo>>>31)^i,this.buf),this}uint64(e){let t=ed.uEnc(e);return ei(t.lo,t.hi,this.buf),this}}class eg{constructor(e,t){this.varint64=et,this.uint32=el,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=null!=t?t:new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=7&e;if(t<=0||i<0||i>5)throw Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case l.Varint:for(;128&this.buf[this.pos++];);break;case l.Bit64:this.pos+=4;case l.Bit32:this.pos+=4;break;case l.LengthDelimited:let n=this.uint32();this.pos+=n;break;case l.StartGroup:for(;;){let[e,i]=this.tag();if(i===l.EndGroup){if(void 0!==t&&e!==t)throw Error("invalid end group tag");break}this.skip(i,e)}break;default:throw Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return ed.dec(...this.varint64())}uint64(){return ed.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(1&e);return e=(e>>>1|(1&t)<<31)^i,t=t>>>1^i,ed.dec(e,t)}bool(){let[e,t]=this.varint64();return 0!==e||0!==t}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return ed.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return ed.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 ef(e){let t=e.field.localName,i=Object.create(null);return i[t]=function(e){let t=e.field;if(t.repeated)return[];if(void 0!==t.default)return t.default;switch(t.kind){case"enum":return t.T.values[0].no;case"scalar":return eh(t.T,t.L);case"message":let i=t.T,n=new i;return i.fieldWrapper?i.fieldWrapper.unwrapField(n):n;case"map":throw"map fields are not allowed to be extensions"}}(e),[i,()=>i[t]]}let ev="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),eb=[];for(let e=0;e<ev.length;e++)eb[ev[e].charCodeAt(0)]=e;eb[45]=ev.indexOf("+"),eb[95]=ev.indexOf("/");let ek={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let i=new Uint8Array(t),n=0,r=0,s,a=0;for(let t=0;t<e.length;t++){if(void 0===(s=eb[e.charCodeAt(t)]))switch(e[t]){case"=":r=0;case"\n":case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:a=s,r=1;break;case 1:i[n++]=a<<2|(48&s)>>4,a=s,r=2;break;case 2:i[n++]=(15&a)<<4|(60&s)>>2,a=s,r=3;break;case 3:i[n++]=(3&a)<<6|s,r=0}}if(1==r)throw Error("invalid base64 string.");return i.subarray(0,n)},enc(e){let t="",i=0,n,r=0;for(let s=0;s<e.length;s++)switch(n=e[s],i){case 0:t+=ev[n>>2],r=(3&n)<<4,i=1;break;case 1:t+=ev[r|n>>4],r=(15&n)<<2,i=2;break;case 2:t+=ev[r|n>>6],t+=ev[63&n],i=0}return i&&(t+=ev[r],t+="=",1==i&&(t+="=")),t}};function ey(e,t){let i=e.getType();return t.extendee.typeName===i.typeName&&!!i.runtime.bin.listUnknownFields(e).find(e=>e.no==t.field.no)}function eT(e,t){K(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function eC(e,t){let i=e.localName;if(e.repeated)return t[i].length>0;if(e.oneof)return t[e.oneof.localName].case===i;switch(e.kind){case"enum":case"scalar":if(e.opt||e.req)return void 0!==t[i];if("enum"==e.kind)return t[i]!==e.T.values[0].no;return!ep(e.T,t[i]);case"message":return void 0!==t[i];case"map":return Object.keys(t[i]).length>0}}function eS(e,t){let i=e.localName,n=!e.opt&&!e.req;if(e.repeated)t[i]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case"map":t[i]={};break;case"enum":t[i]=n?e.T.values[0].no:void 0;break;case"scalar":t[i]=n?eh(e.T,e.L):void 0;break;case"message":t[i]=void 0}}function ew(e,t){if(null===e||"object"!=typeof e||!Object.getOwnPropertyNames(ee.prototype).every(t=>t in e&&"function"==typeof e[t]))return!1;let i=e.getType();return null!==i&&"function"==typeof i&&"typeName"in i&&"string"==typeof i.typeName&&(void 0===t||i.typeName==t.typeName)}function eE(e,t){return ew(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}o.DOUBLE,o.FLOAT,o.INT64,o.UINT64,o.INT32,o.UINT32,o.BOOL,o.STRING,o.BYTES;let eP={ignoreUnknownFields:!1},eR={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},eI=Symbol(),eO=Symbol();function eD(e){if(null===e)return"null";switch(typeof e){case"object":return Array.isArray(e)?"array":"object";case"string":return e.length>100?"string":'"'.concat(e.split('"').join('\\"'),'"');default:return String(e)}}function ex(e,t,i,n,r){let s=i.localName;if(i.repeated){if(K("map"!=i.kind),null===t)return;if(!Array.isArray(t))throw Error("cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(eD(t)));let a=e[s];for(let e of t){if(null===e)throw Error("cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(eD(e)));switch(i.kind){case"message":a.push(i.T.fromJson(e,n));break;case"enum":let t=eM(i.T,e,n.ignoreUnknownFields,!0);t!==eO&&a.push(t);break;case"scalar":try{a.push(e_(i.T,e,i.L,!0))}catch(n){let t="cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(eD(e));throw n instanceof Error&&n.message.length>0&&(t+=": ".concat(n.message)),Error(t)}}}}else if("map"==i.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw Error("cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(eD(t)));let a=e[s];for(let[e,s]of Object.entries(t)){let l;if(null===s)throw Error("cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: map value null"));try{l=function(e,t){if(e===o.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return e_(e,t,c.BIGINT,!0).toString()}(i.K,e)}catch(n){let e="cannot decode map key for field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(eD(t));throw n instanceof Error&&n.message.length>0&&(e+=": ".concat(n.message)),Error(e)}switch(i.V.kind){case"message":a[l]=i.V.T.fromJson(s,n);break;case"enum":let d=eM(i.V.T,s,n.ignoreUnknownFields,!0);d!==eO&&(a[l]=d);break;case"scalar":try{a[l]=e_(i.V.T,s,c.BIGINT,!0)}catch(n){let e="cannot decode map value for field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(eD(t));throw n instanceof Error&&n.message.length>0&&(e+=": ".concat(n.message)),Error(e)}}}}else switch(i.oneof&&(e=e[i.oneof.localName]={case:s},s="value"),i.kind){case"message":let a=i.T;if(null===t&&"google.protobuf.Value"!=a.typeName)return;let l=e[s];ew(l)?l.fromJson(t,n):(e[s]=l=a.fromJson(t,n),a.fieldWrapper&&!i.oneof&&(e[s]=a.fieldWrapper.unwrapField(l)));break;case"enum":let d=eM(i.T,t,n.ignoreUnknownFields,!1);switch(d){case eI:eS(i,e);break;case eO:break;default:e[s]=d}break;case"scalar":try{let n=e_(i.T,t,i.L,!1);n===eI?eS(i,e):e[s]=n}catch(n){let e="cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(eD(t));throw n instanceof Error&&n.message.length>0&&(e+=": ".concat(n.message)),Error(e)}}}function e_(e,t,i,n){if(null===t)return n?eh(e,i):eI;switch(e){case o.DOUBLE:case o.FLOAT:if("NaN"===t)return NaN;if("Infinity"===t)return 1/0;if("-Infinity"===t)return-1/0;if(""===t||"string"==typeof t&&t.trim().length!==t.length||"string"!=typeof t&&"number"!=typeof t)break;let r=Number(t);if(Number.isNaN(r)||!Number.isFinite(r))break;return e==o.FLOAT&&Q(r),r;case o.INT32:case o.FIXED32:case o.SFIXED32:case o.SINT32:case o.UINT32:let s;if("number"==typeof t?s=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(s=Number(t)),void 0===s)break;return e==o.UINT32||e==o.FIXED32?J(s):z(s),s;case o.INT64:case o.SFIXED64:case o.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;let a=ed.parse(t);return i?a.toString():a;case o.FIXED64:case o.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;let c=ed.uParse(t);return i?c.toString():c;case o.BOOL:if("boolean"!=typeof t)break;return t;case o.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw Error("invalid UTF8")}return t;case o.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return ek.dec(t)}throw Error()}function eM(e,t,i,n){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:n?e.values[0].no:eI;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":let r=e.findName(t);if(void 0!==r)return r.no;if(i)return eO}throw Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(eD(t)))}function eA(e,t,i){if("map"==e.kind){K("object"==typeof t&&null!=t);let n={},r=Object.entries(t);switch(e.V.kind){case"scalar":for(let[t,i]of r)n[t.toString()]=eL(e.V.T,i);break;case"message":for(let[e,t]of r)n[e.toString()]=t.toJson(i);break;case"enum":let s=e.V.T;for(let[e,t]of r)n[e.toString()]=eN(s,t,i.enumAsInteger)}return i.emitDefaultValues||r.length>0?n:void 0}if(e.repeated){K(Array.isArray(t));let n=[];switch(e.kind){case"scalar":for(let i=0;i<t.length;i++)n.push(eL(e.T,t[i]));break;case"enum":for(let r=0;r<t.length;r++)n.push(eN(e.T,t[r],i.enumAsInteger));break;case"message":for(let e=0;e<t.length;e++)n.push(t[e].toJson(i))}return i.emitDefaultValues||n.length>0?n:void 0}switch(e.kind){case"scalar":return eL(e.T,t);case"enum":return eN(e.T,t,i.enumAsInteger);case"message":return eE(e.T,t).toJson(i)}}function eN(e,t,i){var n;if(K("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(i)return t;let r=e.findNumber(t);return null!=(n=null==r?void 0:r.name)?n:t}function eL(e,t){switch(e){case o.INT32:case o.SFIXED32:case o.SINT32:case o.FIXED32:case o.UINT32:return K("number"==typeof t),t;case o.FLOAT:case o.DOUBLE:if(K("number"==typeof t),Number.isNaN(t))return"NaN";if(t===1/0)return"Infinity";if(t===-1/0)return"-Infinity";return t;case o.STRING:return K("string"==typeof t),t;case o.BOOL:return K("boolean"==typeof t),t;case o.UINT64:case o.FIXED64:case o.INT64:case o.SFIXED64:case o.SINT64:return K("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case o.BYTES:return K(t instanceof Uint8Array),ek.enc(t)}}let eU=Symbol("@bufbuild/protobuf/unknown-fields"),ej={readUnknownFields:!0,readerFactory:e=>new eg(e)},eF={writeUnknownFields:!0,writerFactory:()=>new em};function eB(e,t,i,n,r){let{repeated:s,localName:a}=i;switch(i.oneof&&((e=e[i.oneof.localName]).case!=a&&delete e.value,e.case=a,a="value"),i.kind){case"scalar":case"enum":let d="enum"==i.kind?o.INT32:i.T,u=eH;if("scalar"==i.kind&&i.L>0&&(u=eq),s){let i=e[a];if(n==l.LengthDelimited&&d!=o.STRING&&d!=o.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)i.push(u(t,d))}else i.push(u(t,d))}else e[a]=u(t,d);break;case"message":let h=i.T;s?e[a].push(eV(t,new h,r,i)):ew(e[a])?eV(t,e[a],r,i):(e[a]=eV(t,new h,r,i),!h.fieldWrapper||i.oneof||i.repeated||(e[a]=h.fieldWrapper.unwrapField(e[a])));break;case"map":let[p,m]=function(e,t,i){let n,r,s=t.uint32(),a=t.pos+s;for(;t.pos<a;){let[s]=t.tag();switch(s){case 1:n=eH(t,e.K);break;case 2:switch(e.V.kind){case"scalar":r=eH(t,e.V.T);break;case"enum":r=t.int32();break;case"message":r=eV(t,new e.V.T,i,void 0)}}}if(void 0===n&&(n=eh(e.K,c.BIGINT)),"string"!=typeof n&&"number"!=typeof n&&(n=n.toString()),void 0===r)switch(e.V.kind){case"scalar":r=eh(e.V.T,c.BIGINT);break;case"enum":r=e.V.T.values[0].no;break;case"message":r=new e.V.T}return[n,r]}(i,t,r);e[a][p]=m}}function eV(e,t,i,n){let r=t.getType().runtime.bin,s=null==n?void 0:n.delimited;return r.readMessage(t,e,s?n.no:e.uint32(),i,s),t}function eq(e,t){let i=eH(e,t);return"bigint"==typeof i?i.toString():i}function eH(e,t){switch(t){case o.STRING:return e.string();case o.BOOL:return e.bool();case o.DOUBLE:return e.double();case o.FLOAT:return e.float();case o.INT32:return e.int32();case o.INT64:return e.int64();case o.UINT64:return e.uint64();case o.FIXED64:return e.fixed64();case o.BYTES:return e.bytes();case o.FIXED32:return e.fixed32();case o.SFIXED32:return e.sfixed32();case o.SFIXED64:return e.sfixed64();case o.SINT64:return e.sint64();case o.UINT32:return e.uint32();case o.SINT32:return e.sint32()}}function eG(e,t,i,n){K(void 0!==t);let r=e.repeated;switch(e.kind){case"scalar":case"enum":let s="enum"==e.kind?o.INT32:e.T;if(r)if(K(Array.isArray(t)),e.packed)!function(e,t,i,n){if(!n.length)return;e.tag(i,l.LengthDelimited).fork();let[,r]=ez(t);for(let t=0;t<n.length;t++)e[r](n[t]);e.join()}(i,s,e.no,t);else for(let n of t)eK(i,s,e.no,n);else eK(i,s,e.no,t);break;case"message":if(r)for(let r of(K(Array.isArray(t)),t))eW(i,n,e,r);else eW(i,n,e,t);break;case"map":for(let[r,s]of(K("object"==typeof t&&null!=t),Object.entries(t)))!function(e,t,i,n,r){e.tag(i.no,l.LengthDelimited),e.fork();let s=n;switch(i.K){case o.INT32:case o.FIXED32:case o.UINT32:case o.SFIXED32:case o.SINT32:s=Number.parseInt(n);break;case o.BOOL:K("true"==n||"false"==n),s="true"==n}switch(eK(e,i.K,1,s),i.V.kind){case"scalar":eK(e,i.V.T,2,r);break;case"enum":eK(e,o.INT32,2,r);break;case"message":K(void 0!==r),e.tag(2,l.LengthDelimited).bytes(r.toBinary(t))}e.join()}(i,n,e,r,s)}}function eW(e,t,i,n){let r=eE(i.T,n);i.delimited?e.tag(i.no,l.StartGroup).raw(r.toBinary(t)).tag(i.no,l.EndGroup):e.tag(i.no,l.LengthDelimited).bytes(r.toBinary(t))}function eK(e,t,i,n){K(void 0!==n);let[r,s]=ez(t);e.tag(i,r)[s](n)}function ez(e){let t=l.Varint;switch(e){case o.BYTES:case o.STRING:t=l.LengthDelimited;break;case o.DOUBLE:case o.FIXED64:case o.SFIXED64:t=l.Bit64;break;case o.FIXED32:case o.SFIXED32:case o.FLOAT:t=l.Bit32}return[t,o[e].toLowerCase()]}function eJ(e){if(void 0===e)return e;if(ew(e))return e.clone();if(e instanceof Uint8Array){let t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function eQ(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class eY{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){let e={};for(let t of this.list())e[t.jsonName]=e[t.name]=t;this.jsonNames=e}return this.jsonNames[e]}find(e){if(!this.numbers){let e={};for(let t of this.list())e[t.no]=t;this.numbers=e}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){let e;this.members=[];let t=this.members;for(let i of this.list())i.oneof?i.oneof!==e&&(e=i.oneof,t.push(e)):t.push(i)}return this.members}}function eX(e,t){let i=e$(e);return t?i:e4(e3(i))}let eZ=e$;function e$(e){let t=!1,i=[];for(let n=0;n<e.length;n++){let r=e.charAt(n);switch(r){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":i.push(r),t=!1;break;default:t&&(t=!1,r=r.toUpperCase()),i.push(r)}}return i.join("")}let e0=new Set(["constructor","toString","toJSON","valueOf"]),e1=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),e2=e=>"".concat(e,"$"),e3=e=>e1.has(e)?e2(e):e,e4=e=>e0.has(e)?e2(e):e;class e6{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=eX(e,!1)}addField(e){K(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 e=0;e<this.fields.length;e++)this._lookup[this.fields[e].localName]=this.fields[e]}return this._lookup[e]}}let e9=(s=e=>new eY(e,e=>(function(e,t){var i,n,r,s,a,l;let d,u=[];for(let t of"function"==typeof e?e():e){if(t.localName=eX(t.name,void 0!==t.oneof),t.jsonName=null!=(i=t.jsonName)?i:eZ(t.name),t.repeated=null!=(n=t.repeated)&&n,"scalar"==t.kind&&(t.L=null!=(r=t.L)?r:c.BIGINT),t.delimited=null!=(s=t.delimited)&&s,t.req=null!=(a=t.req)&&a,t.opt=null!=(l=t.opt)&&l,void 0===t.packed&&(t.packed="enum"==t.kind||"scalar"==t.kind&&t.T!=o.BYTES&&t.T!=o.STRING),void 0!==t.oneof){let e="string"==typeof t.oneof?t.oneof:t.oneof.name;d&&d.name==e||(d=new e6(e)),t.oneof=d,d.addField(t)}u.push(t)}return u})(e)),a=e=>{for(let t of e.getType().fields.byMember()){if(t.opt)continue;let i=t.localName;if(t.repeated){e[i]=[];continue}switch(t.kind){case"oneof":e[i]={case:void 0};break;case"enum":e[i]=0;break;case"map":e[i]={};break;case"scalar":e[i]=eh(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:function(e){return e?Object.assign(Object.assign({},eP),e):eP},makeWriteOptions:function(e){return e?Object.assign(Object.assign({},eR),e):eR},readMessage(e,t,i,n){if(null==t||Array.isArray(t)||"object"!=typeof t)throw Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(eD(t)));n=null!=n?n:new e;let r=new Map,s=i.typeRegistry;for(let[a,o]of Object.entries(t)){let t=e.fields.findJsonName(a);if(t){if(t.oneof){if(null===o&&"scalar"==t.kind)continue;let i=r.get(t.oneof);if(void 0!==i)throw Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(t.oneof.name,'" present: "').concat(i,'", "').concat(a,'"'));r.set(t.oneof,a)}ex(n,o,t,i,e)}else{let t=!1;if((null==s?void 0:s.findExtension)&&a.startsWith("[")&&a.endsWith("]")){let r=s.findExtension(a.substring(1,a.length-1));if(r&&r.extendee.typeName==e.typeName){t=!0;let[e,s]=ef(r);ex(e,o,r.field,i,r),function(e,t,i,n){eT(t,e);let r=t.runtime.bin.makeReadOptions(n),s=t.runtime.bin.makeWriteOptions(n);if(ey(e,t)){let i=e.getType().runtime.bin.listUnknownFields(e).filter(e=>e.no!=t.field.no);for(let t of(e.getType().runtime.bin.discardUnknownFields(e),i))e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}let a=s.writerFactory(),o=t.field;o.opt||o.repeated||"enum"!=o.kind&&"scalar"!=o.kind||(o=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(o,i,a,s);let c=r.readerFactory(a.finish());for(;c.pos<c.len;){let[t,i]=c.tag(),n=c.skip(i,t);e.getType().runtime.bin.onUnknownField(e,t,i,n)}}(n,r,s(),i)}}if(!t&&!i.ignoreUnknownFields)throw Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(a,'" is unknown'))}}return n},writeMessage(e,t){let i,n=e.getType(),r={};try{for(i of n.fields.byNumber()){if(!eC(i,e)){var s;if(i.req)throw"required field not set";if(!t.emitDefaultValues||!((s=i).repeated||"map"==s.kind||!s.oneof&&"message"!=s.kind&&!s.opt&&!s.req))continue}let n=i.oneof?e[i.oneof.localName].value:e[i.localName],a=eA(i,n,t);void 0!==a&&(r[t.useProtoFieldName?i.name:i.jsonName]=a)}let a=t.typeRegistry;if(null==a?void 0:a.findExtensionFor)for(let i of n.runtime.bin.listUnknownFields(e)){let s=a.findExtensionFor(n.typeName,i.no);if(s&&ey(e,s)){let i=function(e,t,i){eT(t,e);let n=t.runtime.bin.makeReadOptions(i),r=function(e,t){if(!t.repeated&&("enum"==t.kind||"scalar"==t.kind)){for(let i=e.length-1;i>=0;--i)if(e[i].no==t.no)return[e[i]];return[]}return e.filter(e=>e.no===t.no)}(e.getType().runtime.bin.listUnknownFields(e),t.field),[s,a]=ef(t);for(let e of r)t.runtime.bin.readField(s,n.readerFactory(e.data),t.field,e.wireType,n);return a()}(e,s,t),n=eA(s.field,i,t);void 0!==n&&(r[s.field.jsonName]=n)}}}catch(r){let e=i?"cannot encode field ".concat(n.typeName,".").concat(i.name," to JSON"):"cannot encode message ".concat(n.typeName," to JSON"),t=r instanceof Error?r.message:String(r);throw Error(e+(t.length>0?": ".concat(t):""))}return r},readScalar:(e,t,i)=>e_(e,t,null!=i?i:c.BIGINT,!0),writeScalar(e,t,i){if(void 0!==t&&(i||ep(e,t)))return eL(e,t)},debug:eD},bin:{makeReadOptions:function(e){return e?Object.assign(Object.assign({},ej),e):ej},makeWriteOptions:function(e){return e?Object.assign(Object.assign({},eF),e):eF},listUnknownFields(e){var t;return null!=(t=e[eU])?t:[]},discardUnknownFields(e){delete e[eU]},writeUnknownFields(e,t){let i=e[eU];if(i)for(let e of i)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,i,n){Array.isArray(e[eU])||(e[eU]=[]),e[eU].push({no:t,wireType:i,data:n})},readMessage(e,t,i,n,r){let s,a,o=e.getType(),c=r?t.len:t.pos+i;for(;t.pos<c&&([s,a]=t.tag(),!0!==r||a!=l.EndGroup);){let i=o.fields.find(s);if(!i){let i=t.skip(a,s);n.readUnknownFields&&this.onUnknownField(e,s,a,i);continue}eB(e,t,i,a,n)}if(r&&(a!=l.EndGroup||s!==i))throw Error("invalid end group tag")},readField:eB,writeMessage(e,t,i){let n=e.getType();for(let r of n.fields.byNumber()){if(!eC(r,e)){if(r.req)throw Error("cannot encode field ".concat(n.typeName,".").concat(r.name," to binary: required field not set"));continue}let s=r.oneof?e[r.oneof.localName].value:e[r.localName];eG(r,s,t,i)}return i.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,i,n){void 0!==t&&eG(e,t,i,n)}},util:Object.assign(Object.assign({},{setEnumType:X,initPartial(e,t){if(void 0!==e)for(let i of t.getType().fields.byMember()){let n=i.localName;if(null!=e[n])switch(i.kind){case"oneof":let r=e[n].case;if(void 0===r)continue;let s=i.findField(r),a=e[n].value;s&&"message"==s.kind&&!ew(a,s.T)?a=new s.T(a):s&&"scalar"===s.kind&&s.T===o.BYTES&&(a=eQ(a)),t[n]={case:r,value:a};break;case"scalar":case"enum":let c=e[n];i.T===o.BYTES&&(c=i.repeated?c.map(eQ):eQ(c)),t[n]=c;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===o.BYTES)for(let[i,r]of Object.entries(e[n]))t[n][i]=eQ(r);else Object.assign(t[n],e[n]);break;case"message":let l=i.V.T;for(let i of Object.keys(e[n])){let r=e[n][i];l.fieldWrapper||(r=new l(r)),t[n][i]=r}}break;case"message":let d=i.T;if(i.repeated)t[n]=e[n].map(e=>ew(e,d)?e:new d(e));else{let i=e[n];d.fieldWrapper?"google.protobuf.BytesValue"===d.typeName?t[n]=eQ(i):t[n]=i:t[n]=ew(i,d)?i:new d(i)}}}},equals:(e,t,i)=>t===i||!!t&&!!i&&e.fields.byMember().every(e=>{let n=t[e.localName],r=i[e.localName];if(e.repeated){if(n.length!==r.length)return!1;switch(e.kind){case"message":return n.every((t,i)=>e.T.equals(t,r[i]));case"scalar":return n.every((t,i)=>eu(e.T,t,r[i]));case"enum":return n.every((e,t)=>eu(o.INT32,e,r[t]))}throw Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":let s=n,a=r;return e.T.fieldWrapper&&(void 0===s||ew(s)||(s=e.T.fieldWrapper.wrapField(s)),void 0===a||ew(a)||(a=e.T.fieldWrapper.wrapField(a))),e.T.equals(s,a);case"enum":return eu(o.INT32,n,r);case"scalar":return eu(e.T,n,r);case"oneof":if(n.case!==r.case)return!1;let c=e.findField(n.case);if(void 0===c)return!0;switch(c.kind){case"message":return c.T.equals(n.value,r.value);case"enum":return eu(o.INT32,n.value,r.value);case"scalar":return eu(c.T,n.value,r.value)}throw Error("oneof cannot contain ".concat(c.kind));case"map":let l=Object.keys(n).concat(Object.keys(r));switch(e.V.kind){case"message":let d=e.V.T;return l.every(e=>d.equals(n[e],r[e]));case"enum":return l.every(e=>eu(o.INT32,n[e],r[e]));case"scalar":let u=e.V.T;return l.every(e=>eu(u,n[e],r[e]))}}}),clone(e){let t=e.getType(),i=new t;for(let n of t.fields.byMember()){let t,r=e[n.localName];if(n.repeated)t=r.map(eJ);else if("map"==n.kind)for(let[e,s]of(t=i[n.localName],Object.entries(r)))t[e]=eJ(s);else t="oneof"==n.kind?n.findField(r.case)?{case:r.case,value:eJ(r.value)}:{case:void 0}:eJ(r);i[n.localName]=t}for(let n of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(i,n.no,n.wireType,n.data);return i}}),{newFieldList:s,initFields:a}),makeMessageType(e,t,i){return function(e,t,i,n){var r;let s=null!=(r=null==n?void 0:n.localName)?r:t.substring(t.lastIndexOf(".")+1),a={[s]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[s];return Object.setPrototypeOf(a.prototype,new ee),Object.assign(a,{runtime:e,typeName:t,fields:e.util.newFieldList(i),fromBinary:(e,t)=>new a().fromBinary(e,t),fromJson:(e,t)=>new a().fromJson(e,t),fromJsonString:(e,t)=>new a().fromJsonString(e,t),equals:(t,i)=>e.util.equals(a,t,i)}),a}(this,e,t,i)},makeEnum:function(e,t,i){let n={};for(let e of t){let t=$(e);n[t.localName]=t.no,n[t.no]=t.localName}return X(n,e,t),n},makeEnumType:Z,getEnumType:function(e){let t=e[Y];return K(t,"missing enum type on enum object"),t},makeExtension(e,t,i){var n;let r;return n=this,{typeName:e,extendee:t,get field(){if(!r){let t="function"==typeof i?i():i;t.name=e.split(".").pop(),t.jsonName="[".concat(e,"]"),r=n.util.newFieldList([t]).list()[0]}return r},runtime:n}}});class e5 extends ee{constructor(e){super(),this.seconds=ed.zero,this.nanos=0,e9.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(e9.json.debug(e)));let i=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");let n=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(n))throw Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(n<Date.parse("0001-01-01T00:00:00Z")||n>Date.parse("9999-12-31T23:59:59Z"))throw 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=ed.parse(n/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){let t=1e3*Number(this.seconds);if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw 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 Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){let e=(this.nanos+1e9).toString().substring(1);i="000000"===e.substring(3)?"."+e.substring(0,3)+"Z":"000"===e.substring(6)?"."+e.substring(0,6)+"Z":"."+e+"Z"}return new Date(t).toISOString().replace(".000Z",i)}toDate(){return new Date(1e3*Number(this.seconds)+Math.ceil(this.nanos/1e6))}static now(){return e5.fromDate(new Date)}static fromDate(e){let t=e.getTime();return new e5({seconds:ed.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new e5().fromBinary(e,t)}static fromJson(e,t){return new e5().fromJson(e,t)}static fromJsonString(e,t){return new e5().fromJsonString(e,t)}static equals(e,t){return e9.util.equals(e5,e,t)}}e5.runtime=e9,e5.typeName="google.protobuf.Timestamp",e5.fields=e9.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);let e8=e9.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:e5},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:e7,repeated:!0},{no:5,name:"events",kind:"message",T:tt,repeated:!0}]),e7=e9.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:te,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),te=e9.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:e5},{no:3,name:"value",kind:"scalar",T:2}]),tt=e9.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:e5},{no:7,name:"normalized_end_timestamp",kind:"message",T:e5,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),ti=e9.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),tn=e9.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),tr=e9.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"}]),ts=e9.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),ta=e9.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),to=e9.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),tc=e9.makeEnum("livekit.DisconnectReason",[{no:0,name:"UNKNOWN_REASON"},{no:1,name:"CLIENT_INITIATED"},{no:2,name:"DUPLICATE_IDENTITY"},{no:3,name:"SERVER_SHUTDOWN"},{no:4,name:"PARTICIPANT_REMOVED"},{no:5,name:"ROOM_DELETED"},{no:6,name:"STATE_MISMATCH"},{no:7,name:"JOIN_FAILURE"},{no:8,name:"MIGRATION"},{no:9,name:"SIGNAL_CLOSE"},{no:10,name:"ROOM_CLOSED"},{no:11,name:"USER_UNAVAILABLE"},{no:12,name:"USER_REJECTED"},{no:13,name:"SIP_TRUNK_FAILURE"},{no:14,name:"CONNECTION_TIMEOUT"},{no:15,name:"MEDIA_FAILURE"}]),tl=e9.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"}]),td=e9.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),tu=e9.makeEnum("livekit.AudioTrackFeature",[{no:0,name:"TF_STEREO"},{no:1,name:"TF_NO_DTX"},{no:2,name:"TF_AUTO_GAIN_CONTROL"},{no:3,name:"TF_ECHO_CANCELLATION"},{no:4,name:"TF_NOISE_SUPPRESSION"},{no:5,name:"TF_ENHANCED_NOISE_CANCELLATION"},{no:6,name:"TF_PRECONNECT_BUFFER"}]),th=e9.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:tp,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:tG}]),tp=e9.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),tm=e9.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:e9.getEnumType(tr),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}]),tg=e9.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:e9.getEnumType(tf)},{no:4,name:"tracks",kind:"message",T:tT,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:tm},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:e9.getEnumType(tv)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:e9.getEnumType(tc)},{no:18,name:"kind_details",kind:"enum",T:e9.getEnumType(tb),repeated:!0}]),tf=e9.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),tv=e9.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]),tb=e9.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),tk=e9.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),ty=e9.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:tC,repeated:!0}]),tT=e9.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:e9.getEnumType(tn)},{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:e9.getEnumType(tr)},{no:10,name:"layers",kind:"message",T:tC,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:ty,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:e9.getEnumType(tk)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:tG},{no:19,name:"audio_features",kind:"enum",T:e9.getEnumType(tu),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:e9.getEnumType(ti)}]),tC=e9.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:e9.getEnumType(ts)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13},{no:6,name:"spatial_layer",kind:"scalar",T:5},{no:7,name:"rid",kind:"scalar",T:9}]),tS=e9.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:e9.getEnumType(tw)},{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:tR,oneof:"value"},{no:3,name:"speaker",kind:"message",T:tE,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:tI,oneof:"value"},{no:7,name:"transcription",kind:"message",T:tO,oneof:"value"},{no:8,name:"metrics",kind:"message",T:e8,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:tx,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:t_,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:tM,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:tA,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:tJ,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:tQ,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:tY,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),tw=e9.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),tE=e9.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:tP,repeated:!0}]),tP=e9.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}]),tR=e9.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}]),tI=e9.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),tO=e9.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:tD,repeated:!0}]),tD=e9.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}]),tx=e9.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}]),t_=e9.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}]),tM=e9.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),tA=e9.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:tN,oneof:"value"}]),tN=e9.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}]),tL=e9.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),tU=e9.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:e9.getEnumType(tj)},{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}]),tj=e9.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),tF=e9.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:e9.getEnumType(tB)},{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}]),tB=e9.makeEnum("livekit.ClientInfo.SDK",[{no:0,name:"UNKNOWN"},{no:1,name:"JS"},{no:2,name:"SWIFT"},{no:3,name:"ANDROID"},{no:4,name:"FLUTTER"},{no:5,name:"GO"},{no:6,name:"UNITY"},{no:7,name:"REACT_NATIVE"},{no:8,name:"RUST"},{no:9,name:"PYTHON"},{no:10,name:"CPP"},{no:11,name:"UNITY_WEB"},{no:12,name:"NODE"},{no:13,name:"UNREAL"},{no:14,name:"ESP32"}]),tV=e9.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:tq},{no:2,name:"screen",kind:"message",T:tq},{no:3,name:"resume_connection",kind:"enum",T:e9.getEnumType(to)},{no:4,name:"disabled_codecs",kind:"message",T:tH},{no:5,name:"force_relay",kind:"enum",T:e9.getEnumType(to)}]),tq=e9.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:e9.getEnumType(to)}]),tH=e9.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:tp,repeated:!0},{no:2,name:"publish",kind:"message",T:tp,repeated:!0}]),tG=e9.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),tW=e9.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),tK=e9.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:e9.getEnumType(tW)},{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"}),tz=e9.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),tJ=e9.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:e9.getEnumType(tk)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:tK,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:tz,oneof:"content_header"}],{localName:"DataStream_Header"}),tQ=e9.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"}),tY=e9.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"}),tX=e9.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),tZ=e9.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),t$=e9.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),t0=e9.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:ie,oneof:"message"},{no:2,name:"answer",kind:"message",T:ie,oneof:"message"},{no:3,name:"trickle",kind:"message",T:t4,oneof:"message"},{no:4,name:"add_track",kind:"message",T:t3,oneof:"message"},{no:5,name:"mute",kind:"message",T:t6,oneof:"message"},{no:6,name:"subscription",kind:"message",T:ii,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:ir,oneof:"message"},{no:8,name:"leave",kind:"message",T:io,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:il,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:iS,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:iP,oneof:"message"},{no:13,name:"simulate",kind:"message",T:iO,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:id,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:iD,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:is,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:ia,oneof:"message"}]),t1=e9.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:t9,oneof:"message"},{no:2,name:"answer",kind:"message",T:ie,oneof:"message"},{no:3,name:"offer",kind:"message",T:ie,oneof:"message"},{no:4,name:"trickle",kind:"message",T:t4,oneof:"message"},{no:5,name:"update",kind:"message",T:it,oneof:"message"},{no:6,name:"track_published",kind:"message",T:t8,oneof:"message"},{no:8,name:"leave",kind:"message",T:io,oneof:"message"},{no:9,name:"mute",kind:"message",T:t6,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:ih,oneof:"message"},{no:11,name:"room_update",kind:"message",T:ip,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:ig,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:ib,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:iT,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:iw,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:t7,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:t5,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:ix,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:iA,oneof:"message"},{no:22,name:"request_response",kind:"message",T:iN,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:iU,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:iE,oneof:"message"}]),t2=e9.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}]),t3=e9.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:e9.getEnumType(tn)},{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:e9.getEnumType(tr)},{no:9,name:"layers",kind:"message",T:tC,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:t2,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:e9.getEnumType(tk)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:e9.getEnumType(ti)},{no:17,name:"audio_features",kind:"enum",T:e9.getEnumType(tu),repeated:!0}]),t4=e9.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:e9.getEnumType(tX)},{no:3,name:"final",kind:"scalar",T:8}]),t6=e9.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),t9=e9.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:th},{no:2,name:"participant",kind:"message",T:tg},{no:3,name:"other_participants",kind:"message",T:tg,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:iu,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:tV},{no:9,name:"server_region",kind:"scalar",T:9},{no:10,name:"ping_timeout",kind:"scalar",T:5},{no:11,name:"ping_interval",kind:"scalar",T:5},{no:12,name:"server_info",kind:"message",T:tU},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:tp,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),t5=e9.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:iu,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:tV},{no:3,name:"server_info",kind:"message",T:tU},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),t8=e9.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:tT}]),t7=e9.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),ie=e9.makeMessageType("livekit.SessionDescription",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"id",kind:"scalar",T:13}]),it=e9.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:tg,repeated:!0}]),ii=e9.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:tL,repeated:!0}]),ir=e9.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:e9.getEnumType(ts)},{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}]),is=e9.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:e9.getEnumType(tu),repeated:!0}]),ia=e9.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}]),io=e9.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:e9.getEnumType(tc)},{no:3,name:"action",kind:"enum",T:e9.getEnumType(ic)},{no:4,name:"regions",kind:"message",T:i_}]),ic=e9.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),il=e9.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:tC,repeated:!0}]),id=e9.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}]),iu=e9.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}]),ih=e9.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:tP,repeated:!0}]),ip=e9.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:th}]),im=e9.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:e9.getEnumType(ta)},{no:3,name:"score",kind:"scalar",T:2}]),ig=e9.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:im,repeated:!0}]),iv=e9.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:e9.getEnumType(tZ)}]),ib=e9.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:iv,repeated:!0}]),ik=e9.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:e9.getEnumType(ts)},{no:2,name:"enabled",kind:"scalar",T:8}]),iy=e9.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:ik,repeated:!0}]),iT=e9.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:ik,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:iy,repeated:!0}]),iC=e9.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}]),iS=e9.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:iC,repeated:!0}]),iw=e9.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}]),iE=e9.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:th},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:tg},{no:4,name:"other_participants",kind:"message",T:tg,repeated:!0}]),iP=e9.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:ie},{no:2,name:"subscription",kind:"message",T:ii},{no:3,name:"publish_tracks",kind:"message",T:t8,repeated:!0},{no:4,name:"data_channels",kind:"message",T:iI,repeated:!0},{no:5,name:"offer",kind:"message",T:ie},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:iR,repeated:!0}]),iR=e9.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),iI=e9.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:e9.getEnumType(tX)}]),iO=e9.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:e9.getEnumType(t$),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"}]),iD=e9.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),ix=e9.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),i_=e9.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:iM,repeated:!0}]),iM=e9.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}]),iA=e9.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:e9.getEnumType(td)}]),iN=e9.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:e9.getEnumType(iL)},{no:3,name:"message",kind:"scalar",T:9}]),iL=e9.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"}]),iU=e9.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]);var ij={exports:{}},iF=ij.exports,iB=function(){var e;return d?ij.exports:(d=1,e=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"],r={},s=null;function a(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(t){return function(){return Function.prototype.apply.apply(i,[e,arguments])}}}function o(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var i=this.getLevel(),r=0;r<n.length;r++){var s=n[r];this[s]=r<i?e:this.methodFactory(s,i,this.name)}if(this.log=this.debug,typeof console===t&&i<this.levels.SILENT)return"No console available for logging"}function l(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function d(n,r,s){var c;return"debug"===(c=n)&&(c="log"),typeof console!==t&&("trace"===c&&i?o:void 0!==console[c]?a(console,c):void 0!==console.log?a(console,"log"):e)||l.apply(this,arguments)}function u(e,i){var a,o,l,u=this,h="loglevel";function p(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,n=encodeURIComponent(h),r=i.indexOf(n+"=");-1!==r&&(e=/^([^;]+)/.exec(i.slice(r+n.length+1))[1])}catch(e){}return void 0===u.levels[e]&&(e=void 0),e}}function m(e){var t=e;if("string"==typeof t&&void 0!==u.levels[t.toUpperCase()]&&(t=u.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=u.levels.SILENT)return t;throw TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),u.name=e,u.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},u.methodFactory=i||d,u.getLevel=function(){return null!=l?l:null!=o?o:a},u.setLevel=function(e,i){return l=m(e),!1!==i&&function(e){var i=(n[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{window.localStorage[h]=i;return}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"="+i+";"}catch(e){}}}(l),c.call(u)},u.setDefaultLevel=function(e){o=m(e),p()||u.setLevel(e,!1)},u.resetLevel=function(){if(l=null,typeof window!==t&&h){try{window.localStorage.removeItem(h)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}c.call(u)},u.enableAll=function(e){u.setLevel(u.levels.TRACE,e)},u.disableAll=function(e){u.setLevel(u.levels.SILENT,e)},u.rebuild=function(){if(s!==u&&(a=m(s.getLevel())),c.call(u),s===u)for(var e in r)r[e].rebuild()},a=m(s?s.getLevel():"WARN");var g=p();null!=g&&(l=m(g)),c.call(u)}(s=new u).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw TypeError("You must supply a name when creating a logger.");var t=r[e];return t||(t=r[e]=new u(e,s.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return s.noConflict=function(){return typeof window!==t&&window.log===s&&(window.log=h),s},s.getLoggers=function(){return r},s.default=s,s},ij.exports?ij.exports=e():iF.log=e(),ij.exports)}();!function(e){e[e.trace=0]="trace",e[e.debug=1]="debug",e[e.info=2]="info",e[e.warn=3]="warn",e[e.error=4]="error",e[e.silent=5]="silent"}(u||(u={})),function(e){e.Default="livekit",e.Room="livekit-room",e.Participant="livekit-participant",e.Track="livekit-track",e.Publication="livekit-track-publication",e.Engine="livekit-engine",e.Signal="livekit-signal",e.PCManager="livekit-pc-manager",e.PCTransport="livekit-pc-transport",e.E2EE="lk-e2ee"}(h||(h={}));let iV=iB.getLogger("livekit");function iq(e){let t=iB.getLogger(e);return t.setDefaultLevel(iV.getLevel()),t}Object.values(h).map(e=>iB.getLogger(e)),iV.setDefaultLevel(u.info);let iH=iB.getLogger("lk-e2ee"),iG=[0,300,1200,2700,4800,7e3,7e3,7e3,7e3,7e3];class iW{constructor(e){this._retryDelays=void 0!==e?[...e]:iG}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;let t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+1e3*Math.random()}}function iK(e,t,i,n){return new(i||(i=Promise))(function(r,s){function a(e){try{c(n.next(e))}catch(e){s(e)}}function o(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?r(e.value):((t=e.value)instanceof i?t:new i(function(e){e(t)})).then(a,o)}c((n=n.apply(e,t||[])).next())})}function iz(e){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var t,i=e[Symbol.asyncIterator];return i?i.call(e):(e=function(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(i){t[i]=e[i]&&function(t){return new Promise(function(n,r){var s,a,o;s=n,a=r,o=(t=e[i](t)).done,Promise.resolve(t.value).then(function(e){s({value:e,done:o})},a)})}}}"function"==typeof SuppressedError&&SuppressedError;var iJ={exports:{}},iQ=function(){if(p)return iJ.exports;p=1;var e,t="object"==typeof Reflect?Reflect:null,i=t&&"function"==typeof t.apply?t.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};e=t&&"function"==typeof t.ownKeys?t.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var n=Number.isNaN||function(e){return e!=e};function r(){r.init.call(this)}iJ.exports=r,iJ.exports.once=function(e,t){return new Promise(function(i,n){var r,s,a;function o(i){e.removeListener(t,c),n(i)}function c(){"function"==typeof e.removeListener&&e.removeListener("error",o),i([].slice.call(arguments))}g(e,t,c,{once:!0}),"error"!==t&&(r=e,s=o,a={once:!0},"function"==typeof r.on&&g(r,"error",s,a))})},r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var s=10;function a(e){if("function"!=typeof e)throw TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function o(e){return void 0===e._maxListeners?r.defaultMaxListeners:e._maxListeners}function c(e,t,i,n){if(a(i),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),s=e._events),c=s[t]),void 0===c)c=s[t]=i,++e._eventsCount;else if("function"==typeof c?c=s[t]=n?[i,c]:[c,i]:n?c.unshift(i):c.push(i),(r=o(e))>0&&c.length>r&&!c.warned){c.warned=!0;var r,s,c,l=Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=c.length,console&&console.warn&&console.warn(l)}return e}function l(){if(!this.fired)return(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0==arguments.length)?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},r=l.bind(n);return r.listener=i,n.wrapFn=r,r}function u(e,t,i){var n=e._events;if(void 0===n)return[];var r=n[t];return void 0===r?[]:"function"==typeof r?i?[r.listener||r]:[r]:i?function(e){for(var t=Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(r):m(r,r.length)}function h(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function m(e,t){for(var i=Array(t),n=0;n<t;++n)i[n]=e[n];return i}function g(e,t,i,n){if("function"==typeof e.on)n.once?e.once(t,i):e.on(t,i);else if("function"==typeof e.addEventListener)e.addEventListener(t,function r(s){n.once&&e.removeEventListener(t,r),i(s)});else throw TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e)}return Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return s},set:function(e){if("number"!=typeof e||e<0||n(e))throw RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");s=e}}),r.init=function(){(void 0===this._events||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},r.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||n(e))throw RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},r.prototype.getMaxListeners=function(){return o(this)},r.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var r="error"===e,s=this._events;if(void 0!==s)r=r&&void 0===s.error;else if(!r)return!1;if(r){if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var a,o=Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var c=s[e];if(void 0===c)return!1;if("function"==typeof c)i(c,this,t);else for(var l=c.length,d=m(c,l),n=0;n<l;++n)i(d[n],this,t);return!0},r.prototype.addListener=function(e,t){return c(this,e,t,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(e,t){return c(this,e,t,!0)},r.prototype.once=function(e,t){return a(t),this.on(e,d(this,e,t)),this},r.prototype.prependOnceListener=function(e,t){return a(t),this.prependListener(e,d(this,e,t)),this},r.prototype.removeListener=function(e,t){var i,n,r,s,o;if(a(t),void 0===(n=this._events)||void 0===(i=n[e]))return this;if(i===t||i.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(r=-1,s=i.length-1;s>=0;s--)if(i[s]===t||i[s].listener===t){o=i[s].listener,r=s;break}if(r<0)return this;0===r?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,r),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,o||t)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(e){var t,i,n;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0==arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0==arguments.length){var r,s=Object.keys(i);for(n=0;n<s.length;++n)"removeListener"!==(r=s[n])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},r.prototype.listeners=function(e){return u(this,e,!0)},r.prototype.rawListeners=function(e){return u(this,e,!1)},r.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},r.prototype.listenerCount=h,r.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},iJ.exports}();let iY=!0,iX=!0;function iZ(e,t,i){let n=e.match(t);return n&&n.length>=i&&parseFloat(n[i],10)}function i$(e,t,i){if(!e.RTCPeerConnection)return;let n=e.RTCPeerConnection.prototype,r=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return r.apply(this,arguments);let s=e=>{let t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,s),r.apply(this,[e,s])};let s=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t]||!this._eventMap[t].has(i))return s.apply(this,arguments);let n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,n])},Object.defineProperty(n,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function i0(e){return"boolean"!=typeof e?Error("Argument type: "+typeof e+". Please use a boolean."):(iY=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function i1(e){return"boolean"!=typeof e?Error("Argument type: "+typeof e+". Please use a boolean."):(iX=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function i2(){"object"==typeof window&&(iY||"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments))}function i3(e,t){iX&&console.warn(e+" is deprecated, please use "+t+" instead.")}function i4(e){return"[object Object]"===Object.prototype.toString.call(e)}function i6(e,t,i){let n=i?"outbound-rtp":"inbound-rtp",r=new Map;if(null===t)return r;let s=[];return e.forEach(e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)}),s.forEach(t=>{e.forEach(i=>{i.type===n&&i.trackId===t.id&&function e(t,i,n){!i||n.has(i.id)||(n.set(i.id,i),Object.keys(i).forEach(r=>{r.endsWith("Id")?e(t,t.get(i[r]),n):r.endsWith("Ids")&&i[r].forEach(i=>{e(t,t.get(i),n)})}))}(e,i,r)})}),r}function i9(e,t){let i=e&&e.navigator;if(!i.mediaDevices)return;let n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;let t={};return Object.keys(e).forEach(i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;let n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);let r=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[r("min",i)]=n.ideal,t.optional.push(e),(e={})[r("max",i)]=n.ideal):e[r("",i)]=n.ideal,t.optional.push(e)}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[r("",i)]=n.exact):["min","max"].forEach(e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,i)]=n[e])})}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},r=function(e,r){if(t.version>=61)return r(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){let t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});let a=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&!(i.mediaDevices.getSupportedConstraints&&i.mediaDevices.getSupportedConstraints().facingMode&&!a)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:("user"===s.exact||"user"===s.ideal)&&(t=["front"]),t)return i.mediaDevices.enumerateDevices().then(i=>{let a=(i=i.filter(e=>"videoinput"===e.kind)).find(e=>t.some(t=>e.label.toLowerCase().includes(t)));return!a&&i.length&&t.includes("back")&&(a=i[i.length-1]),a&&(e.video.deviceId=s.exact?{exact:a.deviceId}:{ideal:a.deviceId}),e.video=n(e.video),i2("chrome: "+JSON.stringify(e)),r(e)})}e.video=n(e.video)}return i2("chrome: "+JSON.stringify(e)),r(e)},s=function(e){return t.version>=64?e:{name:({PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"})[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=(function(e,t,n){r(e,e=>{i.webkitGetUserMedia(e,t,e=>{n&&n(s(e))})})}).bind(i),i.mediaDevices.getUserMedia){let e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return r(t,t=>e(t).then(e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach(e=>{e.stop()}),new DOMException("","NotFoundError");return e},e=>Promise.reject(s(e))))}}}function i5(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function i8(e){if("object"!=typeof e||!e.RTCPeerConnection||"ontrack"in e.RTCPeerConnection.prototype)i$(e,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e));else{Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===i.track.id):{track:i.track};let r=new Event("track");r.track=i.track,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)}),t.stream.getTracks().forEach(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===i.id):{track:i};let r=new Event("track");r.track=i,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}}function i7(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){let t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};let i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let r=i.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r};let n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);let t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}let i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach(e=>{this._senders.push(t(this,e))})};let n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach(e=>{let t=this._senders.find(t=>t.track===e);t&&this._senders.splice(this._senders.indexOf(t),1)})}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){let t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function ne(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){let t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});let i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>i6(t,e.track,!0))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){let t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),i$(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>i6(t,e.track,!1))}}if(!("getStats"in e.RTCRtpSender.prototype&&"getStats"in e.RTCRtpReceiver.prototype))return;let t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){let e,t,i,n=arguments[0];return(this.getSenders().forEach(t=>{t.track===n&&(e?i=!0:e=t)}),this.getReceivers().forEach(e=>(e.track===n&&(t?i=!0:t=e),e.track===n)),i||e&&t)?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):e?e.getStats():t?t.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function nt(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(e=>this._shimmedLocalStreams[e][0])};let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};let n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};let i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException("Track already exists.","InvalidAccessError")});let t=this.getSenders();i.apply(this,arguments);let n=this.getSenders().filter(e=>-1===t.indexOf(e));this._shimmedLocalStreams[e.id]=[e].concat(n)};let n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};let r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(t=>{let i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]}),r.apply(this,arguments)}}function ni(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return nt(e);let i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){let e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map(e=>this._reverseStreams[e.id])};let n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[t.id]){let i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};let r=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{let n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(RegExp(r.id,"g"),n.id)}),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");let n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find(e=>e===t))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(e=>e.track===t))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};let r=this._streams[i.id];if(r)r.addTrack(t),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{let n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find(e=>e.track===t)},["createOffer","createAnswer"].forEach(function(t){let i=e.RTCPeerConnection.prototype[t];e.RTCPeerConnection.prototype[t]=({[t](){let e=arguments,t=arguments.length&&"function"==typeof arguments[0];return t?i.apply(this,[t=>{let i=s(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then(e=>s(this,e))}})[t]});let a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){var e,t;let i;return arguments.length&&arguments[0].type?(arguments[0]=(e=this,t=arguments[0],i=t.sdp,Object.keys(e._reverseStreams||[]).forEach(t=>{let n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(RegExp(n.id,"g"),r.id)}),new RTCSessionDescription({type:t.type,sdp:i})),a.apply(this,arguments)):a.apply(this,arguments)};let o=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){let e=o.get.apply(this);return""===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){let t;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(e._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{},Object.keys(this._streams).forEach(i=>{this._streams[i].getTracks().find(t=>e.track===t)&&(t=this._streams[i])}),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function nn(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){let i=e.RTCPeerConnection.prototype[t];e.RTCPeerConnection.prototype[t]=({[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}})[t]})}function nr(e,t){i$(e,"negotiationneeded",e=>{let i=e.target;if(!(t.version<72)&&(!i.getConfiguration||"plan-b"!==i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e})}var ns=Object.freeze({__proto__:null,fixNegotiationNeeded:nr,shimAddTrackRemoveTrack:ni,shimAddTrackRemoveTrackWithNative:nt,shimGetSendersWithDtmf:i7,shimGetUserMedia:i9,shimMediaStream:i5,shimOnTrack:i8,shimPeerConnection:nn,shimSenderReceiverGetStats:ne});function na(e,t){let i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){i3("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){let e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(e((i=JSON.parse(JSON.stringify(i))).audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},n&&n.prototype.getSettings){let t=n.prototype.getSettings;n.prototype.getSettings=function(){let i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(n&&n.prototype.applyConstraints){let t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(e(i=JSON.parse(JSON.stringify(i)),"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function no(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function nc(e,t){if("object"!=typeof e||!(e.RTCPeerConnection||e.mozRTCPeerConnection))return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){let i=e.RTCPeerConnection.prototype[t];e.RTCPeerConnection.prototype[t]=({[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}})[t]});let i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){let[e,r,s]=arguments;return n.apply(this,[e||null]).then(e=>{if(t.version<53&&!r)try{e.forEach(e=>{e.type=i[e.type]||e.type})}catch(t){if("TypeError"!==t.name)throw t;e.forEach((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))})}return e}).then(r,s)}}function nl(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;let t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});let i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function nd(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;let t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),i$(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function nu(e){!e.RTCPeerConnection||"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){i3("removeStream","removeTrack"),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function nh(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function np(e){if(!("object"==typeof e&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]);let i=(e=[...e]).length>0;i&&e.forEach(e=>{if("rid"in e&&!/^[a-z0-9]{0,16}$/i.test(e.rid))throw TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw RangeError("max_framerate must be >= 0.0")});let n=t.apply(this,arguments);if(i){let{sender:t}=n,i=t.getParameters();"encodings"in i&&(1!==i.encodings.length||0!==Object.keys(i.encodings[0]).length)||(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then(()=>{delete t.sendEncodings}).catch(()=>{delete t.sendEncodings})))}return n})}function nm(e){if(!("object"==typeof e&&e.RTCRtpSender))return;let t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){let e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function ng(e){if(!("object"==typeof e&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}function nf(e){if(!("object"==typeof e&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}var nv=Object.freeze({__proto__:null,shimAddTransceiver:np,shimCreateAnswer:nf,shimCreateOffer:ng,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!(i&&i.video)){let e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:nm,shimGetUserMedia:na,shimOnTrack:no,shimPeerConnection:nc,shimRTCDataChannel:nh,shimReceiverGetStats:nd,shimRemoveStream:nu,shimSenderGetStats:nl});function nb(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(i=>t.call(this,i,e)),e.getVideoTracks().forEach(i=>t.call(this,i,e))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var i=arguments.length,n=Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];return n&&n.forEach(e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]}),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);let t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);let i=e.getTracks();this.getSenders().forEach(e=>{i.includes(e.track)&&this.removeTrack(e)})})}}function nk(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach(e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);let t=new Event("addstream");t.stream=e,this.dispatchEvent(t)})})}});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){let e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach(t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);let i=new Event("addstream");i.stream=t,e.dispatchEvent(i)})}),t.apply(e,arguments)}}}function ny(e){if("object"!=typeof e||!e.RTCPeerConnection)return;let t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,r=t.setLocalDescription,s=t.setRemoteDescription,a=t.addIceCandidate;t.createOffer=function(e,t){let n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),Promise.resolve()):r},t.createAnswer=function(e,t){let i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),Promise.resolve()):r};let o=function(e,t,i){let n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=o,t.setRemoteDescription=o=function(e,t,i){let n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=function(e,t,i){let n=a.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n}}function nT(e){let t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){let e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(nC(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=(function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}).bind(t))}function nC(e){return e&&void 0!==e.video?Object.assign({},e,{video:function e(t){return i4(t)?Object.keys(t).reduce(function(i,n){let r=i4(t[n]),s=r?e(t[n]):t[n],a=r&&!Object.keys(s).length;return void 0===s||a?i:Object.assign(i,{[n]:s})},{}):t}(e.video)}):e}function nS(e){if(!e.RTCPeerConnection)return;let t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){let t=[];for(let i=0;i<e.iceServers.length;i++){let n=e.iceServers[i];void 0===n.urls&&n.url?(i3("RTCIceServer.url","RTCIceServer.urls"),(n=JSON.parse(JSON.stringify(n))).urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function nw(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function nE(e){let t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);let t=this.getTransceivers().find(e=>"audio"===e.receiver.track.kind);!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);let i=this.getTransceivers().find(e=>"video"===e.receiver.track.kind);!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function nP(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var nR=Object.freeze({__proto__:null,shimAudioContext:nP,shimCallbacksAPI:ny,shimConstraints:nC,shimCreateOfferLegacy:nE,shimGetUserMedia:nT,shimLocalStreamsAPI:nb,shimRTCIceServerUrls:nS,shimRemoteStreamsAPI:nk,shimTrackEventTransceiver:nw}),nI={exports:{}},nO=function(){if(m)return nI.exports;m=1;let e={};return e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(e){return e.trim().split("\n").map(e=>e.trim())},e.splitSections=function(e){return e.split("\nm=").map((e,t)=>(t>0?"m="+e:e).trim()+"\r\n")},e.getDescription=function(t){let i=e.splitSections(t);return i&&i[0]},e.getMediaSections=function(t){let i=e.splitSections(t);return i.shift(),i},e.matchPrefix=function(t,i){return e.splitLines(t).filter(e=>0===e.indexOf(i))},e.parseCandidate=function(e){let t,i={foundation:(t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" "))[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":i.relatedAddress=t[e+1];break;case"rport":i.relatedPort=parseInt(t[e+1],10);break;case"tcptype":i.tcpType=t[e+1];break;case"ufrag":i.ufrag=t[e+1],i.usernameFragment=t[e+1];break;default:void 0===i[t[e]]&&(i[t[e]]=t[e+1])}return i},e.writeCandidate=function(e){let t=[];t.push(e.foundation);let i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);let n=e.type;return t.push("typ"),t.push(n),"host"!==n&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},e.parseIceOptions=function(e){return e.substring(14).split(" ")},e.parseRtpMap=function(e){let t=e.substring(9).split(" "),i={payloadType:parseInt(t.shift(),10)};return i.name=(t=t[0].split("/"))[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},e.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);let i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},e.parseExtmap=function(e){let t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},e.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},e.parseFmtp=function(e){let t,i={},n=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<n.length;e++)i[(t=n[e].trim().split("="))[0].trim()]=t[1];return i},e.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){let n=[];Object.keys(e.parameters).forEach(t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)}),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return t},e.parseRtcpFb=function(e){let t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},e.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach(e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"}),t},e.parseSsrcMedia=function(e){let t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},e.parseSsrcGroup=function(e){let t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map(e=>parseInt(e,10))}},e.getMid=function(t){let i=e.matchPrefix(t,"a=mid:")[0];if(i)return i.substring(6)},e.parseFingerprint=function(e){let t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},e.getDtlsParameters=function(t,i){return{role:"auto",fingerprints:e.matchPrefix(t+i,"a=fingerprint:").map(e.parseFingerprint)}},e.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach(e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"}),i},e.parseCryptoLine=function(e){let t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},e.writeCryptoLine=function(t){return"a=crypto:"+t.tag+" "+t.cryptoSuite+" "+("object"==typeof t.keyParams?e.writeCryptoKeyParams(t.keyParams):t.keyParams)+(t.sessionParams?" "+t.sessionParams.join(" "):"")+"\r\n"},e.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;let t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},e.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},e.getCryptoParameters=function(t,i){return e.matchPrefix(t+i,"a=crypto:").map(e.parseCryptoLine)},e.getIceParameters=function(t,i){let n=e.matchPrefix(t+i,"a=ice-ufrag:")[0],r=e.matchPrefix(t+i,"a=ice-pwd:")[0];return n&&r?{usernameFragment:n.substring(12),password:r.substring(10)}:null},e.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},e.parseRtpParameters=function(t){let i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=e.splitLines(t)[0].split(" ");i.profile=n[2];for(let r=3;r<n.length;r++){let s=n[r],a=e.matchPrefix(t,"a=rtpmap:"+s+" ")[0];if(a){let n=e.parseRtpMap(a),r=e.matchPrefix(t,"a=fmtp:"+s+" ");switch(n.parameters=r.length?e.parseFmtp(r[0]):{},n.rtcpFeedback=e.matchPrefix(t,"a=rtcp-fb:"+s+" ").map(e.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}e.matchPrefix(t,"a=extmap:").forEach(t=>{i.headerExtensions.push(e.parseExtmap(t))});let r=e.matchPrefix(t,"a=rtcp-fb:* ").map(e.parseRtcpFb);return i.codecs.forEach(e=>{r.forEach(t=>{e.rtcpFeedback.find(e=>e.type===t.type&&e.parameter===t.parameter)||e.rtcpFeedback.push(t)})}),i},e.writeRtpDescription=function(t,i){let n="";n+="m="+t+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map(e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach(t=>{n+=e.writeRtpMap(t),n+=e.writeFmtp(t),n+=e.writeRtcpFb(t)});let r=0;return i.codecs.forEach(e=>{e.maxptime>r&&(r=e.maxptime)}),r>0&&(n+="a=maxptime:"+r+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach(t=>{n+=e.writeExtmap(t)}),n},e.parseRtpEncodingParameters=function(t){let i,n=[],r=e.parseRtpParameters(t),s=-1!==r.fecMechanisms.indexOf("RED"),a=-1!==r.fecMechanisms.indexOf("ULPFEC"),o=e.matchPrefix(t,"a=ssrc:").map(t=>e.parseSsrcMedia(t)).filter(e=>"cname"===e.attribute),c=o.length>0&&o[0].ssrc,l=e.matchPrefix(t,"a=ssrc-group:FID").map(e=>e.substring(17).split(" ").map(e=>parseInt(e,10)));l.length>0&&l[0].length>1&&l[0][0]===c&&(i=l[0][1]),r.codecs.forEach(e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:c,codecPayloadType:parseInt(e.parameters.apt,10)};c&&i&&(t.rtx={ssrc:i}),n.push(t),s&&((t=JSON.parse(JSON.stringify(t))).fec={ssrc:c,mechanism:a?"red+ulpfec":"red"},n.push(t))}}),0===n.length&&c&&n.push({ssrc:c});let d=e.matchPrefix(t,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substring(7),10):0===d[0].indexOf("b=AS:")?1e3*parseInt(d[0].substring(5),10)*.95-16e3:void 0,n.forEach(e=>{e.maxBitrate=d})),n},e.parseRtcpParameters=function(t){let i={},n=e.matchPrefix(t,"a=ssrc:").map(t=>e.parseSsrcMedia(t)).filter(e=>"cname"===e.attribute)[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);let r=e.matchPrefix(t,"a=rtcp-rsize");return i.reducedSize=r.length>0,i.compound=0===r.length,i.mux=e.matchPrefix(t,"a=rtcp-mux").length>0,i},e.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},e.parseMsid=function(t){let i,n=e.matchPrefix(t,"a=msid:");if(1===n.length)return{stream:(i=n[0].substring(7).split(" "))[0],track:i[1]};let r=e.matchPrefix(t,"a=ssrc:").map(t=>e.parseSsrcMedia(t)).filter(e=>"msid"===e.attribute);if(r.length>0)return{stream:(i=r[0].value.split(" "))[0],track:i[1]}},e.parseSctpDescription=function(t){let i,n=e.parseMLine(t),r=e.matchPrefix(t,"a=max-message-size:");r.length>0&&(i=parseInt(r[0].substring(19),10)),isNaN(i)&&(i=65536);let s=e.matchPrefix(t,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:n.fmt,maxMessageSize:i};let a=e.matchPrefix(t,"a=sctpmap:");if(a.length>0){let e=a[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:i}}},e.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},e.generateSessionId=function(){return Math.random().toString().substr(2,22)},e.writeSessionBoilerplate=function(t,i,n){return"v=0\r\no="+(n||"thisisadapterortc")+" "+(t||e.generateSessionId())+" "+(void 0!==i?i:2)+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},e.getDirection=function(t,i){let n=e.splitLines(t);for(let e=0;e<n.length;e++)switch(n[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[e].substring(2)}return i?e.getDirection(i):"sendrecv"},e.getKind=function(t){return e.splitLines(t)[0].split(" ")[0].substring(2)},e.isRejected=function(e){return"0"===e.split(" ",2)[1]},e.parseMLine=function(t){let i=e.splitLines(t)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},e.parseOLine=function(t){let i=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},e.isValidSDP=function(t){if("string"!=typeof t||0===t.length)return!1;let i=e.splitLines(t);for(let e=0;e<i.length;e++)if(i[e].length<2||"="!==i[e].charAt(1))return!1;return!0},nI.exports=e,nI.exports}(),nD=function(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}(nO),nx=function(e,t){return t.forEach(function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach(function(i){if("default"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}})}),Object.freeze(e)}({__proto__:null,default:nD},[nO]);function n_(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;let t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){let i=new t(e),n=nD.parseCandidate(e.candidate);for(let e in n)e in i||Object.defineProperty(i,e,{value:n[e]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,i$(e,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t))}function nM(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||i$(e,"icecandidate",e=>{if(e.candidate){let t=nD.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol=({0:"tls",1:"tcp",2:"udp"})[t.priority>>24])}return e})}function nA(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});let i=function(e){if(!e||!e.sdp)return!1;let t=nD.splitSections(e.sdp);return t.shift(),t.some(e=>{let t=nD.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")})},n=function(e){let t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return -1;let i=parseInt(t[1],10);return i!=i?-1:i},r=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:0x7ffffff5:t.version<60?57===t.version?65535:65536:0x7ffffff5),i},s=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);let r=nD.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?n=parseInt(r[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=0x7ffffff5),n},a=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){let{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(i(arguments[0])){let e,t=n(arguments[0]),i=r(t),a=s(arguments[0],t);e=0===i&&0===a?1/0:0===i||0===a?Math.max(i,a):Math.min(i,a);let o={};Object.defineProperty(o,"maxMessageSize",{get:()=>e}),this._sctp=o}return a.apply(this,arguments)}}function nN(e){if(!(e.RTCPeerConnection&&"createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){let i=e.send;e.send=function(){let n=arguments[0],r=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&r>t.sctp.maxMessageSize)throw TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}let i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){let e=i.apply(this,arguments);return t(e,this),e},i$(e,"datachannel",e=>(t(e.channel,e.target),e))}function nL(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;let t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return({completed:"connected",checking:"connecting"})[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(e=>{let i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{let t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;let i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function nU(e,t){if(!e.RTCPeerConnection||"chrome"===t.browser&&t.version>=71||"safari"===t.browser&&t._safariVersion>=13.1)return;let i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){let i=t.sdp.split("\n").filter(e=>"a=extmap-allow-mixed"!==e.trim()).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function nj(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function nF(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(!(e={type:e.type,sdp:e.sdp}).type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}return e.sdp||"offer"!==e.type&&"answer"!==e.type?i.apply(this,[e]):("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then(e=>i.apply(this,[e]))})}var nB=Object.freeze({__proto__:null,removeExtmapAllowMixed:nU,shimAddIceCandidateNullOrEmpty:nj,shimConnectionState:nL,shimMaxMessageSize:nA,shimParameterlessSetLocalDescription:nF,shimRTCIceCandidate:n_,shimRTCIceCandidateRelayProtocol:nM,shimSendThrowTypeError:nN});!function(){let{window:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0},i=function(e){let t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;let{navigator:i}=e;if(i.userAgentData&&i.userAgentData.brands){let e=i.userAgentData.brands.find(e=>"Chromium"===e.brand);if(e)return{browser:"chrome",version:parseInt(e.version,10)}}return i.mozGetUserMedia?(t.browser="firefox",t.version=parseInt(iZ(i.userAgent,/Firefox\/(\d+)\./,1))):i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection?(t.browser="chrome",t.version=parseInt(iZ(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2))):e.RTCPeerConnection&&i.userAgent.match(/AppleWebKit\/(\d+)\./)?(t.browser="safari",t.version=parseInt(iZ(i.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=iZ(i.userAgent,/Version\/(\d+(\.?\d+))/,1)):t.browser="Not a supported browser.",t}(e),n={browserDetails:i,commonShim:nB,extractVersion:iZ,disableLog:i0,disableWarnings:i1,sdp:nx};switch(i.browser){case"chrome":if(!ns||!nn||!t.shimChrome){i2("Chrome shim is not included in this adapter release.");break}if(null===i.version){i2("Chrome shim can not determine version, not shimming.");break}i2("adapter.js shimming chrome."),n.browserShim=ns,nj(e,i),nF(e),i9(e,i),i5(e),nn(e,i),i8(e),ni(e,i),i7(e),ne(e),nr(e,i),n_(e),nM(e),nL(e),nA(e,i),nN(e),nU(e,i);break;case"firefox":if(!nv||!nc||!t.shimFirefox){i2("Firefox shim is not included in this adapter release.");break}i2("adapter.js shimming firefox."),n.browserShim=nv,nj(e,i),nF(e),na(e,i),nc(e,i),no(e),nu(e),nl(e),nd(e),nh(e),np(e),nm(e),ng(e),nf(e),n_(e),nL(e),nA(e,i),nN(e);break;case"safari":if(!nR||!t.shimSafari){i2("Safari shim is not included in this adapter release.");break}i2("adapter.js shimming safari."),n.browserShim=nR,nj(e,i),nF(e),nS(e),nE(e),ny(e),nb(e),nk(e),nw(e),nT(e),nP(e),n_(e),nM(e),nA(e,i),nN(e),nU(e,i);break;default:i2("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});let nV="lk_e2ee";function nq(){return void 0!==window.RTCRtpScriptTransform}!function(e){e.SetKey="setKey",e.RatchetRequest="ratchetRequest",e.KeyRatcheted="keyRatcheted"}(g||(g={})),(f||(f={})).KeyRatcheted="keyRatcheted",function(e){e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError"}(v||(v={})),(b||(b={})).Error="cryptorError",iQ.EventEmitter;class nH extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}!function(e){e[e.NotAllowed=0]="NotAllowed",e[e.ServerUnreachable=1]="ServerUnreachable",e[e.InternalError=2]="InternalError",e[e.Cancelled=3]="Cancelled",e[e.LeaveRequest=4]="LeaveRequest",e[e.Timeout=5]="Timeout"}(k||(k={}));class nG extends nH{constructor(e,t,i,n){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=n,this.reasonName=k[t]}}class nW extends nH{constructor(e){super(21,null!=e?e:"device is unsupported"),this.name="DeviceUnsupportedError"}}class nK extends nH{constructor(e){super(20,null!=e?e:"track is invalid"),this.name="TrackInvalidError"}}class nz extends nH{constructor(e){super(10,null!=e?e:"unsupported server"),this.name="UnsupportedServer"}}class nJ extends nH{constructor(e){super(12,null!=e?e:"unexpected connection state"),this.name="UnexpectedConnectionState"}}class nQ extends nH{constructor(e){super(13,null!=e?e:"unable to negotiate"),this.name="NegotiationError"}}class nY extends nH{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class nX extends nH{constructor(e,t){super(15,e),this.reason=t,this.reasonName="string"==typeof t?t:iL[t]}}!function(e){e[e.AlreadyOpened=0]="AlreadyOpened",e[e.AbnormalEnd=1]="AbnormalEnd",e[e.DecodeFailed=2]="DecodeFailed",e[e.LengthExceeded=3]="LengthExceeded",e[e.Incomplete=4]="Incomplete",e[e.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered"}(y||(y={}));class nZ extends nH{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=y[t]}}!function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"}(T||(T={})),function(e){e.getFailure=function(t){if(t&&"name"in t)return"NotFoundError"===t.name||"DevicesNotFoundError"===t.name?e.NotFound:"NotAllowedError"===t.name||"PermissionDeniedError"===t.name?e.PermissionDenied:"NotReadableError"===t.name||"TrackStartError"===t.name?e.DeviceInUse:e.Other}}(T||(T={})),function(e){e[e.InvalidKey=0]="InvalidKey",e[e.MissingKey=1]="MissingKey",e[e.InternalError=2]="InternalError"}(C||(C={})),function(e){e.Connected="connected",e.Reconnecting="reconnecting",e.SignalReconnecting="signalReconnecting",e.Reconnected="reconnected",e.Disconnected="disconnected",e.ConnectionStateChanged="connectionStateChanged",e.Moved="moved",e.MediaDevicesChanged="mediaDevicesChanged",e.ParticipantConnected="participantConnected",e.ParticipantDisconnected="participantDisconnected",e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalAudioSilenceDetected="localAudioSilenceDetected",e.ActiveSpeakersChanged="activeSpeakersChanged",e.ParticipantMetadataChanged="participantMetadataChanged",e.ParticipantNameChanged="participantNameChanged",e.ParticipantAttributesChanged="participantAttributesChanged",e.ParticipantActive="participantActive",e.RoomMetadataChanged="roomMetadataChanged",e.DataReceived="dataReceived",e.SipDTMFReceived="sipDTMFReceived",e.TranscriptionReceived="transcriptionReceived",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.AudioPlaybackStatusChanged="audioPlaybackChanged",e.VideoPlaybackStatusChanged="videoPlaybackChanged",e.MediaDevicesError="mediaDevicesError",e.ParticipantPermissionsChanged="participantPermissionsChanged",e.SignalConnected="signalConnected",e.RecordingStatusChanged="recordingStatusChanged",e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError",e.DCBufferStatusChanged="dcBufferStatusChanged",e.ActiveDeviceChanged="activeDeviceChanged",e.ChatMessage="chatMessage",e.LocalTrackSubscribed="localTrackSubscribed",e.MetricsReceived="metricsReceived"}(S||(S={})),function(e){e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalTrackCpuConstrained="localTrackCpuConstrained",e.LocalSenderCreated="localSenderCreated",e.ParticipantMetadataChanged="participantMetadataChanged",e.ParticipantNameChanged="participantNameChanged",e.DataReceived="dataReceived",e.SipDTMFReceived="sipDTMFReceived",e.TranscriptionReceived="transcriptionReceived",e.IsSpeakingChanged="isSpeakingChanged",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.TrackCpuConstrained="trackCpuConstrained",e.MediaDevicesError="mediaDevicesError",e.AudioStreamAcquired="audioStreamAcquired",e.ParticipantPermissionsChanged="participantPermissionsChanged",e.PCTrackAdded="pcTrackAdded",e.AttributesChanged="attributesChanged",e.LocalTrackSubscribed="localTrackSubscribed",e.ChatMessage="chatMessage",e.Active="active"}(w||(w={})),function(e){e.TransportsCreated="transportsCreated",e.Connected="connected",e.Disconnected="disconnected",e.Resuming="resuming",e.Resumed="resumed",e.Restarting="restarting",e.Restarted="restarted",e.SignalResumed="signalResumed",e.SignalRestarted="signalRestarted",e.Closing="closing",e.MediaTrackAdded="mediaTrackAdded",e.ActiveSpeakersUpdate="activeSpeakersUpdate",e.DataPacketReceived="dataPacketReceived",e.RTPVideoMapUpdate="rtpVideoMapUpdate",e.DCBufferStatusChanged="dcBufferStatusChanged",e.ParticipantUpdate="participantUpdate",e.RoomUpdate="roomUpdate",e.SpeakersChanged="speakersChanged",e.StreamStateChanged="streamStateChanged",e.ConnectionQualityUpdate="connectionQualityUpdate",e.SubscriptionError="subscriptionError",e.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",e.RemoteMute="remoteMute",e.SubscribedQualityUpdate="subscribedQualityUpdate",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalTrackSubscribed="localTrackSubscribed",e.Offline="offline",e.SignalRequestResponse="signalRequestResponse",e.SignalConnected="signalConnected",e.RoomMoved="roomMoved"}(E||(E={})),function(e){e.Message="message",e.Muted="muted",e.Unmuted="unmuted",e.Restarted="restarted",e.Ended="ended",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed",e.CpuConstrained="cpuConstrained",e.UpdateSettings="updateSettings",e.UpdateSubscription="updateSubscription",e.AudioPlaybackStarted="audioPlaybackStarted",e.AudioPlaybackFailed="audioPlaybackFailed",e.AudioSilenceDetected="audioSilenceDetected",e.VisibilityChanged="visibilityChanged",e.VideoDimensionsChanged="videoDimensionsChanged",e.VideoPlaybackStarted="videoPlaybackStarted",e.VideoPlaybackFailed="videoPlaybackFailed",e.ElementAttached="elementAttached",e.ElementDetached="elementDetached",e.UpstreamPaused="upstreamPaused",e.UpstreamResumed="upstreamResumed",e.SubscriptionPermissionChanged="subscriptionPermissionChanged",e.SubscriptionStatusChanged="subscriptionStatusChanged",e.SubscriptionFailed="subscriptionFailed",e.TrackProcessorUpdate="trackProcessorUpdate",e.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",e.TranscriptionReceived="transcriptionReceived",e.TimeSyncUpdate="timeSyncUpdate",e.PreConnectBufferFlushed="preConnectBufferFlushed"}(P||(P={}));let n$=/version\/(\d+(\.?_?\d+)+)/i;function n0(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1];if(void 0===e&&"undefined"==typeof navigator)return;let i=(null!=e?e:navigator.userAgent).toLowerCase();if(void 0===n||t){let e=n1.find(e=>{let{test:t}=e;return t.test(i)});n=null==e?void 0:e.describe(i)}return n}let n1=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:n2(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:n3(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:n2(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:n3(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:n2(n$,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:n3(e)})}];function n2(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=t.match(e);return n&&n.length>=i&&n[i]||""}function n3(e){return e.includes("mac os")?n2(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}class n4{}n4.setTimeout=function(){return setTimeout(...arguments)},n4.setInterval=function(){return setInterval(...arguments)},n4.clearTimeout=function(){return clearTimeout(...arguments)},n4.clearInterval=function(){return clearInterval(...arguments)};let n6=[];!function(e){e[e.LOW=0]="LOW",e[e.MEDIUM=1]="MEDIUM",e[e.HIGH=2]="HIGH"}(R||(R={}));class n9 extends iQ.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(e,t){var i;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.attachedElements=[],this.isMuted=!1,this._streamState=n9.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=iV,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),5e3):this.handleAppVisibilityChanged()},this.log=iq(null!=(i=n.loggerName)?i:h.Track),this.loggerContextCb=n.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=n9.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null==(e=this.loggerContextCb)?void 0:e.call(this)),rZ(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===n9.Kind.Video&&(t="video"),0===this.attachedElements.length&&this.kind===n9.Kind.Video&&this.addAppVisibilityListener(),!e&&("audio"===t&&(n6.forEach(t=>{null!==t.parentElement||e||(e=t)}),e&&n6.splice(n6.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),n5(this.mediaStreamTrack,e);let i=e.srcObject.getTracks(),n=i.some(e=>"audio"===e.kind);return e.play().then(()=>{this.emit(n?P.AudioPlaybackStarted:P.VideoPlaybackStarted)}).catch(t=>{"NotAllowedError"===t.name?this.emit(n?P.AudioPlaybackFailed:P.VideoPlaybackFailed,t):"AbortError"===t.name?iV.debug("".concat(n?"audio":"video"," playback aborted, likely due to new play request")):iV.warn("could not playback ".concat(n?"audio":"video"),t),n&&e&&i.some(e=>"video"===e.kind)&&"NotAllowedError"===t.name&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(P.ElementAttached,e),e}detach(e){try{if(e){n8(this.mediaStreamTrack,e);let t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(P.ElementDetached,e)),e}let t=[];return this.attachedElements.forEach(e=>{n8(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(P.ElementDetached,e)}),this.attachedElements=[],t}finally{0===this.attachedElements.length&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=iq(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),n6.forEach(e=>{e.parentElement||(t=!1)}),t&&n6.push(e)}}handleAppVisibilityChanged(){return iK(this,void 0,void 0,function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==n9.Kind.Video||setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){rv()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){rv()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function n5(e,t){let i,n;i=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream,(n="audio"===e.kind?i.getAudioTracks():i.getVideoTracks()).includes(e)||(n.forEach(e=>{i.removeTrack(e)}),i.addTrack(e)),rm()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===i.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==i&&(t.srcObject=i,(rm()||rp())&&t instanceof HTMLVideoElement&&setTimeout(()=>{t.srcObject=i,t.play().catch(()=>{})},0))}function n8(e,t){if(t.srcObject instanceof MediaStream){let i=t.srcObject;i.removeTrack(e),i.getTracks().length>0?t.srcObject=i:t.srcObject=null}}!function(e){var t,i,n;let r,s,a;(t=r=e.Kind||(e.Kind={})).Audio="audio",t.Video="video",t.Unknown="unknown",(i=s=e.Source||(e.Source={})).Camera="camera",i.Microphone="microphone",i.ScreenShare="screen_share",i.ScreenShareAudio="screen_share_audio",i.Unknown="unknown",(n=a=e.StreamState||(e.StreamState={})).Active="active",n.Paused="paused",n.Unknown="unknown",e.kindToProto=function(e){switch(e){case r.Audio:return tn.AUDIO;case r.Video:return tn.VIDEO;default:return tn.DATA}},e.kindFromProto=function(e){switch(e){case tn.AUDIO:return r.Audio;case tn.VIDEO:return r.Video;default:return r.Unknown}},e.sourceToProto=function(e){switch(e){case s.Camera:return tr.CAMERA;case s.Microphone:return tr.MICROPHONE;case s.ScreenShare:return tr.SCREEN_SHARE;case s.ScreenShareAudio:return tr.SCREEN_SHARE_AUDIO;default:return tr.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case tr.CAMERA:return s.Camera;case tr.MICROPHONE:return s.Microphone;case tr.SCREEN_SHARE:return s.ScreenShare;case tr.SCREEN_SHARE_AUDIO:return s.ScreenShareAudio;default:return s.Unknown}},e.streamStateFromProto=function(e){switch(e){case tZ.ACTIVE:return a.Active;case tZ.PAUSED:return a.Paused;default:return a.Unknown}}}(n9||(n9={}));class n7{constructor(e,t,i,n,r){if("object"==typeof e)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(void 0!==t&&void 0!==i)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:n,priority:r};else throw 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}}}let re=["vp8","h264"],rt=["vp8","h264","vp9","av1","h265"];!function(e){e[e.PREFER_REGRESSION=0]="PREFER_REGRESSION",e[e.SIMULCAST=1]="SIMULCAST",e[e.REGRESSION=2]="REGRESSION"}(I||(I={})),function(e){e.telephone={maxBitrate:12e3},e.speech={maxBitrate:24e3},e.music={maxBitrate:48e3},e.musicStereo={maxBitrate:64e3},e.musicHighQuality={maxBitrate:96e3},e.musicHighQualityStereo={maxBitrate:128e3}}(O||(O={}));let ri={h90:new n7(160,90,9e4,20),h180:new n7(320,180,16e4,20),h216:new n7(384,216,18e4,20),h360:new n7(640,360,45e4,20),h540:new n7(960,540,8e5,25),h720:new n7(1280,720,17e5,30),h1080:new n7(1920,1080,3e6,30),h1440:new n7(2560,1440,5e6,30),h2160:new n7(3840,2160,8e6,30)},rn={h120:new n7(160,120,7e4,20),h180:new n7(240,180,125e3,20),h240:new n7(320,240,14e4,20),h360:new n7(480,360,33e4,20),h480:new n7(640,480,5e5,20),h540:new n7(720,540,6e5,25),h720:new n7(960,720,13e5,30),h1080:new n7(1440,1080,23e5,30),h1440:new n7(1920,1440,38e5,30)},rr={h360fps3:new n7(640,360,2e5,3,"medium"),h360fps15:new n7(640,360,4e5,15,"medium"),h720fps5:new n7(1280,720,8e5,5,"medium"),h720fps15:new n7(1280,720,15e5,15,"medium"),h720fps30:new n7(1280,720,2e6,30,"medium"),h1080fps15:new n7(1920,1080,25e5,15,"medium"),h1080fps30:new n7(1920,1080,5e6,30,"medium"),original:new n7(0,0,7e6,30,"medium")},rs="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function ra(e){return iK(this,void 0,void 0,function*(){return new Promise(t=>n4.setTimeout(t,e))})}function ro(){return"addTransceiver"in RTCPeerConnection.prototype}function rc(){return"addTrack"in RTCPeerConnection.prototype}function rl(){return!0}function rd(){return ro()}function ru(e){return"av1"===e||"vp9"===e}function rh(e){return!(!document||rg())&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function rp(){var e;return(null==(e=n0())?void 0:e.name)==="Firefox"}function rm(){var e;return(null==(e=n0())?void 0:e.name)==="Safari"}function rg(){let e=n0();return(null==e?void 0:e.name)==="Safari"||(null==e?void 0:e.os)==="iOS"}function rf(){var e,t;return!!rv()&&(null!=(t=null==(e=navigator.userAgentData)?void 0:e.mobile)?t:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent))}function rv(){return"undefined"!=typeof document}function rb(){return"ReactNative"==navigator.product}function rk(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function ry(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function rT(){if(!rb())return;let e=ry();if(e)return e.platform}function rC(){if(rv())return window.devicePixelRatio;if(rb()){let e=ry();if(e)return e.devicePixelRatio}return 1}function rS(e,t){let i=e.split("."),n=t.split("."),r=Math.min(i.length,n.length);for(let e=0;e<r;++e){let t=parseInt(i[e],10),s=parseInt(n[e],10);if(t>s)return 1;if(t<s)return -1;if(e===r-1&&t===s)return 0}return""===e&&""!==t?-1:""===t?1:i.length==n.length?0:i.length<n.length?-1:1}function rw(e){for(let t of e)t.target.handleResize(t)}function rE(e){for(let t of e)t.target.handleVisibilityChanged(t)}let rP=null,rR=()=>(rP||(rP=new ResizeObserver(rw)),rP),rI=null,rO=()=>(rI||(rI=new IntersectionObserver(rE,{root:null,rootMargin:"0px"})),rI);function rD(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=document.createElement("canvas");r.width=e,r.height=t;let s=r.getContext("2d");null==s||s.fillRect(0,0,r.width,r.height),n&&s&&(s.beginPath(),s.arc(e/2,t/2,50,0,2*Math.PI,!0),s.closePath(),s.fillStyle="grey",s.fill());let[a]=r.captureStream().getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=i,a}function rx(){if(!r){let e=new AudioContext,t=e.createOscillator(),i=e.createGain();i.gain.setValueAtTime(0,0);let n=e.createMediaStreamDestination();if(t.connect(i),i.connect(n),t.start(),[r]=n.stream.getAudioTracks(),!r)throw Error("Could not get empty media stream audio track");r.enabled=!1}return r.clone()}class r_{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((t,i)=>iK(this,void 0,void 0,function*(){this.resolve=t,this.reject=i,e&&(yield e(t,i))})).finally(()=>{var e;this._isResolved=!0,null==(e=this.onFinally)||e.call(this)})}}function rM(e){if("string"==typeof e||"number"==typeof e)return e;if(Array.isArray(e))return e[0];if(void 0!==e.exact)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(void 0!==e.ideal)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error("could not unwrap constraint")}function rA(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function rN(e){switch(e.reason){case k.LeaveRequest:return e.context;case k.Cancelled:return tc.CLIENT_INITIATED;case k.NotAllowed:return tc.USER_REJECTED;case k.ServerUnreachable:return tc.JOIN_FAILURE;default:return tc.UNKNOWN_REASON}}function rL(e){return void 0!==e?Number(e):void 0}function rU(e){return void 0!==e?BigInt(e):void 0}function rj(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function rF(e){return!!e&&e.kind==n9.Kind.Audio}function rB(e){return!!e&&e.kind==n9.Kind.Video}function rV(e){return rj(e)&&rB(e)}function rq(e){return rj(e)&&rF(e)}function rH(e){return!!e&&!e.isLocal}function rG(e){return rH(e)&&rB(e)}function rW(e,t,i){var n,r;let{optionsWithoutProcessor:s,audioProcessor:a,videoProcessor:o}=r$(null!=e?e:{}),c=null==t?void 0:t.processor,l=null==i?void 0:i.processor,d=null!=s?s:{};return!0===d.audio&&(d.audio={}),!0===d.video&&(d.video={}),d.audio&&(rK(d.audio,t),null!=(n=d.audio).deviceId||(n.deviceId={ideal:"default"}),(a||c)&&(d.audio.processor=null!=a?a:c)),d.video&&(rK(d.video,i),null!=(r=d.video).deviceId||(r.deviceId={ideal:"default"}),(o||l)&&(d.video.processor=null!=o?o:l)),d}function rK(e,t){return Object.keys(t).forEach(i=>{void 0===e[i]&&(e[i]=t[i])}),e}function rz(e){var t,i;let n={};if(e.video)if("object"==typeof e.video){let i={},r=e.video;Object.keys(r).forEach(e=>{"resolution"===e?rK(i,r.resolution):i[e]=r[e]}),n.video=i,null!=(t=n.video).deviceId||(t.deviceId={ideal:"default"})}else n.video=!!e.video&&{deviceId:{ideal:"default"}};else n.video=!1;return e.audio?"object"==typeof e.audio?(n.audio=e.audio,null!=(i=n.audio).deviceId||(i.deviceId={ideal:"default"})):n.audio={deviceId:{ideal:"default"}}:n.audio=!1,n}function rJ(e){return iK(this,arguments,void 0,function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){let i=rQ();if(i){let n=i.createAnalyser();n.fftSize=2048;let r=new Uint8Array(n.frequencyBinCount);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(n),yield ra(t),n.getByteTimeDomainData(r);let s=r.some(e=>128!==e&&0!==e);return i.close(),!s}return!1}()})}function rQ(){var e;let t="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(t){let i=new t({latencyHint:"interactive"});if("suspended"===i.state&&"undefined"!=typeof window&&(null==(e=window.document)?void 0:e.body)){let e=()=>iK(this,void 0,void 0,function*(){var t;try{"suspended"===i.state&&(yield i.resume())}catch(e){console.warn("Error trying to auto-resume audio context",e)}null==(t=window.document.body)||t.removeEventListener("click",e)});window.document.body.addEventListener("click",e)}return i}}function rY(e){return e===n9.Source.Microphone?"audioinput":e===n9.Source.Camera?"videoinput":void 0}function rX(e){return e.split("/")[1].toLowerCase()}function rZ(e){return"mediaStreamTrack"in e?{trackID:e.sid,source:e.source,muted:e.isMuted,enabled:e.mediaStreamTrack.enabled,kind:e.kind,streamID:e.mediaStreamID,streamTrackID:e.mediaStreamTrack.id}:{trackID:e.trackSid,enabled:e.isEnabled,muted:e.isMuted,trackInfo:Object.assign({mimeType:e.mimeType,name:e.trackName,encrypted:e.isEncrypted,kind:e.kind,source:e.source},e.track?rZ(e.track):{})}}function r$(e){let t,i,n=Object.assign({},e);return"object"==typeof n.audio&&n.audio.processor&&(t=n.audio.processor,n.audio=Object.assign(Object.assign({},n.audio),{processor:void 0})),"object"==typeof n.video&&n.video.processor&&(i=n.video.processor,n.video=Object.assign(Object.assign({},n.video),{processor:void 0})),{audioProcessor:t,videoProcessor:i,optionsWithoutProcessor:void 0===n?n:"function"!=typeof structuredClone?JSON.parse(JSON.stringify(n)):"object"==typeof n&&null!==n?structuredClone(Object.assign({},n)):structuredClone(n)}}function r0(e,t){return e.width*e.height<t.width*t.height}class r1 extends iQ.EventEmitter{constructor(e){super(),this.onWorkerMessage=e=>{var t,i;let{kind:n,data:r}=e.data;switch(n){case"error":iV.error(r.error.message),this.emit(v.EncryptionError,r.error);break;case"initAck":r.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e)});break;case"enable":if(r.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e)}),this.encryptionEnabled!==r.enabled&&r.participantIdentity===(null==(t=this.room)?void 0:t.localParticipant.identity))this.emit(v.ParticipantEncryptionStatusChanged,r.enabled,this.room.localParticipant),this.encryptionEnabled=r.enabled;else if(r.participantIdentity){let e=null==(i=this.room)?void 0:i.getParticipantByIdentity(r.participantIdentity);if(!e)throw TypeError("couldn't set encryption status, participant not found".concat(r.participantIdentity));this.emit(v.ParticipantEncryptionStatusChanged,r.enabled,e)}break;case"ratchetKey":this.keyProvider.emit(g.KeyRatcheted,r.ratchetResult,r.participantIdentity,r.keyIndex)}},this.onWorkerError=e=>{iV.error("e2ee worker encountered an error:",{error:e.error}),this.emit(v.EncryptionError,e.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!(void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams||nq()))throw new nW("tried to setup end-to-end encryption on an unsupported browser");if(iV.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);let t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:iH.getLevel()}};this.worker&&(iV.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){iV.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):iV.warn("ignoring server sent trailer as it's empty")}setupEngine(e){e.on(E.RTPVideoMapUpdate,e=>{this.postRTPMap(e)})}setupEventListeners(e,t){e.on(S.TrackPublished,(e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==tk.NONE,t.identity)),e.on(S.ConnectionStateChanged,t=>{t===B.Connected&&e.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==tk.NONE,e.identity)})})}).on(S.TrackUnsubscribed,(e,t,i)=>{var n;let r={kind:"removeTransform",data:{participantIdentity:i.identity,trackId:e.mediaStreamID}};null==(n=this.worker)||n.postMessage(r)}).on(S.TrackSubscribed,(e,t,i)=>{this.setupE2EEReceiver(e,i.identity,t.trackInfo)}).on(S.SignalConnected,()=>{if(!this.room)throw TypeError("expected room to be present on signal connect");t.getKeys().forEach(e=>{this.postKey(e)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(w.LocalSenderCreated,(e,t)=>iK(this,void 0,void 0,function*(){this.setupE2EESender(t,e)})),e.localParticipant.on(w.LocalTrackPublished,e=>{if(!rB(e.track)||!rg())return;let t={kind:"updateCodec",data:{trackId:e.track.mediaStreamID,codec:rX(e.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(t)}),t.on(g.SetKey,e=>this.postKey(e)).on(g.RatchetRequest,(e,t)=>this.postRatchetRequest(e,t))}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");this.worker.postMessage({kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}})}postKey(e){var t;let{key:i,participantIdentity:n,keyIndex:r}=e;if(!this.worker)throw Error("could not set key, worker is missing");let s={kind:"setKey",data:{participantIdentity:n,isPublisher:n===(null==(t=this.room)?void 0:t.localParticipant.identity),key:i,keyIndex:r}};this.worker.postMessage(s)}postEnable(e,t){if(this.worker)this.worker.postMessage({kind:"enable",data:{enabled:e,participantIdentity:t}});else throw 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(!(null==(t=this.room)?void 0:t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");let i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");this.worker.postMessage({kind:"setSifTrailer",data:{trailer:e}})}setupE2EEReceiver(e,t,i){if(e.receiver){if(!(null==i?void 0:i.mimeType)||""===i.mimeType)throw TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?rX(i.mimeType):void 0)}}setupE2EESender(e,t){if(!rj(e)||!t){t||iV.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,i,n){return iK(this,void 0,void 0,function*(){if(this.worker){if(nq())e.transform=new RTCRtpScriptTransform(this.worker,{kind:"decode",participantIdentity:i,trackId:t,codec:n});else{if(nV in e&&n)return void this.worker.postMessage({kind:"updateCodec",data:{trackId:t,codec:n,participantIdentity:i}});let r=e.writableStream,s=e.readableStream;if(!r||!s){let t=e.createEncodedStreams();e.writableStream=t.writable,r=t.writable,e.readableStream=t.readable,s=t.readable}let a={kind:"decode",data:{readableStream:s,writableStream:r,trackId:t,codec:n,participantIdentity:i,isReuse:nV in e}};this.worker.postMessage(a,[s,r])}e[nV]=!0}})}handleSender(e,t,i){var n;if(!(nV in e)&&this.worker){if(!(null==(n=this.room)?void 0:n.localParticipant.identity)||""===this.room.localParticipant.identity)throw TypeError("local identity needs to be known in order to set up encrypted sender");if(nq()){iV.info("initialize script transform");let n={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,n)}else{iV.info("initialize encoded streams");let n=e.createEncodedStreams(),r={kind:"encode",data:{readableStream:n.readable,writableStream:n.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(r,[n.readable,n.writable])}e[nV]=!0}}}let r2="default";class r3{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new r3),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return iK(this,arguments,void 0,function(e){var t=this;let i=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function*(){var n;if((null==(n=r3.userMediaPromiseMap)?void 0:n.size)>0){iV.debug("awaiting getUserMedia promise");try{e?yield r3.userMediaPromiseMap.get(e):yield Promise.all(r3.userMediaPromiseMap.values())}catch(e){iV.warn("error waiting for media permissons")}}let r=yield navigator.mediaDevices.enumerateDevices();if(i&&!(rm()&&t.hasDeviceInUse(e))&&(0===r.filter(t=>t.kind===e).length||r.some(t=>{let i=""===t.label,n=!e||t.kind===e;return i&&n}))){let t=yield navigator.mediaDevices.getUserMedia({video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e&&{deviceId:{ideal:"default"}}});r=yield navigator.mediaDevices.enumerateDevices(),t.getTracks().forEach(e=>{e.stop()})}return t._previousDevices=r,e&&(r=r.filter(t=>t.kind===e)),r}()})}normalizeDeviceId(e,t,i){return iK(this,void 0,void 0,function*(){if(t!==r2)return t;let n=yield this.getDevices(e),r=n.find(e=>e.deviceId===r2);if(!r)return void iV.warn("could not reliably determine default device");let s=n.find(e=>e.deviceId!==r2&&e.groupId===(null!=i?i:r.groupId));return s?null==s?void 0:s.deviceId:void iV.warn("could not reliably determine default device")})}hasDeviceInUse(e){return e?r3.userMediaPromiseMap.has(e):r3.userMediaPromiseMap.size>0}}r3.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],r3.userMediaPromiseMap=new Map,function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(D||(D={}));class r4{constructor(){this.pendingTasks=new Map,this.taskMutex=new W,this.nextTaskIndex=0}run(e){return iK(this,void 0,void 0,function*(){let t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:D.WAITING};this.pendingTasks.set(t.id,t);let i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=D.RUNNING,yield e()}finally{t.status=D.COMPLETED,this.pendingTasks.delete(t.id),i()}})}flush(){return iK(this,void 0,void 0,function*(){return this.run(()=>iK(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}function r6(e,t){var i;return e.pathname="".concat((i=e.pathname).endsWith("/")?i:"".concat(i,"/")).concat(t),e.toString()}let r9=["syncState","trickle","offer","answer","simulate","leave"];!function(e){e[e.CONNECTING=0]="CONNECTING",e[e.CONNECTED=1]="CONNECTED",e[e.RECONNECTING=2]="RECONNECTING",e[e.DISCONNECTING=3]="DISCONNECTING",e[e.DISCONNECTED=4]="DISCONNECTED"}(x||(x={}));class r5{get currentState(){return this.state}get isDisconnected(){return this.state===x.DISCONNECTING||this.state===x.DISCONNECTED}get isEstablishingConnection(){return this.state===x.CONNECTING||this.state===x.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){var e;let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.rtt=0,this.state=x.DISCONNECTED,this.log=iV,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=iq(null!=(e=i.loggerName)?e:h.Signal),this.loggerContextCb=i.loggerContextCb,this.useJSON=t,this.requestQueue=new r4,this.queuedRequests=[],this.closingLock=new W,this.connectionLock=new W,this.state=x.DISCONNECTED}get logContext(){var e,t;return null!=(t=null==(e=this.loggerContextCb)?void 0:e.call(this))?t:{}}join(e,t,i,n){return iK(this,void 0,void 0,function*(){return this.state=x.CONNECTING,this.options=i,yield this.connect(e,t,i,n)})}reconnect(e,t,i,n){return iK(this,void 0,void 0,function*(){return this.options?(this.state=x.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:n}))):void this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext)})}connect(e,t,i,n){this.connectOptions=i;let r=function(e,t){let i=new URL(e.startsWith("http")?e.replace(/^(http)/,"ws"):e);return t.forEach((e,t)=>{i.searchParams.set(t,e)}),r6(i,"rtc")}(e,function(e,t,i){var n;let r=new URLSearchParams;return r.set("access_token",e),i.reconnect&&(r.set("reconnect","1"),i.sid&&r.set("sid",i.sid)),r.set("auto_subscribe",i.autoSubscribe?"1":"0"),r.set("sdk",rb()?"reactnative":"js"),r.set("version",t.version),r.set("protocol",t.protocol.toString()),t.deviceModel&&r.set("device_model",t.deviceModel),t.os&&r.set("os",t.os),t.osVersion&&r.set("os_version",t.osVersion),t.browser&&r.set("browser",t.browser),t.browserVersion&&r.set("browser_version",t.browserVersion),i.adaptiveStream&&r.set("adaptive_stream","1"),i.reconnectReason&&r.set("reconnect_reason",i.reconnectReason.toString()),(null==(n=navigator.connection)?void 0:n.type)&&r.set("network",navigator.connection.type),r}(t,function(){var e;let t=new tF({sdk:tB.JS,protocol:16,version:"2.15.7"});return rb()&&(t.os=null!=(e=rT())?e:""),t}(),i)),s=r6(new URL(rA(r)),"validate");return new Promise((e,t)=>iK(this,void 0,void 0,function*(){let a=yield this.connectionLock.lock();try{let a=()=>iK(this,void 0,void 0,function*(){this.close(),clearTimeout(o),t(new nG("room connection has been cancelled (signal)",k.Cancelled))}),o=setTimeout(()=>{this.close(),t(new nG("room connection has timed out (signal)",k.ServerUnreachable))},i.websocketTimeout);(null==n?void 0:n.aborted)&&a(),null==n||n.addEventListener("abort",a);let c=new URL(r);c.searchParams.has("access_token")&&c.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(c),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(r),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(o)},this.ws.onerror=e=>iK(this,void 0,void 0,function*(){if(this.state!==x.CONNECTED){this.state=x.DISCONNECTED,clearTimeout(o);try{let i=yield fetch(s);if(i.status.toFixed(0).startsWith("4")){let e=yield i.text();t(new nG(e,k.NotAllowed,i.status))}else t(new nG("Encountered unknown websocket error during connection: ".concat(e.toString()),k.InternalError,i.status))}catch(e){t(new nG(e instanceof Error?e.message:"server was not reachable",k.ServerUnreachable))}return}this.handleWSError(e)}),this.ws.onmessage=r=>iK(this,void 0,void 0,function*(){var s,o,c;let l;if("string"==typeof r.data){let e=JSON.parse(r.data);l=t1.fromJson(e,{ignoreUnknownFields:!0})}else{if(!(r.data instanceof ArrayBuffer))return void this.log.error("could not decode websocket message: ".concat(typeof r.data),this.logContext);l=t1.fromBinary(new Uint8Array(r.data))}if(this.state!==x.CONNECTED){let r=!1;if((null==(s=l.message)?void 0:s.case)==="join"?(this.state=x.CONNECTED,null==n||n.removeEventListener("abort",a),this.pingTimeoutDuration=l.message.value.pingTimeout,this.pingIntervalDuration=l.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()),e(l.message.value)):this.state===x.RECONNECTING&&"leave"!==l.message.case?(this.state=x.CONNECTED,null==n||n.removeEventListener("abort",a),this.startPingInterval(),(null==(o=l.message)?void 0:o.case)==="reconnect"?e(l.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),e(void 0),r=!0)):this.isEstablishingConnection&&"leave"===l.message.case?t(new nG("Received leave request while trying to (re)connect",k.LeaveRequest,void 0,l.message.value.reason)):i.reconnect||t(new nG("did not receive join response, got ".concat(null==(c=l.message)?void 0:c.case," instead"),k.InternalError)),!r)return}this.signalLatency&&(yield ra(this.signalLatency)),this.handleSignalResponse(l)}),this.ws.onclose=e=>{this.isEstablishingConnection&&t(new nG("Websocket got closed during a (re)connection attempt",k.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:e.reason,code:e.code,wasClean:e.wasClean,state:this.state})),this.handleOnClose(e.reason)}}finally{a()}}))}close(){return iK(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0];return function*(){let i=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=x.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;let t=new Promise(t=>{e.ws?e.ws.onclose=()=>{t()}:t()});e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([t,ra(250)])),e.ws=void 0}}finally{t&&(e.state=x.DISCONNECTED),i()}}()})}sendOffer(e,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:r7(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:r7(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new t4({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new t6({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return iK(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){let r=i.getNextRequestId();return yield i.sendRequest({case:"updateMetadata",value:new id({requestId:r,metadata:e,name:t,attributes:n})}),r}()})}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 il({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new iS({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:ed.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new iD({timestamp:ed.parse(Date.now()),rtt:ed.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new is({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new io({reason:tc.CLIENT_INITIATED,action:ic.DISCONNECT})})}sendRequest(e){return iK(this,arguments,void 0,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){if(!i&&!function(e){let t=r9.indexOf(e.case)>=0;return iV.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e)&&t.state===x.RECONNECTING)return void t.queuedRequests.push(()=>iK(t,void 0,void 0,function*(){yield this.sendRequest(e,!0)}));if(i||(yield t.requestQueue.flush()),t.signalLatency&&(yield ra(t.signalLatency)),t.isDisconnected)return void t.log.debug("skipping signal request (type: ".concat(e.case,") - SignalClient disconnected"));if(!t.ws||t.ws.readyState!==t.ws.OPEN)return void t.log.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case),t.logContext);let n=new t0({message:e});try{t.useJSON?t.ws.send(n.toJsonString()):t.ws.send(n.toBinary())}catch(e){t.log.error("error sending signal message",Object.assign(Object.assign({},t.logContext),{error:e}))}}()})}handleSignalResponse(e){var t,i;let n=e.message;if(void 0==n)return void this.log.debug("received unsupported message",this.logContext);let r=!1;if("answer"===n.case){let e=r8(n.value);this.onAnswer&&this.onAnswer(e,n.value.id)}else if("offer"===n.case){let e=r8(n.value);this.onOffer&&this.onOffer(e,n.value.id)}else if("trickle"===n.case){let e=JSON.parse(n.value.candidateInit);this.onTrickle&&this.onTrickle(e,n.value.target)}else"update"===n.case?this.onParticipantUpdate&&this.onParticipantUpdate(null!=(t=n.value.participants)?t:[]):"trackPublished"===n.case?this.onLocalTrackPublished&&this.onLocalTrackPublished(n.value):"speakersChanged"===n.case?this.onSpeakersChanged&&this.onSpeakersChanged(null!=(i=n.value.speakers)?i:[]):"leave"===n.case?this.onLeave&&this.onLeave(n.value):"mute"===n.case?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(n.value.sid,n.value.muted):"roomUpdate"===n.case?this.onRoomUpdate&&n.value.room&&this.onRoomUpdate(n.value.room):"connectionQuality"===n.case?this.onConnectionQuality&&this.onConnectionQuality(n.value):"streamStateUpdate"===n.case?this.onStreamStateUpdate&&this.onStreamStateUpdate(n.value):"subscribedQualityUpdate"===n.case?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(n.value):"subscriptionPermissionUpdate"===n.case?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(n.value):"refreshToken"===n.case?this.onTokenRefresh&&this.onTokenRefresh(n.value):"trackUnpublished"===n.case?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(n.value):"subscriptionResponse"===n.case?this.onSubscriptionError&&this.onSubscriptionError(n.value):"pong"===n.case||("pongResp"===n.case?(this.rtt=Date.now()-Number.parseInt(n.value.lastPingTimestamp.toString()),this.resetPingTimeout(),r=!0):"requestResponse"===n.case?this.onRequestResponse&&this.onRequestResponse(n.value):"trackSubscribed"===n.case?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(n.value.trackSid):"roomMoved"===n.case?(this.onTokenRefresh&&this.onTokenRefresh(n.value.token),this.onRoomMoved&&this.onRoomMoved(n.value)):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:n.case})));r||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){let e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return iK(this,void 0,void 0,function*(){if(this.state===x.DISCONNECTED)return;let 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)return void this.log.warn("ping timeout duration not set",this.logContext);this.pingTimeout=n4.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},1e3*this.pingTimeoutDuration)}clearPingTimeout(){this.pingTimeout&&n4.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration)return void this.log.warn("ping interval duration not set",this.logContext);this.log.debug("start ping interval",this.logContext),this.pingInterval=n4.setInterval(()=>{this.sendPing()},1e3*this.pingIntervalDuration)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&n4.clearInterval(this.pingInterval)}}function r8(e){let t={type:"offer",sdp:e.sdp};switch(e.type){case"answer":case"offer":case"pranswer":case"rollback":t.type=e.type}return t}function r7(e,t){return new ie({sdp:e.sdp,type:e.type,id:t})}class se{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){let e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0;)if(this.buffer[0].sequence<=e)this.pop();else break}alignBufferedAmount(e){for(;this.buffer.length>0;){let t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class st{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){let i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();let n=i+this.ttl;return this._map.set(e,{value:t,expiresAt:n}),this}get(e){let t=this._map.get(e);if(t)return t.expiresAt<Date.now()?void this._map.delete(e):t.value}has(e){let t=this._map.get(e);return!!t&&(!(t.expiresAt<Date.now())||(this._map.delete(e),!1))}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){let e=Date.now();for(let[t,i]of this._map.entries())i.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){for(let[t,i]of(this.cleanup(),this._map.entries()))i.expiresAt>=Date.now()&&e(i.value,t,this.asValueMap())}map(e){this.cleanup();let t=[],i=this.asValueMap();for(let[n,r]of i.entries())t.push(e(r,n,i));return t}asValueMap(){let e=new Map;for(let[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e.set(t,i.value);return e}}var si={},sn={},sr={exports:{}};function ss(){if(_)return sr.exports;_=1;var e=sr.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=(null!=e.raddr?" raddr %s rport %d":"%v%v")+(null!=e.tcptype?" tcptype %s":"%v"),null!=e.generation&&(t+=" generation %d"),t+=(null!=e["network-id"]?" network-id %d":"%v")+(null!=e["network-cost"]?" network-cost %d":"%v")}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg: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:RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+((null!=e.id?"id=%s %s":"%v%s")+(null!=e.mediaClockValue?"=%s":"")+(null!=e.rateNumerator?" rate=%s":"")+(null!=e.rateDenominator?"/%s":""))}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(e).forEach(function(t){e[t].forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})}),sr.exports}var sa=function(){if(L)return si;L=1;var e=function(){var e,t,i,n,r,s;return M?sn:(M=1,e=function(e){return String(Number(e))===e?Number(e):e},t=function(t,i,n,r){if(r&&!n)i[r]=e(t[1]);else for(var s=0;s<n.length;s+=1)null!=t[s+1]&&(i[n[s]]=e(t[s+1]))},i=function(e,i,n){var r=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:r&&!i[e.name]&&(i[e.name]={});var s=e.push?{}:r?i[e.name]:i;t(n.match(e.reg),s,e.names,e.name),e.push&&i[e.push].push(s)},n=ss(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/),sn.parse=function(e){var t={},s=[],a=t;return e.split(/(\r\n|\r|\n)/).filter(r).forEach(function(e){var t=e[0],r=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),a=s[s.length-1]);for(var o=0;o<(n[t]||[]).length;o+=1){var c=n[t][o];if(c.reg.test(r))return i(c,a,r)}}),t.media=s,t},s=function(t,i){var n=i.split(/=(.+)/,2);return 2===n.length?t[n[0]]=e(n[1]):1===n.length&&i.length>1&&(t[n[0]]=void 0),t},sn.parseParams=function(e){return e.split(/;\s?/).reduce(s,{})},sn.parseFmtpConfig=sn.parseParams,sn.parsePayloads=function(e){return e.toString().split(" ").map(Number)},sn.parseRemoteCandidates=function(t){for(var i=[],n=t.split(" ").map(e),r=0;r<n.length;r+=3)i.push({component:n[r],ip:n[r+1],port:n[r+2]});return i},sn.parseImageAttributes=function(e){return e.split(" ").map(function(e){return e.substring(1,e.length-1).split(",").reduce(s,{})})},sn.parseSimulcastStreamList=function(t){return t.split(";").map(function(t){return t.split(",").map(function(t){var i,n=!1;return"~"!==t[0]?i=e(t):(i=e(t.substring(1,t.length)),n=!0),{scid:i,paused:n}})})},sn)}(),t=function(){if(N)return A;N=1;var e=ss(),t=/%[sdv%]/g,i=function(e){var i=1,n=arguments,r=n.length;return e.replace(t,function(e){if(i>=r)return e;var t=n[i];switch(i+=1,e){case"%%":return"%";case"%s":return String(t);case"%d":return Number(t);case"%v":return""}})},n=function(e,t,n){var r=[e+"="+(t.format instanceof Function?t.format(t.push?n:n[t.name]):t.format)];if(t.names)for(var s=0;s<t.names.length;s+=1){var a=t.names[s];t.name?r.push(n[t.name][a]):r.push(n[t.names[s]])}else r.push(n[t.name]);return i.apply(null,r)},r=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["i","c","b","a"];return A=function(t,i){i=i||{},null==t.version&&(t.version=0),null==t.name&&(t.name=" "),t.media.forEach(function(e){null==e.payloads&&(e.payloads="")});var a=i.outerOrder||r,o=i.innerOrder||s,c=[];return a.forEach(function(i){e[i].forEach(function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach(function(t){c.push(n(i,e,t))})})}),t.media.forEach(function(t){c.push(n("m",e.m[0],t)),o.forEach(function(i){e[i].forEach(function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach(function(t){c.push(n(i,e,t))})})})}),c.join("\r\n")+"\r\n"}}();return si.grammar=ss(),si.write=t,si.parse=e.parse,si.parseParams=e.parseParams,si.parseFmtpConfig=e.parseFmtpConfig,si.parsePayloads=e.parsePayloads,si.parseRemoteCandidates=e.parseRemoteCandidates,si.parseImageAttributes=e.parseImageAttributes,si.parseSimulcastStreamList=e.parseSimulcastStreamList,si}();function so(e,t,i){void 0===t&&(t=50),void 0===i&&(i={});var n,r,s,a=null!=(n=i.isImmediate)&&n,o=null!=(r=i.callback)&&r,c=i.maxWait,l=Date.now(),d=[],u=function(){var i=[].slice.call(arguments),n=this;return new Promise(function(r,u){var h=a&&void 0===s;if(void 0!==s&&clearTimeout(s),s=setTimeout(function(){if(s=void 0,l=Date.now(),!a){var t=e.apply(n,i);o&&o(t),d.forEach(function(e){return(0,e.resolve)(t)}),d=[]}},function(){if(void 0!==c){var e=Date.now()-l;if(e+t>=c)return c-e}return t}()),h){var p=e.apply(n,i);return o&&o(p),r(p)}d.push({resolve:r,reject:u})})};return u.cancel=function(e){void 0!==s&&clearTimeout(s),d.forEach(function(t){return(0,t.reject)(e)}),d=[]},u}let sc={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class sl extends iQ.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){var t;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),this.log=iV,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=so(e=>iK(this,void 0,void 0,function*(){this.emit(sc.NegotiationStarted);try{yield this.createAndSendOffer()}catch(t){if(e)e(t);else throw t}}),20),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=iq(null!=(t=i.loggerName)?t:h.PCTransport),this.loggerOptions=i,this.config=e,this._pc=this.createPC(),this.offerLock=new W}createPC(){let e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&(null==(t=this.onIceCandidate)||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;null==(t=this.onIceCandidateError)||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;null==(t=this.onIceConnectionStateChange)||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;null==(t=this.onSignalingStatechange)||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;null==(t=this.onConnectionStateChange)||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;null==(t=this.onDataChannel)||t.call(this,e)},e.ontrack=e=>{var t;null==(t=this.onTrack)||t.call(this,e)},e}get logContext(){var e,t;return Object.assign({},null==(t=(e=this.loggerOptions).loggerContextCb)?void 0:t.call(e))}get isICEConnected(){return null!==this._pc&&("connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState)}addIceCandidate(e){return iK(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return iK(this,void 0,void 0,function*(){var i;let n;if("answer"===e.type&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;if("offer"===e.type){let{stereoMids:t,nackMids:i}=function(e){var t;let i=[],n=[],r=sa.parse(null!=(t=e.sdp)?t:""),s=0;return r.media.forEach(e=>{var t;let r=sh(e.mid);"audio"===e.type&&(e.rtp.some(e=>"opus"===e.codec&&(s=e.payload,!0)),(null==(t=e.rtcpFb)?void 0:t.some(e=>e.payload===s&&"nack"===e.type))&&n.push(r),e.fmtp.some(e=>e.payload===s&&(e.config.includes("sprop-stereo=1")&&i.push(r),!0)))}),{stereoMids:i,nackMids:n}}(e);this.remoteStereoMids=t,this.remoteNackMids=i}else if("answer"===e.type){let t=sa.parse(null!=(i=e.sdp)?i:"");t.media.forEach(e=>{let t=sh(e.mid);"audio"===e.type&&this.trackBitrates.some(i=>{if(!i.transceiver||t!=i.transceiver.mid)return!1;let n=0;if(e.rtp.some(e=>e.codec.toUpperCase()===i.codec.toUpperCase()&&(n=e.payload,!0)),0===n)return!0;let r=!1;for(let t of e.fmtp)if(t.payload===n){t.config=t.config.split(";").filter(e=>!e.includes("maxaveragebitrate")).join(";"),i.maxbr>0&&(t.config+=";maxaveragebitrate=".concat(1e3*i.maxbr)),r=!0;break}return!r&&i.maxbr>0&&e.fmtp.push({payload:n,config:"maxaveragebitrate=".concat(1e3*i.maxbr)}),!0})}),n=sa.write(t)}return yield this.setMungedSDP(e,n,!0),this.pendingCandidates.forEach(e=>{this.pc.addIceCandidate(e)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):"answer"===e.type&&(this.emit(sc.NegotiationComplete),e.sdp&&sa.parse(e.sdp).media.forEach(e=>{"video"===e.type&&this.emit(sc.RTPVideoPayloadTypes,e.rtp)})),!0})}createAndSendOffer(e){return iK(this,void 0,void 0,function*(){var t;let i=yield this.offerLock.lock();try{if(void 0===this.onOffer)return;if((null==e?void 0:e.iceRestart)&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&"have-local-offer"===this._pc.signalingState){let t=this._pc.remoteDescription;if((null==e?void 0:e.iceRestart)&&t)yield this._pc.setRemoteDescription(t);else{this.renegotiate=!0;return}}else if(!this._pc||"closed"===this._pc.signalingState)return void this.log.warn("could not createOffer with closed peer connection",this.logContext);this.log.debug("starting to negotiate",this.logContext);let i=this.latestOfferId+1;this.latestOfferId=i;let n=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:n.sdp},this.logContext));let r=sa.parse(null!=(t=n.sdp)?t:"");if(r.media.forEach(e=>{su(e),"audio"===e.type?sd(e,[],[]):"video"===e.type&&this.trackBitrates.some(t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let i=0;if(e.rtp.some(e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0)),0===i||(ru(t.codec)&&!rm()&&this.ensureVideoDDExtensionForSVC(e,r),"av1"!==t.codec))return!0;let n=Math.round(.7*t.maxbr);for(let t of e.fmtp)if(t.payload===i){t.config.includes("x-google-start-bitrate")||(t.config+=";x-google-start-bitrate=".concat(n));break}return!0})}),this.latestOfferId>i)return void this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:i}));yield this.setMungedSDP(n,sa.write(r)),this.onOffer(n,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return iK(this,void 0,void 0,function*(){var e;let t=yield this.pc.createAnswer(),i=sa.parse(null!=(e=t.sdp)?e:"");return i.media.forEach(e=>{su(e),"audio"===e.type&&sd(e,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,sa.write(i)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new nJ("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 nJ("PC closed, cannot configure");return null==(t=this._pc)?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(null==(e=this._pc)?void 0:e.removeTrack)}removeTrack(e){var t;return null==(t=this._pc)?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return null!=(t=null==(e=this._pc)?void 0:e.connectionState)?t:"closed"}getICEConnectionState(){var e,t;return null!=(t=null==(e=this._pc)?void 0:e.iceConnectionState)?t:"closed"}getSignallingState(){var e,t;return null!=(t=null==(e=this._pc)?void 0:e.signalingState)?t:"closed"}getTransceivers(){var e,t;return null!=(t=null==(e=this._pc)?void 0:e.getTransceivers())?t:[]}getSenders(){var e,t;return null!=(t=null==(e=this._pc)?void 0:e.getSenders())?t:[]}getLocalDescription(){var e;return null==(e=this._pc)?void 0:e.localDescription}getRemoteDescription(){var e;return null==(e=this.pc)?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return iK(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="",i=new Map,n=new Map;if((yield this._pc.getStats()).forEach(e=>{switch(e.type){case"transport":t=e.selectedCandidatePairId;break;case"candidate-pair":""===t&&e.selected&&(t=e.id),i.set(e.id,e);break;case"remote-candidate":n.set(e.id,"".concat(e.address,":").concat(e.port))}}),""===t)return;let r=null==(e=i.get(t))?void 0:e.remoteCandidateId;if(void 0!==r)return n.get(r)})}setMungedSDP(e,t,i){return iK(this,void 0,void 0,function*(){if(t){let n=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(i){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:i,sdp:t})),e.sdp=n}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(r){let t="unknown error";r instanceof Error?t=r.message:"string"==typeof r&&(t=r);let n={error:t,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(n.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:n})),new nQ(t)}})}ensureVideoDDExtensionForSVC(e,t){var i,n;if(!(null==(i=e.ext)?void 0:i.some(e=>e.uri===rs))){if(0===this.ddExtID){let e=0;t.media.forEach(t=>{var i;"video"===t.type&&(null==(i=t.ext)||i.forEach(t=>{t.value>e&&(e=t.value)}))}),this.ddExtID=e+1}null==(n=e.ext)||n.push({value:this.ddExtID,uri:rs})}}}function sd(e,t,i){let n=sh(e.mid),r=0;e.rtp.some(e=>"opus"===e.codec&&(r=e.payload,!0)),r>0&&(e.rtcpFb||(e.rtcpFb=[]),i.includes(n)&&!e.rtcpFb.some(e=>e.payload===r&&"nack"===e.type)&&e.rtcpFb.push({payload:r,type:"nack"}),t.includes(n)&&e.fmtp.some(e=>e.payload===r&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0)))}function su(e){if(e.connection){let t=e.connection.ip.indexOf(":")>=0;(4===e.connection.version&&t||6===e.connection.version&&!t)&&(e.connection.ip="0.0.0.0",e.connection.version=4)}}function sh(e){return"number"==typeof e?e.toFixed(0):e}let sp={audioPreset:O.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:rr.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:"vp8",backupCodec:!0,preConnectBuffer:!1},sm={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},sg={deviceId:{ideal:"default"},resolution:ri.h720.resolution},sf={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new iW,disconnectOnPageLeave:!0,webAudioMix:!1},sv={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};!function(e){e[e.NEW=0]="NEW",e[e.CONNECTING=1]="CONNECTING",e[e.CONNECTED=2]="CONNECTED",e[e.FAILED=3]="FAILED",e[e.CLOSING=4]="CLOSING",e[e.CLOSED=5]="CLOSED"}(U||(U={}));class sb{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,i){var n;this.peerConnectionTimeout=sv.peerConnectionTimeout,this.log=iV,this.updateState=()=>{var e;let t=this.state,i=this.requiredTransports.map(e=>e.getConnectionState());i.every(e=>"connected"===e)?this.state=U.CONNECTED:i.some(e=>"failed"===e)?this.state=U.FAILED:i.some(e=>"connecting"===e)?this.state=U.CONNECTING:i.every(e=>"closed"===e)?this.state=U.CLOSED:i.some(e=>"closed"===e)?this.state=U.CLOSING:i.every(e=>"new"===e)&&(this.state=U.NEW),t!==this.state&&(this.log.debug("pc state change: from ".concat(U[t]," to ").concat(U[this.state]),this.logContext),null==(e=this.onStateChange)||e.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=iq(null!=(n=i.loggerName)?n:h.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new sl(e,i),this.subscriber=new sl(e,i),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=e=>{var t;null==(t=this.onIceCandidate)||t.call(this,e,tX.PUBLISHER)},this.subscriber.onIceCandidate=e=>{var t;null==(t=this.onIceCandidate)||t.call(this,e,tX.SUBSCRIBER)},this.subscriber.onDataChannel=e=>{var t;null==(t=this.onDataChannel)||t.call(this,e)},this.subscriber.onTrack=e=>{var t;null==(t=this.onTrack)||t.call(this,e)},this.publisher.onOffer=(e,t)=>{var i;null==(i=this.onPublisherOffer)||i.call(this,e,t)},this.state=U.NEW,this.connectionLock=new W,this.remoteOfferLock=new W}get logContext(){var e,t;return Object.assign({},null==(t=(e=this.loggerOptions).loggerContextCb)?void 0:t.call(e))}requirePublisher(){let e=!(arguments.length>0)||void 0===arguments[0]||arguments[0];this.isPublisherConnectionRequired=e,this.updateState()}requireSubscriber(){let e=!(arguments.length>0)||void 0===arguments[0]||arguments[0];this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return iK(this,void 0,void 0,function*(){if(this.publisher&&"closed"!==this.publisher.getSignallingState()){let e=this.publisher;for(let t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(e){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:e}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return iK(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return iK(this,void 0,void 0,function*(){t===tX.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return iK(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()}));let i=yield this.remoteOfferLock.lock();try{if(!(yield this.subscriber.setRemoteDescription(e,t)))return;return yield this.subscriber.createAndSetAnswer()}finally{i()}})}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return iK(this,void 0,void 0,function*(){var i;let n=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&"connected"!==this.publisher.getConnectionState()&&"connecting"!==this.publisher.getConnectionState()&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all(null==(i=this.requiredTransports)?void 0:i.map(i=>this.ensureTransportConnected(i,e,t)))}finally{n()}})}negotiate(e){return iK(this,void 0,void 0,function*(){return new Promise((t,i)=>iK(this,void 0,void 0,function*(){let n=setTimeout(()=>{i("negotiation timed out")},this.peerConnectionTimeout);e.signal.addEventListener("abort",()=>{clearTimeout(n),i("negotiation aborted")}),this.publisher.once(sc.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(sc.NegotiationComplete,()=>{clearTimeout(n),t()})}),yield this.publisher.negotiate(e=>{clearTimeout(n),i(e)})}))})}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===tX.PUBLISHER||e===tX.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){let e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return iK(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.peerConnectionTimeout;return function*(){if("connected"!==e.getConnectionState())return new Promise((e,r)=>iK(i,void 0,void 0,function*(){let i=()=>{this.log.warn("abort transport connection",this.logContext),n4.clearTimeout(s),r(new nG("room connection has been cancelled",k.Cancelled))};(null==t?void 0:t.signal.aborted)&&i(),null==t||t.signal.addEventListener("abort",i);let s=n4.setTimeout(()=>{null==t||t.signal.removeEventListener("abort",i),r(new nG("could not establish pc connection",k.InternalError))},n);for(;this.state!==U.CONNECTED;)if(yield ra(50),null==t?void 0:t.signal.aborted)return void r(new nG("room connection has been cancelled",k.Cancelled));n4.clearTimeout(s),null==t||t.signal.removeEventListener("abort",i),e()}))}()})}}class sk extends Error{constructor(e,t,i){super(t),this.code=e,this.message=sT(t,sk.MAX_MESSAGE_BYTES),this.data=i?sT(i,sk.MAX_DATA_BYTES):void 0}static fromProto(e){return new sk(e.code,e.message,e.data)}toProto(){return new tN({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new sk(sk.ErrorCode[e],sk.ErrorMessage[e],t)}}function sy(e){return new TextEncoder().encode(e).length}function sT(e,t){if(sy(e)<=t)return e;let i=0,n=e.length,r=new TextEncoder;for(;i<n;){let s=Math.floor((i+n+1)/2);r.encode(e.slice(0,s)).length<=t?i=s:n=s-1}return e.slice(0,i)}function sC(e,t){let i,n;return t?("bytesReceived"in e?(i=e.bytesReceived,n=t.bytesReceived):"bytesSent"in e&&(i=e.bytesSent,n=t.bytesSent),void 0===i||void 0===n||void 0===e.timestamp||void 0===t.timestamp)?0:(i-n)*8e3/(e.timestamp-t.timestamp):0}sk.MAX_MESSAGE_BYTES=256,sk.MAX_DATA_BYTES=15360,sk.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},sk.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"};let sS="undefined"!=typeof MediaRecorder;class sw{constructor(){throw Error("MediaRecorder is not available in this environment")}}let sE=sS?MediaRecorder:sw;class sP extends sE{constructor(e,t){let i,n;if(!sS)throw Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),t);let r=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",r),this.removeEventListener("error",s),null==n||n.close(),n=void 0},s=e=>{null==n||n.error(e),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",r),this.removeEventListener("error",s),n=void 0};this.byteStream=new ReadableStream({start:e=>{n=e,i=t=>iK(this,void 0,void 0,function*(){let i;if(t.data.arrayBuffer)i=new Uint8Array((yield t.data.arrayBuffer()));else if(t.data.byteArray)i=t.data.byteArray;else throw Error("no data available!");void 0!==n&&e.enqueue(i)}),this.addEventListener("dataavailable",i)},cancel:()=>{r()}}),this.addEventListener("stop",r),this.addEventListener("error",s)}}class sR extends n9{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,i){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],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=so(()=>iK(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>iK(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(P.Ended,this)},this.reacquireTrack=!1,this.providedByUser=n,this.muteLock=new W,this.pauseUpstreamLock=new W,this.trackChangeLock=new W,this.trackChangeLock.lock().then(t=>iK(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{t()}})),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==n9.Kind.Video)return;let{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 null!=(t=null==(e=this.processor)?void 0:e.processedTrack)?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return iK(this,void 0,void 0,function*(){var i;let n;if(e!==this._mediaStreamTrack||t){if(this._mediaStreamTrack&&(this.attachedElements.forEach(e=>{n8(this._mediaStreamTrack,e)}),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()),this.processor&&e){if(this.log.debug("restarting processor",this.logContext),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(n5(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),n=this.processor.processedTrack}this.sender&&(null==(i=this.sender.transport)?void 0:i.state)!=="closed"&&(yield this.sender.replaceTrack(null!=n?n:e)),this.providedByUser||this._mediaStreamTrack===e||this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(t=>{n5(null!=n?n:e,t)}))}})}waitForDimensions(){return iK(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;return function*(){var i;if(e.kind===n9.Kind.Audio)throw Error("cannot get dimensions for audio tracks");(null==(i=n0())?void 0:i.os)==="iOS"&&(yield ra(10));let n=Date.now();for(;Date.now()-n<t;){let t=e.dimensions;if(t)return t;yield ra(50)}throw new nK("unable to get track dimensions after timeout")}()})}setDeviceId(e){return iK(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===rM(e)||(this._constraints.deviceId=e,!!this.isMuted||(yield this.restartTrack(),rM(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return iK(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0];return function*(){if(e.source===n9.Source.ScreenShare)return;let{deviceId:i,groupId:n}=e._mediaStreamTrack.getSettings(),r=e.kind===n9.Kind.Audio?"audioinput":"videoinput";return t?r3.getInstance().normalizeDeviceId(r,i,n):i}()})}mute(){return iK(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return iK(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return iK(this,void 0,void 0,function*(){let i=yield this.trackChangeLock.lock();try{let i,n;if(!this.sender)throw new nK("unable to replace an unpublished track");return"boolean"==typeof t?i=t:void 0!==t&&(i=t.userProvidedTrack,n=t.stopProcessor),this.providedByUser=null==i||i,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),n&&this.processor&&(yield this.internalStopProcessor()),this}finally{i()}})}restart(e){return iK(this,void 0,void 0,function*(){this.manuallyStopped=!1;let t=yield this.trackChangeLock.lock();try{e||(e=this._constraints);let{deviceId:t,facingMode:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&0>t.indexOf(n)&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,n=Object.getOwnPropertySymbols(e);r<n.length;r++)0>t.indexOf(n[r])&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]]);return i}(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));let r={audio:!1,video:!1};this.kind===n9.Kind.Video?r.video=!t&&!i||{deviceId:t,facingMode:i}:r.audio=!t||Object.assign({deviceId:t},n),this.attachedElements.forEach(e=>{n8(this.mediaStreamTrack,e)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();let s=(yield navigator.mediaDevices.getUserMedia(r)).getTracks()[0];return this.kind===n9.Kind.Video&&(yield s.applyConstraints(n)),s.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(s),this._constraints=e,this.emit(P.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?P.Muted:P.Unmuted,this))}get needsReAcquisition(){return"live"!==this._mediaStreamTrack.readyState||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return iK(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),rf()&&(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),null==(e=this.processor)||e.destroy(),this.processor=void 0}pauseUpstream(){return iK(this,void 0,void 0,function*(){var e;let t=yield this.pauseUpstreamLock.lock();try{if(!0===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to pause upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!0,this.emit(P.UpstreamPaused,this);let t=n0();if((null==t?void 0:t.name)==="Safari"&&0>rS(t.version,"12.0"))throw new nW("pauseUpstream is not supported on Safari < 12.");(null==(e=this.sender.transport)?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return iK(this,void 0,void 0,function*(){var e;let t=yield this.pauseUpstreamLock.lock();try{if(!1===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to resume upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!1,this.emit(P.UpstreamResumed,this),(null==(e=this.sender.transport)?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return iK(this,void 0,void 0,function*(){var e;if(null==(e=this.sender)?void 0:e.getStats)return yield this.sender.getStats()})}setProcessor(e){return iK(this,arguments,void 0,function(e){var t=this;let i=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function*(){var n;let r=yield t.trackChangeLock.lock();try{t.log.debug("setting up processor",t.logContext);let r=document.createElement(t.kind),s={kind:t.kind,track:t._mediaStreamTrack,element:r,audioContext:t.audioContext};if(yield e.init(s),t.log.debug("processor initialized",t.logContext),t.processor&&(yield t.internalStopProcessor()),"unknown"===t.kind)throw TypeError("cannot set processor on track of unknown kind");if(n5(t._mediaStreamTrack,r),r.muted=!0,r.play().catch(e=>{e instanceof DOMException&&"AbortError"===e.name?(t.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},t.logContext),{error:e})),setTimeout(()=>{r.play().catch(e=>{t.log.error("failed to play processor element",Object.assign(Object.assign({},t.logContext),{err:e}))})},100)):t.log.error("failed to play processor element",Object.assign(Object.assign({},t.logContext),{error:e}))}),t.processor=e,t.processorElement=r,t.processor.processedTrack){for(let e of t.attachedElements)e!==t.processorElement&&i&&(n8(t._mediaStreamTrack,e),n5(t.processor.processedTrack,e));yield null==(n=t.sender)?void 0:n.replaceTrack(t.processor.processedTrack)}t.emit(P.TrackProcessorUpdate,t.processor)}finally{r()}}()})}getProcessor(){return this.processor}stopProcessor(){return iK(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0];return function*(){let i=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{i()}}()})}internalStopProcessor(){return iK(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0];return function*(){var i,n;e.processor&&(e.log.debug("stopping processor",e.logContext),null==(i=e.processor.processedTrack)||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||(null==(n=e.processorElement)||n.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(P.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100;if(!sS)return void this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext);if(this.localTrackRecorder)return void this.log.warn("preconnect buffer already started");{let e="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(e)||(e="video/mp4"),this.localTrackRecorder=new sP(this,{mimeType:e})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},1e4)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return null==(e=this.localTrackRecorder)?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return null==(e=this.localTrackRecorder)?void 0:e.mimeType}}class sI extends sR{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=!(arguments.length>2)||void 0===arguments[2]||arguments[2],n=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(e,n9.Kind.Audio,t,i,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>iK(this,void 0,void 0,function*(){let e;if(!this.sender){this._currentBitrate=0;return}try{e=yield this.getSenderStats()}catch(e){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:e}));return}e&&this.prevStats&&(this._currentBitrate=sC(e,this.prevStats)),this.prevStats=e}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(P.AudioTrackFeatureUpdate,this,tu.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(P.AudioTrackFeatureUpdate,this,tu.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=n,this.checkForSilence()}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return iK(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{if(this.isMuted)return this.log.debug("Track already muted",this.logContext),this;return this.source===n9.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(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return iK(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;let t=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==rM(this._constraints.deviceId);return this.source===n9.Source.Microphone&&(this.stopOnMute||"ended"===this._mediaStreamTrack.readyState||t)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return iK(this,void 0,void 0,function*(){let t;if(e){let i=rz({audio:e});"boolean"!=typeof i.audio&&(t=i.audio)}yield this.restart(t)})}restart(e){let t=Object.create(null,{restart:{get:()=>super.restart}});return iK(this,void 0,void 0,function*(){let i=yield t.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){rv()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},2e3)))}setProcessor(e){return iK(this,void 0,void 0,function*(){var t;let i=yield this.trackChangeLock.lock();try{if(!rb()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());let i={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(i),this.processor=e,this.processor.processedTrack&&(yield null==(t=this.sender)?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(P.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return iK(this,void 0,void 0,function*(){var e;let t;if(null==(e=this.sender)?void 0:e.getStats)return(yield this.sender.getStats()).forEach(e=>{"outbound-rtp"===e.type&&(t={type:"audio",streamId:e.id,packetsSent:e.packetsSent,packetsLost:e.packetsLost,bytesSent:e.bytesSent,timestamp:e.timestamp,roundTripTime:e.roundTripTime,jitter:e.jitter})}),t})}checkForSilence(){return iK(this,void 0,void 0,function*(){let e=yield rJ(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(P.AudioSilenceDetected)),e})}}let sO=Object.values(ri),sD=Object.values(rn),sx=Object.values(rr),s_=[ri.h180,ri.h360],sM=[rn.h180,rn.h360],sA=["q","h","f"];function sN(e,t,i,n){var r,s,a;let o,c=null==n?void 0:n.videoEncoding;e&&(c=null==n?void 0:n.screenShareEncoding);let l=null==n?void 0:n.simulcast,d=null==n?void 0:n.scalabilityMode,u=null==n?void 0:n.videoCodec;if(!c&&!l&&!d||!t||!i)return[{}];c||(c=function(e,t,i,n){let r=function(e,t,i){if(e)return sx;let n=t>i?t/i:i/t;return Math.abs(n-16/9)<Math.abs(n-4/3)?sO:sD}(e,t,i),{encoding:s}=r[0],a=Math.max(t,i);for(let e=0;e<r.length;e+=1){let t=r[e];if(s=t.encoding,t.width>=a)break}if(n)switch(n){case"av1":case"h265":(s=Object.assign({},s)).maxBitrate=.7*s.maxBitrate;break;case"vp9":(s=Object.assign({},s)).maxBitrate=.85*s.maxBitrate}return s}(e,t,i,u),iV.debug("using video encoding",c));let h=c.maxFramerate,p=new n7(t,i,c.maxBitrate,c.maxFramerate,c.priority);if(d&&ru(u)){let e=new sF(d),t=[];if(e.spatial>3)throw Error("unsupported scalabilityMode: ".concat(d));let i=n0();if(rg()||rb()||(null==i?void 0:i.name)==="Chrome"&&0>rS(null==i?void 0:i.version,"113")){let n="h"==e.suffix?2:3,r=((a=i)||(a=n0()),(null==a?void 0:a.name)==="Safari"&&rS(a.version,"18.3")>0||(null==a?void 0:a.os)==="iOS"&&!!(null==a?void 0:a.osVersion)&&rS(a.osVersion,"18.3")>0);for(let i=0;i<e.spatial;i+=1)t.push({rid:sA[2-i],maxBitrate:c.maxBitrate/Math.pow(n,i),maxFramerate:p.encoding.maxFramerate,scaleResolutionDownBy:r?Math.pow(2,i):void 0});t[0].scalabilityMode=d}else t.push({maxBitrate:c.maxBitrate,maxFramerate:p.encoding.maxFramerate,scalabilityMode:d});return p.encoding.priority&&(t[0].priority=p.encoding.priority,t[0].networkPriority=p.encoding.priority),iV.debug("using svc encoding",{encodings:t}),t}if(!l)return[c];let m=[];if((m=e?null!=(r=sj(null==n?void 0:n.screenShareSimulcastLayers))?r:sL(e,p):null!=(s=sj(null==n?void 0:n.videoSimulcastLayers))?s:sL(e,p)).length>0){let e=m[0];m.length>1&&([,o]=m);let n=Math.max(t,i);if(n>=960&&o)return sU(t,i,[e,o,p],h);if(n>=480)return sU(t,i,[e,p],h)}return sU(t,i,[p])}function sL(e,t){if(e)return[{scaleResolutionDownBy:2,fps:t.encoding.maxFramerate}].map(e=>{var i,n;return new n7(Math.floor(t.width/e.scaleResolutionDownBy),Math.floor(t.height/e.scaleResolutionDownBy),Math.max(15e4,Math.floor(t.encoding.maxBitrate/(Math.pow(e.scaleResolutionDownBy,2)*((null!=(i=t.encoding.maxFramerate)?i:30)/(null!=(n=e.fps)?n:30))))),e.fps,t.encoding.priority)});let{width:i,height:n}=t,r=i>n?i/n:n/i;return Math.abs(r-16/9)<Math.abs(r-4/3)?s_:sM}function sU(e,t,i,n){let r=[];if(i.forEach((i,s)=>{if(s>=sA.length)return;let a=Math.min(e,t),o={rid:sA[s],scaleResolutionDownBy:Math.max(1,a/Math.min(i.width,i.height)),maxBitrate:i.encoding.maxBitrate},c=n&&i.encoding.maxFramerate?Math.min(n,i.encoding.maxFramerate):i.encoding.maxFramerate;c&&(o.maxFramerate=c);let l=rp()||0===s;i.encoding.priority&&l&&(o.priority=i.encoding.priority,o.networkPriority=i.encoding.priority),r.push(o)}),rb()&&"ios"===rT()){let e;r.forEach(t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate});let t=!0;r.forEach(i=>{var n;i.maxFramerate!=e&&(t&&(t=!1,iV.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),iV.info('Setting framerate of encoding "'.concat(null!=(n=i.rid)?n:"",'" to ').concat(e)),i.maxFramerate=e)})}return r}function sj(e){if(e)return e.sort((e,t)=>{let{encoding:i}=e,{encoding:n}=t;return i.maxBitrate>n.maxBitrate?1:i.maxBitrate<n.maxBitrate?-1:i.maxBitrate===n.maxBitrate&&i.maxFramerate&&n.maxFramerate?i.maxFramerate>n.maxFramerate?1:-1:0})}class sF{constructor(e){let t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat(null!=(e=this.suffix)?e:"")}}class sB extends sR{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=!(arguments.length>2)||void 0===arguments[2]||arguments[2],n=arguments.length>3?arguments[3]:void 0;super(e,n9.Kind.Video,t,i,n),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>iK(this,void 0,void 0,function*(){let e;if(!this.sender){this._currentBitrate=0;return}try{e=yield this.getSenderStats()}catch(e){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:e}));return}let t=new Map(e.map(e=>[e.rid,e])),i=e.some(e=>"cpu"===e.qualityLimitationReason);if(i!==this.isCpuConstrained&&(this.isCpuConstrained=i,this.isCpuConstrained&&this.emit(P.CpuConstrained)),this.prevStats){let e=0;t.forEach((t,i)=>{var n;let r=null==(n=this.prevStats)?void 0:n.get(i);e+=sC(t,r)}),this._currentBitrate=e}this.prevStats=t}),this.senderLock=new W}get isSimulcast(){return!!this.sender&&!!(this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!rv())return;let i=null==(t=this.sender)?void 0:t.getParameters();i&&(this.encodings=i.encodings),this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},2e3))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){let e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return iK(this,void 0,void 0,function*(){yield e.pauseUpstream.call(this);try{for(var t,i,n,r,s,a,o=!0,c=iz(this.simulcastCodecs.values());!(t=(a=yield c.next()).done);o=!0)r=a.value,o=!1,yield null==(s=r.sender)?void 0:s.replaceTrack(null)}catch(e){i={error:e}}finally{try{!o&&!t&&(n=c.return)&&(yield n.call(c))}finally{if(i)throw i.error}}})}resumeUpstream(){let e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return iK(this,void 0,void 0,function*(){yield e.resumeUpstream.call(this);try{for(var t,i,n,r,s,a,o=!0,c=iz(this.simulcastCodecs.values());!(t=(a=yield c.next()).done);o=!0)r=a.value,o=!1,yield null==(s=r.sender)?void 0:s.replaceTrack(r.mediaStreamTrack)}catch(e){i={error:e}}finally{try{!o&&!t&&(n=c.return)&&(yield n.call(c))}finally{if(i)throw i.error}}})}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return iK(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{if(this.isMuted)return this.log.debug("Track already muted",this.logContext),this;return this.source!==n9.Source.Camera||this.isUserProvided||(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this}finally{t()}})}unmute(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return iK(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;return this.source!==n9.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}setTrackMuted(e){for(let t of(super.setTrackMuted(e),this.simulcastCodecs.values()))t.mediaStreamTrack.enabled=!e}getSenderStats(){return iK(this,void 0,void 0,function*(){var e;if(!(null==(e=this.sender)?void 0:e.getStats))return[];let t=[],i=yield this.sender.getStats();return i.forEach(e=>{var n;if("outbound-rtp"===e.type){let r={type:"video",streamId:e.id,frameHeight:e.frameHeight,frameWidth:e.frameWidth,framesPerSecond:e.framesPerSecond,framesSent:e.framesSent,firCount:e.firCount,pliCount:e.pliCount,nackCount:e.nackCount,packetsSent:e.packetsSent,bytesSent:e.bytesSent,qualityLimitationReason:e.qualityLimitationReason,qualityLimitationDurations:e.qualityLimitationDurations,qualityLimitationResolutionChanges:e.qualityLimitationResolutionChanges,rid:null!=(n=e.rid)?n:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,targetBitrate:e.targetBitrate,timestamp:e.timestamp},s=i.get(e.remoteId);s&&(r.jitter=s.jitter,r.packetsLost=s.packetsLost,r.roundTripTime=s.roundTripTime),t.push(r)}}),t.sort((e,t)=>{var i,n;return(null!=(i=t.frameWidth)?i:0)-(null!=(n=e.frameWidth)?n:0)}),t})}setPublishingQuality(e){let t=[];for(let i=R.LOW;i<=R.HIGH;i+=1)t.push(new ik({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(ru(this.codec),t)}restartTrack(e){return iK(this,void 0,void 0,function*(){let t;if(e){let i=rz({video:e});"boolean"!=typeof i.video&&(t=i.video)}yield this.restart(t),this.isCpuConstrained=!1;try{for(var i,n,r,s,a,o,c=!0,l=iz(this.simulcastCodecs.values());!(i=(o=yield l.next()).done);c=!0)s=o.value,c=!1,s.sender&&(null==(a=s.sender.transport)?void 0:a.state)!=="closed"&&(s.mediaStreamTrack=this.mediaStreamTrack.clone(),yield s.sender.replaceTrack(s.mediaStreamTrack))}catch(e){n={error:e}}finally{try{!c&&!i&&(r=l.return)&&(yield r.call(l))}finally{if(n)throw n.error}}})}setProcessor(e){let t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return iK(this,arguments,void 0,function(e){var i=this;let n=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function*(){if(yield t.setProcessor.call(i,e,n),null==(c=i.processor)?void 0:c.processedTrack)try{for(var r,s,a,o,c,l,d,u=!0,h=iz(i.simulcastCodecs.values());!(r=(d=yield h.next()).done);u=!0)o=d.value,u=!1,yield null==(l=o.sender)?void 0:l.replaceTrack(i.processor.processedTrack)}catch(e){s={error:e}}finally{try{!u&&!r&&(a=h.return)&&(yield a.call(h))}finally{if(s)throw s.error}}}()})}setDegradationPreference(e){return iK(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);let t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(e){this.log.warn("failed to set degradationPreference",Object.assign({error:e},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e))return void this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);let i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){let i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},5e3))}setPublishingCodecs(e){return iK(this,void 0,void 0,function*(){var t,i,n,r,s,a,o;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(ru(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;let c=[];try{for(t=!0,i=iz(e);!(r=(n=yield i.next()).done);t=!0)if(o=n.value,t=!1,this.codec&&this.codec!==o.codec){let e=this.simulcastCodecs.get(o.codec);if(this.log.debug("try setPublishingCodec for ".concat(o.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:e})),e&&e.sender)e.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(o.codec),this.logContext),yield sV(e.sender,e.encodings,o.qualities,this.senderLock,ru(o.codec),this.log,this.logContext));else for(let e of o.qualities)if(e.enabled){c.push(o.codec);break}}else yield this.setPublishingLayers(ru(o.codec),o.qualities)}catch(e){s={error:e}}finally{try{!t&&!r&&(a=i.return)&&(yield a.call(i))}finally{if(s)throw s.error}}return c})}setPublishingLayers(e,t){return iK(this,void 0,void 0,function*(){if(this.optimizeForPerformance)return void this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:t}));this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),this.sender&&this.encodings&&(yield sV(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return iK(this,void 0,void 0,function*(){if(!this.sender)throw Error("sender not found");let e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;let e=this.sender.getParameters();e.encodings=e.encodings.map((e,t)=>{var i;return Object.assign(Object.assign({},e),{active:0===t,scaleResolutionDownBy:Math.max(1,Math.ceil((null!=(i=this.mediaStreamTrack.getSettings().height)?i:360)/360)),scalabilityMode:0===t&&ru(this.codec)?"L1T3":void 0,maxFramerate:15*(0===t),maxBitrate:0===t?e.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:e.encodings})),this.encodings=e.encodings,yield this.sender.setParameters(e)}catch(e){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:e})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return iK(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),rf()&&this.isInBackground&&this.source===n9.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function sV(e,t,i,n,r,s,a){return iK(this,void 0,void 0,function*(){let o=yield n.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},a),{sender:e,qualities:i,senderEncodings:t}));try{let n=e.getParameters(),{encodings:o}=n;if(!o)return;if(o.length!==t.length)return void s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},a),{encodings:o,senderEncodings:t}));let c=!1;r&&i.some(e=>e.enabled)&&i.forEach(e=>e.enabled=!0),o.forEach((e,n)=>{var r;let o=null!=(r=e.rid)?r:"";""===o&&(o="q");let l=sq(o),d=i.find(e=>e.quality===l);d&&e.active!==d.enabled&&(c=!0,e.active=d.enabled,s.debug("setting layer ".concat(d.quality," to ").concat(e.active?"enabled":"disabled"),a),rp()&&(d.enabled?(e.scaleResolutionDownBy=t[n].scaleResolutionDownBy,e.maxBitrate=t[n].maxBitrate,e.maxFrameRate=t[n].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))}),c&&(n.encodings=o,s.debug("setting encodings",Object.assign(Object.assign({},a),{encodings:n.encodings})),yield e.setParameters(n))}finally{o()}})}function sq(e){switch(e){case"f":default:return R.HIGH;case"h":return R.MEDIUM;case"q":return R.LOW}}function sH(e,t,i,n){if(!i)return[new tC({quality:R.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(n){let n=new sF(i[0].scalabilityMode),r=[],s="h"==n.suffix?1.5:2,a="h"==n.suffix?2:3;for(let o=0;o<n.spatial;o+=1)r.push(new tC({quality:Math.min(R.HIGH,n.spatial-1)-o,width:Math.ceil(e/Math.pow(s,o)),height:Math.ceil(t/Math.pow(s,o)),bitrate:i[0].maxBitrate?Math.ceil(i[0].maxBitrate/Math.pow(a,o)):0,ssrc:0}));return r}return i.map(i=>{var n,r,s;let a=null!=(n=i.scaleResolutionDownBy)?n:1;return new tC({quality:sq(null!=(r=i.rid)?r:""),width:Math.ceil(e/a),height:Math.ceil(t/a),bitrate:null!=(s=i.maxBitrate)?s:0,ssrc:0})})}let sG="_lossy",sW="_reliable",sK="leave-reconnect";!function(e){e[e.New=0]="New",e[e.Connected=1]="Connected",e[e.Disconnected=2]="Disconnected",e[e.Reconnecting=3]="Reconnecting",e[e.Closed=4]="Closed"}(j||(j={}));class sz extends iQ.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=sv.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=j.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=iV,this.reliableDataSequence=1,this.reliableMessageBuffer=new se,this.reliableReceivedState=new st(3e4),this.handleDataChannel=e=>iK(this,[e],void 0,function(e){var t=this;let{channel:i}=e;return function*(){if(i){if(i.label===sW)t.reliableDCSub=i;else{if(i.label!==sG)return;t.lossyDCSub=i}t.log.debug("on data channel ".concat(i.id,", ").concat(i.label),t.logContext),i.onmessage=t.handleDataMessage}}()}),this.handleDataMessage=e=>iK(this,void 0,void 0,function*(){var t,i;let n=yield this.dataProcessLock.lock();try{let n;if(e.data instanceof ArrayBuffer)n=e.data;else{if(!(e.data instanceof Blob))return void this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:e.data}));n=yield e.data.arrayBuffer()}let r=tS.fromBinary(new Uint8Array(n));if(r.sequence>0&&""!==r.participantSid){let e=this.reliableReceivedState.get(r.participantSid);if(e&&r.sequence<=e)return;this.reliableReceivedState.set(r.participantSid,r.sequence)}(null==(t=r.value)?void 0:t.case)==="speaker"?this.emit(E.ActiveSpeakersUpdate,r.value.value.speakers):((null==(i=r.value)?void 0:i.case)==="user"&&function(e,t){let i=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=i,t.participantIdentity=i;let n=0!==e.destinationIdentities.length?e.destinationIdentities:t.destinationIdentities;e.destinationIdentities=n,t.destinationIdentities=n}(r,r.value.value),this.emit(E.DataPacketReceived,r))}finally{n()}}),this.handleDataError=e=>{let t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent&&e.error){let{error:i}=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(e.message),Object.assign(Object.assign({},this.logContext),{error:i}))}else this.log.error("Unknown DataChannel error on ".concat(t),Object.assign(Object.assign({},this.logContext),{event:e}))},this.handleBufferedAmountLow=e=>{let t=0===e.currentTarget.maxRetransmits?tw.LOSSY:tw.RELIABLE;this.updateAndEmitDCBufferStatus(t)},this.handleDisconnect=(e,t)=>{if(this._isClosed)return;this.log.warn("".concat(e," disconnected"),this.logContext),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());let i=e=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(e,"ms. giving up"),this.logContext),this.emit(E.Disconnected),this.close()},n=Date.now()-this.reconnectStart,r=this.getNextRetryDelay({elapsedMs:n,retryCount:this.reconnectAttempts});if(null===r)return void i(n);e===sK&&(r=0),this.log.debug("reconnecting in ".concat(r,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=n4.setTimeout(()=>this.attemptReconnect(t).finally(()=>this.reconnectTimeout=void 0),r)},this.waitForRestarted=()=>new Promise((e,t)=>{this.pcState===j.Connected&&e();let i=()=>{this.off(E.Disconnected,n),e()},n=()=>{this.off(E.Restarted,i),t()};this.once(E.Restarted,i),this.once(E.Disconnected,n)}),this.updateAndEmitDCBufferStatus=e=>{let t=this.isBufferStatusLow(e);void 0!==t&&t!==this.dcBufferStatus.get(e)&&(this.dcBufferStatus.set(e,t),this.emit(E.DCBufferStatusChanged,t,e))},this.isBufferStatusLow=e=>{let t=this.dataChannelForKind(e);if(t)return e===tw.RELIABLE&&this.reliableMessageBuffer.alignBufferedAmount(t.bufferedAmount),t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===x.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(tl.RR_SIGNAL_DISCONNECTED))},this.log=iq(null!=(t=e.loggerName)?t:h.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new r5(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new W,this.dataProcessLock=new W,this.dcBufferStatus=new Map([[tw.LOSSY,!0],[tw.RELIABLE,!0]]),this.client.onParticipantUpdate=e=>this.emit(E.ParticipantUpdate,e),this.client.onConnectionQuality=e=>this.emit(E.ConnectionQualityUpdate,e),this.client.onRoomUpdate=e=>this.emit(E.RoomUpdate,e),this.client.onSubscriptionError=e=>this.emit(E.SubscriptionError,e),this.client.onSubscriptionPermissionUpdate=e=>this.emit(E.SubscriptionPermissionUpdate,e),this.client.onSpeakersChanged=e=>this.emit(E.SpeakersChanged,e),this.client.onStreamStateUpdate=e=>this.emit(E.StreamStateChanged,e),this.client.onRequestResponse=e=>this.emit(E.SignalRequestResponse,e)}get logContext(){var e,t,i,n,r,s;return{room:null==(t=null==(e=this.latestJoinResponse)?void 0:e.room)?void 0:t.name,roomID:null==(n=null==(i=this.latestJoinResponse)?void 0:i.room)?void 0:n.sid,participant:null==(s=null==(r=this.latestJoinResponse)?void 0:r.participant)?void 0:s.identity,pID:this.participantSid}}join(e,t,i,n){return iK(this,void 0,void 0,function*(){this.url=e,this.token=t,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();let r=yield this.client.join(e,t,i,n);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,this.emit(E.SignalConnected,r),r}catch(r){if(r instanceof nG&&r.reason===k.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,i,n);throw r}})}close(){return iK(this,void 0,void 0,function*(){let e=yield this.closingLock.lock();if(this.isClosed)return void e();try{this._isClosed=!0,this.joinAttempts=0,this.emit(E.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return iK(this,void 0,void 0,function*(){var e;yield null==(e=this.pcManager)?void 0:e.close(),this.pcManager=void 0;let t=e=>{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new se,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupClient(){return iK(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new nK("a track with the same ID has already been published");return new Promise((t,i)=>{let n=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(new nG("publication of local track timed out, no response from server",k.Timeout))},1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(n),t(e)},reject:()=>{clearTimeout(n),i(Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){let{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(e){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:e}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null==(e=this.reliableDCSub)?void 0:e.readyState}getConnectedServerAddress(){return iK(this,void 0,void 0,function*(){var e;return null==(e=this.pcManager)?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){return iK(this,void 0,void 0,function*(){var t,i,n;if(this.pcManager&&this.pcManager.currentState!==U.NEW)return;this.participantSid=null==(t=e.participant)?void 0:t.sid;let r=this.makeRTCConfiguration(e);this.pcManager=new sb(r,e.subscriberPrimary,this.loggerOptions),this.emit(E.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(e,t)=>{this.client.sendIceCandidate(e,t)},this.pcManager.onPublisherOffer=(e,t)=>{this.client.sendOffer(e,t)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(t,i,n)=>iK(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(t),this.logContext),["closed","disconnected","failed"].includes(i)&&(this.publisherConnectionPromise=void 0),t===U.CONNECTED){let t=this.pcState===j.New;this.pcState=j.Connected,t&&this.emit(E.Connected,e)}else t===U.FAILED&&this.pcState===j.Connected&&(this.pcState=j.Disconnected,this.handleDisconnect("peerconnection failed","failed"===n?tl.RR_SUBSCRIBER_FAILED:tl.RR_PUBLISHER_FAILED));let r=this.client.isDisconnected||this.client.currentState===x.RECONNECTING,s=[U.FAILED,U.CLOSING,U.CLOSED].includes(t);r&&s&&!this._isClosed&&this.emit(E.Offline)}),this.pcManager.onTrack=e=>{this.emit(E.MediaTrackAdded,e.track,e.streams[0],e.receiver)},void 0!==(n=null==(i=e.serverInfo)?void 0:i.protocol)&&n>13||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t)=>iK(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,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t)=>iK(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;let i=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);i&&this.client.sendAnswer(i,t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:null==(t=e.track)?void 0:t.sid})),!this.pendingTrackResolvers[e.cid])return void this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));let{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(E.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(E.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(E.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(E.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=null==(t=e.participant)?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(E.RoomMoved,e)},this.client.onClose=()=>{this.handleDisconnect("signal",tl.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:null==e?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(e.regions)),e.action){case ic.DISCONNECT:this.emit(E.Disconnected,null==e?void 0:e.reason),this.close();break;case ic.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(sK);break;case ic.RESUME:this.handleDisconnect(sK)}}}makeRTCConfiguration(e){var t;let i=Object.assign({},this.rtcConfig);if((null==(t=this.signalOpts)?void 0:t.e2eeEnabled)&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){let t=[];e.iceServers.forEach(e=>{let i={urls:e.urls};e.username&&(i.username=e.username),e.credential&&(i.credential=e.credential),t.push(i)}),i.iceServers=t}return e.clientConfiguration&&e.clientConfiguration.forceRelay===to.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(sG,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(sW,{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,i){return iK(this,void 0,void 0,function*(){if(ro())return yield this.createTransceiverRTCRtpSender(e,t,i);if(rc())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new nJ("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,i,n){return iK(this,void 0,void 0,function*(){if(ro())return this.createSimulcastTransceiverSender(e,t,i,n);if(rc())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new nJ("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,i){return iK(this,void 0,void 0,function*(){if(!this.pcManager)throw new nJ("publisher is closed");let n=[];e.mediaStream&&n.push(e.mediaStream),rB(e)&&(e.codec=t.videoCodec);let r={direction:"sendonly",streams:n};return i&&(r.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender})}createSimulcastTransceiverSender(e,t,i,n){return iK(this,void 0,void 0,function*(){if(!this.pcManager)throw new nJ("publisher is closed");let r={direction:"sendonly"};n&&(r.sendEncodings=n);let s=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,s.sender),s.sender})}createRTCRtpSender(e){return iK(this,void 0,void 0,function*(){if(!this.pcManager)throw new nJ("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return iK(this,void 0,void 0,function*(){var t,i,n;if(!this._isClosed){if(this.attemptingReconnect)return void iV.warn("already attempting reconnect, returning early",this.logContext);((null==(t=this.clientConfiguration)?void 0:t.resumeConnection)===to.DISABLED||(null!=(n=null==(i=this.pcManager)?void 0:i.currentState)?n:U.NEW)===U.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(t){this.reconnectAttempts+=1;let e=!0;t instanceof nJ?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:t})),e=!1):t instanceof sJ||(this.fullReconnectOnNext=!0),e?this.handleDisconnect("reconnect",tl.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(E.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:e}))}return null}restartConnection(e){return iK(this,void 0,void 0,function*(){var t,i,n;try{let i;if(!this.url||!this.token)throw new nJ("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(E.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new sJ;i=yield this.join(null!=e?e:this.url,this.token,this.signalOpts)}catch(e){if(e instanceof nG&&e.reason===k.NotAllowed)throw new nJ("could not reconnect, token might be expired");throw new sJ}if(this.shouldFailNext)throw this.shouldFailNext=!1,Error("simulated failure");if(this.client.setReconnected(),this.emit(E.SignalRestarted,i),yield this.waitForPCReconnected(),this.client.currentState!==x.CONNECTED)throw new sJ("Signal connection got severed during reconnect");null==(t=this.regionUrlProvider)||t.resetAttempts(),this.emit(E.Restarted)}catch(t){let e=yield null==(i=this.regionUrlProvider)?void 0:i.getNextBestRegionUrl();if(e)return void(yield this.restartConnection(e));throw null==(n=this.regionUrlProvider)||n.resetAttempts(),t}})}resumeConnection(e){return iK(this,void 0,void 0,function*(){var t;let i;if(!this.url||!this.token)throw new nJ("could not reconnect, url or token not saved");if(!this.pcManager)throw new nJ("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(E.Resuming);try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(t){let e="";if(t instanceof Error&&(e=t.message,this.log.error(t.message,Object.assign(Object.assign({},this.logContext),{error:t}))),t instanceof nG&&t.reason===k.NotAllowed)throw new nJ("could not reconnect, token might be expired");if(t instanceof nG&&t.reason===k.LeaveRequest)throw t;throw new sJ(e)}if(this.emit(E.SignalResumed),i){let e=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(e),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==x.CONNECTED)throw new sJ("Signal connection got severed during reconnect");this.client.setReconnected(),(null==(t=this.reliableDC)?void 0:t.readyState)==="open"&&null===this.reliableDC.id&&this.createDataChannels(),(null==i?void 0:i.lastMessageSeq)&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(E.Resumed)})}waitForPCInitialConnection(e,t){return iK(this,void 0,void 0,function*(){if(!this.pcManager)throw new nJ("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return iK(this,void 0,void 0,function*(){this.pcState=j.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield ra(2e3),!this.pcManager)throw new nJ("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=j.Connected}catch(e){throw this.pcState=j.Disconnected,new nG("could not establish PC connection, ".concat(e.message),k.InternalError)}})}publishRpcResponse(e,t,i,n){return iK(this,void 0,void 0,function*(){let r=new tS({destinationIdentities:[e],kind:tw.RELIABLE,value:{case:"rpcResponse",value:new tA({requestId:t,value:n?{case:"error",value:n.toProto()}:{case:"payload",value:null!=i?i:""}})}});yield this.sendDataPacket(r,tw.RELIABLE)})}publishRpcAck(e,t){return iK(this,void 0,void 0,function*(){let i=new tS({destinationIdentities:[e],kind:tw.RELIABLE,value:{case:"rpcAck",value:new tM({requestId:t})}});yield this.sendDataPacket(i,tw.RELIABLE)})}sendDataPacket(e,t){return iK(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(t),t===tw.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);let i=e.toBinary(),n=this.dataChannelForKind(t);if(n){if(t===tw.RELIABLE&&this.reliableMessageBuffer.push({data:i,sequence:e.sequence}),this.attemptingReconnect)return;n.send(i)}this.updateAndEmitDCBufferStatus(t)})}resendReliableMessagesForResume(e){return iK(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(tw.RELIABLE);let t=this.dataChannelForKind(tw.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(e=>{t.send(e.data)})),this.updateAndEmitDCBufferStatus(tw.RELIABLE)})}waitForBufferStatusLow(e){return new Promise((t,i)=>iK(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{let n=()=>i("Engine closed");for(this.once(E.Closing,n);!this.dcBufferStatus.get(e);)yield ra(10);this.off(E.Closing,n),t()}}))}ensureDataTransportConnected(e){return iK(this,arguments,void 0,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;return function*(){var n;if(!t.pcManager)throw new nJ("PC manager is closed");let r=i?t.pcManager.subscriber:t.pcManager.publisher,s=i?"Subscriber":"Publisher";if(!r)throw new nG("".concat(s," connection not set"),k.InternalError);let a=!1;i||t.dataChannelForKind(e,i)||(t.createDataChannels(),a=!0),a||i||t.pcManager.publisher.isICEConnected||"checking"===t.pcManager.publisher.getICEConnectionState()||(a=!0),a&&t.negotiate();let o=t.dataChannelForKind(e,i);if((null==o?void 0:o.readyState)==="open")return;let c=new Date().getTime()+t.peerConnectionTimeout;for(;new Date().getTime()<c;){if(r.isICEConnected&&(null==(n=t.dataChannelForKind(e,i))?void 0:n.readyState)==="open")return;yield ra(50)}throw new nG("could not establish ".concat(s," connection, state: ").concat(r.getICEConnectionState()),k.InternalError)}()})}ensurePublisherConnected(e){return iK(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!!this.pcManager&&this.pcManager.currentState===U.CONNECTED&&!!this.client.ws&&this.client.ws.readyState!==WebSocket.CLOSED}negotiate(){return iK(this,void 0,void 0,function*(){return new Promise((e,t)=>iK(this,void 0,void 0,function*(){if(!this.pcManager)return void t(new nQ("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.lossyDC||this.reliableDC||this.createDataChannels();let i=new AbortController,n=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(E.Closing,n),this.pcManager.publisher.once(sc.RTPVideoPayloadTypes,e=>{let t=new Map;e.forEach(e=>{let i=e.codec.toLowerCase();rt.includes(i)&&t.set(e.payload,i)}),this.emit(E.RTPVideoMapUpdate,t)});try{yield this.pcManager.negotiate(i),e()}catch(e){e instanceof nQ&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",tl.RR_UNKNOWN),t(e)}finally{this.off(E.Closing,n)}}))})}dataChannelForKind(e,t){if(t){if(e===tw.LOSSY)return this.lossyDCSub;if(e===tw.RELIABLE)return this.reliableDCSub}else{if(e===tw.LOSSY)return this.lossyDC;if(e===tw.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,n;if(!this.pcManager)return void this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);let r=this.pcManager.subscriber.getLocalDescription(),s=this.pcManager.subscriber.getRemoteDescription(),a=null==(n=null==(i=this.signalOpts)?void 0:i.autoSubscribe)||n,o=[],c=[];e.forEach(e=>{e.isDesired!==a&&o.push(e.trackSid),e.isEnabled||c.push(e.trackSid)}),this.client.sendSyncState(new iP({answer:r?r7({sdp:r.sdp,type:r.type}):void 0,offer:s?r7({sdp:s.sdp,type:s.type}):void 0,subscription:new ii({trackSids:o,subscribe:!a,participantTracks:[]}),publishTracks:function(e){let t=[];return e.forEach(e=>{void 0!==e.track&&t.push(new t8({cid:e.track.mediaStreamID,track:e.trackInfo}))}),t}(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:c,datachannelReceiveStates:this.reliableReceivedState.map((e,t)=>new iR({publisherSid:t,lastSeq:e}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){let e=[],t=(t,i)=>{(null==t?void 0:t.id)!==void 0&&null!==t.id&&e.push(new iI({label:t.label,id:t.id,target:i}))};return t(this.dataChannelForKind(tw.LOSSY),tX.PUBLISHER),t(this.dataChannelForKind(tw.RELIABLE),tX.PUBLISHER),t(this.dataChannelForKind(tw.LOSSY,!0),tX.SUBSCRIBER),t(this.dataChannelForKind(tw.RELIABLE,!0),tX.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&n4.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){rv()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){rv()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class sJ extends Error{}class sQ{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 rk(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return iK(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));let t=this.regionSettings.regions.filter(e=>!this.attemptedRegions.find(t=>t.url===e.url));if(!(t.length>0))return null;{let e=t[0];return this.attemptedRegions.push(e),iV.debug("next region: ".concat(e.region)),e.url}})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return iK(this,void 0,void 0,function*(){var t;let i=yield fetch("".concat((t=this.serverUrl,"".concat(t.protocol.replace("ws","http"),"//").concat(t.host,"/settings")),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(i.ok){let e=yield i.json();return this.lastUpdateAt=Date.now(),e}throw new nG("Could not fetch region settings: ".concat(i.statusText),401===i.status?k.NotAllowed:k.InternalError,i.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}class sY{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if("number"==typeof this.totalByteSize&&0!==this.totalByteSize){if(e&&this.bytesReceived<this.totalByteSize)throw new nZ("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),y.Incomplete);else if(this.bytesReceived>this.totalByteSize)throw new nZ("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),y.LengthExceeded)}}constructor(e,t,i,n){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=n}}class sX extends sY{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();let i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null==(t=this.onProgress)||t.call(this,i)}[Symbol.asyncIterator](){let e=this.reader.getReader(),t=new r_,i=null,n=null;if(this.signal){let e=this.signal;n=()=>{var i;null==(i=t.reject)||i.call(t,e.reason)},e.addEventListener("abort",n),i=e}let r=()=>{e.releaseLock(),i&&n&&i.removeEventListener("abort",n),this.signal=void 0};return{next:()=>iK(this,void 0,void 0,function*(){var i,n;try{let{done:r,value:s}=yield Promise.race([e.read(),t.promise,null!=(n=null==(i=this.outOfBandFailureRejectingFuture)?void 0:i.promise)?n:new Promise(()=>{})]);if(r)return this.validateBytesReceived(!0),{done:!0,value:void 0};return this.handleChunkReceived(s),{done:!1,value:s.content}}catch(e){throw r(),e}}),return(){return iK(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return iK(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var i,n,r,s;let a=new Set,o=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,l=!0,d=iz(o);!(i=(c=yield d.next()).done);l=!0)s=c.value,l=!1,a.add(s)}catch(e){n={error:e}}finally{try{!l&&!i&&(r=d.return)&&(yield r.call(d))}finally{if(n)throw n.error}}return Array.from(a)}()})}}class sZ extends sY{constructor(e,t,i,n){super(e,t,i,n),this.receivedChunks=new Map}handleChunkReceived(e){var t;let i=rL(e.chunkIndex),n=this.receivedChunks.get(i);if(n&&n.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();let r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null==(t=this.onProgress)||t.call(this,r)}[Symbol.asyncIterator](){let e=this.reader.getReader(),t=new TextDecoder("utf-8",{fatal:!0}),i=new r_,n=null,r=null;if(this.signal){let e=this.signal;r=()=>{var t;null==(t=i.reject)||t.call(i,e.reason)},e.addEventListener("abort",r),n=e}let s=()=>{e.releaseLock(),n&&r&&n.removeEventListener("abort",r),this.signal=void 0};return{next:()=>iK(this,void 0,void 0,function*(){var n,r;try{let{done:s,value:a}=yield Promise.race([e.read(),i.promise,null!=(r=null==(n=this.outOfBandFailureRejectingFuture)?void 0:n.promise)?r:new Promise(()=>{})]);if(s)return this.validateBytesReceived(!0),{done:!0,value:void 0};{let e;this.handleChunkReceived(a);try{e=t.decode(a.content)}catch(e){throw new nZ("Cannot decode datastream chunk ".concat(a.chunkIndex," as text: ").concat(e),y.DecodeFailed)}return{done:!1,value:e}}}catch(e){throw s(),e}}),return(){return iK(this,void 0,void 0,function*(){return s(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return iK(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var i,n,r,s;let a="",o=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,l=!0,d=iz(o);!(i=(c=yield d.next()).done);l=!0)s=c.value,l=!1,a+=s}catch(e){n={error:e}}finally{try{!l&&!i&&(r=d.return)&&(yield r.call(d))}finally{if(n)throw n.error}}return a}()})}}class s${constructor(){this.log=iV,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new nZ('A text stream handler for topic "'.concat(e,'" has already been set.'),y.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new nZ('A byte stream handler for topic "'.concat(e,'" has already been set.'),y.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearHandlersAndControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.byteStreamHandlers.clear(),this.textStreamHandlers.clear()}validateParticipantHasNoActiveDataStreams(e){var t,i,n,r;let s=Array.from(this.textStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e),a=Array.from(this.byteStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e);if(s.length>0||a.length>0){let o=new nZ("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),y.AbnormalEnd);for(let[e,n]of a)null==(i=(t=n.outOfBandFailureRejectingFuture).reject)||i.call(t,o),this.byteStreamControllers.delete(e);for(let[e,t]of s)null==(r=(n=t.outOfBandFailureRejectingFuture).reject)||r.call(n,o),this.textStreamControllers.delete(e)}}handleDataStreamPacket(e){return iK(this,void 0,void 0,function*(){switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity);case"streamChunk":return this.handleStreamChunk(e.value.value);case"streamTrailer":return this.handleStreamTrailer(e.value.value);default:throw Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}})}handleStreamHeader(e,t){return iK(this,void 0,void 0,function*(){var i;if("byteHeader"===e.contentHeader.case){let n,r=this.byteStreamHandlers.get(e.topic);if(!r)return void this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);let s=new r_,a={id:e.streamId,name:null!=(i=e.contentHeader.value.name)?i:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:rL(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:i=>{if(n=i,this.textStreamControllers.has(e.streamId))throw new nZ("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),y.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:a,controller:n,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:s})}});r(new sX(a,o,rL(e.totalLength),s),{identity:t})}else if("textHeader"===e.contentHeader.case){let i,n=this.textStreamHandlers.get(e.topic);if(!n)return void this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);let r=new r_,s={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:n=>{if(i=n,this.textStreamControllers.has(e.streamId))throw new nZ("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),y.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:s,controller:i,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:r})}});n(new sZ(s,a,rL(e.totalLength),r),{identity:t})}})}handleStreamChunk(e){let t=this.byteStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e);let i=this.textStreamControllers.get(e.streamId);i&&e.content.length>0&&i.controller.enqueue(e)}handleStreamTrailer(e){let 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));let i=this.byteStreamControllers.get(e.streamId);i&&(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.byteStreamControllers.delete(e.streamId))}}class s0{constructor(e,t,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return iK(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),null==(e=this.onClose)||e.call(this)})}}class s1 extends s0{}class s2 extends s0{}class s3{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return iK(this,void 0,void 0,function*(){var i;let n=crypto.randomUUID(),r=new TextEncoder().encode(e).byteLength,s=null==(i=null==t?void 0:t.attachments)?void 0:i.map(()=>crypto.randomUUID()),a=Array(s?s.length+1:1).fill(0),o=(e,i)=>{var n;a[i]=e;let r=a.reduce((e,t)=>e+t,0);null==(n=null==t?void 0:t.onProgress)||n.call(t,r)},c=yield this.streamText({streamId:n,totalSize:r,destinationIdentities:null==t?void 0:t.destinationIdentities,topic:null==t?void 0:t.topic,attachedStreamIds:s,attributes:null==t?void 0:t.attributes});return yield c.write(e),o(1,0),yield c.close(),(null==t?void 0:t.attachments)&&s&&(yield Promise.all(t.attachments.map((e,i)=>iK(this,void 0,void 0,function*(){return this._sendFile(s[i],e,{topic:t.topic,mimeType:e.type,onProgress:e=>{o(e,i+1)}})})))),c.info})}streamText(e){return iK(this,void 0,void 0,function*(){var t,i;let n=null!=(t=null==e?void 0:e.streamId)?t:crypto.randomUUID(),r={id:n,mimeType:"text/plain",timestamp:Date.now(),topic:null!=(i=null==e?void 0:e.topic)?i:"",size:null==e?void 0:e.totalSize,attributes:null==e?void 0:e.attributes},s=new tJ({streamId:n,mimeType:r.mimeType,topic:r.topic,timestamp:rU(r.timestamp),totalLength:rU(null==e?void 0:e.totalSize),attributes:r.attributes,contentHeader:{case:"textHeader",value:new tK({version:null==e?void 0:e.version,attachedStreamIds:null==e?void 0:e.attachedStreamIds,replyToStreamId:null==e?void 0:e.replyToStreamId,operationType:(null==e?void 0:e.type)==="update"?tW.UPDATE:tW.CREATE})}}),a=null==e?void 0:e.destinationIdentities,o=new tS({destinationIdentities:a,value:{case:"streamHeader",value:s}});yield this.engine.sendDataPacket(o,tw.RELIABLE);let c=0,l=this.engine,d=new WritableStream({write(e){return iK(this,void 0,void 0,function*(){for(let t of function(e,t){let i=[],n=new TextEncoder().encode(e);for(;n.length>15e3;){let e=15e3;for(;e>0;){let t=n[e];if(void 0!==t&&(192&t)!=128)break;e--}i.push(n.slice(0,e)),n=n.slice(e)}return n.length>0&&i.push(n),i}(e,15e3)){yield l.waitForBufferStatusLow(tw.RELIABLE);let e=new tS({destinationIdentities:a,value:{case:"streamChunk",value:new tQ({content:t,streamId:n,chunkIndex:rU(c)})}});yield l.sendDataPacket(e,tw.RELIABLE),c+=1}})},close(){return iK(this,void 0,void 0,function*(){let e=new tS({destinationIdentities:a,value:{case:"streamTrailer",value:new tY({streamId:n})}});yield l.sendDataPacket(e,tw.RELIABLE)})},abort(e){console.log("Sink error:",e)}}),u=()=>iK(this,void 0,void 0,function*(){yield h.close()});l.once(E.Closing,u);let h=new s1(d,r,()=>this.engine.off(E.Closing,u));return h})}sendFile(e,t){return iK(this,void 0,void 0,function*(){let i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return iK(this,void 0,void 0,function*(){var n;let r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:null!=(n=null==i?void 0:i.mimeType)?n:t.type,topic:null==i?void 0:i.topic,destinationIdentities:null==i?void 0:i.destinationIdentities}),s=t.stream().getReader();for(;;){let{done:e,value:t}=yield s.read();if(e)break;yield r.write(t)}return yield r.close(),r.info})}streamBytes(e){return iK(this,void 0,void 0,function*(){var t,i,n,r,s;let a=null!=(t=null==e?void 0:e.streamId)?t:crypto.randomUUID(),o=null==e?void 0:e.destinationIdentities,c={id:a,mimeType:null!=(i=null==e?void 0:e.mimeType)?i:"application/octet-stream",topic:null!=(n=null==e?void 0:e.topic)?n:"",timestamp:Date.now(),attributes:null==e?void 0:e.attributes,size:null==e?void 0:e.totalSize,name:null!=(r=null==e?void 0:e.name)?r:"unknown"},l=new tS({destinationIdentities:o,value:{case:"streamHeader",value:new tJ({totalLength:rU(null!=(s=c.size)?s:0),mimeType:c.mimeType,streamId:a,topic:c.topic,timestamp:rU(Date.now()),attributes:c.attributes,contentHeader:{case:"byteHeader",value:new tz({name:c.name})}})}});yield this.engine.sendDataPacket(l,tw.RELIABLE);let d=0,u=new W,h=this.engine,p=this.log;return new s2(new WritableStream({write(e){return iK(this,void 0,void 0,function*(){let t=yield u.lock(),i=0;try{for(;i<e.byteLength;){let t=e.slice(i,i+15e3);yield h.waitForBufferStatusLow(tw.RELIABLE);let n=new tS({destinationIdentities:o,value:{case:"streamChunk",value:new tQ({content:t,streamId:a,chunkIndex:rU(d)})}});yield h.sendDataPacket(n,tw.RELIABLE),d+=1,i+=t.byteLength}}finally{t()}})},close(){return iK(this,void 0,void 0,function*(){let e=new tS({destinationIdentities:o,value:{case:"streamTrailer",value:new tY({streamId:a})}});yield h.sendDataPacket(e,tw.RELIABLE)})},abort(e){p.error("Sink error:",e)}}),c)})}}class s4 extends n9{constructor(e,t,i,n,r){super(e,i,r),this.sid=t,this.receiver=n}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?P.Muted:P.Unmuted,this))}setMediaStream(e){this.mediaStream=e;let t=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(P.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return iK(this,void 0,void 0,function*(){var e;if(null==(e=this.receiver)?void 0:e.getStats)return yield this.receiver.getStats()})}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;else 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(),2e3)),"undefined"!=typeof RTCRtpReceiver&&"getSynchronizationSources"in RTCRtpReceiver&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){let e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());let i=null==(t=this.receiver)?void 0:t.getSynchronizationSources()[0];if(i){let{timestamp:e,rtpTimestamp:t}=i;t&&this.rtpTimestamp!==t&&(this.emit(P.TimeSyncUpdate,{timestamp:e,rtpTimestamp:t}),this.rtpTimestamp=t)}};e()}}class s6 extends s4{constructor(e,t,i,n,r,s){super(e,t,n9.Kind.Audio,i,s),this.monitorReceiver=()=>iK(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=sC(e,this.prevStats)),this.prevStats=e}),this.audioContext=n,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(let i of this.attachedElements)this.audioContext?null==(t=this.gainNode)||t.gain.setTargetAtTime(e,0,.1):i.volume=e;rb()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(rb())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return iK(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(rh(t))return t.setSinkId(e)}))})}attach(e){let t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&rh(e)&&e.setSinkId(this.sinkId).catch(e=>{this.log.error("Failed to set sink id on remote audio track",e,this.logContext)}),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(e=>{i.connect(e),i=e}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==e.state&&e.resume().then(()=>{"running"!==e.state&&this.emit(P.AudioPlaybackFailed,Error("Audio Context couldn't be started automatically"))}).catch(e=>{this.emit(P.AudioPlaybackFailed,e)})}disconnectWebAudio(){var e,t;null==(e=this.gainNode)||e.disconnect(),null==(t=this.sourceNode)||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return iK(this,void 0,void 0,function*(){let e;if(this.receiver&&this.receiver.getStats)return(yield this.receiver.getStats()).forEach(t=>{"inbound-rtp"===t.type&&(e={type:"audio",streamId:t.id,timestamp:t.timestamp,jitter:t.jitter,bytesReceived:t.bytesReceived,concealedSamples:t.concealedSamples,concealmentEvents:t.concealmentEvents,silentConcealedSamples:t.silentConcealedSamples,silentConcealmentEvents:t.silentConcealmentEvents,totalAudioEnergy:t.totalAudioEnergy,totalSamplesDuration:t.totalSamplesDuration})}),e})}}class s9 extends s4{constructor(e,t,i,n,r){super(e,t,n9.Kind.Video,i,r),this.elementInfos=[],this.monitorReceiver=()=>iK(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=sC(e,this.prevStats)),this.prevStats=e}),this.debouncedHandleResize=so(()=>{this.updateDimensions()},100),this.adaptiveStreamSettings=n}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}setStreamState(e){super.setStreamState(e),console.log("setStreamState",e),e===n9.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?n8(this._mediaStreamTrack,t):n5(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&void 0===this.elementInfos.find(t=>t.element===e)){let t=new s5(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&void 0===this.elementInfos.find(t=>t===e)?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream)return void this.log.warn("stopObservingElementInfo ignored",this.logContext);for(let t of this.elementInfos.filter(t=>t===e))t.stopObserving();this.elementInfos=this.elementInfos.filter(t=>t!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);for(let e of t=super.detach())this.stopObservingElement(e);return t}getDecoderImplementation(){var e;return null==(e=this.prevStats)?void 0:e.decoderImplementation}getReceiverStats(){return iK(this,void 0,void 0,function*(){let e;if(!this.receiver||!this.receiver.getStats)return;let t=yield this.receiver.getStats(),i="",n=new Map;return t.forEach(t=>{"inbound-rtp"===t.type?(i=t.codecId,e={type:"video",streamId:t.id,framesDecoded:t.framesDecoded,framesDropped:t.framesDropped,framesReceived:t.framesReceived,packetsReceived:t.packetsReceived,packetsLost:t.packetsLost,frameWidth:t.frameWidth,frameHeight:t.frameHeight,pliCount:t.pliCount,firCount:t.firCount,nackCount:t.nackCount,jitter:t.jitter,timestamp:t.timestamp,bytesReceived:t.bytesReceived,decoderImplementation:t.decoderImplementation}):"codec"===t.type&&n.set(t.id,t)}),e&&""!==i&&n.get(i)&&(e.mimeType=n.get(i).mimeType),e})}stopObservingElement(e){for(let t of this.elementInfos.filter(t=>t.element===e))this.stopObservingElementInfo(t)}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return iK(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,i;let n=this.elementInfos.reduce((e,t)=>Math.max(e,t.visibilityChangedAt||0),0),r=(null==(i=null==(t=this.adaptiveStreamSettings)?void 0:t.pauseVideoInBackground)||!!i)&&this.isInBackground,s=this.elementInfos.some(e=>e.pictureInPicture),a=this.elementInfos.some(e=>e.visible)&&!r||s;if(this.lastVisible!==a||e){if(!a&&Date.now()-n<100)return void n4.setTimeout(()=>{this.updateVisibility()},100);this.lastVisible=a,this.emit(P.VisibilityChanged,a,this)}}updateDimensions(){var e,t;let i=0,n=0,r=this.getPixelDensity();for(let e of this.elementInfos){let t=e.width()*r,s=e.height()*r;t+s>i+n&&(i=t,n=s)}((null==(e=this.lastDimensions)?void 0:e.width)!==i||(null==(t=this.lastDimensions)?void 0:t.height)!==n)&&(this.lastDimensions={width:i,height:n},this.emit(P.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;let t=null==(e=this.adaptiveStreamSettings)?void 0:e.pixelDensity;return"screen"===t?rC():t?t:rC()>2?2:1}}class s5{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;let{target:i,isIntersecting:n}=e;i===this.element&&(this.isIntersecting=n,this.isPiP=s8(this.element),this.visibilityChangedAt=Date.now(),null==(t=this.handleVisibilityChanged)||t.call(this))},this.onEnterPiP=()=>{var e,t,i;null==(t=null==(e=window.documentPictureInPicture)?void 0:e.window)||t.addEventListener("pagehide",this.onLeavePiP),this.isPiP=s8(this.element),null==(i=this.handleVisibilityChanged)||i.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=s8(this.element),null==(e=this.handleVisibilityChanged)||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:s7(e),this.isPiP=rv()&&s8(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=s7(this.element),this.isPiP=s8(this.element),this.element.handleResize=()=>{var e;null==(e=this.handleResize)||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,rO().observe(this.element),rR().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),null==(e=window.documentPictureInPicture)||e.addEventListener("enter",this.onEnterPiP),null==(i=null==(t=window.documentPictureInPicture)?void 0:t.window)||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,n,r;null==(e=rO())||e.unobserve(this.element),null==(t=rR())||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),null==(i=window.documentPictureInPicture)||i.removeEventListener("enter",this.onEnterPiP),null==(r=null==(n=window.documentPictureInPicture)?void 0:n.window)||r.removeEventListener("pagehide",this.onLeavePiP)}}function s8(e){var t,i;return document.pictureInPictureElement===e||null!=(t=window.documentPictureInPicture)&&!!t.window&&s7(e,null==(i=window.documentPictureInPicture)?void 0:i.window)}function s7(e,t){let i=t||window,n=e.offsetTop,r=e.offsetLeft,s=e.offsetWidth,a=e.offsetHeight,{hidden:o}=e,{display:c}=getComputedStyle(e);for(;e.offsetParent;)n+=(e=e.offsetParent).offsetTop,r+=e.offsetLeft;return n<i.pageYOffset+i.innerHeight&&r<i.pageXOffset+i.innerWidth&&n+a>i.pageYOffset&&r+s>i.pageXOffset&&!o&&"none"!==c}class ae extends iQ.EventEmitter{constructor(e,t,i,n){var r;super(),this.metadataMuted=!1,this.encryption=tk.NONE,this.log=iV,this.handleMuted=()=>{this.emit(P.Muted)},this.handleUnmuted=()=>{this.emit(P.Unmuted)},this.log=iq(null!=(r=null==n?void 0:n.loggerName)?r:h.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=n9.Source.Unknown}setTrack(e){this.track&&(this.track.off(P.Muted,this.handleMuted),this.track.off(P.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(P.Muted,this.handleMuted),e.on(P.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},null==(e=this.loggerContextCb)?void 0:e.call(this)),rZ(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==tk.NONE}get audioTrack(){if(rF(this.track))return this.track}get videoTrack(){if(rB(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=n9.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===n9.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(e){var t,i;(t=e.SubscriptionStatus||(e.SubscriptionStatus={})).Desired="desired",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed",(i=e.PermissionStatus||(e.PermissionStatus={})).Allowed="allowed",i.NotAllowed="not_allowed"}(ae||(ae={}));class at extends ae{get isUpstreamPaused(){var e;return null==(e=this.track)?void 0:e.isUpstreamPaused}constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.handleTrackEnded=()=>{this.emit(P.Ended)},this.handleCpuConstrained=()=>{this.track&&rB(this.track)&&this.emit(P.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(P.Ended,this.handleTrackEnded),this.track.off(P.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(P.Ended,this.handleTrackEnded),e.on(P.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return iK(this,void 0,void 0,function*(){var e;return null==(e=this.track)?void 0:e.mute()})}unmute(){return iK(this,void 0,void 0,function*(){var e;return null==(e=this.track)?void 0:e.unmute()})}pauseUpstream(){return iK(this,void 0,void 0,function*(){var e;yield null==(e=this.track)?void 0:e.pauseUpstream()})}resumeUpstream(){return iK(this,void 0,void 0,function*(){var e;yield null==(e=this.track)?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(!rF(this.track))return[];{let t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(tu.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(tu.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(tu.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(tu.TF_STEREO),(null==(e=this.options)?void 0:e.dtx)||i.add(tu.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(tu.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}}}function ai(e,t){return iK(this,void 0,void 0,function*(){null!=e||(e={});let i=!1,{audioProcessor:n,videoProcessor:r,optionsWithoutProcessor:s}=r$(e),a=s.audio,o=s.video;if(n&&"object"==typeof s.audio&&(s.audio.processor=n),r&&"object"==typeof s.video&&(s.video.processor=r),e.audio&&"object"==typeof s.audio&&"string"==typeof s.audio.deviceId){let e=s.audio.deviceId;s.audio.deviceId={exact:e},i=!0,a=Object.assign(Object.assign({},s.audio),{deviceId:{ideal:e}})}if(s.video&&"object"==typeof s.video&&"string"==typeof s.video.deviceId){let e=s.video.deviceId;s.video.deviceId={exact:e},i=!0,o=Object.assign(Object.assign({},s.video),{deviceId:{ideal:e}})}!0!==s.audio&&("object"!=typeof s.audio||s.audio.deviceId)||(s.audio={deviceId:"default"}),!0===s.video?s.video={deviceId:"default"}:"object"!=typeof s.video||s.video.deviceId||(s.video.deviceId="default");let c=rW(s,sm,sg),l=rz(c),d=navigator.mediaDevices.getUserMedia(l);s.audio&&(r3.userMediaPromiseMap.set("audioinput",d),d.catch(()=>r3.userMediaPromiseMap.delete("audioinput"))),s.video&&(r3.userMediaPromiseMap.set("videoinput",d),d.catch(()=>r3.userMediaPromiseMap.delete("videoinput")));try{let e=yield d;return yield Promise.all(e.getTracks().map(i=>iK(this,void 0,void 0,function*(){let s,a="audio"===i.kind,o=a?c.audio:c.video;"boolean"!=typeof o&&o||(o={});let d=a?l.audio:l.video;"boolean"!=typeof d&&(s=d);let u=i.getSettings().deviceId;(null==s?void 0:s.deviceId)&&rM(s.deviceId)!==u?s.deviceId=u:s||(s={deviceId:u});let h=function(e,t,i){switch(e.kind){case"audio":return new sI(e,t,!1,void 0,i);case"video":return new sB(e,t,!1,i);default:throw new nK("unsupported track type: ".concat(e.kind))}}(i,s,t);return h.kind===n9.Kind.Video?h.source=n9.Source.Camera:h.kind===n9.Kind.Audio&&(h.source=n9.Source.Microphone),h.mediaStream=e,rF(h)&&n?yield h.setProcessor(n):rB(h)&&r&&(yield h.setProcessor(r)),h})))}catch(n){if(!i)throw n;return ai(Object.assign(Object.assign({},e),{audio:a,video:o}),t)}})}function an(e){return iK(this,void 0,void 0,function*(){return(yield ai({audio:null==e||e,video:!1}))[0]})}!function(e){e.Excellent="excellent",e.Good="good",e.Poor="poor",e.Lost="lost",e.Unknown="unknown"}(F||(F={}));class ar extends iQ.EventEmitter{get logContext(){var e,t;return Object.assign({},null==(t=null==(e=this.loggerOptions)?void 0:e.loggerContextCb)?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(null==(e=this.permissions)?void 0:e.agent)||this.kind===tv.AGENT}get isActive(){var e;return(null==(e=this.participantInfo)?void 0:e.state)===tf.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,n,r,s){var a;let o=arguments.length>6&&void 0!==arguments[6]?arguments[6]:tv.STANDARD;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=F.Unknown,this.log=iV,this.log=iq(null!=(a=null==s?void 0:s.loggerName)?a:h.Participant),this.loggerOptions=s,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=n,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=null!=r?r:{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(let[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(let[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():(this.activeFuture||(this.activeFuture=new r_,this.once(w.Active,()=>{var e,t;null==(t=null==(e=this.activeFuture)?void 0:e.resolve)||t.call(e),this.activeFuture=void 0})),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;let t=this.getTrackPublication(n9.Source.Camera);return!(null==(e=null==t?void 0:t.isMuted)||e)}get isMicrophoneEnabled(){var e;let t=this.getTrackPublication(n9.Source.Microphone);return!(null==(e=null==t?void 0:t.isMuted)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(n9.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(this.participantInfo.joinedAt.toString())):new Date}updateInfo(e){var t;return(!this.participantInfo||this.participantInfo.sid!==e.sid||!(this.participantInfo.version>e.version))&&(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===tf.ACTIVE&&(null==(t=this.participantInfo)?void 0:t.state)!==tf.ACTIVE&&this.emit(w.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){let t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(w.ParticipantMetadataChanged,i)}_setName(e){let t=this.name!==e;this.name=e,t&&this.emit(w.ParticipantNameChanged,e)}_setAttributes(e){let t=function(e,t){var i;void 0===e&&(e={}),void 0===t&&(t={});let n=[...Object.keys(t),...Object.keys(e)],r={};for(let s of n)e[s]!==t[s]&&(r[s]=null!=(i=t[s])?i:"");return r}(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(w.AttributesChanged,t)}setPermissions(e){var t,i,n,r,s,a;let o=this.permissions,c=e.canPublish!==(null==(t=this.permissions)?void 0:t.canPublish)||e.canSubscribe!==(null==(i=this.permissions)?void 0:i.canSubscribe)||e.canPublishData!==(null==(n=this.permissions)?void 0:n.canPublishData)||e.hidden!==(null==(r=this.permissions)?void 0:r.hidden)||e.recorder!==(null==(s=this.permissions)?void 0:s.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((e,t)=>{var i;return e!==(null==(i=this.permissions)?void 0:i.canPublishSources[t])})||e.canSubscribeMetrics!==(null==(a=this.permissions)?void 0:a.canSubscribeMetrics);return this.permissions=e,c&&this.emit(w.ParticipantPermissionsChanged,o),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(w.IsSpeakingChanged,e))}setConnectionQuality(e){let t=this._connectionQuality;this._connectionQuality=function(e){switch(e){case ta.EXCELLENT:return F.Excellent;case ta.GOOD:return F.Good;case ta.POOR:return F.Poor;case ta.LOST:return F.Lost;default:return F.Unknown}}(e),t!==this._connectionQuality&&this.emit(w.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&(null==(t=(e=this.activeFuture).reject)||t.call(e,Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>rF(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){switch(e.on(P.Muted,()=>{this.emit(w.TrackMuted,e)}),e.on(P.Unmuted,()=>{this.emit(w.TrackUnmuted,e)}),e.track&&(e.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case n9.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case n9.Kind.Video:this.videoTrackPublications.set(e.trackSid,e)}}}class as extends ar{constructor(e,t,i,n,r,s){super(e,t,void 0,void 0,void 0,{loggerName:n.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=tk.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new r_)},this.handleReconnected=()=>{var e,t;null==(t=null==(e=this.reconnectFuture)?void 0:e.resolve)||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var e,t,i,n,r,s;this.reconnectFuture&&(this.reconnectFuture.promise.catch(e=>this.log.warn(e.message,this.logContext)),null==(t=null==(e=this.reconnectFuture)?void 0:e.reject)||t.call(e,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0),this.signalConnectedFuture&&(null==(n=(i=this.signalConnectedFuture).reject)||n.call(i,"Got disconnected without signal connected"),this.signalConnectedFuture=void 0),null==(s=null==(r=this.activeAgentFuture)?void 0:r.reject)||s.call(r,"Got disconnected without active agent present"),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=e=>{var t,i;e.participant&&this.updateInfo(e.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new r_),null==(i=(t=this.signalConnectedFuture).resolve)||i.call(t)},this.handleSignalRequestResponse=e=>{let{requestId:t,reason:i,message:n}=e,r=this.pendingSignalRequests.get(t);r&&(i!==iL.OK&&r.reject(new nX(n,i)),this.pendingSignalRequests.delete(t))},this.handleDataPacket=e=>{switch(e.value.case){case"rpcResponse":let t=e.value.value,i=null,n=null;"payload"===t.value.case?i=t.value.value:"error"===t.value.case&&(n=sk.fromProto(t.value.value)),this.handleIncomingRpcResponse(t.requestId,i,n);break;case"rpcAck":let r=e.value.value;this.handleIncomingRpcAck(r.requestId)}},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(e=>(function(e){var t,i,n;if(!e.participantSid&&!e.participantIdentity)throw Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new iC({participantIdentity:null!=(t=e.participantIdentity)?t:"",participantSid:null!=(i=e.participantSid)?i:"",allTracks:null!=(n=e.allowAll)&&n,trackSids:e.allowedTrackSids||[]})})(e)))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{if(void 0===t&&(t=!0),!e.sid)return void this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),rZ(e)));this.engine.updateMuteStatus(e.sid,t)},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),rZ(e))),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),rZ(e))),this.onTrackMuted(e,e.isMuted)},this.onTrackFeatureUpdate=e=>{let t=this.audioTrackPublications.get(e.sid);if(!t)return void this.log.warn("Could not update local audio track settings, missing publication for track ".concat(e.sid),this.logContext);this.engine.client.sendUpdateLocalAudioTrack(t.trackSid,t.getTrackFeatures())},this.onTrackCpuConstrained=(e,t)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),rZ(t))),this.emit(w.LocalTrackCpuConstrained,e,t)},this.handleSubscribedQualityUpdate=e=>iK(this,void 0,void 0,function*(){if(!(null==(o=this.roomOptions)?void 0:o.dynacast))return;let t=this.videoTrackPublications.get(e.trackSid);if(!t)return void this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}));if(!t.videoTrack)return;let i=yield t.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var n,r,s,a,o,c,l=!0,d=iz(i);!(n=(c=yield d.next()).done);l=!0)a=c.value,l=!1,function(e){return!!re.find(t=>t===e)}(a)&&(this.log.debug("publish ".concat(a," for ").concat(t.videoTrack.sid),Object.assign(Object.assign({},this.logContext),rZ(t))),yield this.publishAdditionalCodecForTrack(t.videoTrack,a,t.options))}catch(e){r={error:e}}finally{try{!l&&!n&&(s=d.return)&&(yield s.call(d))}finally{if(r)throw r.error}}}),this.handleLocalTrackUnpublished=e=>{let t=this.trackPublications.get(e.trackSid);if(!t)return void this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}));this.unpublishTrack(t.track)},this.handleTrackEnded=e=>iK(this,void 0,void 0,function*(){if(e.source===n9.Source.ScreenShare||e.source===n9.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),rZ(e))),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(rq(e)||rV(e))try{if(rv())try{let t=yield null==navigator?void 0:navigator.permissions.query({name:e.source===n9.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw this.log.warn("user has revoked access to ".concat(e.source),Object.assign(Object.assign({},this.logContext),rZ(e))),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},Error("GetUserMedia Permission denied")}catch(e){}e.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),rZ(e))),rq(e)?yield e.restartTrack({deviceId:"default"}):yield e.restartTrack())}catch(t){this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),rZ(e))),yield e.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=n,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=r,this.roomOutgoingDataStreamManager=s}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==tk.NONE}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(E.RemoteMute,(e,t)=>{let i=this.trackPublications.get(e);i&&i.track&&(t?i.mute():i.unmute())}),(null==(t=this.signalConnectedFuture)?void 0:t.isResolved)&&(this.signalConnectedFuture=void 0),this.engine.on(E.Connected,this.handleReconnected).on(E.SignalConnected,this.handleSignalConnected).on(E.SignalRestarted,this.handleReconnected).on(E.SignalResumed,this.handleReconnected).on(E.Restarting,this.handleReconnecting).on(E.Resuming,this.handleReconnecting).on(E.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(E.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(E.Closing,this.handleClosing).on(E.SignalRequestResponse,this.handleSignalRequestResponse).on(E.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return iK(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return iK(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return iK(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return iK(this,arguments,void 0,function(e){var t=this;let{metadata:i,name:n,attributes:r}=e;return function*(){return new Promise((e,s)=>iK(t,void 0,void 0,function*(){var t,a;try{let o=!1,c=yield this.engine.client.sendUpdateLocalMetadata(null!=(t=null!=i?i:this.metadata)?t:"",null!=(a=null!=n?n:this.name)?a:"",r),l=performance.now();for(this.pendingSignalRequests.set(c,{resolve:e,reject:e=>{s(e),o=!0},values:{name:n,metadata:i,attributes:r}});performance.now()-l<5e3&&!o;){if((!n||this.name===n)&&(!i||this.metadata===i)&&(!r||Object.entries(r).every(e=>{let[t,i]=e;return this.attributes[t]===i||""===i&&!this.attributes[t]}))){this.pendingSignalRequests.delete(c),e();return}yield ra(50)}s(new nX("Request to update local metadata timed out","TimeoutError"))}catch(e){e instanceof Error&&s(e)}}))}()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(n9.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(n9.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(n9.Source.ScreenShare,e,t,i)}setE2EEEnabled(e){return iK(this,void 0,void 0,function*(){this.encryptionType=e?tk.GCM:tk.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,i,n){return iK(this,void 0,void 0,function*(){this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let r=this.getTrackPublication(e);if(t)if(r)yield r.unmute();else{let t;if(this.pendingPublishing.has(e)){let t=yield this.waitForPendingPublicationOfSource(e);return t||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield null==t?void 0:t.unmute(),t}this.pendingPublishing.add(e);try{switch(e){case n9.Source.Camera:t=yield this.createTracks({video:null==i||i});break;case n9.Source.Microphone:t=yield this.createTracks({audio:null==i||i});break;case n9.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},i));break;default:throw new nK(e)}}catch(i){throw null==t||t.forEach(e=>{e.stop()}),i instanceof Error&&this.emit(w.MediaDevicesError,i,rY(e)),this.pendingPublishing.delete(e),i}for(let n of t){let t=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===n9.Source.Microphone&&rF(n)&&t.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),n.startPreConnectBuffer())}try{let e=[];for(let i of t)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),rZ(i))),e.push(this.publishTrack(i,n));let i=yield Promise.all(e);[r]=i}catch(e){throw null==t||t.forEach(e=>{e.stop()}),e}finally{this.pendingPublishing.delete(e)}}else if(!(null==r?void 0:r.track)&&this.pendingPublishing.has(e)&&((r=yield this.waitForPendingPublicationOfSource(e))||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),r&&r.track)if(e===n9.Source.ScreenShare){r=yield this.unpublishTrack(r.track);let e=this.getTrackPublication(n9.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield r.mute();return r})}enableCameraAndMicrophone(){return iK(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(n9.Source.Camera)||this.pendingPublishing.has(n9.Source.Microphone))){this.pendingPublishing.add(n9.Source.Camera),this.pendingPublishing.add(n9.Source.Microphone);try{let e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(e=>this.publishTrack(e)))}finally{this.pendingPublishing.delete(n9.Source.Camera),this.pendingPublishing.delete(n9.Source.Microphone)}}})}createTracks(e){return iK(this,void 0,void 0,function*(){var t,i;null!=e||(e={});let n=rW(e,null==(t=this.roomOptions)?void 0:t.audioCaptureDefaults,null==(i=this.roomOptions)?void 0:i.videoCaptureDefaults);try{return(yield ai(n,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(e=>(rF(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=n9.Source.Microphone,this.emit(w.AudioStreamAcquired)),rB(e)&&(this.cameraError=void 0,e.source=n9.Source.Camera),e))}catch(t){throw t instanceof Error&&(e.audio&&(this.microphoneError=t),e.video&&(this.cameraError=t)),t}})}createScreenTracks(e){return iK(this,void 0,void 0,function*(){var t,i,n;let r;if(void 0===e&&(e={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new nW("getDisplayMedia not supported");void 0===e.resolution&&!function(){let e=n0();return(null==e?void 0:e.name)==="Safari"&&e.version.startsWith("17.")||(null==e?void 0:e.os)==="iOS"&&!!(null==e?void 0:e.osVersion)&&rS(e.osVersion,"17")>=0}()&&(e.resolution=rr.h1080fps30.resolution);let s=(r=null==(i=(t=e).video)||i,t.resolution&&t.resolution.width>0&&t.resolution.height>0&&(r="boolean"==typeof r?{}:r,r=rm()?Object.assign(Object.assign({},r),{width:{max:t.resolution.width},height:{max:t.resolution.height},frameRate:t.resolution.frameRate}):Object.assign(Object.assign({},r),{width:{ideal:t.resolution.width},height:{ideal:t.resolution.height},frameRate:t.resolution.frameRate})),{audio:null!=(n=t.audio)&&n,video:r,controller:t.controller,selfBrowserSurface:t.selfBrowserSurface,surfaceSwitching:t.surfaceSwitching,systemAudio:t.systemAudio,preferCurrentTab:t.preferCurrentTab}),a=yield navigator.mediaDevices.getDisplayMedia(s),o=a.getVideoTracks();if(0===o.length)throw new nK("no video track found");let c=new sB(o[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});c.source=n9.Source.ScreenShare,e.contentHint&&(c.mediaStreamTrack.contentHint=e.contentHint);let l=[c];if(a.getAudioTracks().length>0){this.emit(w.AudioStreamAcquired);let e=new sI(a.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e.source=n9.Source.ScreenShareAudio,l.push(e)}return l})}publishTrack(e,t){return iK(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return iK(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function*(){var r,s;let a,o;if(rq(e)&&e.setAudioContext(i.audioContext),yield null==(r=i.reconnectFuture)?void 0:r.promise,i.republishPromise&&!n&&(yield i.republishPromise),rj(e)&&i.pendingPublishPromises.has(e)&&(yield i.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)a=e.getConstraints();else{let t;switch(a=e.constraints,e.source){case n9.Source.Microphone:t="audioinput";break;case n9.Source.Camera:t="videoinput"}t&&i.activeDeviceMap.has(t)&&(a=Object.assign(Object.assign({},a),{deviceId:i.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new sI(e,a,!0,i.audioContext,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;case"video":e=new sB(e,a,!0,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;default:throw new nK("unsupported MediaStreamTrack kind ".concat(e.kind))}else e.updateLoggerOptions({loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});if(i.trackPublications.forEach(t=>{t.track&&t.track===e&&(o=t)}),o)return i.log.warn("track has already been published, skipping",Object.assign(Object.assign({},i.logContext),rZ(o))),o;let c=Object.assign(Object.assign({},i.roomOptions.publishDefaults),t),l="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,d=null!=(s=c.forceStereo)?s:l;d&&(void 0===c.dtx&&i.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},i.logContext),rZ(e))),void 0===c.red&&i.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!=c.dtx||(c.dtx=!1),null!=c.red||(c.red=!1)),!function(){let e=n0(),t="17.2";if(e)if("Safari"!==e.name&&"iOS"!==e.os)return!0;else if("iOS"===e.os&&e.osVersion&&rS(e.osVersion,t)>=0)return!0;else if("Safari"===e.name&&rS(e.version,t)>=0)return!0;else return!1}()&&i.roomOptions.e2ee&&(i.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({},i.logContext)),c.simulcast=!1),c.source&&(e.source=c.source);let u=new Promise((t,n)=>iK(i,void 0,void 0,function*(){try{if(this.engine.client.currentState!==x.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:rZ(e)}));let i=setTimeout(()=>{n(new nY("publishing rejected as engine not connected within timeout",408))},15e3);yield this.waitUntilEngineConnected(),clearTimeout(i);let r=yield this.publish(e,c,d);t(r)}else try{let i=yield this.publish(e,c,d);t(i)}catch(e){n(e)}}catch(e){n(e)}}));i.pendingPublishPromises.set(e,u);try{return yield u}catch(e){throw e}finally{i.pendingPublishPromises.delete(e)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new r_),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),rZ(e))),!1;let{canPublish:t,canPublishSources:i}=this.permissions;return!!(t&&(0===i.length||i.map(e=>(function(e){switch(e){case tr.CAMERA:return n9.Source.Camera;case tr.MICROPHONE:return n9.Source.Microphone;case tr.SCREEN_SHARE:return n9.Source.ScreenShare;case tr.SCREEN_SHARE_AUDIO:return n9.Source.ScreenShareAudio;default:return n9.Source.Unknown}})(e)).includes(e.source)))||(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),rZ(e))),!1)}publish(e,t,i){return iK(this,void 0,void 0,function*(){var n,r,s,a,o,c,l,d,u,h;let p,m;if(!this.hasPermissionsToPublish(e))throw new nY("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(t=>rj(e)&&t.source===e.source)&&e.source!==n9.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),rZ(e))),t.stopMicTrackOnMute&&rF(e)&&(e.stopOnMute=!0),e.source===n9.Source.ScreenShare&&rp()&&(t.simulcast=!1),"av1"===t.videoCodec&&!function(){if(!("getCapabilities"in RTCRtpSender)||rm()||rp())return!1;let e=RTCRtpSender.getCapabilities("video"),t=!1;if(e){for(let i of e.codecs)if("video/AV1"===i.mimeType){t=!0;break}}return t}()&&(t.videoCodec=void 0),"vp9"===t.videoCodec&&!function(){if(!("getCapabilities"in RTCRtpSender)||rp())return!1;if(rm()){let e=n0();if((null==e?void 0:e.version)&&0>rS(e.version,"16")||(null==e?void 0:e.os)==="iOS"&&(null==e?void 0:e.osVersion)&&0>rS(e.osVersion,"16"))return!1}let e=RTCRtpSender.getCapabilities("video"),t=!1;if(e){for(let i of e.codecs)if("video/VP9"===i.mimeType){t=!0;break}}return t}()&&(t.videoCodec=void 0),void 0===t.videoCodec&&(t.videoCodec="vp8"),this.enabledPublishVideoCodecs.length>0&&!this.enabledPublishVideoCodecs.some(e=>t.videoCodec===rX(e.mime))&&(t.videoCodec=rX(this.enabledPublishVideoCodecs[0].mime));let g=t.videoCodec;e.on(P.Muted,this.onTrackMuted),e.on(P.Unmuted,this.onTrackUnmuted),e.on(P.Ended,this.handleTrackEnded),e.on(P.UpstreamPaused,this.onTrackUpstreamPaused),e.on(P.UpstreamResumed,this.onTrackUpstreamResumed),e.on(P.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);let f=[],v=!(null==(n=t.dtx)||n),b=e.getSourceTrackSettings();b.autoGainControl&&f.push(tu.TF_AUTO_GAIN_CONTROL),b.echoCancellation&&f.push(tu.TF_ECHO_CANCELLATION),b.noiseSuppression&&f.push(tu.TF_NOISE_SUPPRESSION),b.channelCount&&b.channelCount>1&&f.push(tu.TF_STEREO),v&&f.push(tu.TF_NO_DTX),rq(e)&&e.hasPreConnectBuffer&&f.push(tu.TF_PRECONNECT_BUFFER);let k=new t3({cid:e.mediaStreamTrack.id,name:t.name,type:n9.kindToProto(e.kind),muted:e.isMuted,source:n9.sourceToProto(e.source),disableDtx:v,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(null==(r=t.red)||r),stream:null==t?void 0:t.stream,backupCodecPolicy:null==t?void 0:t.backupCodecPolicy,audioFeatures:f});if(e.kind===n9.Kind.Video){let i={width:0,height:0};try{i=yield e.waitForDimensions()}catch(n){let t=null!=(a=null==(s=this.roomOptions.videoCaptureDefaults)?void 0:s.resolution)?a:ri.h720.resolution;i={width:t.width,height:t.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),rZ(e)),{dims:i}))}k.width=i.width,k.height=i.height,rV(e)&&(ru(g)&&(e.source===n9.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),rZ(e))))),t.scalabilityMode=null!=(o=t.scalabilityMode)?o:"L3T3_KEY"),k.simulcastCodecs=[new t2({codec:g,cid:e.mediaStreamTrack.id})],!0===t.backupCodec&&(t.backupCodec={codec:"vp8"}),t.backupCodec&&g!==t.backupCodec.codec&&k.encryption===tk.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),k.simulcastCodecs.push(new t2({codec:t.backupCodec.codec,cid:""})))),p=sN(e.source===n9.Source.ScreenShare,k.width,k.height,t),k.layers=sH(k.width,k.height,p,ru(t.videoCodec))}else e.kind===n9.Kind.Audio&&(p=[{maxBitrate:null==(c=t.audioPreset)?void 0:c.maxBitrate,priority:null!=(d=null==(l=t.audioPreset)?void 0:l.priority)?d:"high",networkPriority:null!=(h=null==(u=t.audioPreset)?void 0:u.priority)?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new nJ("cannot publish track when not connected");let y=()=>iK(this,void 0,void 0,function*(){var i,n;if(!this.engine.pcManager)throw new nJ("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,p),this.emit(w.LocalSenderCreated,e.sender,e),rV(e)&&(null!=t.degradationPreference||(t.degradationPreference=e.source===n9.Source.ScreenShare||e.constraints.height&&rM(e.constraints.height)>=1080?"maintain-resolution":"balanced"),e.setDegradationPreference(t.degradationPreference)),p)if(rp()&&e.kind===n9.Kind.Audio){let t;for(let i of this.engine.pcManager.publisher.getTransceivers())if(i.sender===e.sender){t=i;break}t&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:t,codec:"opus",maxbr:(null==(i=p[0])?void 0:i.maxBitrate)?p[0].maxBitrate/1e3:0})}else e.codec&&ru(e.codec)&&(null==(n=p[0])?void 0:n.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:k.cid,codec:e.codec,maxbr:p[0].maxBitrate/1e3});yield this.engine.negotiate()}),T=new Promise((t,i)=>iK(this,void 0,void 0,function*(){var n;try{m=yield this.engine.addTrack(k),t(m)}catch(t){e.sender&&(null==(n=this.engine.pcManager)?void 0:n.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(t=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),rZ(e)),{error:t}))})),i(t)}}));if(this.enabledPublishVideoCodecs.length>0)m=(yield Promise.all([T,y()]))[0];else{let i;if((m=yield T).codecs.forEach(e=>{void 0===i&&(i=e.mimeType)}),i&&e.kind===n9.Kind.Video){let n=rX(i);n!==g&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),rZ(e)),{codec:n})),t.videoCodec=n,p=sN(e.source===n9.Source.ScreenShare,k.width,k.height,t))}yield y()}let C=new at(e.kind,m,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(C.on(P.CpuConstrained,e=>this.onTrackCpuConstrained(e,C)),C.options=t,e.sid=m.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:p,trackInfo:m})),rV(e)?e.startMonitor(this.engine.client):rq(e)&&e.startMonitor(),this.addTrackPublication(C),this.emit(w.LocalTrackPublished,C),rq(e)&&m.audioFeatures.includes(tu.TF_PRECONNECT_BUFFER)){let t=e.getPreConnectBuffer(),i=e.getPreConnectBufferMimeType();this.on(w.LocalTrackSubscribed,t=>{if(t.trackSid===m.sid){if(!e.hasPreConnectBuffer)return void this.log.warn("subscribe event came to late, buffer already closed",this.logContext);this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),rZ(e))),e.stopPreConnectBuffer()}}),t&&new Promise((n,r)=>iK(this,void 0,void 0,function*(){try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),rZ(e)));let m=setTimeout(()=>{r(Error("agent not active within 10 seconds"))},1e4),g=yield this.waitUntilActiveAgentPresent();clearTimeout(m),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),rZ(e)));let f=yield this.streamBytes({name:"preconnect-buffer",mimeType:i,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[g.identity],attributes:{trackId:C.trackSid,sampleRate:String(null!=(l=b.sampleRate)?l:"48000"),channels:String(null!=(d=b.channelCount)?d:"1")}});try{for(var s,a,o,c,l,d,u,h=!0,p=iz(t);!(s=(u=yield p.next()).done);h=!0)c=u.value,h=!1,yield f.write(c)}catch(e){a={error:e}}finally{try{!h&&!s&&(o=p.return)&&(yield o.call(p))}finally{if(a)throw a.error}}yield f.close(),n()}catch(e){r(e)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),rZ(e)))}).catch(t=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),rZ(e)),{error:t}))})}return C})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return iK(this,void 0,void 0,function*(){var n;let r;if(this.encryptionType!==tk.NONE)return;if(this.trackPublications.forEach(t=>{t.track&&t.track===e&&(r=t)}),!r)throw new nK("track is not published");if(!rV(e))throw new nK("track is not a video track");let s=Object.assign(Object.assign({},null==(n=this.roomOptions)?void 0:n.publishDefaults),i),a=function(e,t,i){var n,r,s,a;if(!i.backupCodec||!0===i.backupCodec||i.backupCodec.codec===i.videoCodec)return;t!==i.backupCodec.codec&&iV.warn("requested a different codec than specified as backup",{serverRequested:t,backup:i.backupCodec.codec}),i.videoCodec=t,i.videoEncoding=i.backupCodec.encoding;let o=e.mediaStreamTrack.getSettings(),c=null!=(n=o.width)?n:null==(r=e.dimensions)?void 0:r.width,l=null!=(s=o.height)?s:null==(a=e.dimensions)?void 0:a.height;return e.source===n9.Source.ScreenShare&&i.simulcast&&(i.simulcast=!1),sN(e.source===n9.Source.ScreenShare,c,l,i)}(e,t,s);if(!a)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),rZ(e)));let o=e.addSimulcastTrack(t,a);if(!o)return;let c=new t3({cid:o.mediaStreamTrack.id,type:n9.kindToProto(e.kind),muted:e.isMuted,source:n9.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:s.videoCodec,cid:o.mediaStreamTrack.id}]});if(c.layers=sH(c.width,c.height,a),!this.engine||this.engine.isClosed)throw new nJ("cannot publish track when not connected");let l=()=>iK(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,o,s,a),yield this.engine.negotiate()}),d=(yield Promise.all([this.engine.addTrack(c),l()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:a,trackInfo:d}))})}unpublishTrack(e,t){return iK(this,void 0,void 0,function*(){var i,n;if(rj(e)){let t=this.pendingPublishPromises.get(e);t&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),rZ(e))),yield t)}let r=this.getPublicationForTrack(e),s=r?rZ(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),s)),!r||!r.track)return void this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),s));(e=r.track).off(P.Muted,this.onTrackMuted),e.off(P.Unmuted,this.onTrackUnmuted),e.off(P.Ended,this.handleTrackEnded),e.off(P.UpstreamPaused,this.onTrackUpstreamPaused),e.off(P.UpstreamResumed,this.onTrackUpstreamResumed),e.off(P.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),void 0===t&&(t=null==(n=null==(i=this.roomOptions)?void 0:i.stopLocalTrackOnUnpublish)||n),t?e.stop():e.stopMonitor();let a=!1,o=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<U.FAILED&&o)try{for(let e of this.engine.pcManager.publisher.getTransceivers())e.sender===o&&(e.direction="inactive",a=!0);if(this.engine.removeTrack(o)&&(a=!0),rV(e)){for(let[,t]of e.simulcastCodecs)t.sender&&(this.engine.removeTrack(t.sender)&&(a=!0),t.sender=void 0);e.simulcastCodecs.clear()}}catch(e){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),s),{error:e}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case n9.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case n9.Kind.Video:this.videoTrackPublications.delete(r.trackSid)}return this.emit(w.LocalTrackUnpublished,r),r.setTrack(void 0),a&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return iK(this,void 0,void 0,function*(){return(yield Promise.all(e.map(e=>this.unpublishTrack(e)))).filter(e=>!!e)})}republishAllTracks(e){return iK(this,arguments,void 0,function(e){var t=this;let i=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new Promise((n,r)=>iK(t,void 0,void 0,function*(){try{let t=[];this.trackPublications.forEach(i=>{i.track&&(e&&(i.options=Object.assign(Object.assign({},i.options),e)),t.push(i))}),yield Promise.all(t.map(e=>iK(this,void 0,void 0,function*(){let t=e.track;yield this.unpublishTrack(t,!1),i&&!t.isMuted&&t.source!==n9.Source.ScreenShare&&t.source!==n9.Source.ScreenShareAudio&&(rq(t)||rV(t))&&!t.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:e.trackSid})),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))),n()}catch(e){r(e)}finally{this.republishPromise=void 0}})),yield t.republishPromise}()})}publishData(e){return iK(this,arguments,void 0,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){let n=i.reliable?tw.RELIABLE:tw.LOSSY,r=i.destinationIdentities,s=i.topic,a=new tS({kind:n,value:{case:"user",value:new tR({participantIdentity:t.identity,payload:e,destinationIdentities:r,topic:s})}});yield t.engine.sendDataPacket(a,n)}()})}publishDtmf(e,t){return iK(this,void 0,void 0,function*(){let i=new tS({kind:tw.RELIABLE,value:{case:"sipDtmf",value:new tI({code:e,digit:t})}});yield this.engine.sendDataPacket(i,tw.RELIABLE)})}sendChatMessage(e,t){return iK(this,void 0,void 0,function*(){let i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:null==t?void 0:t.attachments},n=new tS({value:{case:"chatMessage",value:new tx(Object.assign(Object.assign({},i),{timestamp:ed.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(n,tw.RELIABLE),this.emit(w.ChatMessage,i),i})}editChatMessage(e,t){return iK(this,void 0,void 0,function*(){let i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),n=new tS({value:{case:"chatMessage",value:new tx(Object.assign(Object.assign({},i),{timestamp:ed.parse(i.timestamp),editTimestamp:ed.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(n,tw.RELIABLE),this.emit(w.ChatMessage,i),i})}sendText(e,t){return iK(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return iK(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return iK(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return iK(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){return iK(this,arguments,void 0,function(e){var t=this;let{destinationIdentity:i,method:n,payload:r,responseTimeout:s=1e4}=e;return function*(){return new Promise((e,a)=>iK(t,void 0,void 0,function*(){var t,o,c,l;if(sy(r)>15360)return void a(sk.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));if((null==(o=null==(t=this.engine.latestJoinResponse)?void 0:t.serverInfo)?void 0:o.version)&&0>rS(null==(l=null==(c=this.engine.latestJoinResponse)?void 0:c.serverInfo)?void 0:l.version,"1.8.0"))return void a(sk.builtIn("UNSUPPORTED_SERVER"));let d=crypto.randomUUID();yield this.publishRpcRequest(i,d,n,r,s-2e3);let u=setTimeout(()=>{this.pendingAcks.delete(d),a(sk.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(d),clearTimeout(h)},2e3);this.pendingAcks.set(d,{resolve:()=>{clearTimeout(u)},participantIdentity:i});let h=setTimeout(()=>{this.pendingResponses.delete(d),a(sk.builtIn("RESPONSE_TIMEOUT"))},s);this.pendingResponses.set(d,{resolve:(t,i)=>{clearTimeout(h),this.pendingAcks.has(d)&&(console.warn("RPC response received before ack",d),this.pendingAcks.delete(d),clearTimeout(u)),i?a(i):e(null!=t?t:"")},participantIdentity:i})}))}()})}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&&void 0!==arguments[1]?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){let t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,i){let n=this.pendingResponses.get(e);n?(n.resolve(t,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,i,n,r){return iK(this,void 0,void 0,function*(){let s=new tS({destinationIdentities:[e],kind:tw.RELIABLE,value:{case:"rpcRequest",value:new t_({id:t,method:i,payload:n,responseTimeoutMs:r,version:1})}});yield this.engine.sendDataPacket(s,tw.RELIABLE)})}handleParticipantDisconnected(e){for(let[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(let[t,{participantIdentity:i,resolve:n}]of this.pendingResponses)i===e&&(n(null,sk.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(e=>"video"===e.mime.split("/")[0].toLowerCase())}updateInfo(e){return!!super.updateInfo(e)&&(e.tracks.forEach(e=>{var t,i;let n=this.trackPublications.get(e.sid);if(n){let r=n.isMuted||null!=(i=null==(t=n.track)?void 0:t.isUpstreamPaused)&&i;r!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),rZ(n)),{mutedOnServer:r})),this.engine.client.sendMuteTrack(e.sid,r))}}),!0)}setActiveAgent(e){var t,i,n,r;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?null==(i=null==(t=this.activeAgentFuture)?void 0:t.resolve)||i.call(t,e):null==(r=null==(n=this.activeAgentFuture)?void 0:n.reject)||r.call(n,"Agent disconnected"),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new r_),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{let n=i.track;n&&(e instanceof MediaStreamTrack?(rq(n)||rV(n))&&n.mediaStreamTrack===e&&(t=i):e===n&&(t=i))}),t}waitForPendingPublicationOfSource(e){return iK(this,void 0,void 0,function*(){let t=Date.now();for(;Date.now()<t+1e4;){let t=Array.from(this.pendingPublishPromises.entries()).find(t=>{let[i]=t;return i.source===e});if(t)return t[1];yield ra(20)}})}}class aa extends ae{constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=e=>{this.setTrack(void 0),this.emit(P.Ended,e)},this.handleVisibilityChange=e=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(e),this.logContext),this.visible=e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug("adaptivestream video dimensions ".concat(e.width,"x").concat(e.height),this.logContext),this.videoDimensionsAdaptiveStream=e,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){let t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);let n=new ii({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new tL({participantSid:"",trackSids:[this.trackSid]})]});this.emit(P.UpdateSubscription,n),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?ae.SubscriptionStatus.Unsubscribed:super.isSubscribed?ae.SubscriptionStatus.Subscribed:ae.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?ae.PermissionStatus.Allowed:ae.PermissionStatus.NotAllowed}get isSubscribed(){return!1!==this.subscribed&&super.isSubscribed}get isDesired(){return!1!==this.subscribed}get isEnabled(){return void 0!==this.requestedDisabled?!this.requestedDisabled:!this.isAdaptiveStream||this.visible}get isLocal(){return!1}setEnabled(e){this.isManualOperationAllowed()&&!e!==this.requestedDisabled&&(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){this.isManualOperationAllowed()&&this.requestedMaxQuality!==e&&(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&((null==(t=this.requestedVideoDimensions)?void 0:t.width)!==e.width||(null==(i=this.requestedVideoDimensions)?void 0:i.height)!==e.height)&&(rG(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate())}setVideoFPS(e){this.isManualOperationAllowed()&&rG(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return null!=(e=this.requestedMaxQuality)?e:R.HIGH}setTrack(e){let t=this.subscriptionStatus,i=this.permissionStatus,n=this.track;n!==e&&(n&&(n.off(P.VideoDimensionsChanged,this.handleVideoDimensionsChange),n.off(P.VisibilityChanged,this.handleVisibilityChange),n.off(P.Ended,this.handleEnded),n.detach(),n.stopMonitor(),this.emit(P.Unsubscribed,n)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(P.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(P.VisibilityChanged,this.handleVisibilityChange),e.on(P.Ended,this.handleEnded),this.emit(P.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){let t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(P.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);let t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?P.Muted:P.Unmuted)}emitSubscriptionUpdateIfChanged(e){let t=this.subscriptionStatus;e!==t&&this.emit(P.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(P.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return rG(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){let e=new ir({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===n9.Kind.Video){let r=this.requestedVideoDimensions;if(void 0!==this.videoDimensionsAdaptiveStream)if(r)r0(this.videoDimensionsAdaptiveStream,r)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),r=this.videoDimensionsAdaptiveStream);else if(void 0!==this.requestedMaxQuality&&this.trackInfo){var t,i,n;let e=(t=this.trackInfo,i=this.requestedMaxQuality,null==(n=t.layers)?void 0:n.find(e=>e.quality===i));e&&r0(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),r=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),r=this.videoDimensionsAdaptiveStream;r?(e.width=Math.ceil(r.width),e.height=Math.ceil(r.height)):void 0!==this.requestedMaxQuality?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:R.HIGH})),e.quality=R.HIGH)}this.emit(P.UpdateSettings,e)}}class ao extends ar{static fromParticipantInfo(e,t,i){return new ao(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,n,r,s,a){let o=arguments.length>7&&void 0!==arguments[7]?arguments[7]:tv.STANDARD;super(t,i||"",n,r,s,a,o),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(P.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),rZ(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(P.UpdateSubscription,e=>{e.participantTracks.forEach(e=>{e.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(e)}),e.on(P.SubscriptionPermissionChanged,t=>{this.emit(w.TrackSubscriptionPermissionChanged,e,t)}),e.on(P.SubscriptionStatusChanged,t=>{this.emit(w.TrackSubscriptionStatusChanged,e,t)}),e.on(P.Subscribed,t=>{this.emit(w.TrackSubscribed,t,e)}),e.on(P.Unsubscribed,t=>{this.emit(w.TrackUnsubscribed,t,e)}),e.on(P.SubscriptionFailed,t=>{this.emit(w.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n9.Source.Microphone;this.volumeMap.set(t,e);let i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:n9.Source.Microphone,t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,n,r,s){let a,o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(t=>{o||e.kind!==t.kind.toString()||(o=t)}),!o){if(0===s){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(w.TrackSubscriptionFailed,t);return}void 0===s&&(s=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,n,r,s-1)},150);return}if("ended"===e.readyState){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),rZ(o))),this.emit(w.TrackSubscriptionFailed,t);return}return(a="video"===e.kind?new s9(e,t,n,r):new s6(e,t,n,this.audioContext,this.audioOutput)).source=o.source,a.isMuted=o.isMuted,a.setMediaStream(i),a.start(),o.setTrack(a),this.volumeMap.has(o.source)&&rH(a)&&rF(a)&&a.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;let t=new Map,i=new Map;return e.tracks.forEach(e=>{var n,r;let s=this.getTrackPublicationBySid(e.sid);if(s)s.updateInfo(e);else{let t=n9.kindFromProto(e.type);if(!t)return;(s=new aa(t,e,null==(n=this.signalClient.connectOptions)?void 0:n.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null==(r=this.loggerOptions)?void 0:r.loggerName})).updateInfo(e),i.set(e.sid,s);let a=Array.from(this.trackPublications.values()).find(e=>e.source===(null==s?void 0:s.source));a&&s.source!==n9.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(s.source),Object.assign(Object.assign({},this.logContext),{oldTrack:rZ(a),newTrack:rZ(s)})),this.addTrackPublication(s)}t.set(e.sid,s)}),this.trackPublications.forEach(e=>{t.has(e.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),rZ(e))),this.unpublishTrack(e.trackSid,!0))}),i.forEach(e=>{this.emit(w.TrackPublished,e)}),!0}unpublishTrack(e,t){let i=this.trackPublications.get(e);if(!i)return;let{track:n}=i;switch(n&&(n.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case n9.Kind.Audio:this.audioTrackPublications.delete(e);break;case n9.Kind.Video:this.videoTrackPublications.delete(e)}t&&this.emit(w.TrackUnpublished,i)}setAudioOutput(e){return iK(this,void 0,void 0,function*(){this.audioOutput=e;let t=[];this.audioTrackPublications.forEach(i=>{var n;rF(i.track)&&rH(i.track)&&t.push(i.track.setSinkId(null!=(n=e.deviceId)?n:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,i=Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}!function(e){e.Disconnected="disconnected",e.Connecting="connecting",e.Connected="connected",e.Reconnecting="reconnecting",e.SignalReconnecting="signalReconnecting"}(B||(B={}));class ac extends iQ.EventEmitter{constructor(e){var t,i,n,r;if(super(),t=this,this.state=B.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=iV,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(e,t,i)=>iK(this,void 0,void 0,function*(){var n;if(!("undefined"!=typeof RTCPeerConnection&&(ro()||rc())))if(rb())throw Error("WebRTC isn't detected, have you called registerGlobals?");else throw 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.");let r=yield this.disconnectLock.lock();if(this.state===B.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),r(),Promise.resolve();if(this.connectFuture)return r(),this.connectFuture.promise;this.setAndEmitConnectionState(B.Connecting),(null==(n=this.regionUrlProvider)?void 0:n.getServerUrl().toString())!==e&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),rk(new URL(e))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new sQ(e,t):this.regionUrlProvider.updateToken(t),this.regionUrlProvider.fetchRegionSettings().then(e=>{var t;null==(t=this.regionUrlProvider)||t.setServerReportedRegions(e)}).catch(e=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:e}))}));let s=(n,a,o)=>iK(this,void 0,void 0,function*(){var c,l;this.abortController&&this.abortController.abort();let d=new AbortController;this.abortController=d,null==r||r();try{yield this.attemptConnection(null!=o?o:e,t,i,d),this.abortController=void 0,n()}catch(e){if(this.regionUrlProvider&&e instanceof nG&&e.reason!==k.Cancelled&&e.reason!==k.NotAllowed){let t=null;try{t=yield this.regionUrlProvider.getNextBestRegionUrl(null==(c=this.abortController)?void 0:c.signal)}catch(e){if(e instanceof nG&&(401===e.status||e.reason===k.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),a(e);return}}!t||(null==(l=this.abortController)?void 0:l.signal.aborted)?(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,rN(e)),a(e)):(this.log.info("Initial connection failed with ConnectionError: ".concat(e.message,". Retrying with another region: ").concat(t),this.logContext),this.recreateEngine(),yield s(n,a,t))}else{let t=tc.UNKNOWN_REASON;e instanceof nG&&(t=rN(e)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,t),a(e)}}}),a=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new r_((e,t)=>{s(e,t,a)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(e,t,i,n,r,s)=>iK(this,void 0,void 0,function*(){var a,o,c;let l=yield i.join(e,t,{autoSubscribe:n.autoSubscribe,adaptiveStream:"object"==typeof r.adaptiveStream||r.adaptiveStream,maxRetries:n.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:n.websocketTimeout},s.signal),d=l.serverInfo;if(d||(d={version:l.serverVersion,region:l.serverRegion}),this.serverInfo=d,this.log.debug("connected to Livekit Server ".concat(Object.entries(d).map(e=>{let[t,i]=e;return"".concat(t,": ").concat(i)}).join(", ")),{room:null==(a=l.room)?void 0:a.name,roomSid:null==(o=l.room)?void 0:o.sid,identity:null==(c=l.participant)?void 0:c.identity}),!d.version)throw new nz("unknown server version");return"0.15.1"===d.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),r.dynacast=!1),l}),this.applyJoinResponse=e=>{let t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(e.sifTrailer)}catch(e){this.log.error(e instanceof Error?e.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:e}))}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(e,t,i,n)=>iK(this,void 0,void 0,function*(){var r,s;this.state===B.Reconnecting||this.isResuming||(null==(r=this.engine)?void 0:r.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),(null==(s=this.regionUrlProvider)?void 0:s.isCloud())&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},sv),i),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{let i=yield this.connectSignal(e,t,this.engine,this.connOptions,this.options,n);this.applyJoinResponse(i),this.setupLocalParticipantEvents(),this.emit(S.SignalConnected)}catch(t){yield this.engine.close(),this.recreateEngine();let e=new nG("could not establish signal connection",k.ServerUnreachable);throw t instanceof Error&&(e.message="".concat(e.message,": ").concat(t.message)),t instanceof nG&&(e.reason=t.reason,e.status=t.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:t})),e}if(n.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new nG("Connection attempt aborted",k.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,n)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}rv()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),rv()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(B.Connected),this.emit(S.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var e=arguments.length,i=Array(e),n=0;n<e;n++)i[n]=arguments[n];return iK(t,[...i],void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0];return function*(){var i,n,r,s;let a=yield e.disconnectLock.lock();try{if(e.state===B.Disconnected)return void e.log.debug("already disconnected",e.logContext);e.log.info("disconnect from room",Object.assign({},e.logContext)),(e.state===B.Connecting||e.state===B.Reconnecting||e.isResuming)&&(e.log.warn("abort connection attempt",e.logContext),null==(i=e.abortController)||i.abort(),null==(r=null==(n=e.connectFuture)?void 0:n.reject)||r.call(n,new nG("Client initiated disconnect",k.Cancelled)),e.connectFuture=void 0),(null==(s=e.engine)?void 0:s.client.isDisconnected)||(yield e.engine.client.sendLeave()),e.engine&&(yield e.engine.close()),e.handleDisconnect(t,tc.CLIENT_INITIATED),e.engine=void 0}finally{a()}}()})},this.onPageLeave=()=>iK(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>iK(this,void 0,void 0,function*(){let e=[],t=n0();if(t&&"iOS"===t.os){let t="livekit-dummy-audio-el",i=document.getElementById(t);if(!i){(i=document.createElement("audio")).id=t,i.autoplay=!0,i.hidden=!0;let e=rx();e.enabled=!0;let n=new MediaStream([e]);i.srcObject=n,document.addEventListener("visibilitychange",()=>{i&&(i.srcObject=document.hidden?null:n,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(i),this.once(S.Disconnected,()=>{null==i||i.remove(),i=null})}e.push(i)}this.remoteParticipants.forEach(t=>{t.audioTrackPublications.forEach(t=>{t.track&&t.track.attachedElements.forEach(t=>{e.push(t)})})});try{yield Promise.all([this.acquireAudioContext(),...e.map(e=>(e.muted=!1,e.play()))]),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}}),this.startVideo=()=>iK(this,void 0,void 0,function*(){let e=[];for(let t of this.remoteParticipants.values())t.videoTrackPublications.forEach(t=>{var i;null==(i=t.track)||i.attachedElements.forEach(t=>{e.includes(t)||e.push(t)})});yield Promise.all(e.map(e=>e.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(e=>{"NotAllowedError"===e.name?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{for(let e of(this.clearConnectionReconcile(),this.isResuming=!1,this.remoteParticipants.values()))this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(B.Reconnecting)&&this.emit(S.Reconnecting)},this.handleSignalRestarted=e=>iK(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(e.serverRegion),Object.assign(Object.assign({},this.logContext),{region:e.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(e);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(e){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:e}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:e.serverRegion}))}catch(e){return}this.setAndEmitConnectionState(B.Connected),this.emit(S.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=e=>{e.forEach(e=>{var t;if(e.identity===this.localParticipant.identity)return void this.localParticipant.updateInfo(e);""===e.identity&&(e.identity=null!=(t=this.sidToIdentity.get(e.sid))?t:"");let i=this.remoteParticipants.get(e.identity);e.state===tf.DISCONNECTED?this.handleParticipantDisconnected(e.identity,i):i=this.getOrCreateParticipant(e.identity,e)})},this.handleActiveSpeakersUpdate=e=>{let t=[],i={};e.forEach(e=>{if(i[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),t.push(this.localParticipant);else{let i=this.getRemoteParticipantBySid(e.sid);i&&(i.audioLevel=e.level,i.setIsSpeaking(!0),t.push(i))}}),i[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(e=>{i[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))}),this.activeSpeakers=t,this.emitWhenConnected(S.ActiveSpeakersChanged,t)},this.handleSpeakersChanged=e=>{let t=new Map;this.activeSpeakers.forEach(e=>{let i=this.remoteParticipants.get(e.identity);i&&i.sid!==e.sid||t.set(e.sid,e)}),e.forEach(e=>{let i=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(i=this.localParticipant),i&&(i.audioLevel=e.level,i.setIsSpeaking(e.active),e.active?t.set(e.sid,i):t.delete(e.sid))});let i=Array.from(t.values());i.sort((e,t)=>t.audioLevel-e.audioLevel),this.activeSpeakers=i,this.emitWhenConnected(S.ActiveSpeakersChanged,i)},this.handleStreamStateUpdate=e=>{e.streamStates.forEach(e=>{let t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;let i=t.getTrackPublicationBySid(e.trackSid);if(!i||!i.track)return;let n=n9.streamStateFromProto(e.state);i.track.setStreamState(n),n!==i.track.streamState&&(t.emit(w.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(S.TrackStreamStateChanged,i,i.track.streamState,t))})},this.handleSubscriptionPermissionUpdate=e=>{let t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;let i=t.getTrackPublicationBySid(e.trackSid);i&&i.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{let t=Array.from(this.remoteParticipants.values()).find(t=>t.trackPublications.has(e.trackSid));if(!t)return;let i=t.getTrackPublicationBySid(e.trackSid);i&&i.setSubscriptionError(e.err)},this.handleDataPacket=e=>{let t=this.remoteParticipants.get(e.participantIdentity);if("user"===e.value.case)this.handleUserPacket(t,e.value.value,e.kind);else if("transcription"===e.value.case)this.handleTranscription(t,e.value.value);else if("sipDtmf"===e.value.case)this.handleSipDtmf(t,e.value.value);else if("chatMessage"===e.value.case)this.handleChatMessage(t,e.value.value);else if("metrics"===e.value.case)this.handleMetrics(e.value.value,t);else if("streamHeader"===e.value.case||"streamChunk"===e.value.case||"streamTrailer"===e.value.case)this.handleDataStream(e);else if("rpcRequest"===e.value.case){let t=e.value.value;this.handleIncomingRpcRequest(e.participantIdentity,t.id,t.method,t.payload,t.responseTimeoutMs,t.version)}},this.handleUserPacket=(e,t,i)=>{this.emit(S.DataReceived,t.payload,e,i,t.topic),null==e||e.emit(w.DataReceived,t.payload,i)},this.handleSipDtmf=(e,t)=>{this.emit(S.SipDTMFReceived,t,e),null==e||e.emit(w.SipDTMFReceived,t)},this.handleTranscription=(e,t)=>{let i=t.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(t.transcribedParticipantIdentity),n=null==i?void 0:i.trackPublications.get(t.trackId),r=function(e,t){return e.segments.map(e=>{var i;let{id:n,text:r,language:s,startTime:a,endTime:o,final:c}=e,l=null!=(i=t.get(n))?i:Date.now(),d=Date.now();return c?t.delete(n):t.set(n,l),{id:n,text:r,startTime:Number.parseInt(a.toString()),endTime:Number.parseInt(o.toString()),final:c,language:s,firstReceivedTime:l,lastReceivedTime:d}})}(t,this.transcriptionReceivedTimes);null==n||n.emit(P.TranscriptionReceived,r),null==i||i.emit(w.TranscriptionReceived,r,n),this.emit(S.TranscriptionReceived,r,i,n)},this.handleChatMessage=(e,t)=>{let i=function(e){let{id:t,timestamp:i,message:n,editTimestamp:r}=e;return{id:t,timestamp:Number.parseInt(i.toString()),editTimestamp:r?Number.parseInt(r.toString()):void 0,message:n}}(t);this.emit(S.ChatMessage,i,e)},this.handleMetrics=(e,t)=>{this.emit(S.MetricsReceived,e,t)},this.handleDataStream=e=>{this.incomingDataStreamManager.handleDataStreamPacket(e)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(S.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=e=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:e})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(S.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(S.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(S.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>iK(this,void 0,void 0,function*(){var e;(null==(e=n0())?void 0:e.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(S.MediaDevicesChanged)}),this.handleRoomUpdate=e=>{let t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected(S.RoomMetadataChanged,e.metadata),(null==t?void 0:t.activeRecording)!==e.activeRecording&&this.emitWhenConnected(S.RecordingStatusChanged,e.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach(e=>{if(e.participantSid===this.localParticipant.sid)return void this.localParticipant.setConnectionQuality(e.quality);let t=this.getRemoteParticipantBySid(e.participantSid);t&&t.setConnectionQuality(e.quality)})},this.onLocalParticipantMetadataChanged=e=>{this.emit(S.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit(S.ParticipantNameChanged,e,this.localParticipant)},this.onLocalAttributesChanged=e=>{this.emit(S.ParticipantAttributesChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(S.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(S.TrackUnmuted,e,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;null==(t=null==e?void 0:e.onPublish)||t.call(e,this)},this.onLocalTrackPublished=e=>iK(this,void 0,void 0,function*(){var t,i,n,r,s,a;null==(t=e.track)||t.on(P.TrackProcessorUpdate,this.onTrackProcessorUpdate),null==(i=e.track)||i.on(P.Restarted,this.onLocalTrackRestarted),null==(s=null==(r=null==(n=e.track)?void 0:n.getProcessor())?void 0:r.onPublish)||s.call(r,this),this.emit(S.LocalTrackPublished,e,this.localParticipant),rq(e.track)&&(yield e.track.checkForSilence())&&this.emit(S.LocalAudioSilenceDetected,e);let o=yield null==(a=e.track)?void 0:a.getDeviceId(!1),c=rY(e.source);c&&o&&o!==this.localParticipant.activeDeviceMap.get(c)&&(this.localParticipant.activeDeviceMap.set(c,o),this.emit(S.ActiveDeviceChanged,c,o))}),this.onLocalTrackUnpublished=e=>{var t,i;null==(t=e.track)||t.off(P.TrackProcessorUpdate,this.onTrackProcessorUpdate),null==(i=e.track)||i.off(P.Restarted,this.onLocalTrackRestarted),this.emit(S.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalTrackRestarted=e=>iK(this,void 0,void 0,function*(){let t=yield e.getDeviceId(!1),i=rY(e.source);i&&t&&t!==this.localParticipant.activeDeviceMap.get(i)&&(this.log.debug("local track restarted, setting ".concat(i," ").concat(t," active"),this.logContext),this.localParticipant.activeDeviceMap.set(i,t),this.emit(S.ActiveDeviceChanged,i,t))}),this.onLocalConnectionQualityChanged=e=>{this.emit(S.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=(e,t)=>{this.emit(S.MediaDevicesError,e,t)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(S.ParticipantPermissionsChanged,e,this.localParticipant)},this.onLocalChatMessageSent=e=>{this.emit(S.ChatMessage,e,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},sf),e),this.log=iq(null!=(i=this.options.loggerName)?i:h.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},sm),null==e?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},sg),null==e?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},sp),null==e?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new s$,this.outgoingDataStreamManager=new s3(this.engine,this.log),this.disconnectLock=new W,this.localParticipant=new as("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",rM(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",rM(this.options.audioCaptureDefaults.deviceId)),(null==(n=this.options.audioOutput)?void 0:n.deviceId)&&this.switchActiveDevice("audiooutput",rM(this.options.audioOutput.deviceId)).catch(e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),rv()){let e=new AbortController;null==(r=navigator.mediaDevices)||r.addEventListener("devicechange",this.handleDeviceChange,{signal:e.signal}),ac.cleanupRegistry&&ac.cleanupRegistry.register(this,()=>{e.abort()})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}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)}setE2EEEnabled(e){return iK(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 r1(this.options.e2ee),this.e2eeManager.on(v.ParticipantEncryptionStatusChanged,(e,t)=>{t.isLocal&&(this.isE2EEEnabled=e),this.emit(S.ParticipantEncryptionStatusChanged,e,t)}),this.e2eeManager.on(v.EncryptionError,e=>this.emit(S.EncryptionError,e)),null==(e=this.e2eeManager)||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:null==(e=this.roomInfo)?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return null!=(t=null==(e=this.roomInfo)?void 0:e.activeRecording)&&t}getSid(){return iK(this,void 0,void 0,function*(){return this.state===B.Disconnected?"":this.roomInfo&&""!==this.roomInfo.sid?this.roomInfo.sid:new Promise((e,t)=>{let i=t=>{""!==t.sid&&(this.engine.off(E.RoomUpdate,i),e(t.sid))};this.engine.on(E.RoomUpdate,i),this.once(S.Disconnected,()=>{this.engine.off(E.RoomUpdate,i),t("Room disconnected before room server id was available")})})})}get name(){var e,t;return null!=(t=null==(e=this.roomInfo)?void 0:e.name)?t:""}get metadata(){var e;return null==(e=this.roomInfo)?void 0:e.metadata}get numParticipants(){var e,t;return null!=(t=null==(e=this.roomInfo)?void 0:e.numParticipants)?t:0}get numPublishers(){var e,t;return null!=(t=null==(e=this.roomInfo)?void 0:e.numPublishers)?t:0}maybeCreateEngine(){(!this.engine||this.engine.isClosed)&&(this.engine=new sz(this.options),this.engine.on(E.ParticipantUpdate,this.handleParticipantUpdates).on(E.RoomUpdate,this.handleRoomUpdate).on(E.SpeakersChanged,this.handleSpeakersChanged).on(E.StreamStateChanged,this.handleStreamStateUpdate).on(E.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(E.SubscriptionError,this.handleSubscriptionError).on(E.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(E.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(E.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(E.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(E.DataPacketReceived,this.handleDataPacket).on(E.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(B.SignalReconnecting)&&this.emit(S.SignalReconnecting)}).on(E.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(B.Connected)&&this.emit(S.Reconnected)}).on(E.SignalResumed,()=>{this.bufferedEvents=[],(this.state===B.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(E.Restarting,this.handleRestarting).on(E.SignalRestarted,this.handleSignalRestarted).on(E.Offline,()=>{this.setAndEmitConnectionState(B.Reconnecting)&&this.emit(S.Reconnecting)}).on(E.DCBufferStatusChanged,(e,t)=>{this.emit(S.DCBufferStatusChanged,e,t)}).on(E.LocalTrackSubscribed,e=>{let t=this.localParticipant.getTrackPublications().find(t=>{let{trackSid:i}=t;return i===e});if(!t)return void this.log.warn("could not find local track subscription for subscribed event",this.logContext);this.localParticipant.emit(w.LocalTrackSubscribed,t),this.emitWhenConnected(S.LocalTrackSubscribed,t,this.localParticipant)}).on(E.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((e,t)=>{this.handleParticipantDisconnected(t,e)}),this.emit(S.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return r3.getInstance().getDevices(e,t)}prepareConnection(e,t){return iK(this,void 0,void 0,function*(){if(this.state===B.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(rk(new URL(e))&&t){this.regionUrlProvider=new sQ(e,t);let i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===B.Disconnected&&(this.regionUrl=i,yield fetch(rA(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(rA(e),{method:"HEAD"})}catch(e){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:e}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return iK(this,void 0,void 0,function*(){let i,n=()=>iK(this,void 0,void 0,function*(){});switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new iO({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new iO({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new iO({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new iO({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=()=>iK(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new iO({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>iK(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new iO({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":i=new iO({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),n=()=>iK(this,void 0,void 0,function*(){let e=this.engine.client.onLeave;e&&e(new io({reason:tc.CLIENT_INITIATED,action:ic.RECONNECT}))});break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw Error("subscriber-bandwidth requires a number as argument");i=new iO({scenario:{case:"subscriberBandwidth",value:rU(t)}});break;case"leave-full-reconnect":i=new iO({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return iK(this,arguments,void 0,function(e,t){var i=this;let n=!(arguments.length>2)||void 0===arguments[2]||arguments[2];return function*(){var r,s,a,o,c,l;let d=!0,u=!1,h=n?{exact:t}:t;if("audioinput"===e){u=0===i.localParticipant.audioTrackPublications.size;let t=null!=(r=i.getActiveDevice(e))?r:i.options.audioCaptureDefaults.deviceId;i.options.audioCaptureDefaults.deviceId=h;let n=Array.from(i.localParticipant.audioTrackPublications.values()).filter(e=>e.source===n9.Source.Microphone);try{d=(yield Promise.all(n.map(e=>{var t;return null==(t=e.audioTrack)?void 0:t.setDeviceId(h)}))).every(e=>!0===e)}catch(e){throw i.options.audioCaptureDefaults.deviceId=t,e}let s=n.some(e=>{var t,i;return null!=(i=null==(t=e.track)?void 0:t.isMuted)&&i});d&&s&&(u=!0)}else if("videoinput"===e){u=0===i.localParticipant.videoTrackPublications.size;let t=null!=(s=i.getActiveDevice(e))?s:i.options.videoCaptureDefaults.deviceId;i.options.videoCaptureDefaults.deviceId=h;let n=Array.from(i.localParticipant.videoTrackPublications.values()).filter(e=>e.source===n9.Source.Camera);try{d=(yield Promise.all(n.map(e=>{var t;return null==(t=e.videoTrack)?void 0:t.setDeviceId(h)}))).every(e=>!0===e)}catch(e){throw i.options.videoCaptureDefaults.deviceId=t,e}let r=n.some(e=>{var t,i;return null!=(i=null==(t=e.track)?void 0:t.isMuted)&&i});d&&r&&(u=!0)}else if("audiooutput"===e){if(u=!0,!rh()&&!i.options.webAudioMix||i.options.webAudioMix&&i.audioContext&&!("setSinkId"in i.audioContext))throw Error("cannot switch audio output, the current browser does not support it");i.options.webAudioMix&&(t=null!=(a=yield r3.getInstance().normalizeDeviceId("audiooutput",t))?a:""),null!=(l=i.options).audioOutput||(l.audioOutput={});let n=null!=(o=i.getActiveDevice(e))?o:i.options.audioOutput.deviceId;i.options.audioOutput.deviceId=t;try{i.options.webAudioMix&&(null==(c=i.audioContext)||c.setSinkId(t)),yield Promise.all(Array.from(i.remoteParticipants.values()).map(e=>e.setAudioOutput({deviceId:t})))}catch(e){throw i.options.audioOutput.deviceId=n,e}}return u&&(i.localParticipant.activeDeviceMap.set(e,t),i.emit(S.ActiveDeviceChanged,e,t)),d}()})}setupLocalParticipantEvents(){this.localParticipant.on(w.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(w.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(w.AttributesChanged,this.onLocalAttributesChanged).on(w.TrackMuted,this.onLocalTrackMuted).on(w.TrackUnmuted,this.onLocalTrackUnmuted).on(w.LocalTrackPublished,this.onLocalTrackPublished).on(w.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(w.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(w.MediaDevicesError,this.onMediaDevicesError).on(w.AudioStreamAcquired,this.startAudio).on(w.ChatMessage,this.onLocalChatMessageSent).on(w.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;null==(e=this.engine)||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,i){let n;if(this.state===B.Connecting||this.state===B.Reconnecting){let n=()=>{this.onTrackAdded(e,t,i),r()},r=()=>{this.off(S.Reconnected,n),this.off(S.Connected,n),this.off(S.Disconnected,r)};this.once(S.Reconnected,n),this.once(S.Connected,n),this.once(S.Disconnected,r);return}if(this.state===B.Disconnected)return void this.log.warn("skipping incoming track after Room disconnected",this.logContext);if("ended"===e.readyState)return void this.log.info("skipping incoming track as it already ended",this.logContext);let r=function(e){let t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(t.id),s=r[0],a=r[1],o=e.id;if(a&&a.startsWith("TR")&&(o=a),s===this.localParticipant.sid)return void this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);let c=Array.from(this.remoteParticipants.values()).find(e=>e.sid===s);if(!c)return void this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);this.options.adaptiveStream&&(n="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{});let l=c.addSubscribedMediaTrack(e,o,t,i,n);(null==l?void 0:l.isEncrypted)&&!this.e2eeManager&&this.emit(S.EncryptionError,Error("Encrypted ".concat(l.source," track received from participant ").concat(c.sid,", but room does not have encryption enabled!")))}handleDisconnect(){var e;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0],i=arguments.length>1?arguments[1]:void 0;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearHandlersAndControllers(),this.state!==B.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{e.unpublishTrack(t.trackSid)})}),this.localParticipant.trackPublications.forEach(e=>{var i,n,r;e.track&&this.localParticipant.unpublishTrack(e.track,t),t?(null==(i=e.track)||i.detach(),null==(n=e.track)||n.stop()):null==(r=e.track)||r.stopMonitor()}),this.localParticipant.off(w.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(w.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(w.AttributesChanged,this.onLocalAttributesChanged).off(w.TrackMuted,this.onLocalTrackMuted).off(w.TrackUnmuted,this.onLocalTrackUnmuted).off(w.LocalTrackPublished,this.onLocalTrackPublished).off(w.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(w.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(w.MediaDevicesError,this.onMediaDevicesError).off(w.AudioStreamAcquired,this.startAudio).off(w.ChatMessage,this.onLocalChatMessageSent).off(w.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&&"boolean"==typeof this.options.webAudioMix&&(this.audioContext.close(),this.audioContext=void 0),rv()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null==(e=navigator.mediaDevices)||e.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(B.Disconnected),this.emit(S.Disconnected,i)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),t.trackPublications.forEach(e=>{t.unpublishTrack(e.trackSid,!0)}),this.emit(S.ParticipantDisconnected,t),t.setDisconnected(),null==(i=this.localParticipant)||i.handleParticipantDisconnected(t.identity))}handleIncomingRpcRequest(e,t,i,n,r,s){return iK(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),1!==s)return void(yield this.engine.publishRpcResponse(e,t,null,sk.builtIn("UNSUPPORTED_VERSION")));let a=this.rpcHandlers.get(i);if(!a)return void(yield this.engine.publishRpcResponse(e,t,null,sk.builtIn("UNSUPPORTED_METHOD")));let o=null,c=null;try{let s=yield a({requestId:t,callerIdentity:e,payload:n,responseTimeout:r});sy(s)>15360?(o=sk.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(i))):c=s}catch(e){e instanceof sk?o=e:(console.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),e),o=sk.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,c,o)})}selectDefaultDevices(){return iK(this,void 0,void 0,function*(){var e,t,i;let n=r3.getInstance().previousDevices,r=yield r3.getInstance().getDevices(void 0,!1),s=n0();if((null==s?void 0:s.name)==="Chrome"&&"iOS"!==s.os)for(let e of r){let t=n.find(t=>t.deviceId===e.deviceId);t&&""!==t.label&&t.kind===e.kind&&t.label!==e.label&&"default"===this.getActiveDevice(e.kind)&&this.emit(S.ActiveDeviceChanged,e.kind,e.deviceId)}for(let s of["audiooutput","audioinput","videoinput"]){let a="audioinput"===s?n9.Source.Microphone:"videoinput"===s?n9.Source.Camera:n9.Source.Unknown,o=this.localParticipant.getTrackPublication(a);if(o&&(null==(e=o.track)?void 0:e.isUserProvided))continue;let c=r.filter(e=>e.kind===s),l=this.getActiveDevice(s);if(l===(null==(t=n.filter(e=>e.kind===s)[0])?void 0:t.deviceId)&&c.length>0&&(null==(i=c[0])?void 0:i.deviceId)!==l){yield this.switchActiveDevice(s,c[0].deviceId);continue}("audioinput"!==s||rg())&&"videoinput"!==s&&(!(c.length>0)||c.find(e=>e.deviceId===this.getActiveDevice(s))||"audiooutput"===s&&rg()||(yield this.switchActiveDevice(s,c[0].deviceId)))}})}acquireAudioContext(){return iK(this,void 0,void 0,function*(){var e,t;if("boolean"!=typeof this.options.webAudioMix&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:this.audioContext&&"closed"!==this.audioContext.state||(this.audioContext=null!=(e=rQ())?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(e=>e.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&"suspended"===this.audioContext.state)try{yield Promise.race([this.audioContext.resume(),ra(200)])}catch(e){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:e}))}let i=(null==(t=this.audioContext)?void 0:t.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(S.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let n;return n=t?ao.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new ao(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&n.setAudioContext(this.audioContext),(null==(i=this.options.audioOutput)?void 0:i.deviceId)&&n.setAudioOutput(this.options.audioOutput).catch(e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext)),n}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){let i=this.remoteParticipants.get(e);return t&&i.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),i}let i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(S.ParticipantConnected,i),i.on(w.TrackPublished,e=>{this.emitWhenConnected(S.TrackPublished,e,i)}).on(w.TrackSubscribed,(e,t)=>{e.kind===n9.Kind.Audio?(e.on(P.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(P.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):e.kind===n9.Kind.Video&&(e.on(P.VideoPlaybackFailed,this.handleVideoPlaybackFailed),e.on(P.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(S.TrackSubscribed,e,t,i)}).on(w.TrackUnpublished,e=>{this.emit(S.TrackUnpublished,e,i)}).on(w.TrackUnsubscribed,(e,t)=>{this.emit(S.TrackUnsubscribed,e,t,i)}).on(w.TrackMuted,e=>{this.emitWhenConnected(S.TrackMuted,e,i)}).on(w.TrackUnmuted,e=>{this.emitWhenConnected(S.TrackUnmuted,e,i)}).on(w.ParticipantMetadataChanged,e=>{this.emitWhenConnected(S.ParticipantMetadataChanged,e,i)}).on(w.ParticipantNameChanged,e=>{this.emitWhenConnected(S.ParticipantNameChanged,e,i)}).on(w.AttributesChanged,e=>{this.emitWhenConnected(S.ParticipantAttributesChanged,e,i)}).on(w.ConnectionQualityChanged,e=>{this.emitWhenConnected(S.ConnectionQualityChanged,e,i)}).on(w.ParticipantPermissionsChanged,e=>{this.emitWhenConnected(S.ParticipantPermissionsChanged,e,i)}).on(w.TrackSubscriptionStatusChanged,(e,t)=>{this.emitWhenConnected(S.TrackSubscriptionStatusChanged,e,t,i)}).on(w.TrackSubscriptionFailed,(e,t)=>{this.emit(S.TrackSubscriptionFailed,e,i,t)}).on(w.TrackSubscriptionPermissionChanged,(e,t)=>{this.emitWhenConnected(S.TrackSubscriptionPermissionChanged,e,t,i)}).on(w.Active,()=>{this.emitWhenConnected(S.ParticipantActive,i),i.kind===tv.AGENT&&this.localParticipant.setActiveAgent(i)}),t&&i.updateInfo(t),i}sendSyncState(){let e=Array.from(this.remoteParticipants.values()).reduce((e,t)=>(e.push(...t.getTrackPublications()),e),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(let t of this.remoteParticipants.values())for(let i of t.videoTrackPublications.values()){var e;i.isSubscribed&&(e=i)&&!e.isLocal&&i.emitTrackUpdate()}}getRemoteParticipantBySid(e){let t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=n4.setInterval(()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?e=0:(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,tc.STATE_MISMATCH)))},4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&n4.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e!==this.state&&(this.state=e,this.emit(S.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,i]=e;this.emit(t,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(this.state===B.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===B.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return iK(this,void 0,void 0,function*(){var t,i;let n=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 th({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:ed.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new tg({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(S.SignalConnected),this.emit(S.Connected),this.setAndEmitConnectionState(B.Connected),n.video){let e=new at(n9.Kind.Video,new tT({source:tr.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:tn.AUDIO,name:"video-dummy"}),new sB(n.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:rD(160*(null!=(t=r.aspectRatios[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(e),this.localParticipant.emit(w.LocalTrackPublished,e)}if(n.audio){let e=new at(n9.Kind.Audio,new tT({source:tr.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:tn.AUDIO}),new sI(n.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:rx(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(w.LocalTrackPublished,e)}for(let e=0;e<r.count-1;e+=1){let t=new tg({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:tf.ACTIVE,tracks:[],joinedAt:ed.parse(Date.now())}),n=this.getOrCreateParticipant(t.identity,t);if(r.video){let s=rD(160*(null!=(i=r.aspectRatios[e%r.aspectRatios.length])?i:1),160,!1,!0),a=new tT({source:tr.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:tn.AUDIO});n.addSubscribedMediaTrack(s,a.sid,new MediaStream([s]),new RTCRtpReceiver),t.tracks=[...t.tracks,a]}if(r.audio){let e=rx(),i=new tT({source:tr.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:tn.AUDIO});n.addSubscribedMediaTrack(e,i.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,i]}n.updateInfo(t)}})}emit(e){for(var t=arguments.length,i=Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(e!==S.ActiveSpeakersChanged&&e!==S.TranscriptionReceived){let t=(function e(t){return t.map(t=>{if(t)return Array.isArray(t)?e(t):"object"==typeof t?"logContext"in t?t.logContext:void 0:t})})(i).filter(e=>void 0!==e);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:t}))}return super.emit(e,...i)}}ac.cleanupRegistry="undefined"!=typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()}),!function(e){e[e.IDLE=0]="IDLE",e[e.RUNNING=1]="RUNNING",e[e.SKIPPED=2]="SKIPPED",e[e.SUCCESS=3]="SUCCESS",e[e.FAILED=4]="FAILED"}(V||(V={}));class al extends iQ.EventEmitter{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.status=V.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new ac(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return iK(this,void 0,void 0,function*(){if(this.status!==V.IDLE)throw Error("check is running already");this.setStatus(V.RUNNING);try{yield this.perform()}catch(e){e instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(e.message):this.appendError(e.message))}return yield this.disconnect(),yield new Promise(e=>setTimeout(e,500)),this.status!==V.SKIPPED&&this.setStatus(this.isSuccess()?V.SUCCESS:V.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>"error"===e.level)}connect(e){return iK(this,void 0,void 0,function*(){return this.room.state===B.Connected||(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions)),this.room})}disconnect(){return iK(this,void 0,void 0,function*(){this.room&&this.room.state!==B.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(V.SKIPPED)}switchProtocol(e){return iK(this,void 0,void 0,function*(){let t=!1,i=!1;if(this.room.on(S.Reconnecting,()=>{t=!0}),this.room.once(S.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(e=>setTimeout(e,1e3)),!t)return;let n=Date.now()+1e4;for(;Date.now()<n;){if(i)return;yield ra(100)}throw 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 null==(e=this.room)?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}iQ.EventEmitter}}]);