livekit-client 2.24.0 → 2.24.1

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 (61) hide show
  1. package/README.md +3 -4
  2. package/dist/core/api/SignalClient.mjs +3 -1
  3. package/dist/core/api/SignalClient.mjs.map +1 -1
  4. package/dist/core/e2ee/E2eeManager.mjs +7 -10
  5. package/dist/core/e2ee/E2eeManager.mjs.map +1 -1
  6. package/dist/core/package.json.mjs +1 -1
  7. package/dist/core/room/rpc/client/RpcClientManager.mjs +18 -0
  8. package/dist/core/room/rpc/client/RpcClientManager.mjs.map +1 -1
  9. package/dist/core/room/rpc/extension.mjs +1 -0
  10. package/dist/core/room/rpc/extension.mjs.map +1 -1
  11. package/dist/core/room/rpc/utils.mjs +2 -0
  12. package/dist/core/room/rpc/utils.mjs.map +1 -1
  13. package/dist/core/room/utils.mjs +4 -1
  14. package/dist/core/room/utils.mjs.map +1 -1
  15. package/dist/core/ts4.2/e2ee/E2eeManager.d.ts +1 -0
  16. package/dist/core/ts4.2/room/rpc/extension.d.ts +3 -3
  17. package/dist/core/ts4.2/room/rpc/utils.d.ts +1 -0
  18. package/dist/core/types/src/e2ee/E2eeManager.d.ts +1 -0
  19. package/dist/core/types/src/room/rpc/extension.d.ts +3 -3
  20. package/dist/core/types/src/room/rpc/utils.d.ts +1 -0
  21. package/dist/livekit-client.e2ee.worker.js +1 -1
  22. package/dist/livekit-client.e2ee.worker.js.map +1 -1
  23. package/dist/livekit-client.e2ee.worker.mjs +6 -3
  24. package/dist/livekit-client.e2ee.worker.mjs.map +1 -1
  25. package/dist/livekit-client.esm.mjs +48 -21
  26. package/dist/livekit-client.esm.mjs.map +1 -1
  27. package/dist/livekit-client.fm.worker.js.map +1 -1
  28. package/dist/livekit-client.fm.worker.mjs.map +1 -1
  29. package/dist/livekit-client.umd.js +1 -1
  30. package/dist/livekit-client.umd.js.map +1 -1
  31. package/dist/src/api/SignalClient.d.ts.map +1 -1
  32. package/dist/src/e2ee/E2eeManager.d.ts +1 -0
  33. package/dist/src/e2ee/E2eeManager.d.ts.map +1 -1
  34. package/dist/src/e2ee/worker/FrameCryptor.d.ts.map +1 -1
  35. package/dist/src/room/rpc/client/RpcClientManager.d.ts +5 -0
  36. package/dist/src/room/rpc/client/RpcClientManager.d.ts.map +1 -1
  37. package/dist/src/room/rpc/extension.d.ts +3 -3
  38. package/dist/src/room/rpc/extension.d.ts.map +1 -1
  39. package/dist/src/room/rpc/legacyExtension.d.ts +1 -1
  40. package/dist/src/room/rpc/utils.d.ts +1 -0
  41. package/dist/src/room/rpc/utils.d.ts.map +1 -1
  42. package/dist/src/room/utils.d.ts.map +1 -1
  43. package/dist/ts4.2/e2ee/E2eeManager.d.ts +1 -0
  44. package/dist/ts4.2/room/rpc/client/RpcClientManager.d.ts +5 -0
  45. package/dist/ts4.2/room/rpc/extension.d.ts +3 -3
  46. package/dist/ts4.2/room/rpc/legacyExtension.d.ts +1 -1
  47. package/dist/ts4.2/room/rpc/utils.d.ts +1 -0
  48. package/package.json +1 -1
  49. package/src/api/SignalClient.test.ts +43 -0
  50. package/src/api/SignalClient.ts +6 -1
  51. package/src/e2ee/E2eeManager.test.ts +86 -2
  52. package/src/e2ee/E2eeManager.ts +11 -9
  53. package/src/e2ee/worker/FrameCryptor.test.ts +26 -0
  54. package/src/e2ee/worker/FrameCryptor.ts +7 -4
  55. package/src/room/Room.test.ts +24 -0
  56. package/src/room/rpc/client/RpcClientManager.test.ts +29 -0
  57. package/src/room/rpc/client/RpcClientManager.ts +17 -0
  58. package/src/room/rpc/extension.ts +4 -1
  59. package/src/room/rpc/utils.ts +2 -0
  60. package/src/room/utils.test.ts +36 -1
  61. package/src/room/utils.ts +11 -1
