!function(){"use strict";function e(e,t,n,r){return new(n||(n=Promise))(function(i,o){function s(e){try{c(r.next(e))}catch(e){o(e)}}function a(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){e.done?i(e.value):function(e){return e instanceof n?e:new n(function(t){t(e)})}(e.value).then(s,a)}c((r=r.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;var t,n={exports:{}};var r,i,o,s,a,c=(t||(t=1,o=n.exports,s=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={},o=null;function s(e,t){var n=e[t];if("function"==typeof n.bind)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch{return function(){return Function.prototype.apply.apply(n,[e,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var n=this.getLevel(),i=0;i=0&&t<=l.levels.SILENT)return t;throw new TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?y+=":"+e:"symbol"==typeof e&&(y=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 d??a??s},l.setLevel=function(e,n){return d=h(e),!1!==n&&function(e){var n=(r[e]||"silent").toUpperCase();if(typeof window!==t&&y){try{return void(window.localStorage[y]=n)}catch{}try{window.document.cookie=encodeURIComponent(y)+"="+n+";"}catch{}}}(d),c.call(l)},l.setDefaultLevel=function(e){a=h(e),p()||l.setLevel(e,!1)},l.resetLevel=function(){d=null,function(){if(typeof window!==t&&y){try{window.localStorage.removeItem(y)}catch{}try{window.document.cookie=encodeURIComponent(y)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}(),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(o!==l&&(s=h(o.getLevel())),c.call(l),o===l)for(var e in i)i[e].rebuild()},s=h(o?o.getLevel():"WARN");var f=p();null!=f&&(d=h(f)),c.call(l)}(o=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,o.methodFactory)),t};var y=typeof window!==t?window.log:void 0;return o.noConflict=function(){return typeof window!==t&&window.log===o&&(window.log=y),o},o.getLoggers=function(){return i},o.default=o,o},(i=n).exports?i.exports=s():o.log=s()),n.exports);!function(e){e[e.trace=0]="trace",e[e.debug=1]="debug",e[e.info=2]="info",e[e.warn=3]="warn",e[e.error=4]="error",e[e.silent=5]="silent"}(r||(r={})),function(e){e.Default="livekit",e.Room="livekit-room",e.Participant="livekit-participant",e.Track="livekit-track",e.Publication="livekit-track-publication",e.Engine="livekit-engine",e.Signal="livekit-signal",e.PCManager="livekit-pc-manager",e.PCTransport="livekit-pc-transport",e.E2EE="lk-e2ee"}(a||(a={}));let d=c.getLogger("livekit");Object.values(a).map(e=>c.getLogger(e)),d.setDefaultLevel(r.info);const u=c.getLogger("lk-e2ee");var l,y=Object.defineProperty,p=(e,t,n)=>((e,t,n)=>t in e?y(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n);class h{constructor(){p(this,"_locking"),p(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"}(l||(l={}));const f="AES-GCM",g={key:10,delta:3,audio:1,empty:0},v={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:10,keyringSize:16};class m extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var I,L,w,b,_,k,A,S;!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"}(I||(I={})),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"}(L||(L={})),function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"}(w||(w={})),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}}(w||(w={})),function(e){e[e.InvalidKey=0]="InvalidKey",e[e.MissingKey=1]="MissingKey",e[e.InternalError=2]="InternalError"}(b||(b={}));class E extends m{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:b.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"}(_||(_={})),function(e){e.KeyRatcheted="keyRatcheted"}(k||(k={})),function(e){e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError"}(A||(A={})),function(e){e.Error="cryptorError"}(S||(S={}));var T,R={exports:{}};var C=function(){if(T)return R.exports;T=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)}R.exports=i,R.exports.once=function(e,t){return new Promise(function(n,r){function i(n){e.removeListener(t,o),r(n)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",i),n([].slice.call(arguments))}h(e,t,o,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&h(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 o=10;function s(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function a(e){return void 0===e._maxListeners?i.defaultMaxListeners:e._maxListeners}function c(e,t,n,r){var i,o,c;if(s(n),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),o=e._events),c=o[t]),void 0===c)c=o[t]=n,++e._eventsCount;else if("function"==typeof c?c=o[t]=r?[n,c]:[c,n]:r?c.unshift(n):c.push(n),(i=a(e))>0&&c.length>i&&!c.warned){c.warned=!0;var d=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");d.name="MaxListenersExceededWarning",d.emitter=e,d.type=t,d.count=c.length,function(e){console&&console.warn&&console.warn(e)}(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;n0&&(s=t[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var c=o[e];if(void 0===c)return!1;if("function"==typeof c)n(c,this,t);else{var d=c.length,u=p(c,d);for(r=0;r=0;o--)if(n[o]===t||n[o].listener===t){a=n[o].listener,i=o;break}if(i<0)return this;0===i?n.shift():function(e,t){for(;t+1=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):y.call(e,t)},i.prototype.listenerCount=y,i.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},R.exports}();function P(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 N(t,n){return e(this,void 0,void 0,function*(){const e=P(t.algorithm.name,n),r=yield crypto.subtle.deriveKey(e,t,{name:f,length:128},!1,["encrypt","decrypt"]);return{material:t,encryptionKey:r}})}var K,U;function x(e){return 31&e}function O(e){return e>>1&63}function D(e){return e===K.SLICE_IDR||e===K.SLICE_NON_IDR}function F(e){return e===U.TRAIL_N||e===U.TRAIL_R||e===U.TSA_N||e===U.TSA_R||e===U.STSA_N||e===U.STSA_R||e===U.RADL_N||e===U.RADL_R||e===U.RASL_N||e===U.RASL_R||e===U.BLA_W_LP||e===U.BLA_W_RADL||e===U.BLA_N_LP||e===U.IDR_W_RADL||e===U.IDR_N_LP||e===U.CRA_NUT}function M(e,t){const n=function(e){const t=[];let n=0,r=0,i=e.length-3;for(;r=i&&(r=e.length);let o=r;for(;o>n&&0===e[o-1];)o--;if(0===n){if(o!==n)throw TypeError("byte stream contains leading data")}else t.push(n);let s=3;re.toString(16).padStart(2,"0")).join("")})}(t)){case B:return"vp8";case j:case q:case W:return"h264";case X:return"opus";default:return null}})}const V=new Map;class G extends C.EventEmitter{encodeFunction(e,t){throw Error("not implemented for subclass")}decodeFunction(e,t){throw Error("not implemented for subclass")}}class H extends G{constructor(e){var t;super(),this.isTransformActive=!1,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){u.debug("setting new participant on cryptor",Object.assign(Object.assign({},this.logContext),{participant:e})),this.participantIdentity&&u.error("cryptor has already a participant set, participant should have been unset before",Object.assign({},this.logContext)),this.participantIdentity=e,this.keys=t}unsetParticipant(){u.debug("unsetting participant",this.logContext),this.participantIdentity=void 0}isEnabled(){if(this.participantIdentity)return V.get(this.participantIdentity)}getParticipantIdentity(){return this.participantIdentity}getTrackId(){return this.trackId}setVideoCodec(e){this.videoCodec=e}setRtpMap(e){this.rtpMap=e}setupTransform(e,t,n,r,i,o){if(o&&(u.info("setting codec on cryptor to",{codec:o}),this.videoCodec=o),u.debug("Setting up frame cryptor transform",Object.assign({operation:e,passedTrackId:r,codec:o},this.logContext)),i&&this.isTransformActive)return void u.debug("reuse transform",Object.assign({},this.logContext));const s="encode"===e?this.encodeFunction:this.decodeFunction,a=new TransformStream({transform:s.bind(this)});this.isTransformActive=!0,t.pipeThrough(a).pipeTo(n).catch(e=>{u.warn(e),this.emit(S.Error,e instanceof E?e:new E(e.message,void 0,this.participantIdentity))}).finally(()=>{this.isTransformActive=!1}),this.trackId=r}setSifTrailer(e){u.debug("setting SIF trailer",Object.assign(Object.assign({},this.logContext),{trailer:e})),this.sifTrailer=e}encodeFunction(t,n){return e(this,void 0,void 0,function*(){var e;if(!this.isEnabled()||0===t.data.byteLength)return n.enqueue(t);const r=this.keys.getKeySet();if(!r)return void this.emit(S.Error,new E("key set not found for ".concat(this.participantIdentity," at index ").concat(this.keys.getCurrentKeyIndex()),b.MissingKey,this.participantIdentity));const{encryptionKey:i}=r,o=this.keys.getCurrentKeyIndex();if(i){const r=this.makeIV(null!==(e=t.getMetadata().synchronizationSource)&&void 0!==e?e:-1,t.timestamp);let a=this.getUnencryptedBytes(t);const c=new Uint8Array(t.data,0,a.unencryptedBytes),d=new Uint8Array(2);d[0]=12,d[1]=o;try{const e=yield crypto.subtle.encrypt({name:f,iv:r,additionalData:new Uint8Array(t.data,0,c.byteLength)},i,new Uint8Array(t.data,a.unencryptedBytes));let o=new Uint8Array(e.byteLength+r.byteLength+d.byteLength);o.set(new Uint8Array(e)),o.set(new Uint8Array(r),e.byteLength),o.set(d,e.byteLength+r.byteLength),a.requiresNALUProcessing&&(o=function(e){const t=[];for(var n=0,r=0;r=2&&(t.push(3),n=0),t.push(i),0==i?++n:n=0}return new Uint8Array(t)}(o));var s=new Uint8Array(c.byteLength+o.byteLength);return s.set(c),s.set(o,c.byteLength),t.data=s.buffer,n.enqueue(t)}catch(e){u.error(e)}}else u.debug("failed to encrypt, emitting error",this.logContext),this.emit(S.Error,new E("encryption key missing for encoding",b.MissingKey,this.participantIdentity))})}decodeFunction(t,n){return e(this,void 0,void 0,function*(){if(!this.isEnabled()||0===t.data.byteLength)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 z(t.data))?(u.debug("enqueue SIF",this.logContext),n.enqueue(t)):void u.warn("Unexpected SIF frame payload, dropping frame",this.logContext);const e=new Uint8Array(t.data)[t.data.byteLength-1];if(!this.keys.hasInvalidKeyAtIndex(e))if(this.keys.getKeySet(e))try{const r=yield this.decryptFrame(t,e);if(this.keys.decryptionSuccess(e),r)return n.enqueue(r)}catch(t){t instanceof E&&t.reason===b.InvalidKey?this.keys.hasValidKey&&(this.emit(S.Error,t),this.keys.decryptionFailure(e)):u.warn("decoding frame failed",{error:t})}else u.warn("skipping decryption due to missing key at index ".concat(e)),this.emit(S.Error,new E("missing key at index ".concat(e," for participant ").concat(this.participantIdentity),b.MissingKey,this.participantIdentity)),this.keys.decryptionFailure(e)})}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 o;const s=n.keys.getKeySet(t);if(!i.encryptionKey&&!s)throw new TypeError("no encryption key found for decryption of ".concat(n.participantIdentity));let a=n.getUnencryptedBytes(e);try{const t=new Uint8Array(e.data,0,a.unencryptedBytes);var c=new Uint8Array(e.data,t.length,e.data.byteLength-t.length);if(a.requiresNALUProcessing&&function(e){for(var t=0;t=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)}(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),y=yield crypto.subtle.decrypt({name:f,iv:d,additionalData:new Uint8Array(e.data,0,t.byteLength)},null!==(o=i.encryptionKey)&&void 0!==o?o:s.encryptionKey,new Uint8Array(e.data,u,l)),p=new ArrayBuffer(t.byteLength+y.byteLength),h=new Uint8Array(p);return h.set(new Uint8Array(e.data,0,t.byteLength)),h.set(new Uint8Array(y),t.byteLength),e.data=p,e}catch(o){if(n.keyProviderOptions.ratchetWindowSize>0){if(i.ratchetCount256)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&&u.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=t??this.getCurrentKeyIndex(),i=this.ratchetPromiseMap.get(r);if(typeof i<"u")return i;const o=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 o=i.material,s=yield function(t,n){return e(this,void 0,void 0,function*(){const e=P(t.algorithm.name,n);return crypto.subtle.deriveBits(e,t,256)})}(o,this.keyProviderOptions.ratchetSalt),a=yield function(t){return e(this,arguments,void 0,function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{name:f},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"])}()})}(s,o.algorithm.name,"derive"),c={chainKey:s,cryptoKey:a};n&&(yield this.setKeyFromMaterial(a,r,c)),t(c)}catch(e){i(e)}finally{this.ratchetPromiseMap.delete(r)}}));return this.ratchetPromiseMap.set(r,o),o}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;return function*(){yield t.setKeyFromMaterial(e,n),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;return function*(){const i=yield N(e,n.keyProviderOptions.ratchetSalt),o=t>=0?t%n.cryptoKeyRing.length:n.currentKeyIndex;u.debug("setting new key with index ".concat(t),{usage:e.usages,algorithm:e.algorithm,ratchetSalt:n.keyProviderOptions.ratchetSalt}),n.setKeySet(i,o,r),o>=0&&(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(k.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[e??this.currentKeyIndex]}}const Q=[],J=new Map;let Z,$,ee=new class{constructor(){this.pendingTasks=new Map,this.taskMutex=new h,this.nextTaskIndex=0}run(t){return e(this,void 0,void 0,function*(){const e={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:l.WAITING};this.pendingTasks.set(e.id,e);const n=yield this.taskMutex.lock();try{return e.executedAt=Date.now(),e.status=l.RUNNING,yield t()}finally{e.status=l.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())}},te=!1,ne=v,re=new Map;function ie(e,t){let n=Q.filter(e=>e.getTrackId()===t);if(n.length>1){const r=n.map(e=>({participant:e.getParticipantIdentity()})).join(",");u.error("Found multiple cryptors for the same trackID ".concat(t,". target participant: ").concat(e," "),{participants:r})}let r=n[0];if(r)e!==r.getParticipantIdentity()&&r.setParticipant(e,oe(e));else{if(u.info("creating new cryptor for",{participantIdentity:e,trackId:t}),!ne)throw Error("Missing keyProvider options");r=new H({participantIdentity:e,keys:oe(e),keyProviderOptions:ne,sifTrailer:$}),r.setRtpMap(re),function(e){e.on(S.Error,e=>{const t={kind:"error",data:{error:new Error("".concat(b[e.reason],": ").concat(e.message))}};postMessage(t)})}(r),Q.push(r)}return r}function oe(e){if(te)return se();let t=J.get(e);return t||(t=new Y(e,ne),t.on(k.KeyRatcheted,ae),J.set(e,t)),t}function se(){return Z||(u.debug("creating new shared key handler"),Z=new Y("shared-key",ne)),Z}function ae(e,t,n){postMessage({kind:"ratchetKey",data:{participantIdentity:t,keyIndex:n,ratchetResult:e}})}u.setDefaultLevel("info"),onmessage=t=>{ee.run(()=>e(void 0,void 0,void 0,function*(){const{kind:n,data:r}=t.data;switch(n){case"init":u.setLevel(r.loglevel),u.info("worker initialized"),ne=r.keyProviderOptions,te=!!r.keyProviderOptions.sharedKey,postMessage({kind:"initAck",data:{enabled:false}});break;case"enable":(function(e,t){u.debug("setting encryption enabled for all tracks of ".concat(t),{enable:e}),V.set(t,e)})(r.enabled,r.participantIdentity),u.info("updated e2ee enabled status for ".concat(r.participantIdentity," to ").concat(r.enabled)),postMessage(t.data);break;case"decode":case"encode":ie(r.participantIdentity,r.trackId).setupTransform(n,r.readableStream,r.writableStream,r.trackId,r.isReuse,r.codec);break;case"setKey":te?yield function(t,n){return e(this,void 0,void 0,function*(){u.info("set shared key",{index:n}),yield se().setKey(t,n)})}(r.key,r.keyIndex):r.participantIdentity?(u.info("set participant sender key ".concat(r.participantIdentity," index ").concat(r.keyIndex)),yield oe(r.participantIdentity).setKey(r.key,r.keyIndex)):u.error("no participant Id was provided and shared key usage is disabled");break;case"removeTransform":!function(e,t){const n=Q.filter(n=>n.getParticipantIdentity()===t&&n.getTrackId()===e);n.length>1&&u.error("Found multiple cryptors for the same participant and trackID combination",{trackId:e,participantIdentity:t});const r=n[0];r?r.unsetParticipant():u.warn("Could not unset participant on cryptor",{trackId:e,participantIdentity:t})}(r.trackId,r.participantIdentity);break;case"updateCodec":ie(r.participantIdentity,r.trackId).setVideoCodec(r.codec),u.info("updated codec",{participantIdentity:r.participantIdentity,trackId:r.trackId,codec:r.codec});break;case"setRTPMap":re=r.map,Q.forEach(e=>{e.getParticipantIdentity()===r.participantIdentity&&e.setRtpMap(r.map)});break;case"ratchetRequest":!function(t){e(this,void 0,void 0,function*(){if(te){const e=se();yield e.ratchetKey(t.keyIndex),e.resetKeyStatus()}else if(t.participantIdentity){const e=oe(t.participantIdentity);yield e.ratchetKey(t.keyIndex),e.resetKeyStatus()}else u.error("no participant Id was provided for ratchet request and shared key usage is disabled")})}(r);break;case"setSifTrailer":!function(e){$=e,Q.forEach(t=>{t.setSifTrailer(e)})}(r.trailer)}}))},self.RTCTransformEvent&&(u.debug("setup transform event"),self.onrtctransform=e=>{const t=e.transformer;u.debug("transformer",t);const{kind:n,participantIdentity:r,trackId:i,codec:o}=t.options,s=ie(r,i);u.debug("transform",{codec:o}),s.setupTransform(n,t.readable,t.writable,i,!1,o)})}();