@@ -1,2 +1,2 @@
1
- !function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";function e(e,t,n,r){return new(n||(n=Promise))((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((r=r.apply(e,t||[])).next())}))}function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}"function"==typeof SuppressedError&&SuppressedError;var n,r={exports:{}};var i,a,o,s,c,d=(n||(n=1,a=r.exports,o=function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"],i={},a=null;function o(e,t){var n=e[t];if("function"==typeof n.bind)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch(t){return function(){return Function.prototype.apply.apply(n,[e,arguments])}}}function s(){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 n=this.getLevel(),i=0;i<r.length;i++){var a=r[i];this[a]=i<n?e:this.methodFactory(a,n,this.name)}if(this.log=this.debug,typeof console===t&&n<this.levels.SILENT)return"No console available for logging"}function d(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function u(r,i,a){return function(r){return"debug"===r&&(r="log"),typeof console!==t&&("trace"===r&&n?s:void 0!==console[r]?o(console,r):void 0!==console.log?o(console,"log"):e)}(r)||d.apply(this,arguments)}function l(e,n){var o,s,d,l=this,h="loglevel";function f(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(e){}if(typeof e===t)try{var n=window.document.cookie,r=encodeURIComponent(h),i=n.indexOf(r+"=");-1!==i&&(e=/^([^;]+)/.exec(n.slice(i+r.length+1))[1])}catch(e){}return void 0===l.levels[e]&&(e=void 0),e}}function p(e){var t=e;if("string"==typeof t&&void 0!==l.levels[t.toUpperCase()]&&(t=l.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=l.levels.SILENT)return t;throw new TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),l.name=e,l.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},l.methodFactory=n||u,l.getLevel=function(){return null!=d?d:null!=s?s:o},l.setLevel=function(e,n){return d=p(e),!1!==n&&function(e){var n=(r[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{return void(window.localStorage[h]=n)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"="+n+";"}catch(e){}}}(d),c.call(l)},l.setDefaultLevel=function(e){s=p(e),f()||l.setLevel(e,!1)},l.resetLevel=function(){d=null,function(){if(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(l)},l.enableAll=function(e){l.setLevel(l.levels.TRACE,e)},l.disableAll=function(e){l.setLevel(l.levels.SILENT,e)},l.rebuild=function(){if(a!==l&&(o=p(a.getLevel())),c.call(l),a===l)for(var e in i)i[e].rebuild()},o=p(a?a.getLevel():"WARN");var y=f();null!=y&&(d=p(y)),c.call(l)}(a=new l).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=i[e];return t||(t=i[e]=new l(e,a.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=h),a},a.getLoggers=function(){return i},a.default=a,a},(i=r).exports?i.exports=o():a.log=o()),r.exports),u=t(d);!function(e){e[e.trace=0]="trace",e[e.debug=1]="debug",e[e.info=2]="info",e[e.warn=3]="warn",e[e.error=4]="error",e[e.silent=5]="silent"}(s||(s={})),function(e){e.Default="livekit",e.Room="livekit-room",e.TokenSource="livekit-token-source",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",e.DataTracks="livekit-data-tracks",e.Region="livekit-region",e.ICE="livekit-ice",e.Stats="livekit-stats"}(c||(c={}));let l=u.getLogger(c.Default);function h(e,t){const n=u.getLogger(e);return n.setDefaultLevel(l.getLevel()),t?function(e,t){const n=n=>(r,i)=>{const a=t(),o=a||i?Object.assign(Object.assign({},a),i):void 0;e[n](r,o)},r=Object.create(e);return r.trace=n("trace"),r.debug=n("debug"),r.info=n("info"),r.warn=n("warn"),r.error=n("error"),r}(n,t):n}Object.values(c).map((e=>u.getLogger(e))),l.setDefaultLevel(s.info);const f=u.getLogger(c.E2EE),p=new Set,y=f.setLevel.bind(f);f.setLevel=(e,t)=>{y(e,t);const n=f.getLevel();p.forEach((e=>e(n)))};var m,g=Object.defineProperty,v=(e,t,n)=>((e,t,n)=>t in e?g(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n);class b{constructor(){v(this,"_locking"),v(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;const t=new Promise((t=>e=()=>{this._locks-=1,t()})),n=this._locking.then((()=>e));return this._locking=this._locking.then((()=>t)),n}}!function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(m||(m={}));const k="AES-GCM",T={key:10,delta:3,audio:1,empty:0},w={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:10,keyringSize:16,keySize:128};function I(e,t){if(!e)throw new Error(t)}function S(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>2147483647||e<-2147483648)throw new Error("invalid int 32: "+e)}function E(e){if("number"!=typeof e)throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>4294967295||e<0)throw new Error("invalid uint 32: "+e)}function N(e){if("number"!=typeof e)throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>34028234663852886e22||e<-34028234663852886e22))throw new Error("invalid float 32: "+e)}const A=Symbol("@bufbuild/protobuf/enum-type");function C(e){const t=e[A];return I(t,"missing enum type on enum object"),t}function L(e,t,n,r){e[A]=U(t,n.map((t=>({no:t.no,name:t.name,localName:e[t.no]}))))}function U(e,t,n){const r=Object.create(null),i=Object.create(null),a=[];for(const e of t){const t=R(e);a.push(t),r[e.name]=t,i[e.no]=t}return{typeName:e,values:a,findName:e=>r[e],findNumber:e=>i[e]}}function O(e,t,n){const r={};for(const e of t){const t=R(e);r[t.localName]=t.no,r[t.no]=t.localName}return L(r,e,t),r}function R(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class D{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const n=this.getType().runtime.bin,r=n.makeReadOptions(t);return n.readMessage(this,r.readerFactory(e),e.byteLength,r),this}fromJson(e,t){const n=this.getType(),r=n.runtime.json,i=r.makeReadOptions(t);return r.readMessage(n,e,i,this),this}fromJsonString(e,t){let n;try{n=JSON.parse(e)}catch(e){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(e instanceof Error?e.message:String(e)))}return this.fromJson(n,t)}toBinary(e){const t=this.getType().runtime.bin,n=t.makeWriteOptions(e),r=n.writerFactory();return t.writeMessage(this,r,n),r.finish()}toJson(e){const t=this.getType().runtime.json,n=t.makeWriteOptions(e);return t.writeMessage(this,n)}toJsonString(e){var t;const n=this.toJson(e);return JSON.stringify(n,null,null!==(t=null==e?void 0:e.prettySpaces)&&void 0!==t?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function F(){let e=0,t=0;for(let n=0;n<28;n+=7){let r=this.buf[this.pos++];if(e|=(127&r)<<n,!(128&r))return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(15&n)<<28,t=(112&n)>>4,!(128&n))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let r=this.buf[this.pos++];if(t|=(127&r)<<n,!(128&r))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function P(e,t,n){for(let r=0;r<28;r+=7){const i=e>>>r,a=!(i>>>7==0&&0==t),o=255&(a?128|i:i);if(n.push(o),!a)return}const r=e>>>28&15|(7&t)<<4,i=!!(t>>3);if(n.push(255&(i?128|r:r)),i){for(let e=3;e<31;e+=7){const r=t>>>e,i=!(r>>>7==0),a=255&(i?128|r:r);if(n.push(a),!i)return}n.push(t>>>31&1)}}const _=4294967296;function x(e){const t="-"===e[0];t&&(e=e.slice(1));const n=1e6;let r=0,i=0;function a(t,a){const o=Number(e.slice(t,a));i*=n,r=r*n+o,r>=_&&(i+=r/_|0,r%=_)}return a(-24,-18),a(-18,-12),a(-12,-6),a(-6),t?j(r,i):B(r,i)}function M(e,t){var n=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t);if(e=n.lo,(t=n.hi)<=2097151)return String(_*t+e);const r=16777215&(e>>>24|t<<8),i=t>>16&65535;let a=(16777215&e)+6777216*r+6710656*i,o=r+8147497*i,s=2*i;const c=1e7;return a>=c&&(o+=Math.floor(a/c),a%=c),o>=c&&(s+=Math.floor(o/c),o%=c),s.toString()+K(o)+K(a)}function B(e,t){return{lo:0|e,hi:0|t}}function j(e,t){return t=~t,e?e=1+~e:t+=1,B(e,t)}const K=e=>{const t=String(e);return"0000000".slice(t.length)+t};function V(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let n=0;n<9;n++)t.push(127&e|128),e>>=7;t.push(1)}}function q(){let e=this.buf[this.pos++],t=127&e;if(!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,!(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let t=5;128&e&&t<10;t++)e=this.buf[this.pos++];if(128&e)throw new Error("invalid varint");return this.assertBounds(),t>>>0}const W=function(){const 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 process||"object"!=typeof process.env||"1"!==process.env.BUF_BIGINT_DISABLE)){const t=BigInt("-9223372036854775808"),n=BigInt("9223372036854775807"),r=BigInt("0"),i=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const r="bigint"==typeof e?e:BigInt(e);if(r>n||r<t)throw new Error("int64 invalid: ".concat(e));return r},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>i||t<r)throw new 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,n)=>(e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigInt64(0,!0)),uDec:(t,n)=>(e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigUint64(0,!0))}}const t=e=>I(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),n=e=>I(/^[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()),n(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),t(e),x(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),n(e),x(e)),dec:(e,t)=>function(e,t){let n=B(e,t);const r=2147483648&n.hi;r&&(n=j(n.lo,n.hi));const i=M(n.lo,n.hi);return r?"-"+i:i}(e,t),uDec:(e,t)=>M(e,t)}}();var G,J,X;function H(e,t,n){if(t===n)return!0;if(e==G.BYTES){if(!(t instanceof Uint8Array&&n instanceof Uint8Array))return!1;if(t.length!==n.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==n[e])return!1;return!0}switch(e){case G.UINT64:case G.FIXED64:case G.INT64:case G.SFIXED64:case G.SINT64:return t==n}return!1}function z(e,t){switch(e){case G.BOOL:return!1;case G.UINT64:case G.FIXED64:case G.INT64:case G.SFIXED64:case G.SINT64:return 0==t?W.zero:"0";case G.DOUBLE:case G.FLOAT:return 0;case G.BYTES:return new Uint8Array(0);case G.STRING:return"";default:return 0}}function Y(e,t){switch(e){case G.BOOL:return!1===t;case G.STRING:return""===t;case G.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}function Q(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function $(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,a,o,s=[],c=!0,d=!1;try{if(a=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){d=!0,i=e}finally{try{if(!c&&null!=n.return&&(o=n.return(),Object(o)!==o))return}finally{if(d)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return Q(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Q(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}!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"}(G||(G={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"}(J||(J={})),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"}(X||(X={}));class Z{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),n=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],n),n+=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 new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(E(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return S(e),V(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){N(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){E(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){S(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return S(e),V(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=W.enc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=W.uEnc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=W.enc(e);return P(t.lo,t.hi,this.buf),this}sint64(e){let t=W.enc(e),n=t.hi>>31;return P(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=W.uEnc(e);return P(t.lo,t.hi,this.buf),this}}class ee{constructor(e,t){this.varint64=F,this.uint32=q,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,n=7&e;if(t<=0||n<0||n>5)throw new Error("illegal tag: field no "+t+" wire type "+n);return[t,n]}skip(e,t){let n=this.pos;switch(e){case X.Varint:for(;128&this.buf[this.pos++];);break;case X.Bit64:this.pos+=4;case X.Bit32:this.pos+=4;break;case X.LengthDelimited:let n=this.uint32();this.pos+=n;break;case X.StartGroup:for(;;){const e=$(this.tag(),2),n=e[0],r=e[1];if(r===X.EndGroup){if(void 0!==t&&n!==t)throw new Error("invalid end group tag");break}this.skip(r,n)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return W.dec(...this.varint64())}uint64(){return W.uDec(...this.varint64())}sint64(){let e=$(this.varint64(),2),t=e[0],n=e[1],r=-(1&t);return t=(t>>>1|(1&n)<<31)^r,n=n>>>1^r,W.dec(t,n)}bool(){let e=$(this.varint64(),2),t=e[0],n=e[1];return 0!==t||0!==n}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return W.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return W.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 te(e){const t=e.field.localName,n=Object.create(null);return n[t]=function(e){const 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 z(t.T,t.L);case"message":const e=t.T,n=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(n):n;case"map":throw"map fields are not allowed to be extensions"}}(e),[n,()=>n[t]]}let ne="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),re=[];for(let e=0;e<ne.length;e++)re[ne[e].charCodeAt(0)]=e;re["-".charCodeAt(0)]=ne.indexOf("+"),re["_".charCodeAt(0)]=ne.indexOf("/");const ie={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let n,r=new Uint8Array(t),i=0,a=0,o=0;for(let t=0;t<e.length;t++){if(n=re[e.charCodeAt(t)],void 0===n)switch(e[t]){case"=":a=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(a){case 0:o=n,a=1;break;case 1:r[i++]=o<<2|(48&n)>>4,o=n,a=2;break;case 2:r[i++]=(15&o)<<4|(60&n)>>2,o=n,a=3;break;case 3:r[i++]=(3&o)<<6|n,a=0}}if(1==a)throw Error("invalid base64 string.");return r.subarray(0,i)},enc(e){let t,n="",r=0,i=0;for(let a=0;a<e.length;a++)switch(t=e[a],r){case 0:n+=ne[t>>2],i=(3&t)<<4,r=1;break;case 1:n+=ne[i|t>>4],i=(15&t)<<2,r=2;break;case 2:n+=ne[i|t>>6],n+=ne[63&t],r=0}return r&&(n+=ne[i],n+="=",1==r&&(n+="=")),n}};function ae(e,t,n){ce(t,e);const r=t.runtime.bin.makeReadOptions(n),i=function(e,t){if(!t.repeated&&("enum"==t.kind||"scalar"==t.kind)){for(let n=e.length-1;n>=0;--n)if(e[n].no==t.no)return[e[n]];return[]}return e.filter((e=>e.no===t.no))}(e.getType().runtime.bin.listUnknownFields(e),t.field),a=$(te(t),2),o=a[0],s=a[1];for(const e of i)t.runtime.bin.readField(o,r.readerFactory(e.data),t.field,e.wireType,r);return s()}function oe(e,t,n,r){ce(t,e);const i=t.runtime.bin.makeReadOptions(r),a=t.runtime.bin.makeWriteOptions(r);if(se(e,t)){const n=e.getType().runtime.bin.listUnknownFields(e).filter((e=>e.no!=t.field.no));e.getType().runtime.bin.discardUnknownFields(e);for(const t of n)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}const o=a.writerFactory();let s=t.field;s.opt||s.repeated||"enum"!=s.kind&&"scalar"!=s.kind||(s=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(s,n,o,a);const c=i.readerFactory(o.finish());for(;c.pos<c.len;){const t=$(c.tag(),2),n=t[0],r=t[1],i=c.skip(r,n);e.getType().runtime.bin.onUnknownField(e,n,r,i)}}function se(e,t){const n=e.getType();return t.extendee.typeName===n.typeName&&!!n.runtime.bin.listUnknownFields(e).find((e=>e.no==t.field.no))}function ce(e,t){I(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function de(e,t){const n=e.localName;if(e.repeated)return t[n].length>0;if(e.oneof)return t[e.oneof.localName].case===n;switch(e.kind){case"enum":case"scalar":return e.opt||e.req?void 0!==t[n]:"enum"==e.kind?t[n]!==e.T.values[0].no:!Y(e.T,t[n]);case"message":return void 0!==t[n];case"map":return Object.keys(t[n]).length>0}}function ue(e,t){const n=e.localName,r=!e.opt&&!e.req;if(e.repeated)t[n]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case"map":t[n]={};break;case"enum":t[n]=r?e.T.values[0].no:void 0;break;case"scalar":t[n]=r?z(e.T,e.L):void 0;break;case"message":t[n]=void 0}}function le(e,t){if(null===e||"object"!=typeof e)return!1;if(!Object.getOwnPropertyNames(D.prototype).every((t=>t in e&&"function"==typeof e[t])))return!1;const n=e.getType();return null!==n&&"function"==typeof n&&"typeName"in n&&"string"==typeof n.typeName&&(void 0===t||n.typeName==t.typeName)}function he(e,t){return le(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}G.DOUBLE,G.FLOAT,G.INT64,G.UINT64,G.INT32,G.UINT32,G.BOOL,G.STRING,G.BYTES;const fe={ignoreUnknownFields:!1},pe={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function ye(e){return e?Object.assign(Object.assign({},fe),e):fe}function me(e){return e?Object.assign(Object.assign({},pe),e):pe}const ge=Symbol(),ve=Symbol();function be(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 ke(e,t,n,r,i){let a=n.localName;if(n.repeated){if(I("map"!=n.kind),null===t)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(be(t)));const o=e[a];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(be(e)));switch(n.kind){case"message":o.push(n.T.fromJson(e,r));break;case"enum":const t=Ie(n.T,e,r.ignoreUnknownFields,!0);t!==ve&&o.push(t);break;case"scalar":try{o.push(we(n.T,e,n.L,!0))}catch(t){let r="cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(be(e));throw t instanceof Error&&t.message.length>0&&(r+=": ".concat(t.message)),new Error(r)}}}}else if("map"==n.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw new Error("cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(be(t)));const s=e[a];for(const e of Object.entries(t)){var o=$(e,2);const a=o[0],c=o[1];if(null===c)throw new Error("cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: map value null"));let d;try{d=Te(n.K,a)}catch(e){let r="cannot decode map key for field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(be(t));throw e instanceof Error&&e.message.length>0&&(r+=": ".concat(e.message)),new Error(r)}switch(n.V.kind){case"message":s[d]=n.V.T.fromJson(c,r);break;case"enum":const e=Ie(n.V.T,c,r.ignoreUnknownFields,!0);e!==ve&&(s[d]=e);break;case"scalar":try{s[d]=we(n.V.T,c,J.BIGINT,!0)}catch(e){let r="cannot decode map value for field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(be(t));throw e instanceof Error&&e.message.length>0&&(r+=": ".concat(e.message)),new Error(r)}}}}else switch(n.oneof&&(e=e[n.oneof.localName]={case:a},a="value"),n.kind){case"message":const o=n.T;if(null===t&&"google.protobuf.Value"!=o.typeName)return;let s=e[a];le(s)?s.fromJson(t,r):(e[a]=s=o.fromJson(t,r),o.fieldWrapper&&!n.oneof&&(e[a]=o.fieldWrapper.unwrapField(s)));break;case"enum":const c=Ie(n.T,t,r.ignoreUnknownFields,!1);switch(c){case ge:ue(n,e);break;case ve:break;default:e[a]=c}break;case"scalar":try{const r=we(n.T,t,n.L,!1);if(r===ge)ue(n,e);else e[a]=r}catch(e){let r="cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(be(t));throw e instanceof Error&&e.message.length>0&&(r+=": ".concat(e.message)),new Error(r)}}}function Te(e,t){if(e===G.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return we(e,t,J.BIGINT,!0).toString()}function we(e,t,n,r){if(null===t)return r?z(e,n):ge;switch(e){case G.DOUBLE:case G.FLOAT:if("NaN"===t)return Number.NaN;if("Infinity"===t)return Number.POSITIVE_INFINITY;if("-Infinity"===t)return Number.NEGATIVE_INFINITY;if(""===t)break;if("string"==typeof t&&t.trim().length!==t.length)break;if("string"!=typeof t&&"number"!=typeof t)break;const r=Number(t);if(Number.isNaN(r))break;if(!Number.isFinite(r))break;return e==G.FLOAT&&N(r),r;case G.INT32:case G.FIXED32:case G.SFIXED32:case G.SINT32:case G.UINT32:let i;if("number"==typeof t?i=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(i=Number(t)),void 0===i)break;return e==G.UINT32||e==G.FIXED32?E(i):S(i),i;case G.INT64:case G.SFIXED64:case G.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const a=W.parse(t);return n?a.toString():a;case G.FIXED64:case G.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const o=W.uParse(t);return n?o.toString():o;case G.BOOL:if("boolean"!=typeof t)break;return t;case G.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw new Error("invalid UTF8")}return t;case G.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return ie.dec(t)}throw new Error}function Ie(e,t,n,r){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:r?e.values[0].no:ge;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const r=e.findName(t);if(void 0!==r)return r.no;if(n)return ve}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(be(t)))}function Se(e){return!(!e.repeated&&"map"!=e.kind)||!e.oneof&&("message"!=e.kind&&(!e.opt&&!e.req))}function Ee(e,t,n){if("map"==e.kind){I("object"==typeof t&&null!=t);const o={},s=Object.entries(t);switch(e.V.kind){case"scalar":for(const t of s){var r=$(t,2);const n=r[0],i=r[1];o[n.toString()]=Ae(e.V.T,i)}break;case"message":for(const e of s){var i=$(e,2);const t=i[0],r=i[1];o[t.toString()]=r.toJson(n)}break;case"enum":const t=e.V.T;for(const e of s){var a=$(e,2);const r=a[0],i=a[1];o[r.toString()]=Ne(t,i,n.enumAsInteger)}}return n.emitDefaultValues||s.length>0?o:void 0}if(e.repeated){I(Array.isArray(t));const r=[];switch(e.kind){case"scalar":for(let n=0;n<t.length;n++)r.push(Ae(e.T,t[n]));break;case"enum":for(let i=0;i<t.length;i++)r.push(Ne(e.T,t[i],n.enumAsInteger));break;case"message":for(let e=0;e<t.length;e++)r.push(t[e].toJson(n))}return n.emitDefaultValues||r.length>0?r:void 0}switch(e.kind){case"scalar":return Ae(e.T,t);case"enum":return Ne(e.T,t,n.enumAsInteger);case"message":return he(e.T,t).toJson(n)}}function Ne(e,t,n){var r;if(I("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(n)return t;const i=e.findNumber(t);return null!==(r=null==i?void 0:i.name)&&void 0!==r?r:t}function Ae(e,t){switch(e){case G.INT32:case G.SFIXED32:case G.SINT32:case G.FIXED32:case G.UINT32:return I("number"==typeof t),t;case G.FLOAT:case G.DOUBLE:return I("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case G.STRING:return I("string"==typeof t),t;case G.BOOL:return I("boolean"==typeof t),t;case G.UINT64:case G.FIXED64:case G.INT64:case G.SFIXED64:case G.SINT64:return I("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case G.BYTES:return I(t instanceof Uint8Array),ie.enc(t)}}const Ce=Symbol("@bufbuild/protobuf/unknown-fields"),Le={readUnknownFields:!0,readerFactory:e=>new ee(e)},Ue={writeUnknownFields:!0,writerFactory:()=>new Z};function Oe(e){return e?Object.assign(Object.assign({},Le),e):Le}function Re(e){return e?Object.assign(Object.assign({},Ue),e):Ue}function De(e,t,n,r,i){let a=n.repeated,o=n.localName;switch(n.oneof&&((e=e[n.oneof.localName]).case!=o&&delete e.value,e.case=o,o="value"),n.kind){case"scalar":case"enum":const s="enum"==n.kind?G.INT32:n.T;let c=_e;if("scalar"==n.kind&&n.L>0&&(c=Pe),a){let n=e[o];if(r==X.LengthDelimited&&s!=G.STRING&&s!=G.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)n.push(c(t,s))}else n.push(c(t,s))}else e[o]=c(t,s);break;case"message":const d=n.T;a?e[o].push(Fe(t,new d,i,n)):le(e[o])?Fe(t,e[o],i,n):(e[o]=Fe(t,new d,i,n),!d.fieldWrapper||n.oneof||n.repeated||(e[o]=d.fieldWrapper.unwrapField(e[o])));break;case"map":let u=function(e,t,n){const r=t.uint32(),i=t.pos+r;let a,o;for(;t.pos<i;){switch($(t.tag(),1)[0]){case 1:a=_e(t,e.K);break;case 2:switch(e.V.kind){case"scalar":o=_e(t,e.V.T);break;case"enum":o=t.int32();break;case"message":o=Fe(t,new e.V.T,n,void 0)}}}void 0===a&&(a=z(e.K,J.BIGINT));"string"!=typeof a&&"number"!=typeof a&&(a=a.toString());if(void 0===o)switch(e.V.kind){case"scalar":o=z(e.V.T,J.BIGINT);break;case"enum":o=e.V.T.values[0].no;break;case"message":o=new e.V.T}return[a,o]}(n,t,i),l=$(u,2),h=l[0],f=l[1];e[o][h]=f}}function Fe(e,t,n,r){const i=t.getType().runtime.bin,a=null==r?void 0:r.delimited;return i.readMessage(t,e,a?r.no:e.uint32(),n,a),t}function Pe(e,t){const n=_e(e,t);return"bigint"==typeof n?n.toString():n}function _e(e,t){switch(t){case G.STRING:return e.string();case G.BOOL:return e.bool();case G.DOUBLE:return e.double();case G.FLOAT:return e.float();case G.INT32:return e.int32();case G.INT64:return e.int64();case G.UINT64:return e.uint64();case G.FIXED64:return e.fixed64();case G.BYTES:return e.bytes();case G.FIXED32:return e.fixed32();case G.SFIXED32:return e.sfixed32();case G.SFIXED64:return e.sfixed64();case G.SINT64:return e.sint64();case G.UINT32:return e.uint32();case G.SINT32:return e.sint32()}}function xe(e,t,n,r){I(void 0!==t);const i=e.repeated;switch(e.kind){case"scalar":case"enum":let o="enum"==e.kind?G.INT32:e.T;if(i)if(I(Array.isArray(t)),e.packed)!function(e,t,n,r){if(!r.length)return;e.tag(n,X.LengthDelimited).fork();let i=$(Ke(t),2)[1];for(let t=0;t<r.length;t++)e[i](r[t]);e.join()}(n,o,e.no,t);else for(const r of t)je(n,o,e.no,r);else je(n,o,e.no,t);break;case"message":if(i){I(Array.isArray(t));for(const i of t)Be(n,r,e,i)}else Be(n,r,e,t);break;case"map":I("object"==typeof t&&null!=t);for(const i of Object.entries(t)){var a=$(i,2);Me(n,r,e,a[0],a[1])}}}function Me(e,t,n,r,i){e.tag(n.no,X.LengthDelimited),e.fork();let a=r;switch(n.K){case G.INT32:case G.FIXED32:case G.UINT32:case G.SFIXED32:case G.SINT32:a=Number.parseInt(r);break;case G.BOOL:I("true"==r||"false"==r),a="true"==r}switch(je(e,n.K,1,a),n.V.kind){case"scalar":je(e,n.V.T,2,i);break;case"enum":je(e,G.INT32,2,i);break;case"message":I(void 0!==i),e.tag(2,X.LengthDelimited).bytes(i.toBinary(t))}e.join()}function Be(e,t,n,r){const i=he(n.T,r);n.delimited?e.tag(n.no,X.StartGroup).raw(i.toBinary(t)).tag(n.no,X.EndGroup):e.tag(n.no,X.LengthDelimited).bytes(i.toBinary(t))}function je(e,t,n,r){I(void 0!==r);let i=$(Ke(t),2),a=i[0],o=i[1];e.tag(n,a)[o](r)}function Ke(e){let t=X.Varint;switch(e){case G.BYTES:case G.STRING:t=X.LengthDelimited;break;case G.DOUBLE:case G.FIXED64:case G.SFIXED64:t=X.Bit64;break;case G.FIXED32:case G.SFIXED32:case G.FLOAT:t=X.Bit32}return[t,G[e].toLowerCase()]}function Ve(e){if(void 0===e)return e;if(le(e))return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function qe(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class We{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const e={};for(const t of this.list())e[t.jsonName]=e[t.name]=t;this.jsonNames=e}return this.jsonNames[e]}find(e){if(!this.numbers){const e={};for(const 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){this.members=[];const e=this.members;let t;for(const n of this.list())n.oneof?n.oneof!==t&&(t=n.oneof,e.push(t)):e.push(n)}return this.members}}function Ge(e,t){const n=Xe(e);return t?n:$e(Qe(n))}const Je=Xe;function Xe(e){let t=!1;const n=[];for(let r=0;r<e.length;r++){let i=e.charAt(r);switch(i){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n.push(i),t=!1;break;default:t&&(t=!1,i=i.toUpperCase()),n.push(i)}}return n.join("")}const He=new Set(["constructor","toString","toJSON","valueOf"]),ze=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Ye=e=>"".concat(e,"$"),Qe=e=>ze.has(e)?Ye(e):e,$e=e=>He.has(e)?Ye(e):e;class Ze{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=Ge(e,!1)}addField(e){I(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]}}const et=(tt=e=>new We(e,(e=>function(e){var t,n,r,i,a,o;const s=[];let c;for(const d of"function"==typeof e?e():e){const e=d;if(e.localName=Ge(d.name,void 0!==d.oneof),e.jsonName=null!==(t=d.jsonName)&&void 0!==t?t:Je(d.name),e.repeated=null!==(n=d.repeated)&&void 0!==n&&n,"scalar"==d.kind&&(e.L=null!==(r=d.L)&&void 0!==r?r:J.BIGINT),e.delimited=null!==(i=d.delimited)&&void 0!==i&&i,e.req=null!==(a=d.req)&&void 0!==a&&a,e.opt=null!==(o=d.opt)&&void 0!==o&&o,void 0===d.packed&&(e.packed="enum"==d.kind||"scalar"==d.kind&&d.T!=G.BYTES&&d.T!=G.STRING),void 0!==d.oneof){const t="string"==typeof d.oneof?d.oneof:d.oneof.name;c&&c.name==t||(c=new Ze(t)),e.oneof=c,c.addField(e)}s.push(e)}return s}(e))),nt=e=>{for(const t of e.getType().fields.byMember()){if(t.opt)continue;const n=t.localName,r=e;if(t.repeated)r[n]=[];else switch(t.kind){case"oneof":r[n]={case:void 0};break;case"enum":r[n]=0;break;case"map":r[n]={};break;case"scalar":r[n]=z(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:ye,makeWriteOptions:me,readMessage(e,t,n,r){if(null==t||Array.isArray(t)||"object"!=typeof t)throw new Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(be(t)));r=null!=r?r:new e;const i=new Map,a=n.typeRegistry;for(const s of Object.entries(t)){var o=$(s,2);const t=o[0],c=o[1],d=e.fields.findJsonName(t);if(d){if(d.oneof){if(null===c&&"scalar"==d.kind)continue;const n=i.get(d.oneof);if(void 0!==n)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(d.oneof.name,'" present: "').concat(n,'", "').concat(t,'"'));i.set(d.oneof,t)}ke(r,c,d,n,e)}else{let i=!1;if((null==a?void 0:a.findExtension)&&t.startsWith("[")&&t.endsWith("]")){const o=a.findExtension(t.substring(1,t.length-1));if(o&&o.extendee.typeName==e.typeName){i=!0;const e=$(te(o),2),t=e[0],a=e[1];ke(t,c,o.field,n,o),oe(r,o,a(),n)}}if(!i&&!n.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(t,'" is unknown'))}}return r},writeMessage(e,t){const n=e.getType(),r={};let i;try{for(i of n.fields.byNumber()){if(!de(i,e)){if(i.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!Se(i))continue}const n=Ee(i,i.oneof?e[i.oneof.localName].value:e[i.localName],t);void 0!==n&&(r[t.useProtoFieldName?i.name:i.jsonName]=n)}const a=t.typeRegistry;if(null==a?void 0:a.findExtensionFor)for(const i of n.runtime.bin.listUnknownFields(e)){const o=a.findExtensionFor(n.typeName,i.no);if(o&&se(e,o)){const n=ae(e,o,t),i=Ee(o.field,n,t);void 0!==i&&(r[o.field.jsonName]=i)}}}catch(e){const t=i?"cannot encode field ".concat(n.typeName,".").concat(i.name," to JSON"):"cannot encode message ".concat(n.typeName," to JSON"),r=e instanceof Error?e.message:String(e);throw new Error(t+(r.length>0?": ".concat(r):""))}return r},readScalar:(e,t,n)=>we(e,t,null!=n?n:J.BIGINT,!0),writeScalar(e,t,n){if(void 0!==t)return n||Y(e,t)?Ae(e,t):void 0},debug:be},bin:{makeReadOptions:Oe,makeWriteOptions:Re,listUnknownFields(e){var t;return null!==(t=e[Ce])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[Ce]},writeUnknownFields(e,t){const n=e[Ce];if(n)for(const e of n)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,n,r){const i=e;Array.isArray(i[Ce])||(i[Ce]=[]),i[Ce].push({no:t,wireType:n,data:r})},readMessage(e,t,n,r,i){const a=e.getType(),o=i?t.len:t.pos+n;let s,c;for(;t.pos<o;){var d=$(t.tag(),2);if(s=d[0],c=d[1],!0===i&&c==X.EndGroup)break;const n=a.fields.find(s);if(n)De(e,t,n,c,r);else{const n=t.skip(c,s);r.readUnknownFields&&this.onUnknownField(e,s,c,n)}}if(i&&(c!=X.EndGroup||s!==n))throw new Error("invalid end group tag")},readField:De,writeMessage(e,t,n){const r=e.getType();for(const i of r.fields.byNumber())if(de(i,e))xe(i,i.oneof?e[i.oneof.localName].value:e[i.localName],t,n);else if(i.req)throw new Error("cannot encode field ".concat(r.typeName,".").concat(i.name," to binary: required field not set"));return n.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,n,r){void 0!==t&&xe(e,t,n,r)}},util:Object.assign(Object.assign({},{setEnumType:L,initPartial(e,t){if(void 0===e)return;const n=t.getType();for(const i of n.fields.byMember()){const n=i.localName,a=t,o=e;if(null!=o[n])switch(i.kind){case"oneof":const e=o[n].case;if(void 0===e)continue;const t=i.findField(e);let s=o[n].value;t&&"message"==t.kind&&!le(s,t.T)?s=new t.T(s):t&&"scalar"===t.kind&&t.T===G.BYTES&&(s=qe(s)),a[n]={case:e,value:s};break;case"scalar":case"enum":let c=o[n];i.T===G.BYTES&&(c=i.repeated?c.map(qe):qe(c)),a[n]=c;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===G.BYTES)for(const e of Object.entries(o[n])){var r=$(e,2);const t=r[0],i=r[1];a[n][t]=qe(i)}else Object.assign(a[n],o[n]);break;case"message":const e=i.V.T;for(const t of Object.keys(o[n])){let r=o[n][t];e.fieldWrapper||(r=new e(r)),a[n][t]=r}}break;case"message":const d=i.T;if(i.repeated)a[n]=o[n].map((e=>le(e,d)?e:new d(e)));else{const e=o[n];d.fieldWrapper?"google.protobuf.BytesValue"===d.typeName?a[n]=qe(e):a[n]=e:a[n]=le(e,d)?e:new d(e)}}}},equals:(e,t,n)=>t===n||!(!t||!n)&&e.fields.byMember().every((e=>{const r=t[e.localName],i=n[e.localName];if(e.repeated){if(r.length!==i.length)return!1;switch(e.kind){case"message":return r.every(((t,n)=>e.T.equals(t,i[n])));case"scalar":return r.every(((t,n)=>H(e.T,t,i[n])));case"enum":return r.every(((e,t)=>H(G.INT32,e,i[t])))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":let t=r,n=i;return e.T.fieldWrapper&&(void 0===t||le(t)||(t=e.T.fieldWrapper.wrapField(t)),void 0===n||le(n)||(n=e.T.fieldWrapper.wrapField(n))),e.T.equals(t,n);case"enum":return H(G.INT32,r,i);case"scalar":return H(e.T,r,i);case"oneof":if(r.case!==i.case)return!1;const a=e.findField(r.case);if(void 0===a)return!0;switch(a.kind){case"message":return a.T.equals(r.value,i.value);case"enum":return H(G.INT32,r.value,i.value);case"scalar":return H(a.T,r.value,i.value)}throw new Error("oneof cannot contain ".concat(a.kind));case"map":const o=Object.keys(r).concat(Object.keys(i));switch(e.V.kind){case"message":const t=e.V.T;return o.every((e=>t.equals(r[e],i[e])));case"enum":return o.every((e=>H(G.INT32,r[e],i[e])));case"scalar":const n=e.V.T;return o.every((e=>H(n,r[e],i[e])))}}})),clone(e){const t=e.getType(),n=new t,r=n;for(const n of t.fields.byMember()){const t=e[n.localName];let a;if(n.repeated)a=t.map(Ve);else if("map"==n.kind){a=r[n.localName];for(const e of Object.entries(t)){var i=$(e,2);const t=i[0],n=i[1];a[t]=Ve(n)}}else a="oneof"==n.kind?n.findField(t.case)?{case:t.case,value:Ve(t.value)}:{case:void 0}:Ve(t);r[n.localName]=a}for(const n of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(r,n.no,n.wireType,n.data);return n}}),{newFieldList:tt,initFields:nt}),makeMessageType(e,t,n){return function(e,t,n,r){var i;const a=null!==(i=null==r?void 0:r.localName)&&void 0!==i?i:t.substring(t.lastIndexOf(".")+1),o={[a]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[a];return Object.setPrototypeOf(o.prototype,new D),Object.assign(o,{runtime:e,typeName:t,fields:e.util.newFieldList(n),fromBinary:(e,t)=>(new o).fromBinary(e,t),fromJson:(e,t)=>(new o).fromJson(e,t),fromJsonString:(e,t)=>(new o).fromJsonString(e,t),equals:(t,n)=>e.util.equals(o,t,n)}),o}(this,e,t,n)},makeEnum:O,makeEnumType:U,getEnumType:C,makeExtension(e,t,n){return function(e,t,n,r){let i;return{typeName:t,extendee:n,get field(){if(!i){const n="function"==typeof r?r():r;n.name=t.split(".").pop(),n.jsonName="[".concat(t,"]"),i=e.util.newFieldList([n]).list()[0]}return i},runtime:e}}(this,e,t,n)}});var tt,nt;const rt=et.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),it=et.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"}]),at=et.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]);class ot extends Error{constructor(e,t,n){super(t||"an error has occurred"),this.name="LiveKitError",this.code=e,void 0!==(null==n?void 0:n.cause)&&(this.cause=null==n?void 0:n.cause)}}var st,ct,dt,ut,lt,ht,ft,pt,yt,mt;!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",e[e.WebSocket=6]="WebSocket",e[e.ServiceNotFound=7]="ServiceNotFound"}(st||(st={})),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",e[e.EncryptionTypeMismatch=8]="EncryptionTypeMismatch",e[e.HeaderTooLarge=9]="HeaderTooLarge",e[e.PayloadTooLarge=10]="PayloadTooLarge"}(ct||(ct={})),function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"}(dt||(dt={})),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}}(dt||(dt={})),function(e){e[e.InvalidKey=0]="InvalidKey",e[e.MissingKey=1]="MissingKey",e[e.InternalError=2]="InternalError"}(ut||(ut={}));class gt extends ot{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ut.InternalError,n=arguments.length>2?arguments[2]:void 0;super(40,e),this.reason=t,this.participantIdentity=n}}!function(e){e.SetKey="setKey",e.RatchetRequest="ratchetRequest",e.KeyRatcheted="keyRatcheted"}(lt||(lt={})),function(e){e.KeyRatcheted="keyRatcheted"}(ht||(ht={})),function(e){e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError"}(ft||(ft={})),function(e){e.Error="cryptorError"}(pt||(pt={}));class vt extends(mt=Promise){constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}}yt=vt,vt.resolve=e=>Reflect.get(mt,"resolve",yt).call(yt,e);const bt=/version\/(\d+(\.?_?\d+)+)/i;let kt;function Tt(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if("undefined"==typeof navigator)return;const n=navigator.userAgent.toLowerCase();if(void 0===kt||t){const e=wt.find((e=>e.test.test(n)));kt=null==e?void 0:e.describe(n)}return kt}const wt=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:It(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:St(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:It(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:St(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:It(bt,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:St(e)})}];function It(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;const r=t.match(e);return r&&r.length>=n&&r[n]||""}function St(e){return e.includes("mac os")?It(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}var Et,Nt={exports:{}};var At,Ct,Lt,Ut,Ot=function(){if(Et)return Nt.exports;Et=1;var e,t="object"==typeof Reflect?Reflect:null,n=t&&"function"==typeof t.apply?t.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};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 r=Number.isNaN||function(e){return e!=e};function i(){i.init.call(this)}Nt.exports=i,Nt.exports.once=function(e,t){return new Promise((function(n,r){function i(n){e.removeListener(t,a),r(n)}function a(){"function"==typeof e.removeListener&&e.removeListener("error",i),n([].slice.call(arguments))}p(e,t,a,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&p(e,"error",t,n)}(e,i,{once:!0})}))},i.EventEmitter=i,i.prototype._events=void 0,i.prototype._eventsCount=0,i.prototype._maxListeners=void 0;var a=10;function o(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function s(e){return void 0===e._maxListeners?i.defaultMaxListeners:e._maxListeners}function c(e,t,n,r){var i,a,c,d;if(o(n),void 0===(a=e._events)?(a=e._events=Object.create(null),e._eventsCount=0):(void 0!==a.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),a=e._events),c=a[t]),void 0===c)c=a[t]=n,++e._eventsCount;else if("function"==typeof c?c=a[t]=r?[n,c]:[c,n]:r?c.unshift(n):c.push(n),(i=s(e))>0&&c.length>i&&!c.warned){c.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=c.length,d=u,console&&console.warn&&console.warn(d)}return e}function d(){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 u(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=d.bind(r);return i.listener=n,r.wrapFn=i,i}function l(e,t,n){var r=e._events;if(void 0===r)return[];var i=r[t];return void 0===i?[]:"function"==typeof i?n?[i.listener||i]:[i]:n?function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(i):f(i,i.length)}function h(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function f(e,t){for(var n=new Array(t),r=0;r<t;++r)n[r]=e[r];return n}function p(e,t,n,r){if("function"==typeof e.on)r.once?e.once(t,n):e.on(t,n);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function i(a){r.once&&e.removeEventListener(t,i),n(a)}))}}return Object.defineProperty(i,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(e){if("number"!=typeof e||e<0||r(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");a=e}}),i.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},i.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||r(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},i.prototype.getMaxListeners=function(){return s(this)},i.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var i="error"===e,a=this._events;if(void 0!==a)i=i&&void 0===a.error;else if(!i)return!1;if(i){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var s=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw s.context=o,s}var c=a[e];if(void 0===c)return!1;if("function"==typeof c)n(c,this,t);else{var d=c.length,u=f(c,d);for(r=0;r<d;++r)n(u[r],this,t)}return!0},i.prototype.addListener=function(e,t){return c(this,e,t,!1)},i.prototype.on=i.prototype.addListener,i.prototype.prependListener=function(e,t){return c(this,e,t,!0)},i.prototype.once=function(e,t){return o(t),this.on(e,u(this,e,t)),this},i.prototype.prependOnceListener=function(e,t){return o(t),this.prependListener(e,u(this,e,t)),this},i.prototype.removeListener=function(e,t){var n,r,i,a,s;if(o(t),void 0===(r=this._events))return this;if(void 0===(n=r[e]))return this;if(n===t||n.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(i=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){s=n[a].listener,i=a;break}if(i<0)return this;0===i?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,i),1===n.length&&(r[e]=n[0]),void 0!==r.removeListener&&this.emit("removeListener",e,s||t)}return this},i.prototype.off=i.prototype.removeListener,i.prototype.removeAllListeners=function(e){var t,n,r;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var i,a=Object.keys(n);for(r=0;r<a.length;++r)"removeListener"!==(i=a[r])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(void 0!==t)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this},i.prototype.listeners=function(e){return l(this,e,!0)},i.prototype.rawListeners=function(e){return l(this,e,!1)},i.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},i.prototype.listenerCount=h,i.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},Nt.exports}();function Rt(e){const t={};for(const r of Object.entries(e)){var n=$(r,2);const e=n[0],i=n[1];void 0!==i&&(t[e]=i)}return t}function Dt(e,t){return e&&t?"".concat(e,"x").concat(t):void 0}function Ft(e){return Math.round(1e4*e)/1e4}function Pt(e){const t=e.jitterBufferDelay,n=e.jitterBufferEmittedCount;return void 0!==t&&n?Ft(t/n):void 0}function _t(e,t){if(void 0!==e.playoutDelay)return Ft(e.playoutDelay);const n=null==t?void 0:t.totalPlayoutDelay,r=null==t?void 0:t.totalSamplesCount;return void 0!==n&&r?Ft(n/r):void 0}!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",e.DataTrackPublished="dataTrackPublished",e.DataTrackUnpublished="dataTrackUnpublished",e.LocalDataTrackPublished="localDataTrackPublished",e.LocalDataTrackUnpublished="localDataTrackUnpublished"}(At||(At={})),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"}(Ct||(Ct={})),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.PublishDataTrackResponse="publishDataTrackResponse",e.UnPublishDataTrackResponse="unPublishDataTrackResponse",e.DataTrackSubscriberHandles="dataTrackSubscriberHandles",e.DataTrackPacketReceived="dataTrackPacketReceived",e.Joined="joined",e.TokenRefreshed="tokenRefreshed",e.ServerRegionsReported="serverRegionsReported",e.RequestSubscribedCodecRefresh="requestSubscribedCodecRefresh"}(Lt||(Lt={})),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"}(Ut||(Ut={}));const xt=["vp8","h264","vp9","av1","h265"];var Mt,Bt;function jt(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?jt(e.track):{})}}!function(e){e[e.PREFER_REGRESSION=0]="PREFER_REGRESSION",e[e.SIMULCAST=1]="SIMULCAST",e[e.REGRESSION=2]="REGRESSION"}(Mt||(Mt={})),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}}(Bt||(Bt={}));const Kt=[];var Vt;!function(e){e[e.LOW=0]="LOW",e[e.MEDIUM=1]="MEDIUM",e[e.HIGH=2]="HIGH"}(Vt||(Vt={}));class qt extends Ot.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState!==e&&this.log.debug("stream state changed: ".concat(this._streamState," -> ").concat(e)),this._streamState=e}constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var r;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=qt.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.finalStatsLogged=!1,this.log=l,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.loggerContextCb=n.loggerContextCb,this.log=h(null!==(r=n.loggerName)&&void 0!==r?r:c.Track,(()=>this.logContext)),this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=qt.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),jt(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===qt.Kind.Video&&(t="video"),0===this.attachedElements.length&&this.kind===qt.Kind.Video&&this.addAppVisibilityListener(),e||("audio"===t&&(Kt.forEach((t=>{null!==t.parentElement||e||(e=t)})),e&&Kt.splice(Kt.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),function(e,t){let n,r;n=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream;r="audio"===e.kind?n.getAudioTracks():n.getVideoTracks();r.includes(e)||(r.forEach((e=>{n.removeTrack(e)})),n.addTrack(e));Gt()&&t instanceof HTMLVideoElement||(t.autoplay=!0);t.muted=0===n.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0);t.srcObject!==n&&(t.srcObject=n,(Gt()||function(){var e;return"Firefox"===(null===(e=Tt())||void 0===e?void 0:e.name)}())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=n,t.play().catch((()=>{}))}),0))}(this.mediaStreamTrack,e);const n=e.srcObject.getTracks(),r=n.some((e=>"audio"===e.kind));return e.play().then((()=>{this.emit(r?Ut.AudioPlaybackStarted:Ut.VideoPlaybackStarted)})).catch((t=>{"NotAllowedError"===t.name?this.emit(r?Ut.AudioPlaybackFailed:Ut.VideoPlaybackFailed,t):"AbortError"===t.name?this.log.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):this.log.warn("could not playback ".concat(r?"audio":"video"),{error:t}),r&&e&&n.some((e=>"video"===e.kind))&&"NotAllowedError"===t.name&&(e.muted=!0,e.play().catch((()=>{})))})),this.emit(Ut.ElementAttached,e),e}detach(e){try{if(e){Wt(this.mediaStreamTrack,e);const t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(Ut.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach((e=>{Wt(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(Ut.ElementDetached,e)})),this.attachedElements=[],t}finally{0===this.attachedElements.length&&this.removeAppVisibilityListener()}}stop(){this.log.debug("stopping track"),this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),void 0!==this.timeSyncHandle&&(cancelAnimationFrame(this.timeSyncHandle),this.timeSyncHandle=void 0),this.logFinalStats()}logFinalStats(){this.finalStatsLogged||(this.finalStatsLogged=!0,this.getRTCStatsReport().then((e=>{e&&this.log.info("final track stats",function(e){var t,n;const r=new Map,i=[],a=[],o=[];let s;e.forEach((e=>r.set(e.id,e)));const c=e=>{var t;return e.codecId?null===(t=r.get(e.codecId))||void 0===t?void 0:t.mimeType:void 0},d=(e,t)=>e[t]?r.get(e[t]):void 0;e.forEach((e=>{switch(e.type){case"inbound-rtp":{const t=d(e,"playoutId");a.push(Rt({kind:e.kind,ssrc:e.ssrc,mid:e.mid,trackId:e.trackIdentifier,codec:c(e),decoder:e.decoderImplementation,resolution:Dt(e.frameWidth,e.frameHeight),fps:e.framesPerSecond,bytesReceived:e.bytesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,packetsDiscarded:e.packetsDiscarded,framesReceived:e.framesReceived,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,keyFramesDecoded:e.keyFramesDecoded,freezeCount:e.freezeCount,totalFreezesDuration:e.totalFreezesDuration,pauseCount:e.pauseCount,nackCount:e.nackCount,pliCount:e.pliCount,firCount:e.firCount,jitter:e.jitter,jitterBuffer:Pt(e),playoutDelay:_t(e,t),audioLevel:e.audioLevel,totalSamplesReceived:e.totalSamplesReceived,concealedSamples:e.concealedSamples}));break}case"outbound-rtp":{const t=d(e,"remoteId"),n=d(e,"mediaSourceId");o.push(Rt({kind:e.kind,ssrc:e.ssrc,mid:e.mid,rid:e.rid,trackId:null==n?void 0:n.trackIdentifier,active:e.active,codec:c(e),encoder:e.encoderImplementation,resolution:Dt(e.frameWidth,e.frameHeight),fps:e.framesPerSecond,captureResolution:Dt(null==n?void 0:n.width,null==n?void 0:n.height),captureFps:null==n?void 0:n.framesPerSecond,audioLevel:null==n?void 0:n.audioLevel,targetBitrate:e.targetBitrate,bytesSent:e.bytesSent,packetsSent:e.packetsSent,retransmittedPacketsSent:e.retransmittedPacketsSent,framesEncoded:e.framesEncoded,keyFramesEncoded:e.keyFramesEncoded,limitedBy:"none"===e.qualityLimitationReason?void 0:e.qualityLimitationReason,nackCount:e.nackCount,pliCount:e.pliCount,firCount:e.firCount,remotePacketsLost:null==t?void 0:t.packetsLost,remoteFractionLost:null==t?void 0:t.fractionLost,remoteJitter:null==t?void 0:t.jitter,remoteRoundTripTime:null==t?void 0:t.roundTripTime}));break}case"transport":s=e;break;case"candidate-pair":i.push(e)}}));const u=null==s?void 0:s.selectedCandidatePairId,l=null!==(n=null!==(t=u?r.get(u):void 0)&&void 0!==t?t:i.find((e=>e.selected)))&&void 0!==n?n:i.find((e=>e.nominated)),h=(null==l?void 0:l.localCandidateId)?r.get(l.localCandidateId):void 0,f=(null==l?void 0:l.remoteCandidateId)?r.get(l.remoteCandidateId):void 0,p=Rt({ice:null==s?void 0:s.iceState,dtls:null==s?void 0:s.dtlsState,route:h&&f?"".concat(h.candidateType,"/").concat(h.protocol," -> ").concat(f.candidateType):void 0,network:null==h?void 0:h.networkType,currentRoundTripTime:null==l?void 0:l.currentRoundTripTime,availableOutgoingBitrate:null==l?void 0:l.availableOutgoingBitrate,availableIncomingBitrate:null==l?void 0:l.availableIncomingBitrate,bytesSent:null==l?void 0:l.bytesSent,bytesReceived:null==l?void 0:l.bytesReceived,candidatePairChanges:null==s?void 0:s.selectedCandidatePairChanges});return{connection:Object.keys(p).length>0?p:void 0,outbound:o.length>0?o:void 0,inbound:a.length>0?a:void 0}}(e))})).catch((e=>this.log.debug("could not collect final track stats",{error:e}))))}updateLoggerOptions(e){e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb),e.loggerName&&(this.log=h(e.loggerName,(()=>this.logContext)))}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Kt.forEach((e=>{e.parentElement||(t=!1)})),t&&Kt.push(e)}}handleAppVisibilityChanged(){return e(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==qt.Kind.Video||setTimeout((()=>this.attachedElements.forEach((e=>e.play().catch((()=>{}))))),0)}))}addAppVisibilityListener(){Jt()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Jt()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Wt(e,t){if(t.srcObject instanceof MediaStream){const n=t.srcObject;"audio"===e.kind&&function(){const e=Tt();return!!e&&"Chrome"===e.name&&"iOS"!==e.os}()&&(t.srcObject=null),n.removeTrack(e),n.getTracks().length>0?t.srcObject=n:t.srcObject=null}}function Gt(){var e;return"Safari"===(null===(e=Tt())||void 0===e?void 0:e.name)}function Jt(){return"undefined"!=typeof document}function Xt(e,t){return e instanceof Error?e.name&&e.message?"".concat(e.name,": ").concat(e.message):e.name:"Encountered unknown ".concat(t," error: ").concat(String(e))}function Ht(e){return"type"in e}function zt(e,t){const n=(new TextEncoder).encode(t);switch(e){case"HKDF":return{name:"HKDF",salt:n,hash:"SHA-256",info:new ArrayBuffer(128)};case"PBKDF2":return{name:"PBKDF2",salt:n,hash:"SHA-256",iterations:1e5};default:throw new Error("algorithm ".concat(e," is currently unsupported"))}}function Yt(t,n){return e(this,void 0,void 0,(function*(){const e=zt(t.algorithm.name,n.ratchetSalt),r=yield crypto.subtle.deriveKey(e,t,{name:k,length:n.keySize},!1,["encrypt","decrypt"]);return{material:t,encryptionKey:r}}))}function Qt(e){const t=[];for(var n=e.length,r=0;r<e.length;)n-r>=3&&!e[r]&&!e[r+1]&&3==e[r+2]?(t.push(e[r++]),t.push(e[r++]),r++):t.push(e[r++]);return new Uint8Array(t)}!function(e){let t,n,r;!function(e){e.Audio="audio",e.Video="video",e.Unknown="unknown"}(t=e.Kind||(e.Kind={})),function(e){e.Camera="camera",e.Microphone="microphone",e.ScreenShare="screen_share",e.ScreenShareAudio="screen_share_audio",e.Unknown="unknown"}(n=e.Source||(e.Source={})),function(e){e.Active="active",e.Paused="paused",e.Unknown="unknown"}(r=e.StreamState||(e.StreamState={})),e.kindToProto=function(e){switch(e){case t.Audio:return rt.AUDIO;case t.Video:return rt.VIDEO;default:return rt.DATA}},e.kindFromProto=function(e){switch(e){case rt.AUDIO:return t.Audio;case rt.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case n.Camera:return it.CAMERA;case n.Microphone:return it.MICROPHONE;case n.ScreenShare:return it.SCREEN_SHARE;case n.ScreenShareAudio:return it.SCREEN_SHARE_AUDIO;default:return it.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case it.CAMERA:return n.Camera;case it.MICROPHONE:return n.Microphone;case it.SCREEN_SHARE:return n.ScreenShare;case it.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}},e.streamStateFromProto=function(e){switch(e){case at.ACTIVE:return r.Active;case at.PAUSED:return r.Paused;default:return r.Unknown}}}(qt||(qt={}));function $t(e){const t=[];let n=0;for(let r=0;r<e.length;++r){const i=e[r];i<=3&&n>=2&&(t.push(r),n=0),n=0===i?n+1:0}if(0===t.length)return e;const r=new Uint8Array(e.length+t.length);let i=0;for(let n=0;n<t.length;++n)r.set(e.subarray(i,t[n]),i+n),r[t[n]+n]=3,i=t[n];return r.set(e.subarray(i),i+t.length),r}class Zt{static makeIV(e){const t=new ArrayBuffer(12),n=new DataView(t),r=crypto.getRandomValues(new Uint32Array(1));return n.setUint32(0,r[0]),n.setUint32(4,e),n.setUint32(8,e-Zt.sendCount%65535),Zt.sendCount++,t}static encrypt(t,n){return e(this,void 0,void 0,(function*(){const e=Zt.makeIV(performance.now()),r=yield n.getKeySet();if(!r)throw new Error("No key set found");const i=yield crypto.subtle.encrypt({name:k,iv:e},r.encryptionKey,new Uint8Array(t));return{payload:new Uint8Array(i),iv:new Uint8Array(e),keyIndex:n.getCurrentKeyIndex()}}))}static decrypt(t,n,r){return e(this,arguments,void 0,(function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,i=arguments.length>4?arguments[4]:void 0,a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{ratchetCount:0};return function*(){var o;const s=yield n.getKeySet(r);if(!s)throw new Error("No key set found");try{const n=yield crypto.subtle.decrypt({name:k,iv:t},null!==(o=a.encryptionKey)&&void 0!==o?o:s.encryptionKey,new Uint8Array(e));return{payload:new Uint8Array(n)}}catch(o){if(n.keyProviderOptions.ratchetWindowSize>0){if(a.ratchetCount<n.keyProviderOptions.ratchetWindowSize){let o,c;f.debug("DataCryptor: ratcheting key attempt ".concat(a.ratchetCount," of ").concat(n.keyProviderOptions.ratchetWindowSize,", for data packet")),(null!=i?i:s)===n.getKeySet(r)&&(c=yield n.ratchetKey(r,!1),o=yield Yt(c.cryptoKey,n.keyProviderOptions));const d=yield Zt.decrypt(e,t,n,r,null!=i?i:s,{ratchetCount:a.ratchetCount+1,encryptionKey:null==o?void 0:o.encryptionKey});return d&&o&&(null!=i?i:s)===n.getKeySet(r)&&(n.setKeySet(o,r,c),n.setCurrentKeyIndex(r)),d}throw f.warn("DataCryptor: maximum ratchet attempts exceeded"),new gt("DataCryptor: valid key missing for participant ".concat(n.participantIdentity),ut.InvalidKey,n.participantIdentity)}throw new gt("DataCryptor: Decryption failed: ".concat(Xt(o,"decryption")),ut.InvalidKey,n.participantIdentity)}}()}))}}Zt.sendCount=0;class en{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:6e4,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:5;this.throttleMs=e,this.windowMs=t,this.maxPerWindow=n,this.lastAt=new Map,this.counts=new Map}reset(){this.lastAt.clear(),this.counts.clear()}countFor(e){var t;return null!==(t=this.counts.get(e))&&void 0!==t?t:0}shouldEmit(e,t){var n,r;const i=Date.now(),a=null!==(n=this.lastAt.get(e))&&void 0!==n?n:0,o=null!==(r=this.counts.get(e))&&void 0!==r?r:0;return i-a>this.windowMs?(this.counts.set(e,0),this.lastAt.set(e,i),!0):!(i-a<this.throttleMs)&&(o>=this.maxPerWindow?(o===this.maxPerWindow&&(null==t||t(),this.counts.set(e,o+1)),!1):(this.lastAt.set(e,i),this.counts.set(e,o+1),!0))}}function tn(e){return!(!(null==e?void 0:e.timestamp)&&!(null==e?void 0:e.frameId))}const nn=Uint8Array.from(["L".charCodeAt(0),"K".charCodeAt(0),"T".charCodeAt(0),"S".charCodeAt(0)]);function rn(e,t,n){const r=t!==BigInt(0),i=0!==n;if(!r&&!i)return e;const a=(r?10:0)+(i?6:0)+5,o=new Uint8Array(e.length+a);let s=0;return o.set(e,s),s+=e.length,r&&(o[s++]=254,o[s++]=247,function(e,t,n){const r=Number(n>>BigInt(32)&BigInt(4294967295)),i=Number(n&BigInt(4294967295));e[t]=r>>>24^255,e[t+1]=r>>>16&255^255,e[t+2]=r>>>8&255^255,e[t+3]=255&r^255,e[t+4]=i>>>24^255,e[t+5]=i>>>16&255^255,e[t+6]=i>>>8&255^255,e[t+7]=255&i^255}(o,s,t),s+=8),i&&(o[s++]=253,o[s++]=251,function(e,t,n){for(let r=3;r>=0;r-=1)e[t+(3-r)]=n>>8*r&255^255}(o,s,n),s+=4),o[s++]=255^a,o.set(nn,s),o}function an(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);if(t.length<5)return{data:t};if(!function(e,t){for(let n=0;n<nn.length;n+=1)if(e[t+n]!==nn[n])return!1;return!0}(t,t.length-nn.length))return{data:t};const n=255^t[t.length-5];if(n<5||n>t.length)return{data:t};const r=t.length-n,i=t.length-5,a=t.subarray(0,r);let o=r,s=!1;const c={userTimestamp:BigInt(0),frameId:0};for(;o+2<=i;){const e=255^t[o++],n=255^t[o++];if(o+n>i)break;if(1===e&&8===n)c.userTimestamp=on(t,o),s=!0;else if(2===e&&4===n)c.frameId=sn(t,o,n),s=!0;else if(3===e){const e=new Uint8Array(n);for(let r=0;r<n;r+=1)e[r]=255^t[o+r];c.userData=e,s=!0}o+=n}return s?{data:a,metadata:c}:{data:t}}function on(e,t){const n=BigInt(((255^e[t])<<24|(255^e[t+1])<<16|(255^e[t+2])<<8|255^e[t+3])>>>0),r=BigInt(((255^e[t+4])<<24|(255^e[t+5])<<16|(255^e[t+6])<<8|255^e[t+7])>>>0);return n<<BigInt(32)|r}function sn(e,t,n){let r=0;for(let i=0;i<n;i+=1)r=r<<8|255^e[t+i];return r>>>0}function cn(e){try{const t=e.getMetadata();if("number"==typeof t.synchronizationSource)return t.synchronizationSource}catch(e){}return 0}var dn,un;function ln(e){return 31&e}function hn(e){return e>>1&63}function fn(e){return e===dn.SLICE_IDR||e===dn.SLICE_NON_IDR}function pn(e){return e===un.TRAIL_N||e===un.TRAIL_R||e===un.TSA_N||e===un.TSA_R||e===un.STSA_N||e===un.STSA_R||e===un.RADL_N||e===un.RADL_R||e===un.RASL_N||e===un.RASL_R||e===un.BLA_W_LP||e===un.BLA_W_RADL||e===un.BLA_N_LP||e===un.IDR_W_RADL||e===un.IDR_N_LP||e===un.CRA_NUT}function yn(e){if(ln(e[0])!==dn.SLICE_IDR)return null;const t=Qt(e.subarray(1,17)),n=8*t.length;let r=0;const i=()=>t[r>>3]>>7-(7&r++)&1,a=()=>{let e=0;for(;0===i()&&r<n;)e++;let t=1;for(let n=0;n<e;n++)t=2*t+i();return t-1};a(),a();const o=a();return r<=n?o:null}function mn(e,t){const n=function(e){const t=[];let n=0,r=0,i=e.length-3;for(;r<i;){for(;r<i&&!(r<i-1&&0===e[r]&&0===e[r+1]&&0===e[r+2]&&1===e[r+3])&&(0!==e[r]||0!==e[r+1]||1!==e[r+2]);)r++;r>=i&&(r=e.length);let a=r;for(;a>n&&0===e[a-1];)a--;if(0===n){if(a!==n)throw TypeError("byte stream contains leading data")}else t.push(n);let o=3;r<e.length-3&&0===e[r]&&0===e[r+1]&&0===e[r+2]&&1===e[r+3]&&(o=4),n=r+=o}return t}(e);let r=function(e,t){for(const n of t)if(fn(ln(e[n])))return"h264";for(const n of t)if(pn(hn(e[n])))return"h265";return"unknown"}(e,n);if("unknown"===r&&(r=null!=t?t:"unknown"),"unknown"===r)return{unencryptedBytes:0,detectedCodec:r,requiresNALUProcessing:!1};const i=function(e,t,n){for(const r of t)if("h265"===n){if(pn(hn(e[r])))return r+2}else if(fn(ln(e[r])))return r+2;return null}(e,n,r);if(null===i)throw new TypeError("Could not find NALU");return{unencryptedBytes:i,detectedCodec:r,requiresNALUProcessing:!0}}!function(e){e[e.SLICE_NON_IDR=1]="SLICE_NON_IDR",e[e.SLICE_PARTITION_A=2]="SLICE_PARTITION_A",e[e.SLICE_PARTITION_B=3]="SLICE_PARTITION_B",e[e.SLICE_PARTITION_C=4]="SLICE_PARTITION_C",e[e.SLICE_IDR=5]="SLICE_IDR",e[e.SEI=6]="SEI",e[e.SPS=7]="SPS",e[e.PPS=8]="PPS",e[e.AUD=9]="AUD",e[e.END_SEQ=10]="END_SEQ",e[e.END_STREAM=11]="END_STREAM",e[e.FILLER_DATA=12]="FILLER_DATA",e[e.SPS_EXT=13]="SPS_EXT",e[e.PREFIX_NALU=14]="PREFIX_NALU",e[e.SUBSET_SPS=15]="SUBSET_SPS",e[e.DPS=16]="DPS",e[e.SLICE_AUX=19]="SLICE_AUX",e[e.SLICE_EXT=20]="SLICE_EXT",e[e.SLICE_LAYER_EXT=21]="SLICE_LAYER_EXT"}(dn||(dn={})),function(e){e[e.TRAIL_N=0]="TRAIL_N",e[e.TRAIL_R=1]="TRAIL_R",e[e.TSA_N=2]="TSA_N",e[e.TSA_R=3]="TSA_R",e[e.STSA_N=4]="STSA_N",e[e.STSA_R=5]="STSA_R",e[e.RADL_N=6]="RADL_N",e[e.RADL_R=7]="RADL_R",e[e.RASL_N=8]="RASL_N",e[e.RASL_R=9]="RASL_R",e[e.BLA_W_LP=16]="BLA_W_LP",e[e.BLA_W_RADL=17]="BLA_W_RADL",e[e.BLA_N_LP=18]="BLA_N_LP",e[e.IDR_W_RADL=19]="IDR_W_RADL",e[e.IDR_N_LP=20]="IDR_N_LP",e[e.CRA_NUT=21]="CRA_NUT",e[e.VPS_NUT=32]="VPS_NUT",e[e.SPS_NUT=33]="SPS_NUT",e[e.PPS_NUT=34]="PPS_NUT",e[e.AUD_NUT=35]="AUD_NUT",e[e.EOS_NUT=36]="EOS_NUT",e[e.EOB_NUT=37]="EOB_NUT",e[e.FD_NUT=38]="FD_NUT",e[e.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",e[e.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"}(un||(un={}));const gn="ef0161653d8b2b23aad46624b420af1d03ce48950e9fc85718028f91b50f9219",vn="f0a0e09647d891d6d50aa898bce7108090375d0d55e50a2bb21147afee558e44",bn="61d9665eed71b6d424ae9539330a3bdd5cb386d4d781c808219a6e36750493a7",kn="faffc26b68a2fc09096fa20f3351e706398b6f838a7500c8063472c2e476e90d",Tn="aad8d31fc56b2802ca500e58c2fb9d0b29ad71bb7cb52cd6530251eade188988";function wn(t){return e(this,void 0,void 0,(function*(){const n=yield function(t){return e(this,void 0,void 0,(function*(){const e=yield crypto.subtle.digest("SHA-256",t),n=new Uint8Array(e);return Array.from(n).map((e=>e.toString(16).padStart(2,"0"))).join("")}))}(t);switch(n){case gn:return"vp8";case vn:case bn:case kn:return"h264";case Tn:return"opus";default:return null}}))}let In;class Sn extends Ot.EventEmitter{encodeFunction(e,t){throw Error("not implemented for subclass")}decodeFunction(e,t){throw Error("not implemented for subclass")}}class En extends Sn{constructor(e){var t;super(),this.hasFrameMetadata=!1,this.frameMetadataFrameId=0,this.errorLimiter=new en,this.UNDECRYPTED_TRACK_GRACE_MS=2e3,this.loggedNALUFallbacks=new Set,this.sendCounts=new Map,this.keys=e.keys,this.participantIdentity=e.participantIdentity,this.rtpMap=new Map,this.keyProviderOptions=e.keyProviderOptions,this.sifTrailer=null!==(t=e.sifTrailer)&&void 0!==t?t:Uint8Array.from([])}get logContext(){return{participant:this.participantIdentity,mediaTrackId:this.trackId,fallbackCodec:this.videoCodec}}setParticipant(e,t){f.debug("setting new participant on cryptor",Object.assign(Object.assign({},this.logContext),{newParticipant:e,hadPreviousParticipant:!!this.participantIdentity})),this.participantIdentity&&this.participantIdentity!==e&&(f.warn("cryptor has already a participant set, cleaning up before switching",{oldParticipant:this.participantIdentity,newParticipant:e,trackId:this.trackId}),this.unsetParticipant()),this.participantIdentity=e,this.keys=t}unsetParticipant(){f.debug("unsetting participant",this.logContext),clearTimeout(this.undecryptedTrackTimeout),this.undecryptedTrackTimeout=void 0,this.participantIdentity=void 0,this.encrypted=void 0,this.errorLimiter.reset()}setEncrypted(e){this.encrypted=e}isEnabled(){return this.participantIdentity?this.encrypted:void 0}getParticipantIdentity(){return this.participantIdentity}getTrackId(){return this.trackId}setTrackId(e){this.trackId!==e&&(f.debug("re-pointing cryptor at new trackId",Object.assign(Object.assign({},this.logContext),{newTrackId:e})),this.trackId=e)}hasActiveTransform(){return!!this.currentTransform}scheduleUndecryptedTrackWatchdog(e){clearTimeout(this.undecryptedTrackTimeout),this.undecryptedTrackTimeout=void 0,"decode"===e&&(this.undecryptedTrackTimeout=setTimeout((()=>{!this.currentTransform&&this.isEnabled()&&(f.warn("encrypted track has no active decrypt transform",this.logContext),this.emitThrottledError(new gt("no active decrypt transform for encrypted track ".concat(this.trackId),ut.InternalError,this.participantIdentity)))}),this.UNDECRYPTED_TRACK_GRACE_MS))}ensureTransform(){if(this.currentTransform)return!0;if(!this.retainedStreams||void 0===this.trackId)return f.warn("no streams retained, cannot re-establish transform",this.logContext),!1;const e=this.retainedStreams,t=e.readable,n=e.writable,r=e.operation;return f.info("re-establishing transform",Object.assign(Object.assign({},this.logContext),{operation:r})),this.setupTransform(r,t,n,this.trackId)}setVideoCodec(e){this.videoCodec=e}setRtpMap(e){this.rtpMap=e}setHasFrameMetadata(e){this.hasFrameMetadata=e}setFrameMetadataOpts(e){this.frameMetadataOpts=e,this.frameMetadataFrameId=0}setupTransform(e,t,n,r,i,a){var o;i&&(f.info("setting codec on cryptor to",{codec:i}),this.videoCodec=i),"encode"===e&&this.setFrameMetadataOpts(a),f.debug("Setting up frame cryptor transform",Object.assign({operation:e,passedTrackId:r,codec:i,hasCurrentTransform:!!this.currentTransform},this.logContext)),this.trackId=r,this.retainedStreams={readable:t,writable:n,operation:e},clearTimeout(this.undecryptedTrackTimeout);const s=Symbol("transform"),c="encode"===e?this.encodeFunction:this.decodeFunction,d=new TransformStream({transform:c.bind(this)});this.currentTransform={readable:t,writable:n,transformer:d,trackId:r,symbol:s};try{t.pipeThrough(d).pipeTo(n).catch((e=>{e instanceof TypeError&&"Destination stream closed"===e.message?f.debug("destination stream closed"):(f.warn("transform error",Object.assign({error:e},this.logContext)),this.emit(pt.Error,e instanceof gt?e:new gt(e.message,void 0,this.participantIdentity)))})).finally((()=>{var t;(null===(t=this.currentTransform)||void 0===t?void 0:t.symbol)===s&&(f.debug("transform completed",Object.assign(Object.assign({},this.logContext),{trackId:r})),this.currentTransform=void 0),this.scheduleUndecryptedTrackWatchdog(e)}))}catch(e){return(null===(o=this.currentTransform)||void 0===o?void 0:o.symbol)===s&&(this.currentTransform=void 0),f.error("failed to set up transform",Object.assign({error:e},this.logContext)),this.emit(pt.Error,e instanceof gt?e:new gt(e.message,ut.InternalError,this.participantIdentity)),!1}return!0}setSifTrailer(e){f.debug("setting SIF trailer",Object.assign(Object.assign({},this.logContext),{trailer:e})),this.sifTrailer=e}emitThrottledError(e){const t="".concat(this.participantIdentity,"-").concat(e.reason,"-decrypt");if(!this.errorLimiter.shouldEmit(t,(()=>{f.warn("Suppressing further decryption errors for ".concat(this.participantIdentity),Object.assign(Object.assign({},this.logContext),{errorKey:t}))})))return;const n=this.errorLimiter.countFor(t);n>1&&f.debug("Decryption error (".concat(n," occurrences in window)"),Object.assign(Object.assign({},this.logContext),{reason:ut[e.reason]})),this.emit(pt.Error,e)}encodeFunction(t,n){return e(this,void 0,void 0,(function*(){var e,r;if(0===t.data.byteLength)return n.enqueue(t);if(void 0===In)return void this.emitThrottledError(new gt("encryption state unknown for track ".concat(this.trackId,", dropping frame"),ut.InternalError,this.participantIdentity));if(!In)return this.appendFrameMetadata(t),n.enqueue(t);const i=this.keys.getKeySet();if(!i)return void this.emitThrottledError(new gt("key set not found for ".concat(this.participantIdentity," at index ").concat(this.keys.getCurrentKeyIndex()),ut.MissingKey,this.participantIdentity));const a=i.encryptionKey,o=this.keys.getCurrentKeyIndex();if(a){let i=this.makeIV(null!==(e=t.getMetadata().synchronizationSource)&&void 0!==e?e:-1,t.timestamp),c=this.getUnencryptedBytes(t),d=new Uint8Array(t.data,0,c.unencryptedBytes);c.requiresNALUProcessing&&(d=function(e){const t=[];for(let n=0;n+2<e.length;)0!==e[n+2]?(1!==e[n+2]||0!==e[n]||0!==e[n+1]||0!==n&&0===e[n-1]||t.push(n),n+=3):n+=1;if(0===t.length)return e;const n=new Uint8Array(e.length+t.length);let r=0;for(let i=0;i<t.length;i++){const a=t[i];n.set(e.subarray(r,a),r+i),r=a}return n.set(e.subarray(r),r+t.length),n}(d));const u=new Uint8Array(2);u[0]=12,u[1]=o;try{const e=c.unencryptedBytes-2,o=c.requiresNALUProcessing?yn(new Uint8Array(t.data,e)):null;let l;for(let n=1;l=yield crypto.subtle.encrypt({name:k,iv:i,additionalData:d},a,new Uint8Array(t.data,c.unencryptedBytes)),null!==o&&16!==n;n++){const n=$t(new Uint8Array(l,0,16)),a=new Uint8Array(2+n.byteLength);if(a.set(new Uint8Array(t.data,e,2)),a.set(n,2),yn(a)===o)break;i=this.makeIV(null!==(r=t.getMetadata().synchronizationSource)&&void 0!==r?r:-1,t.timestamp)}let h=new Uint8Array(l.byteLength+i.byteLength+u.byteLength);h.set(new Uint8Array(l)),h.set(new Uint8Array(i),l.byteLength),h.set(u,l.byteLength+i.byteLength),c.requiresNALUProcessing&&(h=$t(h));var s=new Uint8Array(d.byteLength+h.byteLength);return s.set(d),s.set(h,d.byteLength),t.data=s.buffer,this.appendFrameMetadata(t),n.enqueue(t)}catch(e){f.error("error while encrypting",Object.assign(Object.assign({},this.logContext),{error:e}))}}else f.debug("failed to encrypt, emitting error",this.logContext),this.emitThrottledError(new gt("encryption key missing for encoding",ut.MissingKey,this.participantIdentity))}))}appendFrameMetadata(e){var t;tn(this.frameMetadataOpts)&&Ht(e)&&((null===(t=this.frameMetadataOpts)||void 0===t?void 0:t.frameId)&&(this.frameMetadataFrameId=4294967295===this.frameMetadataFrameId?1:this.frameMetadataFrameId+1),function(e,t,n){if(!tn(t)||0===e.data.byteLength)return!1;const r=(null==t?void 0:t.timestamp)?BigInt(Date.now())*BigInt(1e3):BigInt(0),i=(null==t?void 0:t.frameId)?n:0,a=new Uint8Array(e.data),o=rn(a,r,i);o.byteLength!==a.byteLength&&(e.data=o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength))}(e,this.frameMetadataOpts,this.frameMetadataFrameId))}decodeFunction(t,n){return e(this,void 0,void 0,(function*(){if(this.hasFrameMetadata&&Ht(t))try{const e=function(e,t){if(0===e.data.byteLength)return{};const n=an(e.data);if(!n.metadata)return{};const r=n.data.buffer.slice(n.data.byteOffset,n.data.byteOffset+n.data.byteLength),i=function(e){try{const t=e.getMetadata();if("number"==typeof t.rtpTimestamp)return t.rtpTimestamp;if("number"==typeof t.timestamp)return t.timestamp}catch(e){}if("number"==typeof e.timestamp)return e.timestamp}(e);return void 0!==i&&t?{data:r,payload:{trackId:t,rtpTimestamp:i,ssrc:cn(e),metadata:n.metadata}}:{data:r}}(t,this.trackId);if(e.data&&(t.data=e.data),e.payload&&this.participantIdentity){const t={kind:"packetTrailerMetadata",data:e.payload};postMessage(t)}}catch(e){}if(0===t.data.byteLength)return n.enqueue(t);const e=this.isEnabled();if(void 0===e)return void 0===this.participantIdentity?void f.debug("dropping frame for unassigned cryptor",this.logContext):void this.emitThrottledError(new gt("encryption state unknown for track ".concat(this.trackId,", dropping frame"),ut.InternalError,this.participantIdentity));if(!e)return n.enqueue(t);if(function(e,t){if(0===t.byteLength)return!1;const n=new Uint8Array(e.slice(e.byteLength-t.byteLength));return t.every(((e,t)=>e===n[t]))}(t.data,this.sifTrailer))return t.data=t.data.slice(0,t.data.byteLength-this.sifTrailer.byteLength),(yield wn(t.data))?(f.debug("enqueue SIF",this.logContext),n.enqueue(t)):void f.warn("Unexpected SIF frame payload, dropping frame",this.logContext);const r=new Uint8Array(t.data)[t.data.byteLength-1];if(!this.keys.hasInvalidKeyAtIndex(r))if(this.keys.getKeySet(r))try{const e=yield this.decryptFrame(t,r);if(this.keys.decryptionSuccess(r),e)return n.enqueue(e)}catch(e){e instanceof gt&&e.reason===ut.InvalidKey?this.keys.hasValidKey&&(this.emitThrottledError(e),this.keys.decryptionFailure(r)):f.warn("decoding frame failed",{error:e})}else f.warn("skipping decryption due to missing key at index ".concat(r)),this.emitThrottledError(new gt("missing key at index ".concat(r," for participant ").concat(this.participantIdentity),ut.MissingKey,this.participantIdentity)),this.keys.decryptionFailure(r)}))}decryptFrame(t,n){return e(this,arguments,void 0,(function(e,t){var n=this;let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{ratchetCount:0};return function*(){var a;const o=n.keys.getKeySet(t);if(!i.encryptionKey&&!o)throw new TypeError("no encryption key found for decryption of ".concat(n.participantIdentity));let s=n.getUnencryptedBytes(e);try{const t=new Uint8Array(e.data,0,s.unencryptedBytes);var c=new Uint8Array(e.data,t.length,e.data.byteLength-t.length);if(s.requiresNALUProcessing&&function(e){for(var t=0;t<e.length-3;t++)if(0==e[t]&&0==e[t+1]&&3==e[t+2])return!0;return!1}(c)){c=Qt(c);const n=new Uint8Array(t.byteLength+c.byteLength);n.set(t),n.set(c,t.byteLength),e.data=n.buffer}const n=new Uint8Array(e.data,e.data.byteLength-2,2),r=n[0],d=new Uint8Array(e.data,e.data.byteLength-r-n.byteLength,r),u=t.byteLength,l=e.data.byteLength-(t.byteLength+r+n.byteLength),h=yield crypto.subtle.decrypt({name:k,iv:d,additionalData:new Uint8Array(e.data,0,t.byteLength)},null!==(a=i.encryptionKey)&&void 0!==a?a:o.encryptionKey,new Uint8Array(e.data,u,l)),f=new ArrayBuffer(t.byteLength+h.byteLength),p=new Uint8Array(f);return p.set(new Uint8Array(e.data,0,t.byteLength)),p.set(new Uint8Array(h),t.byteLength),e.data=f,e}catch(a){if(n.keyProviderOptions.ratchetWindowSize>0){if(i.ratchetCount<n.keyProviderOptions.ratchetWindowSize){let a,s;f.debug("ratcheting key attempt ".concat(i.ratchetCount," of ").concat(n.keyProviderOptions.ratchetWindowSize,", for kind ").concat(e instanceof RTCEncodedAudioFrame?"audio":"video")),(null!=r?r:o)===n.keys.getKeySet(t)&&(s=yield n.keys.ratchetKey(t,!1),a=yield Yt(s.cryptoKey,n.keyProviderOptions));const c=yield n.decryptFrame(e,t,r||o,{ratchetCount:i.ratchetCount+1,encryptionKey:null==a?void 0:a.encryptionKey});return c&&a&&(null!=r?r:o)===n.keys.getKeySet(t)&&(n.keys.setKeySet(a,t,s),n.keys.setCurrentKeyIndex(t)),c}throw f.warn("maximum ratchet attempts exceeded"),new gt("valid key missing for participant ".concat(n.participantIdentity),ut.InvalidKey,n.participantIdentity)}throw new gt("Decryption failed: ".concat(Xt(a,"decryption")),ut.InvalidKey,n.participantIdentity)}}()}))}makeIV(e,t){var n;const r=new ArrayBuffer(12),i=new DataView(r);this.sendCounts.has(e)||this.sendCounts.set(e,Math.floor(65535*Math.random()));const a=null!==(n=this.sendCounts.get(e))&&void 0!==n?n:0;return i.setUint32(0,e),i.setUint32(4,t),i.setUint32(8,t-a%65535),this.sendCounts.set(e,a+1),r}getUnencryptedBytes(e){var t;if(!Ht(e))return{unencryptedBytes:T.audio,requiresNALUProcessing:!1};const n=null!==(t=this.getVideoCodec(e))&&void 0!==t?t:this.videoCodec;if(n!==this.detectedCodec&&(f.debug("detected different codec",Object.assign({detectedCodec:n,oldCodec:this.detectedCodec},this.logContext)),this.detectedCodec=n),"av1"===n)throw new Error("".concat(n," is not yet supported for end to end encryption"));if("vp8"===n)return{unencryptedBytes:T[e.type],requiresNALUProcessing:!1};if("vp9"===n)return{unencryptedBytes:0,requiresNALUProcessing:!1};const r=e.getMetadata().payloadType,i="".concat(this.participantIdentity,"-").concat(this.trackId,"-").concat(r);try{const t="h264"===n||"h265"===n?n:void 0,r=mn(new Uint8Array(e.data),t);if(r.requiresNALUProcessing)return this.loggedNALUFallbacks.delete(i),{unencryptedBytes:r.unencryptedBytes,requiresNALUProcessing:!0}}catch(t){this.logNALUFallbackOnce(i,e,r,n,t)}return{unencryptedBytes:T[e.type],requiresNALUProcessing:!1}}logNALUFallbackOnce(e,t,n,r,i){this.loggedNALUFallbacks.has(e)||(this.loggedNALUFallbacks.add(e),f.warn("NALU processing failed, falling back to VP8 handling",Object.assign({error:i,payloadType:n,detectedCodec:r,frameType:t.type,byteLength:t.data.byteLength,firstBytes:Array.from(new Uint8Array(t.data,0,Math.min(16,t.data.byteLength))).map((e=>e.toString(16).padStart(2,"0"))).join(" ")},this.logContext)))}getVideoCodec(e){const t=e.getMetadata();if(t.mimeType){const e=t.mimeType.split("/")[1].toLowerCase();if(xt.includes(e))return e}if(0===this.rtpMap.size)return;const n=t.payloadType;return n?this.rtpMap.get(n):void 0}}class Nn extends Ot.EventEmitter{get hasValidKey(){return!this.hasInvalidKeyAtIndex(this.currentKeyIndex)}constructor(e,t){if(super(),this.currentKeyIndex=0,t.keyringSize<1||t.keyringSize>256)throw new TypeError("Keyring size needs to be between 1 and 256");this.cryptoKeyRing=new Array(t.keyringSize).fill(void 0),this.decryptionFailureCounts=new Array(t.keyringSize).fill(0),this.keyProviderOptions=t,this.ratchetPromiseMap=new Map,this.participantIdentity=e}hasInvalidKeyAtIndex(e){return this.keyProviderOptions.failureTolerance>=0&&this.decryptionFailureCounts[e]>this.keyProviderOptions.failureTolerance}decryptionFailure(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.currentKeyIndex;this.keyProviderOptions.failureTolerance<0||(this.decryptionFailureCounts[e]+=1,this.decryptionFailureCounts[e]>this.keyProviderOptions.failureTolerance&&f.warn("key for ".concat(this.participantIdentity," at index ").concat(e," is being marked as invalid")))}decryptionSuccess(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.currentKeyIndex;this.resetKeyStatus(e)}resetKeyStatus(e){void 0===e?this.decryptionFailureCounts.fill(0):this.decryptionFailureCounts[e]=0}ratchetKey(t){let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const r=null!=t?t:this.getCurrentKeyIndex(),i=this.ratchetPromiseMap.get(r);if(void 0!==i)return i;const a=new Promise(((t,i)=>e(this,void 0,void 0,(function*(){try{const i=this.getKeySet(r);if(!i)throw new TypeError("Cannot ratchet key without a valid keyset of participant ".concat(this.participantIdentity));const a=i.material,o=yield function(t,n){return e(this,void 0,void 0,(function*(){const e=zt(t.algorithm.name,n);return crypto.subtle.deriveBits(e,t,256)}))}(a,this.keyProviderOptions.ratchetSalt),s=yield function(t){return e(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{name:k},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"encrypt";return function*(){return crypto.subtle.importKey("raw",e,t,!1,"derive"===n?["deriveBits","deriveKey"]:["encrypt","decrypt"])}()}))}(o,a.algorithm.name,"derive"),c={chainKey:o,cryptoKey:s};n&&(yield this.setKeyFromMaterial(s,r,c)),t(c)}catch(e){i(e)}finally{this.ratchetPromiseMap.delete(r)}}))));return this.ratchetPromiseMap.set(r,a),a}setKey(t){return e(this,arguments,void 0,(function(e){var t=this;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){yield t.setKeyFromMaterial(e,n,null,r),r&&t.resetKeyStatus(n)}()}))}setKeyFromMaterial(t,n){return e(this,arguments,void 0,(function(e,t){var n=this;let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,i=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];return function*(){const a=yield Yt(e,n.keyProviderOptions),o=t>=0?t%n.cryptoKeyRing.length:n.currentKeyIndex;f.debug("setting new key with index ".concat(t),{usage:e.usages,algorithm:e.algorithm,ratchetSalt:n.keyProviderOptions.ratchetSalt}),n.setKeySet(a,o,r),o>=0&&i&&(n.currentKeyIndex=o)}()}))}setKeySet(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;this.cryptoKeyRing[t%this.cryptoKeyRing.length]=e,n&&this.emit(ht.KeyRatcheted,n,this.participantIdentity,t)}setCurrentKeyIndex(t){return e(this,void 0,void 0,(function*(){this.currentKeyIndex=t%this.cryptoKeyRing.length,this.resetKeyStatus(t)}))}getCurrentKeyIndex(){return this.currentKeyIndex}getKeySet(e){return this.cryptoKeyRing[null!=e?e:this.currentKeyIndex]}}const An={encode:[],decode:[]},Cn=new Map;let Ln,Un,On=new class{constructor(){this.pendingTasks=new Map,this.taskMutex=new b,this.nextTaskIndex=0}run(t){return e(this,void 0,void 0,(function*(){const e={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:m.WAITING};this.pendingTasks.set(e.id,e);const n=yield this.taskMutex.lock();try{return e.executedAt=Date.now(),e.status=m.RUNNING,yield t()}finally{e.status=m.COMPLETED,this.pendingTasks.delete(e.id),n()}}))}flush(){return e(this,void 0,void 0,(function*(){return this.run((()=>e(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}},Rn=!1,Dn=w,Fn=new Map;const Pn=new en;function _n(e,t,n,r){const i=An[e];let a=i.filter((e=>e.getTrackId()===n));if(0===a.length&&void 0!==r&&r!==n){const e=i.filter((e=>e.getTrackId()===r));e.length>0&&(f.info("reusing cryptor from previous trackId",{participantIdentity:t,trackId:n,previousTrackId:r}),e[0].setTrackId(n),a=e)}if(a.length>1){const e=a.map((e=>({participant:e.getParticipantIdentity()}))).join(",");f.error("Found multiple cryptors for the same trackID ".concat(n,". target participant: ").concat(t," "),{participants:e})}let o=a[0];if(o)t!==o.getParticipantIdentity()&&o.setParticipant(t,xn(t));else{if(f.info("creating new cryptor for",{participantIdentity:t,trackId:n}),!Dn)throw Error("Missing keyProvider options");o=new En({participantIdentity:t,keys:xn(t),keyProviderOptions:Dn,sifTrailer:Un}),o.setRtpMap(Fn),function(e){e.on(pt.Error,(e=>{const t={kind:"error",data:{error:new Error("".concat(ut[e.reason],": ").concat(e.message)),participantIdentity:e.participantIdentity}};postMessage(t)}))}(o),i.push(o)}return o}function xn(e){if(Rn)return Mn();let t=Cn.get(e);return t||(t=new Nn(e,Dn),t.on(ht.KeyRatcheted,Bn),Cn.set(e,t)),t}function Mn(){return Ln||(f.debug("creating new shared key handler"),Ln=new Nn("shared-key",Dn)),Ln}function Bn(e,t,n){postMessage({kind:"ratchetKey",data:{participantIdentity:t,keyIndex:n,ratchetResult:e}})}f.setDefaultLevel("info"),f.methodFactory=e=>(t,n)=>{postMessage({kind:"log",data:{level:e,msg:t,context:n}})},f.setLevel(f.getLevel()),onmessage=t=>{On.run((()=>e(void 0,void 0,void 0,(function*(){var n;const r=t.data,i=r.kind,a=r.data;switch(i){case"init":f.setLevel(a.loglevel),f.info("e2ee worker initialized"),Dn=a.keyProviderOptions,Rn=!!a.keyProviderOptions.sharedKey;postMessage({kind:"initAck",data:{enabled:false}});break;case"setLogLevel":f.setLevel(a.level);break;case"enable":a.local&&(s=a.enabled,In=s),f.info("updated e2ee enabled status for ".concat(a.participantIdentity," to ").concat(a.enabled)),postMessage(t.data);break;case"decode":let r=_n(i,a.participantIdentity,a.trackId);r.setEncrypted(a.encrypted),r.setHasFrameMetadata(a.hasPacketTrailer),r.setupTransform(i,a.readableStream,a.writableStream,a.trackId,a.codec);break;case"encode":let c=_n(i,a.participantIdentity,a.trackId);c.setHasFrameMetadata(a.hasPacketTrailer),c.setupTransform(i,a.readableStream,a.writableStream,a.trackId,a.codec,a.packetTrailer);break;case"encryptDataRequest":const d=yield Zt.encrypt(a.payload,xn(a.participantIdentity)),u=d.payload,l=d.iv,h=d.keyIndex;postMessage({kind:"encryptDataResponse",data:{payload:u,iv:l,keyIndex:h,uuid:a.uuid}});break;case"decryptDataRequest":try{const e=(yield Zt.decrypt(a.payload,a.iv,xn(a.participantIdentity),a.keyIndex)).payload;postMessage({kind:"decryptDataResponse",data:{payload:e,uuid:a.uuid}})}catch(e){const t="".concat(a.participantIdentity,"-datadecrypt");Pn.shouldEmit(t,(()=>{f.warn("Suppressing further data decryption errors for ".concat(a.participantIdentity),{errorKey:t})}))&&f.error("DataCryptor decryption failed",{error:e,participantIdentity:a.participantIdentity,uuid:a.uuid}),postMessage({kind:"error",data:{error:e instanceof Error?e:new Error(String(e)),uuid:a.uuid}})}break;case"setKey":Rn?yield function(t,n,r){return e(this,void 0,void 0,(function*(){f.info("set shared key",{index:n}),yield Mn().setKey(t,n,r)}))}(a.key,a.keyIndex,a.updateCurrentKeyIndex):a.participantIdentity?(f.info("set participant sender key ".concat(a.participantIdentity," index ").concat(a.keyIndex)),yield xn(a.participantIdentity).setKey(a.key,a.keyIndex,a.updateCurrentKeyIndex)):f.error("no participant Id was provided and shared key usage is disabled");break;case"removeTransform":!function(e,t){const n=An.decode.filter((n=>n.getParticipantIdentity()===t&&n.getTrackId()===e));n.length>1&&f.error("Found multiple cryptors for the same participant and trackID combination",{trackId:e,participantIdentity:t});const r=n[0];r?r.unsetParticipant():f.warn("Could not unset participant on cryptor",{trackId:e,participantIdentity:t})}(a.trackId,a.participantIdentity);break;case"updateCodec":const p=_n(null!==(n=a.operation)&&void 0!==n?n:"decode",a.participantIdentity,a.trackId,a.previousTrackId);a.codec&&p.setVideoCodec(a.codec),p.setHasFrameMetadata(a.hasPacketTrailer),"encode"!==a.operation&&p.setEncrypted(a.encrypted),f.info("updated codec",{participantIdentity:a.participantIdentity,trackId:a.trackId,previousTrackId:a.previousTrackId,codec:a.codec,hasPacketTrailer:a.hasPacketTrailer}),void 0===a.previousTrackId||p.ensureTransform()||f.error("could not re-establish transform for reused receiver",{participantIdentity:a.participantIdentity,trackId:a.trackId,previousTrackId:a.previousTrackId});break;case"setRTPMap":Fn=a.map,An.encode.forEach((e=>{e.setRtpMap(a.map)}));break;case"ratchetRequest":!function(t){e(this,void 0,void 0,(function*(){if(Rn){const e=Mn();yield e.ratchetKey(t.keyIndex),e.resetKeyStatus()}else if(t.participantIdentity){const e=xn(t.participantIdentity);yield e.ratchetKey(t.keyIndex),e.resetKeyStatus()}else f.error("no participant Id was provided for ratchet request and shared key usage is disabled")}))}(a);break;case"setSifTrailer":o=a.trailer,Un=o,An.decode.forEach((e=>{e.setSifTrailer(o)}))}var o,s}))))},self.RTCTransformEvent&&(self.onrtctransform=t=>{const n=t.transformer,r=n.options,i=r.kind,a=r.participantIdentity,o=r.trackId,s=r.codec,c=r.hasPacketTrailer;On.run((()=>e(void 0,void 0,void 0,(function*(){const e=_n(i,a,o);"decode"===i&&e.setEncrypted(r.encrypted),e.setHasFrameMetadata(c),f.debug("onrtctransform setup",{participantIdentity:a,trackId:o,codec:s}),e.setupTransform(i,n.readable,n.writable,o,s,"encode"===i?r.packetTrailer:void 0)}))))})}));
1
+ !function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";function e(e,t,n,r){return new(n||(n=Promise))((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((r=r.apply(e,t||[])).next())}))}function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}"function"==typeof SuppressedError&&SuppressedError;var n,r={exports:{}};var i,a,o,s,c,d=(n||(n=1,a=r.exports,o=function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"],i={},a=null;function o(e,t){var n=e[t];if("function"==typeof n.bind)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch(t){return function(){return Function.prototype.apply.apply(n,[e,arguments])}}}function s(){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 n=this.getLevel(),i=0;i<r.length;i++){var a=r[i];this[a]=i<n?e:this.methodFactory(a,n,this.name)}if(this.log=this.debug,typeof console===t&&n<this.levels.SILENT)return"No console available for logging"}function d(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function u(r,i,a){return function(r){return"debug"===r&&(r="log"),typeof console!==t&&("trace"===r&&n?s:void 0!==console[r]?o(console,r):void 0!==console.log?o(console,"log"):e)}(r)||d.apply(this,arguments)}function l(e,n){var o,s,d,l=this,h="loglevel";function f(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(e){}if(typeof e===t)try{var n=window.document.cookie,r=encodeURIComponent(h),i=n.indexOf(r+"=");-1!==i&&(e=/^([^;]+)/.exec(n.slice(i+r.length+1))[1])}catch(e){}return void 0===l.levels[e]&&(e=void 0),e}}function p(e){var t=e;if("string"==typeof t&&void 0!==l.levels[t.toUpperCase()]&&(t=l.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=l.levels.SILENT)return t;throw new TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),l.name=e,l.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},l.methodFactory=n||u,l.getLevel=function(){return null!=d?d:null!=s?s:o},l.setLevel=function(e,n){return d=p(e),!1!==n&&function(e){var n=(r[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{return void(window.localStorage[h]=n)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"="+n+";"}catch(e){}}}(d),c.call(l)},l.setDefaultLevel=function(e){s=p(e),f()||l.setLevel(e,!1)},l.resetLevel=function(){d=null,function(){if(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(l)},l.enableAll=function(e){l.setLevel(l.levels.TRACE,e)},l.disableAll=function(e){l.setLevel(l.levels.SILENT,e)},l.rebuild=function(){if(a!==l&&(o=p(a.getLevel())),c.call(l),a===l)for(var e in i)i[e].rebuild()},o=p(a?a.getLevel():"WARN");var y=f();null!=y&&(d=p(y)),c.call(l)}(a=new l).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=i[e];return t||(t=i[e]=new l(e,a.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=h),a},a.getLoggers=function(){return i},a.default=a,a},(i=r).exports?i.exports=o():a.log=o()),r.exports),u=t(d);!function(e){e[e.trace=0]="trace",e[e.debug=1]="debug",e[e.info=2]="info",e[e.warn=3]="warn",e[e.error=4]="error",e[e.silent=5]="silent"}(s||(s={})),function(e){e.Default="livekit",e.Room="livekit-room",e.TokenSource="livekit-token-source",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",e.DataTracks="livekit-data-tracks",e.Region="livekit-region",e.ICE="livekit-ice",e.Stats="livekit-stats"}(c||(c={}));let l=u.getLogger(c.Default);function h(e,t){const n=u.getLogger(e);return n.setDefaultLevel(l.getLevel()),t?function(e,t){const n=n=>(r,i)=>{const a=t(),o=a||i?Object.assign(Object.assign({},a),i):void 0;e[n](r,o)},r=Object.create(e);return r.trace=n("trace"),r.debug=n("debug"),r.info=n("info"),r.warn=n("warn"),r.error=n("error"),r}(n,t):n}Object.values(c).map((e=>u.getLogger(e))),l.setDefaultLevel(s.info);const f=u.getLogger(c.E2EE),p=new Set,y=f.setLevel.bind(f);f.setLevel=(e,t)=>{y(e,t);const n=f.getLevel();p.forEach((e=>e(n)))};var m,g=Object.defineProperty,v=(e,t,n)=>((e,t,n)=>t in e?g(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n);class b{constructor(){v(this,"_locking"),v(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;const t=new Promise((t=>e=()=>{this._locks-=1,t()})),n=this._locking.then((()=>e));return this._locking=this._locking.then((()=>t)),n}}!function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(m||(m={}));const k="AES-GCM",T={key:10,delta:3,audio:1,empty:0},w={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:10,keyringSize:16,keySize:128};function I(e,t){if(!e)throw new Error(t)}function S(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>2147483647||e<-2147483648)throw new Error("invalid int 32: "+e)}function E(e){if("number"!=typeof e)throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>4294967295||e<0)throw new Error("invalid uint 32: "+e)}function N(e){if("number"!=typeof e)throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>34028234663852886e22||e<-34028234663852886e22))throw new Error("invalid float 32: "+e)}const A=Symbol("@bufbuild/protobuf/enum-type");function C(e){const t=e[A];return I(t,"missing enum type on enum object"),t}function L(e,t,n,r){e[A]=U(t,n.map((t=>({no:t.no,name:t.name,localName:e[t.no]}))))}function U(e,t,n){const r=Object.create(null),i=Object.create(null),a=[];for(const e of t){const t=R(e);a.push(t),r[e.name]=t,i[e.no]=t}return{typeName:e,values:a,findName:e=>r[e],findNumber:e=>i[e]}}function O(e,t,n){const r={};for(const e of t){const t=R(e);r[t.localName]=t.no,r[t.no]=t.localName}return L(r,e,t),r}function R(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class D{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const n=this.getType().runtime.bin,r=n.makeReadOptions(t);return n.readMessage(this,r.readerFactory(e),e.byteLength,r),this}fromJson(e,t){const n=this.getType(),r=n.runtime.json,i=r.makeReadOptions(t);return r.readMessage(n,e,i,this),this}fromJsonString(e,t){let n;try{n=JSON.parse(e)}catch(e){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(e instanceof Error?e.message:String(e)))}return this.fromJson(n,t)}toBinary(e){const t=this.getType().runtime.bin,n=t.makeWriteOptions(e),r=n.writerFactory();return t.writeMessage(this,r,n),r.finish()}toJson(e){const t=this.getType().runtime.json,n=t.makeWriteOptions(e);return t.writeMessage(this,n)}toJsonString(e){var t;const n=this.toJson(e);return JSON.stringify(n,null,null!==(t=null==e?void 0:e.prettySpaces)&&void 0!==t?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function F(){let e=0,t=0;for(let n=0;n<28;n+=7){let r=this.buf[this.pos++];if(e|=(127&r)<<n,!(128&r))return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(15&n)<<28,t=(112&n)>>4,!(128&n))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let r=this.buf[this.pos++];if(t|=(127&r)<<n,!(128&r))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function P(e,t,n){for(let r=0;r<28;r+=7){const i=e>>>r,a=!(i>>>7==0&&0==t),o=255&(a?128|i:i);if(n.push(o),!a)return}const r=e>>>28&15|(7&t)<<4,i=!!(t>>3);if(n.push(255&(i?128|r:r)),i){for(let e=3;e<31;e+=7){const r=t>>>e,i=!(r>>>7==0),a=255&(i?128|r:r);if(n.push(a),!i)return}n.push(t>>>31&1)}}const _=4294967296;function x(e){const t="-"===e[0];t&&(e=e.slice(1));const n=1e6;let r=0,i=0;function a(t,a){const o=Number(e.slice(t,a));i*=n,r=r*n+o,r>=_&&(i+=r/_|0,r%=_)}return a(-24,-18),a(-18,-12),a(-12,-6),a(-6),t?j(r,i):B(r,i)}function M(e,t){var n=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t);if(e=n.lo,(t=n.hi)<=2097151)return String(_*t+e);const r=16777215&(e>>>24|t<<8),i=t>>16&65535;let a=(16777215&e)+6777216*r+6710656*i,o=r+8147497*i,s=2*i;const c=1e7;return a>=c&&(o+=Math.floor(a/c),a%=c),o>=c&&(s+=Math.floor(o/c),o%=c),s.toString()+K(o)+K(a)}function B(e,t){return{lo:0|e,hi:0|t}}function j(e,t){return t=~t,e?e=1+~e:t+=1,B(e,t)}const K=e=>{const t=String(e);return"0000000".slice(t.length)+t};function V(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let n=0;n<9;n++)t.push(127&e|128),e>>=7;t.push(1)}}function q(){let e=this.buf[this.pos++],t=127&e;if(!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,!(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let t=5;128&e&&t<10;t++)e=this.buf[this.pos++];if(128&e)throw new Error("invalid varint");return this.assertBounds(),t>>>0}const W=function(){const 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 process||"object"!=typeof process.env||"1"!==process.env.BUF_BIGINT_DISABLE)){const t=BigInt("-9223372036854775808"),n=BigInt("9223372036854775807"),r=BigInt("0"),i=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const r="bigint"==typeof e?e:BigInt(e);if(r>n||r<t)throw new Error("int64 invalid: ".concat(e));return r},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>i||t<r)throw new 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,n)=>(e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigInt64(0,!0)),uDec:(t,n)=>(e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigUint64(0,!0))}}const t=e=>I(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),n=e=>I(/^[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()),n(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),t(e),x(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),n(e),x(e)),dec:(e,t)=>function(e,t){let n=B(e,t);const r=2147483648&n.hi;r&&(n=j(n.lo,n.hi));const i=M(n.lo,n.hi);return r?"-"+i:i}(e,t),uDec:(e,t)=>M(e,t)}}();var G,J,X;function H(e,t,n){if(t===n)return!0;if(e==G.BYTES){if(!(t instanceof Uint8Array&&n instanceof Uint8Array))return!1;if(t.length!==n.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==n[e])return!1;return!0}switch(e){case G.UINT64:case G.FIXED64:case G.INT64:case G.SFIXED64:case G.SINT64:return t==n}return!1}function z(e,t){switch(e){case G.BOOL:return!1;case G.UINT64:case G.FIXED64:case G.INT64:case G.SFIXED64:case G.SINT64:return 0==t?W.zero:"0";case G.DOUBLE:case G.FLOAT:return 0;case G.BYTES:return new Uint8Array(0);case G.STRING:return"";default:return 0}}function Y(e,t){switch(e){case G.BOOL:return!1===t;case G.STRING:return""===t;case G.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}function Q(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function $(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,a,o,s=[],c=!0,d=!1;try{if(a=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){d=!0,i=e}finally{try{if(!c&&null!=n.return&&(o=n.return(),Object(o)!==o))return}finally{if(d)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return Q(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Q(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}!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"}(G||(G={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"}(J||(J={})),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"}(X||(X={}));class Z{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),n=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],n),n+=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 new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(E(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return S(e),V(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){N(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){E(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){S(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return S(e),V(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=W.enc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=W.uEnc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=W.enc(e);return P(t.lo,t.hi,this.buf),this}sint64(e){let t=W.enc(e),n=t.hi>>31;return P(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=W.uEnc(e);return P(t.lo,t.hi,this.buf),this}}class ee{constructor(e,t){this.varint64=F,this.uint32=q,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,n=7&e;if(t<=0||n<0||n>5)throw new Error("illegal tag: field no "+t+" wire type "+n);return[t,n]}skip(e,t){let n=this.pos;switch(e){case X.Varint:for(;128&this.buf[this.pos++];);break;case X.Bit64:this.pos+=4;case X.Bit32:this.pos+=4;break;case X.LengthDelimited:let n=this.uint32();this.pos+=n;break;case X.StartGroup:for(;;){const e=$(this.tag(),2),n=e[0],r=e[1];if(r===X.EndGroup){if(void 0!==t&&n!==t)throw new Error("invalid end group tag");break}this.skip(r,n)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return W.dec(...this.varint64())}uint64(){return W.uDec(...this.varint64())}sint64(){let e=$(this.varint64(),2),t=e[0],n=e[1],r=-(1&t);return t=(t>>>1|(1&n)<<31)^r,n=n>>>1^r,W.dec(t,n)}bool(){let e=$(this.varint64(),2),t=e[0],n=e[1];return 0!==t||0!==n}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return W.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return W.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 te(e){const t=e.field.localName,n=Object.create(null);return n[t]=function(e){const 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 z(t.T,t.L);case"message":const e=t.T,n=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(n):n;case"map":throw"map fields are not allowed to be extensions"}}(e),[n,()=>n[t]]}let ne="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),re=[];for(let e=0;e<ne.length;e++)re[ne[e].charCodeAt(0)]=e;re["-".charCodeAt(0)]=ne.indexOf("+"),re["_".charCodeAt(0)]=ne.indexOf("/");const ie={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let n,r=new Uint8Array(t),i=0,a=0,o=0;for(let t=0;t<e.length;t++){if(n=re[e.charCodeAt(t)],void 0===n)switch(e[t]){case"=":a=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(a){case 0:o=n,a=1;break;case 1:r[i++]=o<<2|(48&n)>>4,o=n,a=2;break;case 2:r[i++]=(15&o)<<4|(60&n)>>2,o=n,a=3;break;case 3:r[i++]=(3&o)<<6|n,a=0}}if(1==a)throw Error("invalid base64 string.");return r.subarray(0,i)},enc(e){let t,n="",r=0,i=0;for(let a=0;a<e.length;a++)switch(t=e[a],r){case 0:n+=ne[t>>2],i=(3&t)<<4,r=1;break;case 1:n+=ne[i|t>>4],i=(15&t)<<2,r=2;break;case 2:n+=ne[i|t>>6],n+=ne[63&t],r=0}return r&&(n+=ne[i],n+="=",1==r&&(n+="=")),n}};function ae(e,t,n){ce(t,e);const r=t.runtime.bin.makeReadOptions(n),i=function(e,t){if(!t.repeated&&("enum"==t.kind||"scalar"==t.kind)){for(let n=e.length-1;n>=0;--n)if(e[n].no==t.no)return[e[n]];return[]}return e.filter((e=>e.no===t.no))}(e.getType().runtime.bin.listUnknownFields(e),t.field),a=$(te(t),2),o=a[0],s=a[1];for(const e of i)t.runtime.bin.readField(o,r.readerFactory(e.data),t.field,e.wireType,r);return s()}function oe(e,t,n,r){ce(t,e);const i=t.runtime.bin.makeReadOptions(r),a=t.runtime.bin.makeWriteOptions(r);if(se(e,t)){const n=e.getType().runtime.bin.listUnknownFields(e).filter((e=>e.no!=t.field.no));e.getType().runtime.bin.discardUnknownFields(e);for(const t of n)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}const o=a.writerFactory();let s=t.field;s.opt||s.repeated||"enum"!=s.kind&&"scalar"!=s.kind||(s=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(s,n,o,a);const c=i.readerFactory(o.finish());for(;c.pos<c.len;){const t=$(c.tag(),2),n=t[0],r=t[1],i=c.skip(r,n);e.getType().runtime.bin.onUnknownField(e,n,r,i)}}function se(e,t){const n=e.getType();return t.extendee.typeName===n.typeName&&!!n.runtime.bin.listUnknownFields(e).find((e=>e.no==t.field.no))}function ce(e,t){I(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function de(e,t){const n=e.localName;if(e.repeated)return t[n].length>0;if(e.oneof)return t[e.oneof.localName].case===n;switch(e.kind){case"enum":case"scalar":return e.opt||e.req?void 0!==t[n]:"enum"==e.kind?t[n]!==e.T.values[0].no:!Y(e.T,t[n]);case"message":return void 0!==t[n];case"map":return Object.keys(t[n]).length>0}}function ue(e,t){const n=e.localName,r=!e.opt&&!e.req;if(e.repeated)t[n]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case"map":t[n]={};break;case"enum":t[n]=r?e.T.values[0].no:void 0;break;case"scalar":t[n]=r?z(e.T,e.L):void 0;break;case"message":t[n]=void 0}}function le(e,t){if(null===e||"object"!=typeof e)return!1;if(!Object.getOwnPropertyNames(D.prototype).every((t=>t in e&&"function"==typeof e[t])))return!1;const n=e.getType();return null!==n&&"function"==typeof n&&"typeName"in n&&"string"==typeof n.typeName&&(void 0===t||n.typeName==t.typeName)}function he(e,t){return le(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}G.DOUBLE,G.FLOAT,G.INT64,G.UINT64,G.INT32,G.UINT32,G.BOOL,G.STRING,G.BYTES;const fe={ignoreUnknownFields:!1},pe={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function ye(e){return e?Object.assign(Object.assign({},fe),e):fe}function me(e){return e?Object.assign(Object.assign({},pe),e):pe}const ge=Symbol(),ve=Symbol();function be(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 ke(e,t,n,r,i){let a=n.localName;if(n.repeated){if(I("map"!=n.kind),null===t)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(be(t)));const o=e[a];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(be(e)));switch(n.kind){case"message":o.push(n.T.fromJson(e,r));break;case"enum":const t=Ie(n.T,e,r.ignoreUnknownFields,!0);t!==ve&&o.push(t);break;case"scalar":try{o.push(we(n.T,e,n.L,!0))}catch(t){let r="cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(be(e));throw t instanceof Error&&t.message.length>0&&(r+=": ".concat(t.message)),new Error(r)}}}}else if("map"==n.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw new Error("cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(be(t)));const s=e[a];for(const e of Object.entries(t)){var o=$(e,2);const a=o[0],c=o[1];if(null===c)throw new Error("cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: map value null"));let d;try{d=Te(n.K,a)}catch(e){let r="cannot decode map key for field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(be(t));throw e instanceof Error&&e.message.length>0&&(r+=": ".concat(e.message)),new Error(r)}switch(n.V.kind){case"message":s[d]=n.V.T.fromJson(c,r);break;case"enum":const e=Ie(n.V.T,c,r.ignoreUnknownFields,!0);e!==ve&&(s[d]=e);break;case"scalar":try{s[d]=we(n.V.T,c,J.BIGINT,!0)}catch(e){let r="cannot decode map value for field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(be(t));throw e instanceof Error&&e.message.length>0&&(r+=": ".concat(e.message)),new Error(r)}}}}else switch(n.oneof&&(e=e[n.oneof.localName]={case:a},a="value"),n.kind){case"message":const o=n.T;if(null===t&&"google.protobuf.Value"!=o.typeName)return;let s=e[a];le(s)?s.fromJson(t,r):(e[a]=s=o.fromJson(t,r),o.fieldWrapper&&!n.oneof&&(e[a]=o.fieldWrapper.unwrapField(s)));break;case"enum":const c=Ie(n.T,t,r.ignoreUnknownFields,!1);switch(c){case ge:ue(n,e);break;case ve:break;default:e[a]=c}break;case"scalar":try{const r=we(n.T,t,n.L,!1);if(r===ge)ue(n,e);else e[a]=r}catch(e){let r="cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(be(t));throw e instanceof Error&&e.message.length>0&&(r+=": ".concat(e.message)),new Error(r)}}}function Te(e,t){if(e===G.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return we(e,t,J.BIGINT,!0).toString()}function we(e,t,n,r){if(null===t)return r?z(e,n):ge;switch(e){case G.DOUBLE:case G.FLOAT:if("NaN"===t)return Number.NaN;if("Infinity"===t)return Number.POSITIVE_INFINITY;if("-Infinity"===t)return Number.NEGATIVE_INFINITY;if(""===t)break;if("string"==typeof t&&t.trim().length!==t.length)break;if("string"!=typeof t&&"number"!=typeof t)break;const r=Number(t);if(Number.isNaN(r))break;if(!Number.isFinite(r))break;return e==G.FLOAT&&N(r),r;case G.INT32:case G.FIXED32:case G.SFIXED32:case G.SINT32:case G.UINT32:let i;if("number"==typeof t?i=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(i=Number(t)),void 0===i)break;return e==G.UINT32||e==G.FIXED32?E(i):S(i),i;case G.INT64:case G.SFIXED64:case G.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const a=W.parse(t);return n?a.toString():a;case G.FIXED64:case G.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const o=W.uParse(t);return n?o.toString():o;case G.BOOL:if("boolean"!=typeof t)break;return t;case G.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw new Error("invalid UTF8")}return t;case G.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return ie.dec(t)}throw new Error}function Ie(e,t,n,r){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:r?e.values[0].no:ge;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const r=e.findName(t);if(void 0!==r)return r.no;if(n)return ve}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(be(t)))}function Se(e){return!(!e.repeated&&"map"!=e.kind)||!e.oneof&&("message"!=e.kind&&(!e.opt&&!e.req))}function Ee(e,t,n){if("map"==e.kind){I("object"==typeof t&&null!=t);const o={},s=Object.entries(t);switch(e.V.kind){case"scalar":for(const t of s){var r=$(t,2);const n=r[0],i=r[1];o[n.toString()]=Ae(e.V.T,i)}break;case"message":for(const e of s){var i=$(e,2);const t=i[0],r=i[1];o[t.toString()]=r.toJson(n)}break;case"enum":const t=e.V.T;for(const e of s){var a=$(e,2);const r=a[0],i=a[1];o[r.toString()]=Ne(t,i,n.enumAsInteger)}}return n.emitDefaultValues||s.length>0?o:void 0}if(e.repeated){I(Array.isArray(t));const r=[];switch(e.kind){case"scalar":for(let n=0;n<t.length;n++)r.push(Ae(e.T,t[n]));break;case"enum":for(let i=0;i<t.length;i++)r.push(Ne(e.T,t[i],n.enumAsInteger));break;case"message":for(let e=0;e<t.length;e++)r.push(t[e].toJson(n))}return n.emitDefaultValues||r.length>0?r:void 0}switch(e.kind){case"scalar":return Ae(e.T,t);case"enum":return Ne(e.T,t,n.enumAsInteger);case"message":return he(e.T,t).toJson(n)}}function Ne(e,t,n){var r;if(I("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(n)return t;const i=e.findNumber(t);return null!==(r=null==i?void 0:i.name)&&void 0!==r?r:t}function Ae(e,t){switch(e){case G.INT32:case G.SFIXED32:case G.SINT32:case G.FIXED32:case G.UINT32:return I("number"==typeof t),t;case G.FLOAT:case G.DOUBLE:return I("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case G.STRING:return I("string"==typeof t),t;case G.BOOL:return I("boolean"==typeof t),t;case G.UINT64:case G.FIXED64:case G.INT64:case G.SFIXED64:case G.SINT64:return I("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case G.BYTES:return I(t instanceof Uint8Array),ie.enc(t)}}const Ce=Symbol("@bufbuild/protobuf/unknown-fields"),Le={readUnknownFields:!0,readerFactory:e=>new ee(e)},Ue={writeUnknownFields:!0,writerFactory:()=>new Z};function Oe(e){return e?Object.assign(Object.assign({},Le),e):Le}function Re(e){return e?Object.assign(Object.assign({},Ue),e):Ue}function De(e,t,n,r,i){let a=n.repeated,o=n.localName;switch(n.oneof&&((e=e[n.oneof.localName]).case!=o&&delete e.value,e.case=o,o="value"),n.kind){case"scalar":case"enum":const s="enum"==n.kind?G.INT32:n.T;let c=_e;if("scalar"==n.kind&&n.L>0&&(c=Pe),a){let n=e[o];if(r==X.LengthDelimited&&s!=G.STRING&&s!=G.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)n.push(c(t,s))}else n.push(c(t,s))}else e[o]=c(t,s);break;case"message":const d=n.T;a?e[o].push(Fe(t,new d,i,n)):le(e[o])?Fe(t,e[o],i,n):(e[o]=Fe(t,new d,i,n),!d.fieldWrapper||n.oneof||n.repeated||(e[o]=d.fieldWrapper.unwrapField(e[o])));break;case"map":let u=function(e,t,n){const r=t.uint32(),i=t.pos+r;let a,o;for(;t.pos<i;){switch($(t.tag(),1)[0]){case 1:a=_e(t,e.K);break;case 2:switch(e.V.kind){case"scalar":o=_e(t,e.V.T);break;case"enum":o=t.int32();break;case"message":o=Fe(t,new e.V.T,n,void 0)}}}void 0===a&&(a=z(e.K,J.BIGINT));"string"!=typeof a&&"number"!=typeof a&&(a=a.toString());if(void 0===o)switch(e.V.kind){case"scalar":o=z(e.V.T,J.BIGINT);break;case"enum":o=e.V.T.values[0].no;break;case"message":o=new e.V.T}return[a,o]}(n,t,i),l=$(u,2),h=l[0],f=l[1];e[o][h]=f}}function Fe(e,t,n,r){const i=t.getType().runtime.bin,a=null==r?void 0:r.delimited;return i.readMessage(t,e,a?r.no:e.uint32(),n,a),t}function Pe(e,t){const n=_e(e,t);return"bigint"==typeof n?n.toString():n}function _e(e,t){switch(t){case G.STRING:return e.string();case G.BOOL:return e.bool();case G.DOUBLE:return e.double();case G.FLOAT:return e.float();case G.INT32:return e.int32();case G.INT64:return e.int64();case G.UINT64:return e.uint64();case G.FIXED64:return e.fixed64();case G.BYTES:return e.bytes();case G.FIXED32:return e.fixed32();case G.SFIXED32:return e.sfixed32();case G.SFIXED64:return e.sfixed64();case G.SINT64:return e.sint64();case G.UINT32:return e.uint32();case G.SINT32:return e.sint32()}}function xe(e,t,n,r){I(void 0!==t);const i=e.repeated;switch(e.kind){case"scalar":case"enum":let o="enum"==e.kind?G.INT32:e.T;if(i)if(I(Array.isArray(t)),e.packed)!function(e,t,n,r){if(!r.length)return;e.tag(n,X.LengthDelimited).fork();let i=$(Ke(t),2)[1];for(let t=0;t<r.length;t++)e[i](r[t]);e.join()}(n,o,e.no,t);else for(const r of t)je(n,o,e.no,r);else je(n,o,e.no,t);break;case"message":if(i){I(Array.isArray(t));for(const i of t)Be(n,r,e,i)}else Be(n,r,e,t);break;case"map":I("object"==typeof t&&null!=t);for(const i of Object.entries(t)){var a=$(i,2);Me(n,r,e,a[0],a[1])}}}function Me(e,t,n,r,i){e.tag(n.no,X.LengthDelimited),e.fork();let a=r;switch(n.K){case G.INT32:case G.FIXED32:case G.UINT32:case G.SFIXED32:case G.SINT32:a=Number.parseInt(r);break;case G.BOOL:I("true"==r||"false"==r),a="true"==r}switch(je(e,n.K,1,a),n.V.kind){case"scalar":je(e,n.V.T,2,i);break;case"enum":je(e,G.INT32,2,i);break;case"message":I(void 0!==i),e.tag(2,X.LengthDelimited).bytes(i.toBinary(t))}e.join()}function Be(e,t,n,r){const i=he(n.T,r);n.delimited?e.tag(n.no,X.StartGroup).raw(i.toBinary(t)).tag(n.no,X.EndGroup):e.tag(n.no,X.LengthDelimited).bytes(i.toBinary(t))}function je(e,t,n,r){I(void 0!==r);let i=$(Ke(t),2),a=i[0],o=i[1];e.tag(n,a)[o](r)}function Ke(e){let t=X.Varint;switch(e){case G.BYTES:case G.STRING:t=X.LengthDelimited;break;case G.DOUBLE:case G.FIXED64:case G.SFIXED64:t=X.Bit64;break;case G.FIXED32:case G.SFIXED32:case G.FLOAT:t=X.Bit32}return[t,G[e].toLowerCase()]}function Ve(e){if(void 0===e)return e;if(le(e))return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function qe(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class We{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const e={};for(const t of this.list())e[t.jsonName]=e[t.name]=t;this.jsonNames=e}return this.jsonNames[e]}find(e){if(!this.numbers){const e={};for(const 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){this.members=[];const e=this.members;let t;for(const n of this.list())n.oneof?n.oneof!==t&&(t=n.oneof,e.push(t)):e.push(n)}return this.members}}function Ge(e,t){const n=Xe(e);return t?n:$e(Qe(n))}const Je=Xe;function Xe(e){let t=!1;const n=[];for(let r=0;r<e.length;r++){let i=e.charAt(r);switch(i){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n.push(i),t=!1;break;default:t&&(t=!1,i=i.toUpperCase()),n.push(i)}}return n.join("")}const He=new Set(["constructor","toString","toJSON","valueOf"]),ze=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Ye=e=>"".concat(e,"$"),Qe=e=>ze.has(e)?Ye(e):e,$e=e=>He.has(e)?Ye(e):e;class Ze{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=Ge(e,!1)}addField(e){I(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]}}const et=(tt=e=>new We(e,(e=>function(e){var t,n,r,i,a,o;const s=[];let c;for(const d of"function"==typeof e?e():e){const e=d;if(e.localName=Ge(d.name,void 0!==d.oneof),e.jsonName=null!==(t=d.jsonName)&&void 0!==t?t:Je(d.name),e.repeated=null!==(n=d.repeated)&&void 0!==n&&n,"scalar"==d.kind&&(e.L=null!==(r=d.L)&&void 0!==r?r:J.BIGINT),e.delimited=null!==(i=d.delimited)&&void 0!==i&&i,e.req=null!==(a=d.req)&&void 0!==a&&a,e.opt=null!==(o=d.opt)&&void 0!==o&&o,void 0===d.packed&&(e.packed="enum"==d.kind||"scalar"==d.kind&&d.T!=G.BYTES&&d.T!=G.STRING),void 0!==d.oneof){const t="string"==typeof d.oneof?d.oneof:d.oneof.name;c&&c.name==t||(c=new Ze(t)),e.oneof=c,c.addField(e)}s.push(e)}return s}(e))),nt=e=>{for(const t of e.getType().fields.byMember()){if(t.opt)continue;const n=t.localName,r=e;if(t.repeated)r[n]=[];else switch(t.kind){case"oneof":r[n]={case:void 0};break;case"enum":r[n]=0;break;case"map":r[n]={};break;case"scalar":r[n]=z(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:ye,makeWriteOptions:me,readMessage(e,t,n,r){if(null==t||Array.isArray(t)||"object"!=typeof t)throw new Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(be(t)));r=null!=r?r:new e;const i=new Map,a=n.typeRegistry;for(const s of Object.entries(t)){var o=$(s,2);const t=o[0],c=o[1],d=e.fields.findJsonName(t);if(d){if(d.oneof){if(null===c&&"scalar"==d.kind)continue;const n=i.get(d.oneof);if(void 0!==n)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(d.oneof.name,'" present: "').concat(n,'", "').concat(t,'"'));i.set(d.oneof,t)}ke(r,c,d,n,e)}else{let i=!1;if((null==a?void 0:a.findExtension)&&t.startsWith("[")&&t.endsWith("]")){const o=a.findExtension(t.substring(1,t.length-1));if(o&&o.extendee.typeName==e.typeName){i=!0;const e=$(te(o),2),t=e[0],a=e[1];ke(t,c,o.field,n,o),oe(r,o,a(),n)}}if(!i&&!n.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(t,'" is unknown'))}}return r},writeMessage(e,t){const n=e.getType(),r={};let i;try{for(i of n.fields.byNumber()){if(!de(i,e)){if(i.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!Se(i))continue}const n=Ee(i,i.oneof?e[i.oneof.localName].value:e[i.localName],t);void 0!==n&&(r[t.useProtoFieldName?i.name:i.jsonName]=n)}const a=t.typeRegistry;if(null==a?void 0:a.findExtensionFor)for(const i of n.runtime.bin.listUnknownFields(e)){const o=a.findExtensionFor(n.typeName,i.no);if(o&&se(e,o)){const n=ae(e,o,t),i=Ee(o.field,n,t);void 0!==i&&(r[o.field.jsonName]=i)}}}catch(e){const t=i?"cannot encode field ".concat(n.typeName,".").concat(i.name," to JSON"):"cannot encode message ".concat(n.typeName," to JSON"),r=e instanceof Error?e.message:String(e);throw new Error(t+(r.length>0?": ".concat(r):""))}return r},readScalar:(e,t,n)=>we(e,t,null!=n?n:J.BIGINT,!0),writeScalar(e,t,n){if(void 0!==t)return n||Y(e,t)?Ae(e,t):void 0},debug:be},bin:{makeReadOptions:Oe,makeWriteOptions:Re,listUnknownFields(e){var t;return null!==(t=e[Ce])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[Ce]},writeUnknownFields(e,t){const n=e[Ce];if(n)for(const e of n)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,n,r){const i=e;Array.isArray(i[Ce])||(i[Ce]=[]),i[Ce].push({no:t,wireType:n,data:r})},readMessage(e,t,n,r,i){const a=e.getType(),o=i?t.len:t.pos+n;let s,c;for(;t.pos<o;){var d=$(t.tag(),2);if(s=d[0],c=d[1],!0===i&&c==X.EndGroup)break;const n=a.fields.find(s);if(n)De(e,t,n,c,r);else{const n=t.skip(c,s);r.readUnknownFields&&this.onUnknownField(e,s,c,n)}}if(i&&(c!=X.EndGroup||s!==n))throw new Error("invalid end group tag")},readField:De,writeMessage(e,t,n){const r=e.getType();for(const i of r.fields.byNumber())if(de(i,e))xe(i,i.oneof?e[i.oneof.localName].value:e[i.localName],t,n);else if(i.req)throw new Error("cannot encode field ".concat(r.typeName,".").concat(i.name," to binary: required field not set"));return n.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,n,r){void 0!==t&&xe(e,t,n,r)}},util:Object.assign(Object.assign({},{setEnumType:L,initPartial(e,t){if(void 0===e)return;const n=t.getType();for(const i of n.fields.byMember()){const n=i.localName,a=t,o=e;if(null!=o[n])switch(i.kind){case"oneof":const e=o[n].case;if(void 0===e)continue;const t=i.findField(e);let s=o[n].value;t&&"message"==t.kind&&!le(s,t.T)?s=new t.T(s):t&&"scalar"===t.kind&&t.T===G.BYTES&&(s=qe(s)),a[n]={case:e,value:s};break;case"scalar":case"enum":let c=o[n];i.T===G.BYTES&&(c=i.repeated?c.map(qe):qe(c)),a[n]=c;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===G.BYTES)for(const e of Object.entries(o[n])){var r=$(e,2);const t=r[0],i=r[1];a[n][t]=qe(i)}else Object.assign(a[n],o[n]);break;case"message":const e=i.V.T;for(const t of Object.keys(o[n])){let r=o[n][t];e.fieldWrapper||(r=new e(r)),a[n][t]=r}}break;case"message":const d=i.T;if(i.repeated)a[n]=o[n].map((e=>le(e,d)?e:new d(e)));else{const e=o[n];d.fieldWrapper?"google.protobuf.BytesValue"===d.typeName?a[n]=qe(e):a[n]=e:a[n]=le(e,d)?e:new d(e)}}}},equals:(e,t,n)=>t===n||!(!t||!n)&&e.fields.byMember().every((e=>{const r=t[e.localName],i=n[e.localName];if(e.repeated){if(r.length!==i.length)return!1;switch(e.kind){case"message":return r.every(((t,n)=>e.T.equals(t,i[n])));case"scalar":return r.every(((t,n)=>H(e.T,t,i[n])));case"enum":return r.every(((e,t)=>H(G.INT32,e,i[t])))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":let t=r,n=i;return e.T.fieldWrapper&&(void 0===t||le(t)||(t=e.T.fieldWrapper.wrapField(t)),void 0===n||le(n)||(n=e.T.fieldWrapper.wrapField(n))),e.T.equals(t,n);case"enum":return H(G.INT32,r,i);case"scalar":return H(e.T,r,i);case"oneof":if(r.case!==i.case)return!1;const a=e.findField(r.case);if(void 0===a)return!0;switch(a.kind){case"message":return a.T.equals(r.value,i.value);case"enum":return H(G.INT32,r.value,i.value);case"scalar":return H(a.T,r.value,i.value)}throw new Error("oneof cannot contain ".concat(a.kind));case"map":const o=Object.keys(r).concat(Object.keys(i));switch(e.V.kind){case"message":const t=e.V.T;return o.every((e=>t.equals(r[e],i[e])));case"enum":return o.every((e=>H(G.INT32,r[e],i[e])));case"scalar":const n=e.V.T;return o.every((e=>H(n,r[e],i[e])))}}})),clone(e){const t=e.getType(),n=new t,r=n;for(const n of t.fields.byMember()){const t=e[n.localName];let a;if(n.repeated)a=t.map(Ve);else if("map"==n.kind){a=r[n.localName];for(const e of Object.entries(t)){var i=$(e,2);const t=i[0],n=i[1];a[t]=Ve(n)}}else a="oneof"==n.kind?n.findField(t.case)?{case:t.case,value:Ve(t.value)}:{case:void 0}:Ve(t);r[n.localName]=a}for(const n of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(r,n.no,n.wireType,n.data);return n}}),{newFieldList:tt,initFields:nt}),makeMessageType(e,t,n){return function(e,t,n,r){var i;const a=null!==(i=null==r?void 0:r.localName)&&void 0!==i?i:t.substring(t.lastIndexOf(".")+1),o={[a]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[a];return Object.setPrototypeOf(o.prototype,new D),Object.assign(o,{runtime:e,typeName:t,fields:e.util.newFieldList(n),fromBinary:(e,t)=>(new o).fromBinary(e,t),fromJson:(e,t)=>(new o).fromJson(e,t),fromJsonString:(e,t)=>(new o).fromJsonString(e,t),equals:(t,n)=>e.util.equals(o,t,n)}),o}(this,e,t,n)},makeEnum:O,makeEnumType:U,getEnumType:C,makeExtension(e,t,n){return function(e,t,n,r){let i;return{typeName:t,extendee:n,get field(){if(!i){const n="function"==typeof r?r():r;n.name=t.split(".").pop(),n.jsonName="[".concat(t,"]"),i=e.util.newFieldList([n]).list()[0]}return i},runtime:e}}(this,e,t,n)}});var tt,nt;const rt=et.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),it=et.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"}]),at=et.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]);class ot extends Error{constructor(e,t,n){super(t||"an error has occurred"),this.name="LiveKitError",this.code=e,void 0!==(null==n?void 0:n.cause)&&(this.cause=null==n?void 0:n.cause)}}var st,ct,dt,ut,lt,ht,ft,pt,yt,mt;!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",e[e.WebSocket=6]="WebSocket",e[e.ServiceNotFound=7]="ServiceNotFound"}(st||(st={})),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",e[e.EncryptionTypeMismatch=8]="EncryptionTypeMismatch",e[e.HeaderTooLarge=9]="HeaderTooLarge",e[e.PayloadTooLarge=10]="PayloadTooLarge"}(ct||(ct={})),function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"}(dt||(dt={})),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}}(dt||(dt={})),function(e){e[e.InvalidKey=0]="InvalidKey",e[e.MissingKey=1]="MissingKey",e[e.InternalError=2]="InternalError"}(ut||(ut={}));class gt extends ot{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ut.InternalError,n=arguments.length>2?arguments[2]:void 0;super(40,e),this.reason=t,this.participantIdentity=n}}!function(e){e.SetKey="setKey",e.RatchetRequest="ratchetRequest",e.KeyRatcheted="keyRatcheted"}(lt||(lt={})),function(e){e.KeyRatcheted="keyRatcheted"}(ht||(ht={})),function(e){e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError"}(ft||(ft={})),function(e){e.Error="cryptorError"}(pt||(pt={}));class vt extends(mt=Promise){constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}}yt=vt,vt.resolve=e=>Reflect.get(mt,"resolve",yt).call(yt,e);const bt=/version\/(\d+(\.?_?\d+)+)/i;let kt;function Tt(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if("undefined"==typeof navigator)return;const n=navigator.userAgent.toLowerCase();if(void 0===kt||t){const e=wt.find((e=>e.test.test(n)));kt=null==e?void 0:e.describe(n)}return kt}const wt=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:It(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:St(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:It(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:St(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:It(bt,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:St(e)})}];function It(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;const r=t.match(e);return r&&r.length>=n&&r[n]||""}function St(e){return e.includes("mac os")?It(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}var Et,Nt={exports:{}};var At,Ct,Lt,Ut,Ot=function(){if(Et)return Nt.exports;Et=1;var e,t="object"==typeof Reflect?Reflect:null,n=t&&"function"==typeof t.apply?t.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};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 r=Number.isNaN||function(e){return e!=e};function i(){i.init.call(this)}Nt.exports=i,Nt.exports.once=function(e,t){return new Promise((function(n,r){function i(n){e.removeListener(t,a),r(n)}function a(){"function"==typeof e.removeListener&&e.removeListener("error",i),n([].slice.call(arguments))}p(e,t,a,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&p(e,"error",t,n)}(e,i,{once:!0})}))},i.EventEmitter=i,i.prototype._events=void 0,i.prototype._eventsCount=0,i.prototype._maxListeners=void 0;var a=10;function o(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function s(e){return void 0===e._maxListeners?i.defaultMaxListeners:e._maxListeners}function c(e,t,n,r){var i,a,c,d;if(o(n),void 0===(a=e._events)?(a=e._events=Object.create(null),e._eventsCount=0):(void 0!==a.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),a=e._events),c=a[t]),void 0===c)c=a[t]=n,++e._eventsCount;else if("function"==typeof c?c=a[t]=r?[n,c]:[c,n]:r?c.unshift(n):c.push(n),(i=s(e))>0&&c.length>i&&!c.warned){c.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=c.length,d=u,console&&console.warn&&console.warn(d)}return e}function d(){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 u(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=d.bind(r);return i.listener=n,r.wrapFn=i,i}function l(e,t,n){var r=e._events;if(void 0===r)return[];var i=r[t];return void 0===i?[]:"function"==typeof i?n?[i.listener||i]:[i]:n?function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(i):f(i,i.length)}function h(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function f(e,t){for(var n=new Array(t),r=0;r<t;++r)n[r]=e[r];return n}function p(e,t,n,r){if("function"==typeof e.on)r.once?e.once(t,n):e.on(t,n);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function i(a){r.once&&e.removeEventListener(t,i),n(a)}))}}return Object.defineProperty(i,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(e){if("number"!=typeof e||e<0||r(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");a=e}}),i.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},i.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||r(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},i.prototype.getMaxListeners=function(){return s(this)},i.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var i="error"===e,a=this._events;if(void 0!==a)i=i&&void 0===a.error;else if(!i)return!1;if(i){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var s=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw s.context=o,s}var c=a[e];if(void 0===c)return!1;if("function"==typeof c)n(c,this,t);else{var d=c.length,u=f(c,d);for(r=0;r<d;++r)n(u[r],this,t)}return!0},i.prototype.addListener=function(e,t){return c(this,e,t,!1)},i.prototype.on=i.prototype.addListener,i.prototype.prependListener=function(e,t){return c(this,e,t,!0)},i.prototype.once=function(e,t){return o(t),this.on(e,u(this,e,t)),this},i.prototype.prependOnceListener=function(e,t){return o(t),this.prependListener(e,u(this,e,t)),this},i.prototype.removeListener=function(e,t){var n,r,i,a,s;if(o(t),void 0===(r=this._events))return this;if(void 0===(n=r[e]))return this;if(n===t||n.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(i=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){s=n[a].listener,i=a;break}if(i<0)return this;0===i?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,i),1===n.length&&(r[e]=n[0]),void 0!==r.removeListener&&this.emit("removeListener",e,s||t)}return this},i.prototype.off=i.prototype.removeListener,i.prototype.removeAllListeners=function(e){var t,n,r;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var i,a=Object.keys(n);for(r=0;r<a.length;++r)"removeListener"!==(i=a[r])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(void 0!==t)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this},i.prototype.listeners=function(e){return l(this,e,!0)},i.prototype.rawListeners=function(e){return l(this,e,!1)},i.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},i.prototype.listenerCount=h,i.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},Nt.exports}();function Rt(e){const t={};for(const r of Object.entries(e)){var n=$(r,2);const e=n[0],i=n[1];void 0!==i&&(t[e]=i)}return t}function Dt(e,t){return e&&t?"".concat(e,"x").concat(t):void 0}function Ft(e){return Math.round(1e4*e)/1e4}function Pt(e){const t=e.jitterBufferDelay,n=e.jitterBufferEmittedCount;return void 0!==t&&n?Ft(t/n):void 0}function _t(e,t){if(void 0!==e.playoutDelay)return Ft(e.playoutDelay);const n=null==t?void 0:t.totalPlayoutDelay,r=null==t?void 0:t.totalSamplesCount;return void 0!==n&&r?Ft(n/r):void 0}!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",e.DataTrackPublished="dataTrackPublished",e.DataTrackUnpublished="dataTrackUnpublished",e.LocalDataTrackPublished="localDataTrackPublished",e.LocalDataTrackUnpublished="localDataTrackUnpublished"}(At||(At={})),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"}(Ct||(Ct={})),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.PublishDataTrackResponse="publishDataTrackResponse",e.UnPublishDataTrackResponse="unPublishDataTrackResponse",e.DataTrackSubscriberHandles="dataTrackSubscriberHandles",e.DataTrackPacketReceived="dataTrackPacketReceived",e.Joined="joined",e.TokenRefreshed="tokenRefreshed",e.ServerRegionsReported="serverRegionsReported",e.RequestSubscribedCodecRefresh="requestSubscribedCodecRefresh"}(Lt||(Lt={})),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"}(Ut||(Ut={}));const xt=["vp8","h264","vp9","av1","h265"];var Mt,Bt;function jt(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?jt(e.track):{})}}!function(e){e[e.PREFER_REGRESSION=0]="PREFER_REGRESSION",e[e.SIMULCAST=1]="SIMULCAST",e[e.REGRESSION=2]="REGRESSION"}(Mt||(Mt={})),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}}(Bt||(Bt={}));const Kt=[];var Vt;!function(e){e[e.LOW=0]="LOW",e[e.MEDIUM=1]="MEDIUM",e[e.HIGH=2]="HIGH"}(Vt||(Vt={}));class qt extends Ot.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState!==e&&this.log.debug("stream state changed: ".concat(this._streamState," -> ").concat(e)),this._streamState=e}constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var r;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=qt.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.finalStatsLogged=!1,this.log=l,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.loggerContextCb=n.loggerContextCb,this.log=h(null!==(r=n.loggerName)&&void 0!==r?r:c.Track,(()=>this.logContext)),this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=qt.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),jt(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===qt.Kind.Video&&(t="video"),0===this.attachedElements.length&&this.kind===qt.Kind.Video&&this.addAppVisibilityListener(),e||("audio"===t&&(Kt.forEach((t=>{null!==t.parentElement||e||(e=t)})),e&&Kt.splice(Kt.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),function(e,t){let n,r;n=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream;r="audio"===e.kind?n.getAudioTracks():n.getVideoTracks();r.includes(e)||(r.forEach((e=>{n.removeTrack(e)})),n.addTrack(e));Gt()&&t instanceof HTMLVideoElement||(t.autoplay=!0);t.muted=0===n.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0);t.srcObject!==n&&(t.srcObject=n,(Gt()||function(){var e;return"Firefox"===(null===(e=Tt())||void 0===e?void 0:e.name)}())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=n,t.play().catch((()=>{}))}),0))}(this.mediaStreamTrack,e);const n=e.srcObject.getTracks(),r=n.some((e=>"audio"===e.kind));return e.play().then((()=>{this.emit(r?Ut.AudioPlaybackStarted:Ut.VideoPlaybackStarted)})).catch((t=>{"NotAllowedError"===t.name?this.emit(r?Ut.AudioPlaybackFailed:Ut.VideoPlaybackFailed,t):"AbortError"===t.name?this.log.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):this.log.warn("could not playback ".concat(r?"audio":"video"),{error:t}),r&&e&&n.some((e=>"video"===e.kind))&&"NotAllowedError"===t.name&&(e.muted=!0,e.play().catch((()=>{})))})),this.emit(Ut.ElementAttached,e),e}detach(e){try{if(e){Wt(this.mediaStreamTrack,e);const t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(Ut.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach((e=>{Wt(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(Ut.ElementDetached,e)})),this.attachedElements=[],t}finally{0===this.attachedElements.length&&this.removeAppVisibilityListener()}}stop(){this.log.debug("stopping track"),this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),void 0!==this.timeSyncHandle&&(cancelAnimationFrame(this.timeSyncHandle),this.timeSyncHandle=void 0),this.logFinalStats()}logFinalStats(){this.finalStatsLogged||(this.finalStatsLogged=!0,this.getRTCStatsReport().then((e=>{e&&this.log.info("final track stats",function(e){var t,n;const r=new Map,i=[],a=[],o=[];let s;e.forEach((e=>r.set(e.id,e)));const c=e=>{var t;return e.codecId?null===(t=r.get(e.codecId))||void 0===t?void 0:t.mimeType:void 0},d=(e,t)=>e[t]?r.get(e[t]):void 0;e.forEach((e=>{switch(e.type){case"inbound-rtp":{const t=d(e,"playoutId");a.push(Rt({kind:e.kind,ssrc:e.ssrc,mid:e.mid,trackId:e.trackIdentifier,codec:c(e),decoder:e.decoderImplementation,resolution:Dt(e.frameWidth,e.frameHeight),fps:e.framesPerSecond,bytesReceived:e.bytesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,packetsDiscarded:e.packetsDiscarded,framesReceived:e.framesReceived,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,keyFramesDecoded:e.keyFramesDecoded,freezeCount:e.freezeCount,totalFreezesDuration:e.totalFreezesDuration,pauseCount:e.pauseCount,nackCount:e.nackCount,pliCount:e.pliCount,firCount:e.firCount,jitter:e.jitter,jitterBuffer:Pt(e),playoutDelay:_t(e,t),audioLevel:e.audioLevel,totalSamplesReceived:e.totalSamplesReceived,concealedSamples:e.concealedSamples}));break}case"outbound-rtp":{const t=d(e,"remoteId"),n=d(e,"mediaSourceId");o.push(Rt({kind:e.kind,ssrc:e.ssrc,mid:e.mid,rid:e.rid,trackId:null==n?void 0:n.trackIdentifier,active:e.active,codec:c(e),encoder:e.encoderImplementation,resolution:Dt(e.frameWidth,e.frameHeight),fps:e.framesPerSecond,captureResolution:Dt(null==n?void 0:n.width,null==n?void 0:n.height),captureFps:null==n?void 0:n.framesPerSecond,audioLevel:null==n?void 0:n.audioLevel,targetBitrate:e.targetBitrate,bytesSent:e.bytesSent,packetsSent:e.packetsSent,retransmittedPacketsSent:e.retransmittedPacketsSent,framesEncoded:e.framesEncoded,keyFramesEncoded:e.keyFramesEncoded,limitedBy:"none"===e.qualityLimitationReason?void 0:e.qualityLimitationReason,nackCount:e.nackCount,pliCount:e.pliCount,firCount:e.firCount,remotePacketsLost:null==t?void 0:t.packetsLost,remoteFractionLost:null==t?void 0:t.fractionLost,remoteJitter:null==t?void 0:t.jitter,remoteRoundTripTime:null==t?void 0:t.roundTripTime}));break}case"transport":s=e;break;case"candidate-pair":i.push(e)}}));const u=null==s?void 0:s.selectedCandidatePairId,l=null!==(n=null!==(t=u?r.get(u):void 0)&&void 0!==t?t:i.find((e=>e.selected)))&&void 0!==n?n:i.find((e=>e.nominated)),h=(null==l?void 0:l.localCandidateId)?r.get(l.localCandidateId):void 0,f=(null==l?void 0:l.remoteCandidateId)?r.get(l.remoteCandidateId):void 0,p=Rt({ice:null==s?void 0:s.iceState,dtls:null==s?void 0:s.dtlsState,route:h&&f?"".concat(h.candidateType,"/").concat(h.protocol," -> ").concat(f.candidateType):void 0,network:null==h?void 0:h.networkType,currentRoundTripTime:null==l?void 0:l.currentRoundTripTime,availableOutgoingBitrate:null==l?void 0:l.availableOutgoingBitrate,availableIncomingBitrate:null==l?void 0:l.availableIncomingBitrate,bytesSent:null==l?void 0:l.bytesSent,bytesReceived:null==l?void 0:l.bytesReceived,candidatePairChanges:null==s?void 0:s.selectedCandidatePairChanges});return{connection:Object.keys(p).length>0?p:void 0,outbound:o.length>0?o:void 0,inbound:a.length>0?a:void 0}}(e))})).catch((e=>this.log.debug("could not collect final track stats",{error:e}))))}updateLoggerOptions(e){e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb),e.loggerName&&(this.log=h(e.loggerName,(()=>this.logContext)))}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Kt.forEach((e=>{e.parentElement||(t=!1)})),t&&Kt.push(e)}}handleAppVisibilityChanged(){return e(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==qt.Kind.Video||setTimeout((()=>this.attachedElements.forEach((e=>e.play().catch((()=>{}))))),0)}))}addAppVisibilityListener(){Jt()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Jt()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Wt(e,t){if(t.srcObject instanceof MediaStream){const n=t.srcObject;"audio"===e.kind&&function(){const e=Tt();return!!e&&"Chrome"===e.name&&"iOS"!==e.os}()&&(t.srcObject=null),n.removeTrack(e),n.getTracks().length>0?t.srcObject=n:t.srcObject=null}}function Gt(){var e;return"Safari"===(null===(e=Tt())||void 0===e?void 0:e.name)}function Jt(){return"undefined"!=typeof document}function Xt(e,t){return e instanceof Error?e.name&&e.message?"".concat(e.name,": ").concat(e.message):e.name:"Encountered unknown ".concat(t," error: ").concat(String(e))}function Ht(e){return"type"in e}function zt(e,t){const n=(new TextEncoder).encode(t);switch(e){case"HKDF":return{name:"HKDF",salt:n,hash:"SHA-256",info:new ArrayBuffer(128)};case"PBKDF2":return{name:"PBKDF2",salt:n,hash:"SHA-256",iterations:1e5};default:throw new Error("algorithm ".concat(e," is currently unsupported"))}}function Yt(t,n){return e(this,void 0,void 0,(function*(){const e=zt(t.algorithm.name,n.ratchetSalt),r=yield crypto.subtle.deriveKey(e,t,{name:k,length:n.keySize},!1,["encrypt","decrypt"]);return{material:t,encryptionKey:r}}))}function Qt(e){const t=[];for(var n=e.length,r=0;r<e.length;)n-r>=3&&!e[r]&&!e[r+1]&&3==e[r+2]?(t.push(e[r++]),t.push(e[r++]),r++):t.push(e[r++]);return new Uint8Array(t)}!function(e){let t,n,r;!function(e){e.Audio="audio",e.Video="video",e.Unknown="unknown"}(t=e.Kind||(e.Kind={})),function(e){e.Camera="camera",e.Microphone="microphone",e.ScreenShare="screen_share",e.ScreenShareAudio="screen_share_audio",e.Unknown="unknown"}(n=e.Source||(e.Source={})),function(e){e.Active="active",e.Paused="paused",e.Unknown="unknown"}(r=e.StreamState||(e.StreamState={})),e.kindToProto=function(e){switch(e){case t.Audio:return rt.AUDIO;case t.Video:return rt.VIDEO;default:return rt.DATA}},e.kindFromProto=function(e){switch(e){case rt.AUDIO:return t.Audio;case rt.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case n.Camera:return it.CAMERA;case n.Microphone:return it.MICROPHONE;case n.ScreenShare:return it.SCREEN_SHARE;case n.ScreenShareAudio:return it.SCREEN_SHARE_AUDIO;default:return it.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case it.CAMERA:return n.Camera;case it.MICROPHONE:return n.Microphone;case it.SCREEN_SHARE:return n.ScreenShare;case it.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}},e.streamStateFromProto=function(e){switch(e){case at.ACTIVE:return r.Active;case at.PAUSED:return r.Paused;default:return r.Unknown}}}(qt||(qt={}));function $t(e){const t=[];let n=0;for(let r=0;r<e.length;++r){const i=e[r];i<=3&&n>=2&&(t.push(r),n=0),n=0===i?n+1:0}if(0===t.length)return e;const r=new Uint8Array(e.length+t.length);let i=0;for(let n=0;n<t.length;++n)r.set(e.subarray(i,t[n]),i+n),r[t[n]+n]=3,i=t[n];return r.set(e.subarray(i),i+t.length),r}class Zt{static makeIV(e){const t=new ArrayBuffer(12),n=new DataView(t),r=crypto.getRandomValues(new Uint32Array(1));return n.setUint32(0,r[0]),n.setUint32(4,e),n.setUint32(8,e-Zt.sendCount%65535),Zt.sendCount++,t}static encrypt(t,n){return e(this,void 0,void 0,(function*(){const e=Zt.makeIV(performance.now()),r=yield n.getKeySet();if(!r)throw new Error("No key set found");const i=yield crypto.subtle.encrypt({name:k,iv:e},r.encryptionKey,new Uint8Array(t));return{payload:new Uint8Array(i),iv:new Uint8Array(e),keyIndex:n.getCurrentKeyIndex()}}))}static decrypt(t,n,r){return e(this,arguments,void 0,(function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,i=arguments.length>4?arguments[4]:void 0,a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{ratchetCount:0};return function*(){var o;const s=yield n.getKeySet(r);if(!s)throw new Error("No key set found");try{const n=yield crypto.subtle.decrypt({name:k,iv:t},null!==(o=a.encryptionKey)&&void 0!==o?o:s.encryptionKey,new Uint8Array(e));return{payload:new Uint8Array(n)}}catch(o){if(n.keyProviderOptions.ratchetWindowSize>0){if(a.ratchetCount<n.keyProviderOptions.ratchetWindowSize){let o,c;f.debug("DataCryptor: ratcheting key attempt ".concat(a.ratchetCount," of ").concat(n.keyProviderOptions.ratchetWindowSize,", for data packet")),(null!=i?i:s)===n.getKeySet(r)&&(c=yield n.ratchetKey(r,!1),o=yield Yt(c.cryptoKey,n.keyProviderOptions));const d=yield Zt.decrypt(e,t,n,r,null!=i?i:s,{ratchetCount:a.ratchetCount+1,encryptionKey:null==o?void 0:o.encryptionKey});return d&&o&&(null!=i?i:s)===n.getKeySet(r)&&(n.setKeySet(o,r,c),n.setCurrentKeyIndex(r)),d}throw f.warn("DataCryptor: maximum ratchet attempts exceeded"),new gt("DataCryptor: valid key missing for participant ".concat(n.participantIdentity),ut.InvalidKey,n.participantIdentity)}throw new gt("DataCryptor: Decryption failed: ".concat(Xt(o,"decryption")),ut.InvalidKey,n.participantIdentity)}}()}))}}Zt.sendCount=0;class en{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:6e4,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:5;this.throttleMs=e,this.windowMs=t,this.maxPerWindow=n,this.lastAt=new Map,this.counts=new Map}reset(){this.lastAt.clear(),this.counts.clear()}countFor(e){var t;return null!==(t=this.counts.get(e))&&void 0!==t?t:0}shouldEmit(e,t){var n,r;const i=Date.now(),a=null!==(n=this.lastAt.get(e))&&void 0!==n?n:0,o=null!==(r=this.counts.get(e))&&void 0!==r?r:0;return i-a>this.windowMs?(this.counts.set(e,0),this.lastAt.set(e,i),!0):!(i-a<this.throttleMs)&&(o>=this.maxPerWindow?(o===this.maxPerWindow&&(null==t||t(),this.counts.set(e,o+1)),!1):(this.lastAt.set(e,i),this.counts.set(e,o+1),!0))}}function tn(e){return!(!(null==e?void 0:e.timestamp)&&!(null==e?void 0:e.frameId))}const nn=Uint8Array.from(["L".charCodeAt(0),"K".charCodeAt(0),"T".charCodeAt(0),"S".charCodeAt(0)]);function rn(e,t,n){const r=t!==BigInt(0),i=0!==n;if(!r&&!i)return e;const a=(r?10:0)+(i?6:0)+5,o=new Uint8Array(e.length+a);let s=0;return o.set(e,s),s+=e.length,r&&(o[s++]=254,o[s++]=247,function(e,t,n){const r=Number(n>>BigInt(32)&BigInt(4294967295)),i=Number(n&BigInt(4294967295));e[t]=r>>>24^255,e[t+1]=r>>>16&255^255,e[t+2]=r>>>8&255^255,e[t+3]=255&r^255,e[t+4]=i>>>24^255,e[t+5]=i>>>16&255^255,e[t+6]=i>>>8&255^255,e[t+7]=255&i^255}(o,s,t),s+=8),i&&(o[s++]=253,o[s++]=251,function(e,t,n){for(let r=3;r>=0;r-=1)e[t+(3-r)]=n>>8*r&255^255}(o,s,n),s+=4),o[s++]=255^a,o.set(nn,s),o}function an(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);if(t.length<5)return{data:t};if(!function(e,t){for(let n=0;n<nn.length;n+=1)if(e[t+n]!==nn[n])return!1;return!0}(t,t.length-nn.length))return{data:t};const n=255^t[t.length-5];if(n<5||n>t.length)return{data:t};const r=t.length-n,i=t.length-5,a=t.subarray(0,r);let o=r,s=!1;const c={userTimestamp:BigInt(0),frameId:0};for(;o+2<=i;){const e=255^t[o++],n=255^t[o++];if(o+n>i)break;if(1===e&&8===n)c.userTimestamp=on(t,o),s=!0;else if(2===e&&4===n)c.frameId=sn(t,o,n),s=!0;else if(3===e){const e=new Uint8Array(n);for(let r=0;r<n;r+=1)e[r]=255^t[o+r];c.userData=e,s=!0}o+=n}return s?{data:a,metadata:c}:{data:t}}function on(e,t){const n=BigInt(((255^e[t])<<24|(255^e[t+1])<<16|(255^e[t+2])<<8|255^e[t+3])>>>0),r=BigInt(((255^e[t+4])<<24|(255^e[t+5])<<16|(255^e[t+6])<<8|255^e[t+7])>>>0);return n<<BigInt(32)|r}function sn(e,t,n){let r=0;for(let i=0;i<n;i+=1)r=r<<8|255^e[t+i];return r>>>0}function cn(e){try{const t=e.getMetadata();if("number"==typeof t.synchronizationSource)return t.synchronizationSource}catch(e){}return 0}var dn,un;function ln(e){return 31&e}function hn(e){return e>>1&63}function fn(e){return e===dn.SLICE_IDR||e===dn.SLICE_NON_IDR}function pn(e){return e===un.TRAIL_N||e===un.TRAIL_R||e===un.TSA_N||e===un.TSA_R||e===un.STSA_N||e===un.STSA_R||e===un.RADL_N||e===un.RADL_R||e===un.RASL_N||e===un.RASL_R||e===un.BLA_W_LP||e===un.BLA_W_RADL||e===un.BLA_N_LP||e===un.IDR_W_RADL||e===un.IDR_N_LP||e===un.CRA_NUT}function yn(e){if(ln(e[0])!==dn.SLICE_IDR)return null;const t=Qt(e.subarray(1,17)),n=8*t.length;let r=0;const i=()=>t[r>>3]>>7-(7&r++)&1,a=()=>{let e=0;for(;0===i()&&r<n;)e++;let t=1;for(let n=0;n<e;n++)t=2*t+i();return t-1};a(),a();const o=a();return r<=n?o:null}function mn(e,t){const n=function(e){const t=[];let n=0,r=0,i=e.length-3;for(;r<i;){for(;r<i&&!(r<i-1&&0===e[r]&&0===e[r+1]&&0===e[r+2]&&1===e[r+3])&&(0!==e[r]||0!==e[r+1]||1!==e[r+2]);)r++;r>=i&&(r=e.length);let a=r;for(;a>n&&0===e[a-1];)a--;if(0===n){if(a!==n)throw TypeError("byte stream contains leading data")}else t.push(n);let o=3;r<e.length-3&&0===e[r]&&0===e[r+1]&&0===e[r+2]&&1===e[r+3]&&(o=4),n=r+=o}return t}(e);let r=function(e,t){for(const n of t)if(fn(ln(e[n])))return"h264";for(const n of t)if(pn(hn(e[n])))return"h265";return"unknown"}(e,n);if("unknown"===r&&(r=null!=t?t:"unknown"),"unknown"===r)return{unencryptedBytes:0,detectedCodec:r,requiresNALUProcessing:!1};const i=function(e,t,n){for(const r of t)if("h265"===n){if(pn(hn(e[r])))return r+2}else if(fn(ln(e[r])))return r+2;return null}(e,n,r);if(null===i)throw new TypeError("Could not find NALU");return{unencryptedBytes:i,detectedCodec:r,requiresNALUProcessing:!0}}!function(e){e[e.SLICE_NON_IDR=1]="SLICE_NON_IDR",e[e.SLICE_PARTITION_A=2]="SLICE_PARTITION_A",e[e.SLICE_PARTITION_B=3]="SLICE_PARTITION_B",e[e.SLICE_PARTITION_C=4]="SLICE_PARTITION_C",e[e.SLICE_IDR=5]="SLICE_IDR",e[e.SEI=6]="SEI",e[e.SPS=7]="SPS",e[e.PPS=8]="PPS",e[e.AUD=9]="AUD",e[e.END_SEQ=10]="END_SEQ",e[e.END_STREAM=11]="END_STREAM",e[e.FILLER_DATA=12]="FILLER_DATA",e[e.SPS_EXT=13]="SPS_EXT",e[e.PREFIX_NALU=14]="PREFIX_NALU",e[e.SUBSET_SPS=15]="SUBSET_SPS",e[e.DPS=16]="DPS",e[e.SLICE_AUX=19]="SLICE_AUX",e[e.SLICE_EXT=20]="SLICE_EXT",e[e.SLICE_LAYER_EXT=21]="SLICE_LAYER_EXT"}(dn||(dn={})),function(e){e[e.TRAIL_N=0]="TRAIL_N",e[e.TRAIL_R=1]="TRAIL_R",e[e.TSA_N=2]="TSA_N",e[e.TSA_R=3]="TSA_R",e[e.STSA_N=4]="STSA_N",e[e.STSA_R=5]="STSA_R",e[e.RADL_N=6]="RADL_N",e[e.RADL_R=7]="RADL_R",e[e.RASL_N=8]="RASL_N",e[e.RASL_R=9]="RASL_R",e[e.BLA_W_LP=16]="BLA_W_LP",e[e.BLA_W_RADL=17]="BLA_W_RADL",e[e.BLA_N_LP=18]="BLA_N_LP",e[e.IDR_W_RADL=19]="IDR_W_RADL",e[e.IDR_N_LP=20]="IDR_N_LP",e[e.CRA_NUT=21]="CRA_NUT",e[e.VPS_NUT=32]="VPS_NUT",e[e.SPS_NUT=33]="SPS_NUT",e[e.PPS_NUT=34]="PPS_NUT",e[e.AUD_NUT=35]="AUD_NUT",e[e.EOS_NUT=36]="EOS_NUT",e[e.EOB_NUT=37]="EOB_NUT",e[e.FD_NUT=38]="FD_NUT",e[e.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",e[e.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"}(un||(un={}));const gn="ef0161653d8b2b23aad46624b420af1d03ce48950e9fc85718028f91b50f9219",vn="f0a0e09647d891d6d50aa898bce7108090375d0d55e50a2bb21147afee558e44",bn="61d9665eed71b6d424ae9539330a3bdd5cb386d4d781c808219a6e36750493a7",kn="faffc26b68a2fc09096fa20f3351e706398b6f838a7500c8063472c2e476e90d",Tn="aad8d31fc56b2802ca500e58c2fb9d0b29ad71bb7cb52cd6530251eade188988";function wn(t){return e(this,void 0,void 0,(function*(){const n=yield function(t){return e(this,void 0,void 0,(function*(){const e=yield crypto.subtle.digest("SHA-256",t),n=new Uint8Array(e);return Array.from(n).map((e=>e.toString(16).padStart(2,"0"))).join("")}))}(t);switch(n){case gn:return"vp8";case vn:case bn:case kn:return"h264";case Tn:return"opus";default:return null}}))}let In;class Sn extends Ot.EventEmitter{encodeFunction(e,t){throw Error("not implemented for subclass")}decodeFunction(e,t){throw Error("not implemented for subclass")}}class En extends Sn{constructor(e){var t;super(),this.hasFrameMetadata=!1,this.frameMetadataFrameId=0,this.errorLimiter=new en,this.UNDECRYPTED_TRACK_GRACE_MS=2e3,this.loggedNALUFallbacks=new Set,this.sendCounts=new Map,this.keys=e.keys,this.participantIdentity=e.participantIdentity,this.rtpMap=new Map,this.keyProviderOptions=e.keyProviderOptions,this.sifTrailer=null!==(t=e.sifTrailer)&&void 0!==t?t:Uint8Array.from([])}get logContext(){return{participant:this.participantIdentity,mediaTrackId:this.trackId,fallbackCodec:this.videoCodec}}setParticipant(e,t){f.debug("setting new participant on cryptor",Object.assign(Object.assign({},this.logContext),{newParticipant:e,hadPreviousParticipant:!!this.participantIdentity})),this.participantIdentity&&this.participantIdentity!==e&&(f.warn("cryptor has already a participant set, cleaning up before switching",{oldParticipant:this.participantIdentity,newParticipant:e,trackId:this.trackId}),this.unsetParticipant()),this.participantIdentity=e,this.keys=t}unsetParticipant(){f.debug("unsetting participant",this.logContext),clearTimeout(this.undecryptedTrackTimeout),this.undecryptedTrackTimeout=void 0,this.participantIdentity=void 0,this.encrypted=void 0,this.errorLimiter.reset()}setEncrypted(e){this.encrypted=e}isEnabled(){return this.participantIdentity?this.encrypted:void 0}getParticipantIdentity(){return this.participantIdentity}getTrackId(){return this.trackId}setTrackId(e){this.trackId!==e&&(f.debug("re-pointing cryptor at new trackId",Object.assign(Object.assign({},this.logContext),{newTrackId:e})),this.trackId=e)}hasActiveTransform(){return!!this.currentTransform}scheduleUndecryptedTrackWatchdog(e){clearTimeout(this.undecryptedTrackTimeout),this.undecryptedTrackTimeout=void 0,"decode"===e&&(this.undecryptedTrackTimeout=setTimeout((()=>{!this.currentTransform&&this.isEnabled()&&(f.warn("encrypted track has no active decrypt transform",this.logContext),this.emitThrottledError(new gt("no active decrypt transform for encrypted track ".concat(this.trackId),ut.InternalError,this.participantIdentity)))}),this.UNDECRYPTED_TRACK_GRACE_MS))}ensureTransform(){if(this.currentTransform)return!0;if(!this.retainedStreams||void 0===this.trackId)return f.warn("no streams retained, cannot re-establish transform",this.logContext),!1;const e=this.retainedStreams,t=e.readable,n=e.writable,r=e.operation;return f.info("re-establishing transform",Object.assign(Object.assign({},this.logContext),{operation:r})),this.setupTransform(r,t,n,this.trackId)}setVideoCodec(e){this.videoCodec=e}setRtpMap(e){this.rtpMap=e}setHasFrameMetadata(e){this.hasFrameMetadata=e}setFrameMetadataOpts(e){this.frameMetadataOpts=e,this.frameMetadataFrameId=0}setupTransform(e,t,n,r,i,a){var o;i&&(f.info("setting codec on cryptor to",{codec:i}),this.videoCodec=i),"encode"===e&&this.setFrameMetadataOpts(a),f.debug("Setting up frame cryptor transform",Object.assign({operation:e,passedTrackId:r,codec:i,hasCurrentTransform:!!this.currentTransform},this.logContext)),this.trackId=r,this.retainedStreams={readable:t,writable:n,operation:e},clearTimeout(this.undecryptedTrackTimeout);const s=Symbol("transform"),c="encode"===e?this.encodeFunction:this.decodeFunction,d=new TransformStream({transform:c.bind(this)});this.currentTransform={readable:t,writable:n,transformer:d,trackId:r,symbol:s};try{t.pipeThrough(d).pipeTo(n).catch((e=>{e instanceof TypeError&&"Destination stream closed"===e.message?f.debug("destination stream closed"):(f.warn("transform error",Object.assign({error:e},this.logContext)),this.emit(pt.Error,e instanceof gt?e:new gt(e.message,void 0,this.participantIdentity)))})).finally((()=>{var t;(null===(t=this.currentTransform)||void 0===t?void 0:t.symbol)===s&&(f.debug("transform completed",Object.assign(Object.assign({},this.logContext),{trackId:r})),this.currentTransform=void 0),this.scheduleUndecryptedTrackWatchdog(e)}))}catch(e){return(null===(o=this.currentTransform)||void 0===o?void 0:o.symbol)===s&&(this.currentTransform=void 0),f.error("failed to set up transform",Object.assign({error:e},this.logContext)),this.emit(pt.Error,e instanceof gt?e:new gt(e.message,ut.InternalError,this.participantIdentity)),!1}return!0}setSifTrailer(e){f.debug("setting SIF trailer",Object.assign(Object.assign({},this.logContext),{trailer:e})),this.sifTrailer=e}emitThrottledError(e){const t="".concat(this.participantIdentity,"-").concat(e.reason,"-decrypt");if(!this.errorLimiter.shouldEmit(t,(()=>{f.warn("Suppressing further decryption errors for ".concat(this.participantIdentity),Object.assign(Object.assign({},this.logContext),{errorKey:t}))})))return!1;const n=this.errorLimiter.countFor(t);return n>1&&f.debug("Decryption error (".concat(n," occurrences in window)"),Object.assign(Object.assign({},this.logContext),{reason:ut[e.reason]})),this.emit(pt.Error,e),!0}encodeFunction(t,n){return e(this,void 0,void 0,(function*(){var e,r;if(0===t.data.byteLength)return n.enqueue(t);if(void 0===In)return void this.emitThrottledError(new gt("encryption state unknown for track ".concat(this.trackId,", dropping frame"),ut.InternalError,this.participantIdentity));if(!In)return this.appendFrameMetadata(t),n.enqueue(t);const i=this.keys.getKeySet();if(!i)return void this.emitThrottledError(new gt("key set not found for ".concat(this.participantIdentity," at index ").concat(this.keys.getCurrentKeyIndex()),ut.MissingKey,this.participantIdentity));const a=i.encryptionKey,o=this.keys.getCurrentKeyIndex();if(a){let i=this.makeIV(null!==(e=t.getMetadata().synchronizationSource)&&void 0!==e?e:-1,t.timestamp),c=this.getUnencryptedBytes(t),d=new Uint8Array(t.data,0,c.unencryptedBytes);c.requiresNALUProcessing&&(d=function(e){const t=[];for(let n=0;n+2<e.length;)0!==e[n+2]?(1!==e[n+2]||0!==e[n]||0!==e[n+1]||0!==n&&0===e[n-1]||t.push(n),n+=3):n+=1;if(0===t.length)return e;const n=new Uint8Array(e.length+t.length);let r=0;for(let i=0;i<t.length;i++){const a=t[i];n.set(e.subarray(r,a),r+i),r=a}return n.set(e.subarray(r),r+t.length),n}(d));const u=new Uint8Array(2);u[0]=12,u[1]=o;try{const e=c.unencryptedBytes-2,o=c.requiresNALUProcessing?yn(new Uint8Array(t.data,e)):null;let l;for(let n=1;l=yield crypto.subtle.encrypt({name:k,iv:i,additionalData:d},a,new Uint8Array(t.data,c.unencryptedBytes)),null!==o&&16!==n;n++){const n=$t(new Uint8Array(l,0,16)),a=new Uint8Array(2+n.byteLength);if(a.set(new Uint8Array(t.data,e,2)),a.set(n,2),yn(a)===o)break;i=this.makeIV(null!==(r=t.getMetadata().synchronizationSource)&&void 0!==r?r:-1,t.timestamp)}let h=new Uint8Array(l.byteLength+i.byteLength+u.byteLength);h.set(new Uint8Array(l)),h.set(new Uint8Array(i),l.byteLength),h.set(u,l.byteLength+i.byteLength),c.requiresNALUProcessing&&(h=$t(h));var s=new Uint8Array(d.byteLength+h.byteLength);return s.set(d),s.set(h,d.byteLength),t.data=s.buffer,this.appendFrameMetadata(t),n.enqueue(t)}catch(e){f.error("error while encrypting",Object.assign(Object.assign({},this.logContext),{error:e}))}}else f.debug("failed to encrypt, emitting error",this.logContext),this.emitThrottledError(new gt("encryption key missing for encoding",ut.MissingKey,this.participantIdentity))}))}appendFrameMetadata(e){var t;tn(this.frameMetadataOpts)&&Ht(e)&&((null===(t=this.frameMetadataOpts)||void 0===t?void 0:t.frameId)&&(this.frameMetadataFrameId=4294967295===this.frameMetadataFrameId?1:this.frameMetadataFrameId+1),function(e,t,n){if(!tn(t)||0===e.data.byteLength)return!1;const r=(null==t?void 0:t.timestamp)?BigInt(Date.now())*BigInt(1e3):BigInt(0),i=(null==t?void 0:t.frameId)?n:0,a=new Uint8Array(e.data),o=rn(a,r,i);o.byteLength!==a.byteLength&&(e.data=o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength))}(e,this.frameMetadataOpts,this.frameMetadataFrameId))}decodeFunction(t,n){return e(this,void 0,void 0,(function*(){if(this.hasFrameMetadata&&Ht(t))try{const e=function(e,t){if(0===e.data.byteLength)return{};const n=an(e.data);if(!n.metadata)return{};const r=n.data.buffer.slice(n.data.byteOffset,n.data.byteOffset+n.data.byteLength),i=function(e){try{const t=e.getMetadata();if("number"==typeof t.rtpTimestamp)return t.rtpTimestamp;if("number"==typeof t.timestamp)return t.timestamp}catch(e){}if("number"==typeof e.timestamp)return e.timestamp}(e);return void 0!==i&&t?{data:r,payload:{trackId:t,rtpTimestamp:i,ssrc:cn(e),metadata:n.metadata}}:{data:r}}(t,this.trackId);if(e.data&&(t.data=e.data),e.payload&&this.participantIdentity){const t={kind:"packetTrailerMetadata",data:e.payload};postMessage(t)}}catch(e){}if(0===t.data.byteLength)return n.enqueue(t);const e=this.isEnabled();if(void 0===e)return void 0===this.participantIdentity?void f.debug("dropping frame for unassigned cryptor",this.logContext):void this.emitThrottledError(new gt("encryption state unknown for track ".concat(this.trackId,", dropping frame"),ut.InternalError,this.participantIdentity));if(!e)return n.enqueue(t);if(function(e,t){if(0===t.byteLength)return!1;const n=new Uint8Array(e.slice(e.byteLength-t.byteLength));return t.every(((e,t)=>e===n[t]))}(t.data,this.sifTrailer))return t.data=t.data.slice(0,t.data.byteLength-this.sifTrailer.byteLength),(yield wn(t.data))?(f.debug("enqueue SIF",this.logContext),n.enqueue(t)):void f.warn("Unexpected SIF frame payload, dropping frame",this.logContext);const r=new Uint8Array(t.data)[t.data.byteLength-1];if(!this.keys.hasInvalidKeyAtIndex(r))if(this.keys.getKeySet(r))try{const e=yield this.decryptFrame(t,r);if(this.keys.decryptionSuccess(r),e)return n.enqueue(e)}catch(e){e instanceof gt&&e.reason===ut.InvalidKey?this.keys.hasValidKey&&(this.emitThrottledError(e),this.keys.decryptionFailure(r)):f.warn("decoding frame failed",{error:e})}else{this.emitThrottledError(new gt("missing key at index ".concat(r," for participant ").concat(this.participantIdentity),ut.MissingKey,this.participantIdentity))&&f.warn("skipping decryption due to missing key at index ".concat(r)),this.keys.decryptionFailure(r)}}))}decryptFrame(t,n){return e(this,arguments,void 0,(function(e,t){var n=this;let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{ratchetCount:0};return function*(){var a;const o=n.keys.getKeySet(t);if(!i.encryptionKey&&!o)throw new TypeError("no encryption key found for decryption of ".concat(n.participantIdentity));let s=n.getUnencryptedBytes(e);try{const t=new Uint8Array(e.data,0,s.unencryptedBytes);var c=new Uint8Array(e.data,t.length,e.data.byteLength-t.length);if(s.requiresNALUProcessing&&function(e){for(var t=0;t<e.length-3;t++)if(0==e[t]&&0==e[t+1]&&3==e[t+2])return!0;return!1}(c)){c=Qt(c);const n=new Uint8Array(t.byteLength+c.byteLength);n.set(t),n.set(c,t.byteLength),e.data=n.buffer}const n=new Uint8Array(e.data,e.data.byteLength-2,2),r=n[0],d=new Uint8Array(e.data,e.data.byteLength-r-n.byteLength,r),u=t.byteLength,l=e.data.byteLength-(t.byteLength+r+n.byteLength),h=yield crypto.subtle.decrypt({name:k,iv:d,additionalData:new Uint8Array(e.data,0,t.byteLength)},null!==(a=i.encryptionKey)&&void 0!==a?a:o.encryptionKey,new Uint8Array(e.data,u,l)),f=new ArrayBuffer(t.byteLength+h.byteLength),p=new Uint8Array(f);return p.set(new Uint8Array(e.data,0,t.byteLength)),p.set(new Uint8Array(h),t.byteLength),e.data=f,e}catch(a){if(n.keyProviderOptions.ratchetWindowSize>0){if(i.ratchetCount<n.keyProviderOptions.ratchetWindowSize){let a,s;f.debug("ratcheting key attempt ".concat(i.ratchetCount," of ").concat(n.keyProviderOptions.ratchetWindowSize,", for kind ").concat(e instanceof RTCEncodedAudioFrame?"audio":"video")),(null!=r?r:o)===n.keys.getKeySet(t)&&(s=yield n.keys.ratchetKey(t,!1),a=yield Yt(s.cryptoKey,n.keyProviderOptions));const c=yield n.decryptFrame(e,t,r||o,{ratchetCount:i.ratchetCount+1,encryptionKey:null==a?void 0:a.encryptionKey});return c&&a&&(null!=r?r:o)===n.keys.getKeySet(t)&&(n.keys.setKeySet(a,t,s),n.keys.setCurrentKeyIndex(t)),c}throw f.warn("maximum ratchet attempts exceeded"),new gt("valid key missing for participant ".concat(n.participantIdentity),ut.InvalidKey,n.participantIdentity)}throw new gt("Decryption failed: ".concat(Xt(a,"decryption")),ut.InvalidKey,n.participantIdentity)}}()}))}makeIV(e,t){var n;const r=new ArrayBuffer(12),i=new DataView(r);this.sendCounts.has(e)||this.sendCounts.set(e,Math.floor(65535*Math.random()));const a=null!==(n=this.sendCounts.get(e))&&void 0!==n?n:0;return i.setUint32(0,e),i.setUint32(4,t),i.setUint32(8,t-a%65535),this.sendCounts.set(e,a+1),r}getUnencryptedBytes(e){var t;if(!Ht(e))return{unencryptedBytes:T.audio,requiresNALUProcessing:!1};const n=null!==(t=this.getVideoCodec(e))&&void 0!==t?t:this.videoCodec;if(n!==this.detectedCodec&&(f.debug("detected different codec",Object.assign({detectedCodec:n,oldCodec:this.detectedCodec},this.logContext)),this.detectedCodec=n),"av1"===n)throw new Error("".concat(n," is not yet supported for end to end encryption"));if("vp8"===n)return{unencryptedBytes:T[e.type],requiresNALUProcessing:!1};if("vp9"===n)return{unencryptedBytes:0,requiresNALUProcessing:!1};const r=e.getMetadata().payloadType,i="".concat(this.participantIdentity,"-").concat(this.trackId,"-").concat(r);try{const t="h264"===n||"h265"===n?n:void 0,r=mn(new Uint8Array(e.data),t);if(r.requiresNALUProcessing)return this.loggedNALUFallbacks.delete(i),{unencryptedBytes:r.unencryptedBytes,requiresNALUProcessing:!0}}catch(t){this.logNALUFallbackOnce(i,e,r,n,t)}return{unencryptedBytes:T[e.type],requiresNALUProcessing:!1}}logNALUFallbackOnce(e,t,n,r,i){this.loggedNALUFallbacks.has(e)||(this.loggedNALUFallbacks.add(e),f.warn("NALU processing failed, falling back to VP8 handling",Object.assign({error:i,payloadType:n,detectedCodec:r,frameType:t.type,byteLength:t.data.byteLength,firstBytes:Array.from(new Uint8Array(t.data,0,Math.min(16,t.data.byteLength))).map((e=>e.toString(16).padStart(2,"0"))).join(" ")},this.logContext)))}getVideoCodec(e){const t=e.getMetadata();if(t.mimeType){const e=t.mimeType.split("/")[1].toLowerCase();if(xt.includes(e))return e}if(0===this.rtpMap.size)return;const n=t.payloadType;return n?this.rtpMap.get(n):void 0}}class Nn extends Ot.EventEmitter{get hasValidKey(){return!this.hasInvalidKeyAtIndex(this.currentKeyIndex)}constructor(e,t){if(super(),this.currentKeyIndex=0,t.keyringSize<1||t.keyringSize>256)throw new TypeError("Keyring size needs to be between 1 and 256");this.cryptoKeyRing=new Array(t.keyringSize).fill(void 0),this.decryptionFailureCounts=new Array(t.keyringSize).fill(0),this.keyProviderOptions=t,this.ratchetPromiseMap=new Map,this.participantIdentity=e}hasInvalidKeyAtIndex(e){return this.keyProviderOptions.failureTolerance>=0&&this.decryptionFailureCounts[e]>this.keyProviderOptions.failureTolerance}decryptionFailure(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.currentKeyIndex;this.keyProviderOptions.failureTolerance<0||(this.decryptionFailureCounts[e]+=1,this.decryptionFailureCounts[e]>this.keyProviderOptions.failureTolerance&&f.warn("key for ".concat(this.participantIdentity," at index ").concat(e," is being marked as invalid")))}decryptionSuccess(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.currentKeyIndex;this.resetKeyStatus(e)}resetKeyStatus(e){void 0===e?this.decryptionFailureCounts.fill(0):this.decryptionFailureCounts[e]=0}ratchetKey(t){let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const r=null!=t?t:this.getCurrentKeyIndex(),i=this.ratchetPromiseMap.get(r);if(void 0!==i)return i;const a=new Promise(((t,i)=>e(this,void 0,void 0,(function*(){try{const i=this.getKeySet(r);if(!i)throw new TypeError("Cannot ratchet key without a valid keyset of participant ".concat(this.participantIdentity));const a=i.material,o=yield function(t,n){return e(this,void 0,void 0,(function*(){const e=zt(t.algorithm.name,n);return crypto.subtle.deriveBits(e,t,256)}))}(a,this.keyProviderOptions.ratchetSalt),s=yield function(t){return e(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{name:k},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"encrypt";return function*(){return crypto.subtle.importKey("raw",e,t,!1,"derive"===n?["deriveBits","deriveKey"]:["encrypt","decrypt"])}()}))}(o,a.algorithm.name,"derive"),c={chainKey:o,cryptoKey:s};n&&(yield this.setKeyFromMaterial(s,r,c)),t(c)}catch(e){i(e)}finally{this.ratchetPromiseMap.delete(r)}}))));return this.ratchetPromiseMap.set(r,a),a}setKey(t){return e(this,arguments,void 0,(function(e){var t=this;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){yield t.setKeyFromMaterial(e,n,null,r),r&&t.resetKeyStatus(n)}()}))}setKeyFromMaterial(t,n){return e(this,arguments,void 0,(function(e,t){var n=this;let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,i=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];return function*(){const a=yield Yt(e,n.keyProviderOptions),o=t>=0?t%n.cryptoKeyRing.length:n.currentKeyIndex;f.debug("setting new key with index ".concat(t),{usage:e.usages,algorithm:e.algorithm,ratchetSalt:n.keyProviderOptions.ratchetSalt}),n.setKeySet(a,o,r),o>=0&&i&&(n.currentKeyIndex=o)}()}))}setKeySet(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;this.cryptoKeyRing[t%this.cryptoKeyRing.length]=e,n&&this.emit(ht.KeyRatcheted,n,this.participantIdentity,t)}setCurrentKeyIndex(t){return e(this,void 0,void 0,(function*(){this.currentKeyIndex=t%this.cryptoKeyRing.length,this.resetKeyStatus(t)}))}getCurrentKeyIndex(){return this.currentKeyIndex}getKeySet(e){return this.cryptoKeyRing[null!=e?e:this.currentKeyIndex]}}const An={encode:[],decode:[]},Cn=new Map;let Ln,Un,On=new class{constructor(){this.pendingTasks=new Map,this.taskMutex=new b,this.nextTaskIndex=0}run(t){return e(this,void 0,void 0,(function*(){const e={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:m.WAITING};this.pendingTasks.set(e.id,e);const n=yield this.taskMutex.lock();try{return e.executedAt=Date.now(),e.status=m.RUNNING,yield t()}finally{e.status=m.COMPLETED,this.pendingTasks.delete(e.id),n()}}))}flush(){return e(this,void 0,void 0,(function*(){return this.run((()=>e(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}},Rn=!1,Dn=w,Fn=new Map;const Pn=new en;function _n(e,t,n,r){const i=An[e];let a=i.filter((e=>e.getTrackId()===n));if(0===a.length&&void 0!==r&&r!==n){const e=i.filter((e=>e.getTrackId()===r));e.length>0&&(f.info("reusing cryptor from previous trackId",{participantIdentity:t,trackId:n,previousTrackId:r}),e[0].setTrackId(n),a=e)}if(a.length>1){const e=a.map((e=>({participant:e.getParticipantIdentity()}))).join(",");f.error("Found multiple cryptors for the same trackID ".concat(n,". target participant: ").concat(t," "),{participants:e})}let o=a[0];if(o)t!==o.getParticipantIdentity()&&o.setParticipant(t,xn(t));else{if(f.info("creating new cryptor for",{participantIdentity:t,trackId:n}),!Dn)throw Error("Missing keyProvider options");o=new En({participantIdentity:t,keys:xn(t),keyProviderOptions:Dn,sifTrailer:Un}),o.setRtpMap(Fn),function(e){e.on(pt.Error,(e=>{const t={kind:"error",data:{error:new Error("".concat(ut[e.reason],": ").concat(e.message)),participantIdentity:e.participantIdentity}};postMessage(t)}))}(o),i.push(o)}return o}function xn(e){if(Rn)return Mn();let t=Cn.get(e);return t||(t=new Nn(e,Dn),t.on(ht.KeyRatcheted,Bn),Cn.set(e,t)),t}function Mn(){return Ln||(f.debug("creating new shared key handler"),Ln=new Nn("shared-key",Dn)),Ln}function Bn(e,t,n){postMessage({kind:"ratchetKey",data:{participantIdentity:t,keyIndex:n,ratchetResult:e}})}f.setDefaultLevel("info"),f.methodFactory=e=>(t,n)=>{postMessage({kind:"log",data:{level:e,msg:t,context:n}})},f.setLevel(f.getLevel()),onmessage=t=>{On.run((()=>e(void 0,void 0,void 0,(function*(){var n;const r=t.data,i=r.kind,a=r.data;switch(i){case"init":f.setLevel(a.loglevel),f.info("e2ee worker initialized"),Dn=a.keyProviderOptions,Rn=!!a.keyProviderOptions.sharedKey;postMessage({kind:"initAck",data:{enabled:false}});break;case"setLogLevel":f.setLevel(a.level);break;case"enable":a.local&&(s=a.enabled,In=s),f.info("updated e2ee enabled status for ".concat(a.participantIdentity," to ").concat(a.enabled)),postMessage(t.data);break;case"decode":let r=_n(i,a.participantIdentity,a.trackId);r.setEncrypted(a.encrypted),r.setHasFrameMetadata(a.hasPacketTrailer),r.setupTransform(i,a.readableStream,a.writableStream,a.trackId,a.codec);break;case"encode":let c=_n(i,a.participantIdentity,a.trackId);c.setHasFrameMetadata(a.hasPacketTrailer),c.setupTransform(i,a.readableStream,a.writableStream,a.trackId,a.codec,a.packetTrailer);break;case"encryptDataRequest":const d=yield Zt.encrypt(a.payload,xn(a.participantIdentity)),u=d.payload,l=d.iv,h=d.keyIndex;postMessage({kind:"encryptDataResponse",data:{payload:u,iv:l,keyIndex:h,uuid:a.uuid}});break;case"decryptDataRequest":try{const e=(yield Zt.decrypt(a.payload,a.iv,xn(a.participantIdentity),a.keyIndex)).payload;postMessage({kind:"decryptDataResponse",data:{payload:e,uuid:a.uuid}})}catch(e){const t="".concat(a.participantIdentity,"-datadecrypt");Pn.shouldEmit(t,(()=>{f.warn("Suppressing further data decryption errors for ".concat(a.participantIdentity),{errorKey:t})}))&&f.error("DataCryptor decryption failed",{error:e,participantIdentity:a.participantIdentity,uuid:a.uuid}),postMessage({kind:"error",data:{error:e instanceof Error?e:new Error(String(e)),uuid:a.uuid}})}break;case"setKey":Rn?yield function(t,n,r){return e(this,void 0,void 0,(function*(){f.info("set shared key",{index:n}),yield Mn().setKey(t,n,r)}))}(a.key,a.keyIndex,a.updateCurrentKeyIndex):a.participantIdentity?(f.info("set participant sender key ".concat(a.participantIdentity," index ").concat(a.keyIndex)),yield xn(a.participantIdentity).setKey(a.key,a.keyIndex,a.updateCurrentKeyIndex)):f.error("no participant Id was provided and shared key usage is disabled");break;case"removeTransform":!function(e,t){const n=An.decode.filter((n=>n.getParticipantIdentity()===t&&n.getTrackId()===e));n.length>1&&f.error("Found multiple cryptors for the same participant and trackID combination",{trackId:e,participantIdentity:t});const r=n[0];r?r.unsetParticipant():f.warn("Could not unset participant on cryptor",{trackId:e,participantIdentity:t})}(a.trackId,a.participantIdentity);break;case"updateCodec":const p=_n(null!==(n=a.operation)&&void 0!==n?n:"decode",a.participantIdentity,a.trackId,a.previousTrackId);a.codec&&p.setVideoCodec(a.codec),p.setHasFrameMetadata(a.hasPacketTrailer),"encode"!==a.operation&&p.setEncrypted(a.encrypted),f.info("updated codec",{participantIdentity:a.participantIdentity,trackId:a.trackId,previousTrackId:a.previousTrackId,codec:a.codec,hasPacketTrailer:a.hasPacketTrailer}),void 0===a.previousTrackId||p.ensureTransform()||f.error("could not re-establish transform for reused receiver",{participantIdentity:a.participantIdentity,trackId:a.trackId,previousTrackId:a.previousTrackId});break;case"setRTPMap":Fn=a.map,An.encode.forEach((e=>{e.setRtpMap(a.map)}));break;case"ratchetRequest":!function(t){e(this,void 0,void 0,(function*(){if(Rn){const e=Mn();yield e.ratchetKey(t.keyIndex),e.resetKeyStatus()}else if(t.participantIdentity){const e=xn(t.participantIdentity);yield e.ratchetKey(t.keyIndex),e.resetKeyStatus()}else f.error("no participant Id was provided for ratchet request and shared key usage is disabled")}))}(a);break;case"setSifTrailer":o=a.trailer,Un=o,An.decode.forEach((e=>{e.setSifTrailer(o)}))}var o,s}))))},self.RTCTransformEvent&&(self.onrtctransform=t=>{const n=t.transformer,r=n.options,i=r.kind,a=r.participantIdentity,o=r.trackId,s=r.codec,c=r.hasPacketTrailer;On.run((()=>e(void 0,void 0,void 0,(function*(){const e=_n(i,a,o);"decode"===i&&e.setEncrypted(r.encrypted),e.setHasFrameMetadata(c),f.debug("onrtctransform setup",{participantIdentity:a,trackId:o,codec:s}),e.setupTransform(i,n.readable,n.writable,o,s,"encode"===i?r.packetTrailer:void 0)}))))})}));
2
2
  //# sourceMappingURL=livekit-client.e2ee.worker.js.map