@flowe-ai/cli 0.3.1 → 0.3.2

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.
@@ -45,5 +45,5 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
45
45
  `)+`\r
46
46
  `},ko}var Zl;function o0(){if(Zl)return et;Zl=1;var n=r0(),e=s0(),t=ed();return et.grammar=t,et.write=e,et.parse=n.parse,et.parseParams=n.parseParams,et.parseFmtpConfig=n.parseFmtpConfig,et.parsePayloads=n.parsePayloads,et.parseRemoteCandidates=n.parseRemoteCandidates,et.parseImageAttributes=n.parseImageAttributes,et.parseSimulcastStreamList=n.parseSimulcastStreamList,et}var tt=o0();function a0(n,e){var t;let i=(t=tt.parse(n).media.find(r=>typeof r.msid=="string"&&r.msid.startsWith("".concat(e," "))))===null||t===void 0?void 0:t.msid;return i?.split(" ")[1]}var Mr=class extends Error{constructor(){super("reservation dropped by a reconnect"),this.name="ReservationDroppedError"}};function eu(n){var e;let t=Gc(n);for(let i of["videoSimulcastLayers","screenShareSimulcastLayers"])(e=n[i])===null||e===void 0||e.forEach((r,s)=>{Object.setPrototypeOf(t[i][s],Object.getPrototypeOf(r))});return t}var ga=class{constructor(e,t,i,r,s,a,o){var c,d;this.specification=e,this.options=t,this.encodings=i,this.codec=r,this.canReserve=s,this.publish=a,this.release=o,this.committed=!1,this.settled=!1,this.ownsBuffer=!1,this.kind=e.source===C.Source.Microphone?C.Kind.Audio:C.Kind.Video,this.request=new dn({name:t.name,type:C.kindToProto(this.kind),source:C.sourceToProto(e.source),stream:t.stream,stereo:!!t.forceStereo,disableDtx:!(!((c=t.dtx)!==null&&c!==void 0)||c),disableRed:!(!((d=t.red)!==null&&d!==void 0)||d),muted:!0}),this.resetRegistration(),this.cancellation=new Promise((l,u)=>{this.rejectCancelled=u}),this.cancellation.catch(()=>{})}attachTrack(e){return this.cancelled?Promise.reject(this.cancelled):this.attaching?this.boundTrack===e?this.attaching:Promise.reject(new le("publication already has a track")):e.kind!==this.kind||e.sender?Promise.reject(new le("track kind differs or track already has a sender")):(this.boundTrack=e,this.options.preConnectBuffer&&e.kind===C.Kind.Audio&&!e.hasPreConnectBuffer&&(e.startPreConnectBuffer(),this.ownsBuffer=!0),this.attaching=this.attach(e),this.attaching)}attach(e){return g(this,void 0,void 0,function*(){try{for(;;){yield Promise.race([this.registered,this.cancellation]),this.assertActive(),e.source=this.specification.source;try{let t=yield this.publish(e,this);return this.commit(),this.finish(),t}catch(t){if(!(t instanceof Mr)||this.cancelled)throw t}}}catch(t){throw this.cancel().catch(()=>{}),t}})}commit(){this.committed=!0,this.initial&&this.initial.transport.releaseSender(this.initial.transceiver),this.initial=void 0}get isCommitted(){return this.committed}get isCancelled(){return!!this.cancelled}get registration(){return this.registered}get isWaitingForSender(){return!this.cancelled&&!this.committed&&!this.initial&&!(this.attaching&&this.settled)}skipReservation(){this.settled=!0,this.resolveRegistered()}disconnected(){this.rejectRegistered(new J("room disconnected before publication")),this.cancel().catch(()=>{})}reserve(e){this.assertActive(),this.initial=e,this.settled=!0,this.resolveRegistered(),e.accepted.then(t=>{this.initial===e&&(this.initialTrackSid=t.sid)},t=>{this.initial===e&&(this.cancelled=t instanceof Error?t:new Error(String(t)),this.rejectCancelled(this.cancelled),this.cancel().catch(()=>{}))})}fallback(){this.initialTrackSid=void 0;let e=this.initial;this.initial=void 0,e&&(!this.committed&&!this.cancelled&&this.resetRegistration(),e.engine.cancelPendingTrack(this.request.cid))}resetRegistration(){this.settled=!1,this.registered=new Promise((e,t)=>{this.resolveRegistered=e,this.rejectRegistered=t}),this.registered.catch(()=>{})}senderFor(e,t){return g(this,void 0,void 0,function*(){var i;this.assertActive();let r=this.initial;if(!r)return;let s;try{s=yield r.accepted}catch(u){throw this.initial!==r&&!this.cancelled?new Mr:u}this.assertActive();let a=e.getSourceTrackSettings(),o="".concat(this.kind,"/").concat(this.codec).toLowerCase(),c=s.codecs.filter(u=>u.mimeType.length>0),d=c.length>0&&!c.some(u=>u.mimeType.toLowerCase()===o||this.kind===C.Kind.Audio&&u.mimeType.toLowerCase()==="audio/red"),l=this.specification.source===C.Source.Camera?a.width!==void 0&&a.width!==this.specification.format.width||a.height!==void 0&&a.height!==this.specification.format.height:!!this.options.forceStereo&&a.channelCount!==void 0&&a.channelCount<2;if(t.e2eeManager||t.frameMetadataOptions||r.engine!==t||((i=t.pcManager)===null||i===void 0?void 0:i.publisher)!==r.transport||d||l){yield this.removeInitial();return}return r})}assertActive(){if(this.cancelled)throw this.cancelled}cancel(){var e,t;return this.committed?Promise.resolve():(this.cancelled||(this.cancelled=new le("prepared publication cancelled")),this.rejectCancelled(this.cancelled),this.rejectRegistered(this.cancelled),this.ownsBuffer&&((e=this.boundTrack)===null||e===void 0||e.stopPreConnectBuffer(),this.ownsBuffer=!1),(t=this.cancelling)!==null&&t!==void 0||(this.cancelling=this.removeInitial().then(()=>{var i;return(i=this.attaching)===null||i===void 0?void 0:i.catch(()=>{})}).then(()=>{}).finally(()=>this.finish())),this.cancelling)}removeInitial(){return g(this,void 0,void 0,function*(){var e,t;let i=this.initial;if(i&&(yield i.engine.initialOfferAnswered(),this.initial===i&&(this.initial=void 0,i.engine.cancelPendingTrack(this.request.cid),!(i.engine.isClosed||((e=i.engine.pcManager)===null||e===void 0?void 0:e.publisher)!==i.transport)))){((t=this.boundTrack)===null||t===void 0?void 0:t.sender)===i.transceiver.sender&&(this.boundTrack.sender=void 0),i.transport.releaseSender(i.transceiver),i.transceiver.stop();try{yield i.engine.negotiate()}catch{}}})}finish(){var e;(e=this.release)===null||e===void 0||e.call(this,this),this.release=void 0,this.publish=void 0,this.committed||(this.boundTrack=void 0)}},gi;(function(n){n[n.WAITING=0]="WAITING",n[n.RUNNING=1]="RUNNING",n[n.COMPLETED=2]="COMPLETED"})(gi||(gi={}));var va=class{constructor(){this.pendingTasks=new Map,this.taskMutex=new ye,this.nextTaskIndex=0}run(e){return g(this,void 0,void 0,function*(){let t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:gi.WAITING};this.pendingTasks.set(t.id,t);let i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=gi.RUNNING,yield e()}finally{t.status=gi.COMPLETED,this.pendingTasks.delete(t.id),i()}})}flush(){return g(this,void 0,void 0,function*(){return this.run(()=>g(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}};function Lf(n){if(n.length===0)return new AbortController().signal;if(n.length===1)return n[0];for(let r of n)if(r.aborted)return r;let e=new AbortController,t=Array(n.length),i=()=>{for(let r of t)r()};return n.forEach((r,s)=>{let a=()=>{e.abort(r.reason),i()};r.addEventListener("abort",a),t[s]=()=>r.removeEventListener("abort",a)}),e.signal}function td(n){let e=new AbortController;return setTimeout(()=>{e.abort(new DOMException("signal timed out after ".concat(n," ms"),"TimeoutError"))},n),e.signal}var c0=["client"],To=typeof WeakRef<"u"?WeakRef:class{constructor(n){this.target=n}deref(){return this.target}},Df=class{constructor(){j(this,"listeners",new Map)}on(e,t){let i=this.listeners.get(e);return i||(i=new Set,this.listeners.set(e,i)),i.add(t),{off:()=>{i.delete(t)}}}emit(e,t){let i=this.listeners.get("*");if(i)for(let s of i)s(e,t);let r=this.listeners.get(e);if(r)for(let s of r)s(t)}clear(){this.listeners.clear()}},Ln=class extends Error{constructor(n,e){super("non-serializable value at ".concat(n," (").concat(e,")")),this.path=n,this.label=e}},d0=(n,e)=>ya(n,e,new Set),ya=(n,e,t)=>{if(n===null)return null;switch(typeof n){case"string":case"boolean":return n;case"number":if(!Number.isFinite(n))throw new Ln(e,u0(n));return n;case"object":return l0(n,e,t);default:throw new Ln(e,typeof n)}},l0=(n,e,t)=>{var i,r;if(t.has(n))throw new Ln(e,"circular reference");if(Array.isArray(n)){if(n.length!==Object.keys(n).length)throw new Ln(e,"sparse array or array with non-index properties");t.add(n);let o=n.map((c,d)=>ya(c,"".concat(e,"[").concat(d,"]"),t));return t.delete(n),o}let s=Object.getPrototypeOf(n);if(s!==Object.prototype&&s!==null)throw new Ln(e,(i=(r=n.constructor)===null||r===void 0?void 0:r.name)!==null&&i!==void 0?i:"object");t.add(n);let a={};for(let o of Object.keys(n)){let c=ya(n[o],"".concat(e,".").concat(o),t);Object.defineProperty(a,o,{value:c,enumerable:!0,writable:!0,configurable:!0})}return t.delete(n),a},u0=n=>Number.isNaN(n)?"NaN":n>0?"Infinity":"-Infinity",ba=function(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:new Set;if(n===null||typeof n!="object"||e.has(n))return n;if(Array.isArray(n)){e.add(n);let r=n.map(s=>ba(s,e));return e.delete(n),r}let t=Object.getPrototypeOf(n);if(t!==Object.prototype&&t!==null)return n;e.add(n);let i={};for(let r of Object.keys(n)){let s=ba(n[r],e);Object.defineProperty(i,r,{value:s,enumerable:!0,writable:!0,configurable:!0})}return e.delete(n),i},vi=Symbol("machina.type"),tu=20,h0=class{constructor(e){j(this,"id",void 0),j(this,"initialState",void 0),j(this,vi,"BehavioralFsm"),j(this,"states",void 0),j(this,"emitter",new Df),j(this,"clients",new WeakMap),j(this,"knownClients",new Set),j(this,"childSubscriptions",[]),j(this,"disposed",!1),j(this,"transitionDepth",0),this.id=e.id,this.initialState=e.initialState,this.states=e.states,this.wrapChildLinks(),this.setupChildSubscriptions()}handle(e,t){var i;if(this.disposed)return;let r=this.getOrCreateClientMeta(e);for(var s=arguments.length,a=new Array(s>2?s-2:0),o=2;o<s;o++)a[o-2]=arguments[o];r.currentActionArgs=a;let c=(i=this.states[r.state])===null||i===void 0?void 0:i._child;if(c&&c.canHandle(e,t)){try{c.handle(e,t,...a)}finally{r.currentActionArgs=void 0}return}this.handleLocally(e,t,a,r)}canHandle(e,t){var i,r,s;if(this.disposed)return!1;let a=(i=(r=this.clients.get(e))===null||r===void 0?void 0:r.state)!==null&&i!==void 0?i:this.initialState,o=this.states[a];if((s=o?.[t])!==null&&s!==void 0?s:o?.["*"])return!0;let c=o?._child;return c?c.canHandle(e,t):!1}reset(e){this.disposed||this.transition(e,this.initialState)}currentState(e){var t;return(t=this.clients.get(e))===null||t===void 0?void 0:t.state}transition(e,t){if(this.disposed)return;let i=this.getOrCreateClientMeta(e),r=i.state;if(t!==r){if(!Object.prototype.hasOwnProperty.call(this.states,t)){this.emitter.emit("invalidstate",{stateName:t,client:e});return}if(this.transitionDepth++,this.transitionDepth>tu)throw this.transitionDepth=0,new Error("Max transition depth (".concat(tu,') exceeded in FSM "').concat(this.id,'". Likely an infinite _onEnter \u2192 transition loop.'));try{let s=this.states[r],a=this.states[t];if(s!=null&&s._onExit&&typeof s._onExit=="function"){let l=this.buildHandlerArgs(e,"",i);s._onExit(l)}i.state=t;let o={fromState:r,toState:t,client:e};this.emitter.emit("transitioning",o);let c;if(a!=null&&a._onEnter&&typeof a._onEnter=="function"){let l=this.buildHandlerArgs(e,"",i);c=a._onEnter(l)}this.emitter.emit("transitioned",o);let d=a?._child;d&&d.reset(e),this.processQueue(e,i),typeof c=="string"&&i.state===t&&this.transition(e,c)}finally{this.transitionDepth--}}}compositeState(e){var t;let i=this.clients.get(e);if(!i)return"";let r=(t=this.states[i.state])===null||t===void 0?void 0:t._child;if(r){let s=r.compositeState(e);if(s)return"".concat(i.state,".").concat(s)}return i.state}rehydrate(e,t){if(this.disposed)return;if(typeof t=="string"){this.rehydrateCompositePath(e,t);return}let i=this.planSnapshotWrites(e,t);for(let r of i)r()}dehydrate(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,i=this.clients.get(e);if(!i)return;let r={state:i.state,deferred:i.deferredQueue.map(a=>this.snapshotDeferredInput(a))},s=this.collectChildSnapshots(e,i.state,t);return s&&(r.children=s),r}planSnapshotWrites(e,t){if(this.disposed)return[];let i=t.state,r=t.deferred,s=t.children;if(!Object.prototype.hasOwnProperty.call(this.states,i))throw new Error('rehydrate: unknown state "'.concat(i,'" in FSM "').concat(this.id,'". Valid states: ').concat(Object.keys(this.states).join(", ")));let a=[];if(s)for(let d of Object.keys(s)){var o;if(!Object.prototype.hasOwnProperty.call(this.states,d))throw new Error('rehydrate: unknown state "'.concat(d,'" in FSM "').concat(this.id,'" referenced by snapshot.children.'));let l=(o=this.states[d])===null||o===void 0?void 0:o._child;if(!l)throw new Error('rehydrate: state "'.concat(d,'" in FSM "').concat(this.id,'" has no _child, but the snapshot has a children["').concat(d,'"] entry.'));a.push(...l.planRehydrate(e,s[d]))}let c=r.map(d=>cg({inputName:d.inputName,args:ba(d.args)},d.untilState!==void 0?{untilState:d.untilState}:{}));return a.push(()=>{this.clients.has(e)||this.knownClients.add(new To(e)),this.clients.set(e,{state:i,deferredQueue:c})}),a}rehydrateCompositePath(e,t){let i=t.split("."),r=ug(i),s=r[0],a=Ko(r).slice(1);if(!Object.prototype.hasOwnProperty.call(this.states,s))throw new Error('rehydrate: unknown state "'.concat(s,'" in FSM "').concat(this.id,'". Valid states: ').concat(Object.keys(this.states).join(", ")));if(a.length>0){var o;let c=a.join("."),d=(o=this.states[s])===null||o===void 0?void 0:o._child;if(!d)throw new Error('rehydrate: state "'.concat(s,'" in FSM "').concat(this.id,'" has no _child, but composite path "').concat(t,'" requires one.'));d.rehydrate(e,c)}this.clients.has(e)||this.knownClients.add(new To(e)),this.clients.set(e,{state:s,deferredQueue:[]})}collectChildSnapshots(e,t,i){let r=new Map;for(let o of Object.keys(this.states)){var s;let c=(s=this.states[o])===null||s===void 0?void 0:s._child;if(!c)continue;let d=r.get(c.instance);d?d.stateNames.push(o):r.set(c.instance,{childLink:c,stateNames:[o]})}let a;for(let o of r.values()){let c=o.childLink,d=o.stateNames,l=i&&d.includes(t);if(c.instance[vi]==="Fsm"&&!l)continue;let u=c.dehydrate(e,l);if(u){a??(a={});for(let h of d)a[h]=u}}return a}snapshotDeferredInput(e){let t;try{t=d0(e.args,"args")}catch(r){if(!(r instanceof Ln))throw r;let s=e.untilState?' (until "'.concat(e.untilState,'")'):"";throw new Error('dehydrate: deferred input "'.concat(e.inputName,'"').concat(s,' in FSM "').concat(this.id,'" has a non-serializable value at ').concat(r.path," (").concat(r.label,")"))}let i={inputName:e.inputName,args:t};return e.untilState!==void 0&&(i.untilState=e.untilState),i}on(e,t){return this.disposed?{off(){}}:this.emitter.on(e,t)}emit(e,t){this.disposed||this.emitter.emit(e,t)}dispose(e){this.disposed=!0;for(let i of this.childSubscriptions)i.off();if(!(e!=null&&e.preserveChildren)){let i=new Set;for(let r of Object.keys(this.states)){var t;let s=(t=this.states[r])===null||t===void 0?void 0:t._child;s&&!i.has(s.instance)&&(i.add(s.instance),s.dispose())}}this.emitter.clear()}wrapChildLinks(){for(let e of Object.keys(this.states)){let t=this.states[e],i=t?._child;if(i){if(typeof i!="object")throw new Error('State "'.concat(e,'"._child: expected an Fsm or BehavioralFsm instance, got ').concat(String(i)));if(!(vi in i))throw new Error('State "'.concat(e,'"._child: expected an Fsm or BehavioralFsm instance, got a plain object'));t._child=f0(i)}}}setupChildSubscriptions(){let e=new Set;for(let i of Object.keys(this.states)){var t;let r=(t=this.states[i])===null||t===void 0?void 0:t._child;if(!r||e.has(r.instance))continue;e.add(r.instance);let s=r.onAny((a,o)=>{if(a==="nohandler"){var c;let u=o;if(u.client!==void 0)this.bubbleNohandler(u.client,r,u.inputName,(c=u.args)!==null&&c!==void 0?c:[]);else for(let h of this.knownClients){var d;let f=h.deref();if(f===void 0){this.knownClients.delete(h);continue}this.bubbleNohandler(f,r,u.inputName,(d=u.args)!==null&&d!==void 0?d:[])}return}let l=o;if(l&&typeof l=="object"&&"client"in l)this.isChildActiveForClient(l.client,r)&&this.emitter.emit(a,o);else for(let u of this.knownClients){let h=u.deref();if(!h){this.knownClients.delete(u);continue}if(this.isChildActiveForClient(h,r)){this.emitter.emit(a,o);break}}});this.childSubscriptions.push(s)}}bubbleNohandler(e,t,i,r){if(!this.isChildActiveForClient(e,t))return;let s=this.clients.get(e);s.currentActionArgs=r,this.handleLocally(e,i,r,s)}isChildActiveForClient(e,t){var i;let r=this.clients.get(e);return r?((i=this.states[r.state])===null||i===void 0||(i=i._child)===null||i===void 0?void 0:i.instance)===t.instance:!1}handleLocally(e,t,i,r){var s;let a=this.states[r.state],o=(s=a?.[t])!==null&&s!==void 0?s:a?.["*"];if(!o){this.emitter.emit("nohandler",{inputName:t,args:i,client:e}),r.currentActionArgs=void 0;return}try{this.emitter.emit("handling",{inputName:t,client:e});let c=this.buildHandlerArgs(e,t,r),d;typeof o=="string"?d=o:typeof o=="function"&&(d=o(c,...i)),this.emitter.emit("handled",{inputName:t,client:e}),typeof d=="string"&&this.transition(e,d)}finally{r.currentActionArgs=void 0}}getOrCreateClientMeta(e){let t=this.clients.get(e);return t||(t={state:void 0,deferredQueue:[]},this.clients.set(e,t),this.knownClients.add(new To(e)),this.transition(e,this.initialState),t)}buildHandlerArgs(e,t,i){return{ctx:e,inputName:t,defer:r=>{if(!i.currentActionArgs)return;let s={inputName:t,args:[...i.currentActionArgs],untilState:r?.until};i.deferredQueue.push(s),this.emitter.emit("deferred",{inputName:t,client:e})},emit:(r,s)=>{this.emitter.emit(r,s)}}}processQueue(e,t){let i=[],r=[];for(let s of t.deferredQueue)s.untilState===void 0||s.untilState===t.state?i.push(s):r.push(s);t.deferredQueue=r;for(let s of i)this.handle(e,s.inputName,...s.args)}};function f0(n){if(!n||typeof n!="object")throw new Error("createChildLink: expected an Fsm or BehavioralFsm instance, got ".concat(String(n)));let e=n[vi];if(e==="BehavioralFsm")return{instance:n,canHandle(t,i){return n.canHandle(t,i)},handle(t,i){for(var r=arguments.length,s=new Array(r>2?r-2:0),a=2;a<r;a++)s[a-2]=arguments[a];n.handle(t,i,...s)},reset(t){n.transition(t,n.initialState)},onAny(t){return n.on("*",t)},compositeState(t){return n.compositeState(t)},rehydrate(t,i){n.rehydrate(t,i)},dehydrate(t,i){return n.dehydrate(t,i)},planRehydrate(t,i){return n.planSnapshotWrites(t,i)},dispose(){n.dispose()}};if(e==="Fsm")return{instance:n,canHandle(t,i){return n.canHandle(i)},handle(t,i){for(var r=arguments.length,s=new Array(r>2?r-2:0),a=2;a<r;a++)s[a-2]=arguments[a];n.handle(i,...s)},reset(t){n.reset()},onAny(t){return n.on("*",t)},compositeState(t){return n.compositeState()},rehydrate(t,i){throw new Error("rehydrate: cannot rehydrate an Fsm child. Fsm owns its own context; rehydrate is only valid for BehavioralFsm hierarchies.")},dehydrate(t,i){throw new Error("dehydrate: cannot dehydrate an Fsm child. Fsm owns its own context; dehydrate is only valid for BehavioralFsm hierarchies.")},planRehydrate(t,i){throw new Error("rehydrate: cannot rehydrate an Fsm child. Fsm owns its own context; rehydrate is only valid for BehavioralFsm hierarchies.")},dispose(){n.dispose()}};throw new Error("createChildLink: expected an Fsm or BehavioralFsm instance, got [MACHINA_TYPE] = ".concat(String(e??"undefined")))}var p0=class{constructor(e){var t;j(this,"id",void 0),j(this,"initialState",void 0),j(this,vi,"Fsm"),j(this,"states",void 0),j(this,"bfsm",void 0),j(this,"context",void 0),j(this,"emitter",new Df),j(this,"disposed",!1),this.id=e.id,this.initialState=e.initialState,this.context=(t=e.context)!==null&&t!==void 0?t:{},this.bfsm=new h0(e),this.states=e.states,this.bfsm.on("*",(i,r)=>{if(r&&typeof r=="object"&&"client"in r){r.client;let s=dg(r,c0);this.emitter.emit(i,s)}else this.emitter.emit(i,r)}),this.bfsm.transition(this.context,e.initialState)}handle(e){if(!this.disposed){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];this.bfsm.handle(this.context,e,...i)}}canHandle(e){return this.disposed?!1:this.bfsm.canHandle(this.context,e)}reset(){this.disposed||this.bfsm.reset(this.context)}currentState(){return this.bfsm.currentState(this.context)}transition(e){this.disposed||this.bfsm.transition(this.context,e)}compositeState(){return this.bfsm.compositeState(this.context)}on(e,t){return this.disposed?{off(){}}:this.emitter.on(e,t)}emit(e,t){this.disposed||this.bfsm.emit(e,t)}dispose(e){this.disposed=!0,this.bfsm.dispose(e),this.emitter.clear()}};function m0(n){return new p0(n)}function Nf(n,e){return e.attemptId===n.attemptId}var nu=(n,e)=>{let t=n.ctx;if(Nf(t,e))return"connected"},So=n=>{let e=n.ctx;return e.attemptId+=1,e.lastError=void 0,"connecting"},_o=n=>{let e=n.ctx;return e.attemptId+=1,e.lastError=void 0,"reconnecting"},si=(n,e)=>{let t=n.ctx;return t.closeReason=e.reason,"disconnecting"},g0={new:{connect:So,close:si},connecting:{connectComplete:nu,connectFailed:(n,e)=>{let t=n.ctx;return t.lastError=e.error,"closed"},close:si},connected:{reconnect:_o,transportFailed:(n,e)=>{let t=n.ctx;if(Nf(t,e))return t.lastError=e.reason,"offline"},close:si},offline:{connect:So,reconnect:_o,close:si},reconnecting:{reconnectComplete:nu,reconnectFailed:(n,e)=>{let t=n.ctx;return t.lastError=e.error,e.recoverable?"offline":"closed"},close:si},disconnecting:{closeComplete:"closed"},closed:{connect:So,reconnect:_o}};function v0(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"new";return m0({id:"signal",initialState:n,context:{attemptId:0},states:g0})}var ka=class{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i,r;if(!((i=t.signal)===null||i===void 0)&&i.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;let s=new WebSocket(e,(r=t.protocols)!==null&&r!==void 0?r:[]);s.binaryType="arraybuffer",this.ws=s;let a,o,c=function(){let d=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};s.readyState===WebSocket.CONNECTING&&(a=d,o(U.websocket("Websocket closed before the connection opened")));let l=d.closeCode,u=d.reason;s.close(l,u===void 0?void 0:y0(u))};this.opened=new Pe((d,l)=>{o=l;let u=()=>{l(U.websocket("Encountered websocket error during connection establishment"))},h=f=>{l(U.websocket("Websocket closed during connection establishment with code ".concat(f.code).concat(f.reason?": ".concat(f.reason):"")))};s.onopen=()=>{if(a){c(a);return}d({readable:new ReadableStream({start(f){s.onmessage=m=>{let p=m.data;s.readyState===WebSocket.OPEN&&f.enqueue(p)},s.onerror=m=>f.error(U.websocket(Gy(m,"websocket"))),s.onclose=m=>{m.wasClean||m.code===1e3?f.close():f.error(U.websocket("WS closed unexpectedly with code ".concat(m.code)))}},cancel:c}),writable:new WritableStream({write(f){s.send(f)},abort(){s.close()},close:c}),protocol:s.protocol,extensions:s.extensions}),s.removeEventListener("error",u),s.removeEventListener("close",h)},s.addEventListener("error",u),s.addEventListener("close",h)}),this.closed=new Pe((d,l)=>{let u=()=>g(this,void 0,void 0,function*(){let h=new Pe(m=>{s.readyState!==WebSocket.CLOSED&&s.addEventListener("close",p=>{m(p)},{once:!0})}),f=yield Pe.race([Re(250),h]);f?d(f):l(U.websocket("Encountered unspecified websocket error without a timely close event"))});s.addEventListener("close",h=>{let f=h.code,m=h.reason;d({closeCode:f,reason:m}),s.removeEventListener("error",u)}),s.addEventListener("error",u)}),t.signal&&(t.signal.onabort=()=>c()),this.close=c}},iu=123;function y0(n){let e=new TextEncoder;if(e.encode(n).length<=iu)return n;let t="",i=0;for(let r of n){if(i+=e.encode(r).length,i>iu)break;t+=r}return t}var b0=["syncState","trickle","offer","answer","simulate","leave"];function k0(n){return n instanceof U?n.reason!==Z.LeaveRequest&&n.reason!==Z.NotAllowed:!0}function T0(n){let e=b0.indexOf(n.case)>=0;return W.trace("request allowed to bypass queue:",{canPass:e,req:n}),e}var Me;(function(n){n[n.CONNECTING=0]="CONNECTING",n[n.CONNECTED=1]="CONNECTED",n[n.RECONNECTING=2]="RECONNECTING",n[n.DISCONNECTING=3]="DISCONNECTING",n[n.DISCONNECTED=4]="DISCONNECTED"})(Me||(Me={}));function S0(n){switch(n){case"connected":return Me.CONNECTED;case"connecting":return Me.CONNECTING;case"reconnecting":return Me.RECONNECTING;case"disconnecting":return Me.DISCONNECTING;default:return Me.DISCONNECTED}}var _0=250,C0=5e3,N;(function(n){n.Close="close",n.Joined="joined",n.Answer="answer",n.Offer="offer",n.Trickle="trickle",n.ParticipantUpdate="participantUpdate",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalTrackSubscribed="localTrackSubscribed",n.SpeakersChanged="speakersChanged",n.RemoteMuteChanged="remoteMuteChanged",n.RoomUpdate="roomUpdate",n.ConnectionQuality="connectionQuality",n.StreamStateUpdate="streamStateUpdate",n.SubscribedQualityUpdate="subscribedQualityUpdate",n.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",n.SubscriptionError="subscriptionError",n.TokenRefresh="tokenRefresh",n.Leave="leave",n.RequestResponse="requestResponse",n.RoomMoved="roomMoved",n.MediaSectionsRequirement="mediaSectionsRequirement",n.PublishDataTrackResponse="publishDataTrackResponse",n.UnpublishDataTrackResponse="unpublishDataTrackResponse",n.DataTrackSubscriberHandles="dataTrackSubscriberHandles"})(N||(N={}));var Oi=class extends Oe.EventEmitter{get currentState(){return S0(this.lifecycleState)}get isDisconnected(){let e=this.currentState;return e===Me.DISCONNECTING||e===Me.DISCONNECTED}get lifecycleState(){return this.machine.currentState()}get attemptId(){return this.machine.context.attemptId}sendLifecycleInput(e){let t=this.lifecycleState;return this.machine.handle(e.type,e),this.lifecycleState!==t}settleInFlightClose(){return g(this,void 0,void 0,function*(){this.log.debug("waiting for an in-flight close to settle before establishing a session"),(yield this.closingLock.lock())()})}get isEstablishingConnection(){return this.lifecycleState==="connecting"||this.lifecycleState==="reconnecting"}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;super(),this.rtt=0,this.log=W,this._requestId=0,this.useV0SignalPath=!1,this.loggerContextCb=t.loggerContextCb,this.log=we((i=t.loggerName)!==null&&i!==void 0?i:he.Signal,()=>this.logContext),this.useJSON=e,this.requestQueue=new va,this.queuedRequests=[],this.closingLock=new ye,this.connectionLock=new ye,this.machine=v0(),this.machine.on("transitioned",r=>{let s=r.fromState,a=r.toState;this.log.debug("signal lifecycle: ".concat(s," -> ").concat(a))}),this.machine.on("nohandler",r=>{let s=r.inputName;this.log.debug("ignoring signal lifecycle input ".concat(s," in state ").concat(this.lifecycleState))}),this.machine}get logContext(){var e,t;return(t=(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this))!==null&&t!==void 0?t:{}}join(e,t,i,r){return g(this,arguments,void 0,function(s,a,o,c){var d=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,u=arguments.length>5?arguments[5]:void 0,h=arguments.length>6&&arguments[6]!==void 0?arguments[6]:[];return(function*(){if(d.lifecycleState==="disconnecting"&&(yield d.settleInFlightClose()),!d.sendLifecycleInput({type:"connect"}))throw U.internal("cannot establish a signal session from '".concat(d.lifecycleState,"', close the current one first"));d.options=o;try{return yield d.connect(s,a,o,c,l,u,h)}catch(f){throw d.sendLifecycleInput({type:"connectFailed",error:f}),f}})()})}reconnect(e,t,i,r){return g(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring");return}if(this.lifecycleState==="disconnecting"&&(yield this.settleInFlightClose()),!this.sendLifecycleInput({type:"reconnect"}))throw U.internal("cannot resume the signal session from '".concat(this.lifecycleState,"'"));this.clearPingInterval();try{return yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:r}),void 0,this.useV0SignalPath)}catch(s){throw this.sendLifecycleInput({type:"reconnectFailed",error:s,recoverable:k0(s)}),s}})}connect(e,t,i,r){return g(this,arguments,void 0,function(s,a,o,c){var d=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,u=arguments.length>5?arguments[5]:void 0,h=arguments.length>6&&arguments[6]!==void 0?arguments[6]:[];return(function*(){let f=yield d.connectionLock.lock(),m,p;try{d.connectOptions=o,d.useV0SignalPath=l;let y=Iy(o.clientInfoCapabilities),v=l?w0(a,y,o):yield E0(a,y,o,u,h);m=Wy(s,v,l).toString(),p=Ky(m).toString()}catch(y){throw f(),y}if(c?.aborted)throw f(),d.log.debug("signal connect abandoned before opening a transport"),U.cancelled("Connection aborted");return new Promise((y,v)=>g(d,void 0,void 0,function*(){var _,P,b,k,S;try{let E=!1,O=$=>g(this,void 0,void 0,function*(){if(E)return;E=!0;let xe=typeof Event<"u"&&$ instanceof Event?$.currentTarget:$,V=zy(xe,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(!0,V)).catch(se=>{this.log.error(se),this.close(!0,V)}):this.close(!0,V),q(),v($ instanceof U?$:U.cancelled(V))});c?.addEventListener("abort",O);let q=()=>{clearTimeout(x),c?.removeEventListener("abort",O)},x=setTimeout(()=>{O(U.timeout("room connection has timed out (signal)"))},o.websocketTimeout),D=new URL(m);if(D.searchParams.has("access_token")&&D.searchParams.set("access_token","<redacted>"),this.ws){let $=performance.now();yield this.teardownTransport("replaced by a new connection attempt"),this.log.debug("closed previous ws connection in ".concat(performance.now()-$,"ms"))}if(E){this.log.debug("signal connect abandoned after tearing down the previous transport");return}let B=this.attemptId;this.log.info("signal connecting to ".concat(D),{reconnect:o.reconnect,reconnectReason:o.reconnectReason}),this.ws=new ka(m);let H=!1;this.ws.opened.catch(()=>{H=!0});try{this.ws.closed.then(Q=>{this.isEstablishingConnection&&!H&&v(U.internal("Websocket got closed during a (re)connection attempt: ".concat(Q.reason))),this.log.debug("websocket closed",{reason:Q.reason,code:Q.closeCode,attemptId:B,state:this.lifecycleState}),this.handleOnClose(Q.reason||(Q.closeCode===1e3?"server closed the signal connection":"Unexpected WS error"),B)}).catch(Q=>{this.isEstablishingConnection&&!H&&v(U.internal("Websocket error during a (re)connection attempt: ".concat(Q)))});let $=yield this.ws.opened.catch(Q=>g(this,void 0,void 0,function*(){if(E){this.log.debug("signal connect abandoned while the websocket was opening");return}if(this.lifecycleState!=="connected"){clearTimeout(x);let De=yield this.handleConnectionError(Q,p);v(De);return}this.handleWSError(Q),v(Q)}));if(clearTimeout(x),!$)return;let xe=$.readable.getReader();this.streamWriter=$.writable.getWriter();let V;try{let Q=Date.now()+C0;for(;;){let De=Q-Date.now();if(De<=0)throw U.timeout("signal connection timed out while waiting for the first message");let Qn,Yn=yield Promise.race([xe.read(),new Promise((zi,Xn)=>{Qn=setTimeout(()=>{Xn(U.timeout("signal connection timed out while waiting for the first message"))},De)})]);if(clearTimeout(Qn),!Yn.value)throw U.internal("no message received as first message");let xt=$l(Yn.value);if(this.lifecycleState==="reconnecting"&&((_=xt.message)===null||_===void 0?void 0:_.case)!=="reconnect"&&((P=xt.message)===null||P===void 0?void 0:P.case)!=="leave"){this.log.warn("dropping signal message while awaiting reconnect response",{messageCase:(b=xt.message)===null||b===void 0?void 0:b.case});continue}V=xt;break}}catch(Q){xe.releaseLock(),v(Q),this.close();return}if(xe.releaseLock(),E){this.log.debug("signal connect abandoned while waiting for the first message");return}let se=this.validateFirstMessage(V,(k=o.reconnect)!==null&&k!==void 0?k:!1);if(!se.isValid){v(se.error);return}((S=V.message)===null||S===void 0?void 0:S.case)==="join"&&(this.pingTimeoutDuration=V.message.value.pingTimeout,this.pingIntervalDuration=V.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}),this.emit(N.Joined,V.message.value)),this.handleSignalConnected($,x,B),y(se.response)}catch($){v($)}finally{q()}}finally{f()}}))})()})}startReadingLoop(e){return g(this,void 0,void 0,function*(){let t=this.attemptId;for(;;){this.signalLatency&&(yield Re(this.signalLatency));try{let i=yield e.read(),r=i.done,s=i.value;if(r)break;let a=$l(s);this.handleSignalResponse(a)}catch(i){yield this.handleOnClose("error in reading loop",t,void 0,i);break}}})}close(){return g(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Close method called on signal client";return(function*(){let r=t&&e.sendLifecycleInput({type:"close",reason:i}),s=yield e.closingLock.lock();try{yield e.teardownTransport(i)}finally{r&&e.sendLifecycleInput({type:"closeComplete"}),s()}})()})}teardownTransport(e){return g(this,void 0,void 0,function*(){try{this.clearPingInterval();let t=this.ws;t&&(this.ws=void 0,this.streamWriter=void 0,t.close({closeCode:1e3,reason:e}),yield Promise.race([t.closed,Re(_0)]))}catch(t){this.log.debug("websocket error while closing",{error:t})}})}sendOffer(e,t){this.log.debug("sending offer",{offerSdp:e.sdp}),this.sendRequest({case:"offer",value:Xt(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",{answerSdp:e.sdp}),this.sendRequest({case:"answer",value:Xt(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",{candidate:e}),this.sendRequest({case:"trickle",value:new bs({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new ks({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return g(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(function*(){let o=s.getNextRequestId();return yield s.sendRequest({case:"updateMetadata",value:new Wc({requestId:o,metadata:i,name:r,attributes:a})}),o})()})}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:"updateLayers",value:new lf({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new ff({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:ue.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new gf({timestamp:ue.parse(Date.now()),rtt:ue.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new Vc({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Ss({reason:Ke.CLIENT_INITIATED,action:En.DISCONNECT})})}sendPublishDataTrackRequest(e,t,i){return this.sendRequest({case:"publishDataTrackRequest",value:new Fc({pubHandle:e,name:t,encryption:i?X.GCM:X.NONE})})}sendUnPublishDataTrackRequest(e){return this.sendRequest({case:"unpublishDataTrackRequest",value:new Bc({pubHandle:e})})}sendUpdateDataSubscription(e,t){return this.sendRequest({case:"updateDataSubscription",value:new jc({updates:[new af({trackSid:e,subscribe:t})]})})}sendRequest(e){return g(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return(function*(){let s=!r&&!T0(t),a=i.lifecycleState==="reconnecting"||i.queuedRequests.length>0;if(s&&a){i.queuedRequests.push(()=>g(i,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}r||(yield i.requestQueue.flush()),i.signalLatency&&(yield Re(i.signalLatency));let o=t.case==="leave"&&!!i.streamWriter;if(i.isDisconnected&&!o){i.log.debug("skipping signal request (type: ".concat(t.case,") - SignalClient disconnected"));return}if(!i.streamWriter){i.log.error("cannot send signal request before connected, type: ".concat(t?.case));return}let c=new iv({message:t});try{i.useJSON?yield i.streamWriter.write(c.toJsonString()):yield i.streamWriter.write(c.toBinary().buffer)}catch(d){i.log.error("error sending signal message",{error:d})}})()})}handleSignalResponse(e){var t,i;let r=e.message;if(r==null){this.log.debug("received unsupported message");return}let s=!1;if(r.case==="answer"){let a=ru(r.value);this.emit(N.Answer,a,r.value.id,r.value.midToTrackId)}else if(r.case==="offer"){let a=ru(r.value);this.emit(N.Offer,a,r.value.id,r.value.midToTrackId)}else if(r.case==="trickle"){let a=JSON.parse(r.value.candidateInit);this.emit(N.Trickle,a,r.value.target)}else r.case==="update"?this.emit(N.ParticipantUpdate,(t=r.value.participants)!==null&&t!==void 0?t:[]):r.case==="trackPublished"?this.emit(N.LocalTrackPublished,r.value):r.case==="speakersChanged"?this.emit(N.SpeakersChanged,(i=r.value.speakers)!==null&&i!==void 0?i:[]):r.case==="leave"?this.emit(N.Leave,r.value):r.case==="mute"?this.emit(N.RemoteMuteChanged,r.value.sid,r.value.muted):r.case==="roomUpdate"?r.value.room&&this.emit(N.RoomUpdate,r.value.room):r.case==="connectionQuality"?this.emit(N.ConnectionQuality,r.value):r.case==="streamStateUpdate"?this.emit(N.StreamStateUpdate,r.value):r.case==="subscribedQualityUpdate"?this.emit(N.SubscribedQualityUpdate,r.value):r.case==="subscriptionPermissionUpdate"?this.emit(N.SubscriptionPermissionUpdate,r.value):r.case==="refreshToken"?this.emit(N.TokenRefresh,r.value):r.case==="trackUnpublished"?this.emit(N.LocalTrackUnpublished,r.value):r.case==="subscriptionResponse"?this.emit(N.SubscriptionError,r.value):r.case==="pong"||(r.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(r.value.lastPingTimestamp.toString()),this.resetPingTimeout(),s=!0):r.case==="requestResponse"?this.emit(N.RequestResponse,r.value):r.case==="trackSubscribed"?this.emit(N.LocalTrackSubscribed,r.value.trackSid):r.case==="roomMoved"?(this.emit(N.TokenRefresh,r.value.token),this.emit(N.RoomMoved,r.value)):r.case==="mediaSectionsRequirement"?this.emit(N.MediaSectionsRequirement,r.value):r.case==="publishDataTrackResponse"?this.emit(N.PublishDataTrackResponse,r.value):r.case==="unpublishDataTrackResponse"?this.emit(N.UnpublishDataTrackResponse,r.value):r.case==="dataTrackSubscriberHandles"?this.emit(N.DataTrackSubscriberHandles,r.value):this.log.debug("unsupported message",{msgCase:r.case}));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){let e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return g(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.attemptId,s=arguments.length>2?arguments[2]:void 0,a=arguments.length>3?arguments[3]:void 0;return(function*(){let o=i.listeners(N.Close);if(!i.sendLifecycleInput({type:"transportFailed",attemptId:r,reason:t})){i.log.debug("ignoring transport close in state ".concat(i.lifecycleState),Object.assign({reason:t,attemptId:r,currentAttemptId:i.attemptId},a!==void 0?{error:a}:{}));return}a!==void 0&&i.log.error("error reading from signal stream",{error:a}),yield i.teardownTransport(t),i.log.info("websocket connection closed: ".concat(t),{reason:t}),s&&(i.log.info("waiting for ".concat(s,"ms until reconnecting signal")),yield Re(s));for(let c of o)c(t)})()})}handleWSError(e){this.log.error("websocket error",{error:e})}resetPingTimeout(){if(this.clearPingTimeout(),!this.isDisconnected){if(!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set");return}this.pingTimeout=Y.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString())),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}}clearPingTimeout(){this.pingTimeout&&Y.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn("ping interval duration not set");return}this.log.debug("start ping interval"),this.pingInterval=Y.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval"),this.clearPingTimeout(),this.pingInterval&&Y.clearInterval(this.pingInterval)}handleSignalConnected(e,t,i){if(clearTimeout(t),!this.sendLifecycleInput(this.lifecycleState==="reconnecting"?{type:"reconnectComplete",attemptId:i}:{type:"connectComplete",attemptId:i})){this.log.debug("discarding a connection whose attempt no longer owns the session",{attemptId:i,currentAttemptId:this.attemptId,state:this.lifecycleState});return}this.log.info("signal connected"),this.startPingInterval(),this.startReadingLoop(e.readable.getReader())}validateFirstMessage(e,t){var i,r,s,a;return((i=e.message)===null||i===void 0?void 0:i.case)==="join"?{isValid:!0,response:e.message.value}:this.lifecycleState==="reconnecting"&&((r=e.message)===null||r===void 0?void 0:r.case)==="reconnect"?{isValid:!0,response:e.message.value}:this.isEstablishingConnection&&((s=e.message)===null||s===void 0?void 0:s.case)==="leave"?{isValid:!1,error:U.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:U.internal("Unexpected first message")}:{isValid:!1,error:U.internal("did not receive join response, got ".concat((a=e.message)===null||a===void 0?void 0:a.case," instead"))}}handleConnectionError(e,t){return g(this,void 0,void 0,function*(){try{let i=yield fetch(t,{signal:td(3e3)});switch(i.status){case 404:let r=yield i.text();return r.includes("requested room does not exist")?U.notAllowed(r,i.status):U.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:let s=yield i.text();return U.notAllowed(s,i.status);default:break}return e instanceof U?e:U.internal("Encountered unknown websocket error during connection: ".concat(e),{status:i.status,statusText:i.statusText})}catch(i){return i instanceof U?i:U.serverUnreachable(i instanceof Error?i.message:"server was not reachable")}})}};function ru(n){let e={type:"offer",sdp:n.sdp};switch(n.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=n.type;break}return e}function Xt(n,e){return new Ht({sdp:n.sdp,type:n.type,id:e})}function w0(n,e,t){var i;let r=new URLSearchParams;return r.set("access_token",n),t.reconnect&&(r.set("reconnect","1"),t.sid&&r.set("sid",t.sid)),r.set("auto_subscribe",t.autoSubscribe?"1":"0"),r.set("sdk",fi[e.sdk].toLowerCase().replace(/_/g,"")),r.set("version",e.version),r.set("protocol",e.protocol.toString()),r.set("client_protocol",e.clientProtocol.toString()),e.deviceModel&&r.set("device_model",e.deviceModel),e.os&&r.set("os",e.os),e.osVersion&&r.set("os_version",e.osVersion),e.browser&&r.set("browser",e.browser),e.browserVersion&&r.set("browser_version",e.browserVersion),t.adaptiveStream&&r.set("adaptive_stream","1"),t.disableIceLite&&r.set("disable_ice_lite","1"),typeof t.subscriberAllowPause<"u"&&r.set("subscriber_allow_pause",t.subscriberAllowPause?"1":"0"),t.reconnectReason&&r.set("reconnect_reason",t.reconnectReason.toString()),!((i=navigator.connection)===null||i===void 0)&&i.type&&r.set("network",navigator.connection.type),r}function E0(n,e,t,i){return g(this,arguments,void 0,function(r,s,a,o){let c=arguments.length>4&&arguments[4]!==void 0?arguments[4]:[];return(function*(){let d=new URLSearchParams;d.set("access_token",r);let l=new xv({clientInfo:s,connectionSettings:new vf({autoSubscribe:!!a.autoSubscribe,adaptiveStream:!!a.adaptiveStream,disableIceLite:!!a.disableIceLite,subscriberAllowPause:a.subscriberAllowPause}),reconnect:!!a.reconnect,participantSid:a.sid?a.sid:void 0,publisherOffer:o,addTrackRequests:c});a.reconnectReason&&(l.reconnectReason=a.reconnectReason);let u=l.toBinary(),h,f;if(Of()){let v=new CompressionStream("gzip"),_=v.writable.getWriter();_.write(new Uint8Array(u)),_.close();let P=[],b=v.readable.getReader();for(;;){let O=yield b.read(),q=O.done,x=O.value;if(q)break;P.push(x)}let k=P.reduce((O,q)=>O+q.length,0),S=new Uint8Array(k),E=0;for(let O of P)S.set(O,E),E+=O.length;h=S,f=Xo.GZIP}else h=u,f=Xo.NONE;let p=new Lv({joinRequest:h,compression:f}).toBinary(),y=v=>{let _=Array.from(v,P=>String.fromCodePoint(P)).join("");return btoa(_)};return d.set("join_request",y(p).replace(/\+/g,"-").replace(/\//g,"_")),d})()})}var Ta=class{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){let i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();let r=i+this.ttl;return this._map.set(e,{value:t,expiresAt:r}),this}get(e){let t=this._map.get(e);if(t){if(t.expiresAt<Date.now()){this._map.delete(e);return}return t.value}}has(e){let t=this._map.get(e);return t?t.expiresAt<Date.now()?(this._map.delete(e),!1):!0:!1}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){let e=Date.now();for(let i of this._map.entries()){var t=F(i,2);let r=t[0];t[1].expiresAt<e&&this._map.delete(r)}this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(let i of this._map.entries()){var t=F(i,2);let r=t[0],s=t[1];s.expiresAt>=Date.now()&&e(s.value,r,this.asValueMap())}}map(e){this.cleanup();let t=[],i=this.asValueMap();for(let s of i.entries()){var r=F(s,2);let a=r[0],o=r[1];t.push(e(o,a,i))}return t}asValueMap(){let e=new Map;for(let i of this._map.entries()){var t=F(i,2);let r=t[0],s=t[1];s.expiresAt>=Date.now()&&e.set(r,s.value)}return e}};function nd(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:50,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var i,r;let s,a=(i=t.isImmediate)!==null&&i!==void 0?i:!1,o=(r=t.callback)!==null&&r!==void 0?r:!1,c=t.maxWait,d=Date.now(),l=[];function u(){if(c!==void 0){let f=Date.now()-d;if(f+e>=c)return c-f}return e}let h=function(){for(var f=arguments.length,m=new Array(f),p=0;p<f;p++)m[p]=arguments[p];let y=this;return new Promise((v,_)=>{let P=function(){if(s=void 0,d=Date.now(),!a){let k=n.apply(y,m);o&&o(k),l.forEach(S=>{let E=S.resolve;return E(k)}),l=[]}},b=a&&s===void 0;if(s!==void 0&&Y.clearTimeout(s),s=Y.setTimeout(P,u()),b){let k=n.apply(y,m);return o&&o(k),v(k)}l.push({resolve:v,reject:_})})};return h.cancel=function(f){s!==void 0&&Y.clearTimeout(s),l.forEach(m=>{let p=m.reject;return p(f)}),l=[]},h}var P0=.9,Cr=1e3,id=300,su=1500,R0=3500,I0=500,A0=20;function Ff(n,e,t){var i,r,s;if(!((i=n.msid)===null||i===void 0)&&i.includes(e))return(s=(r=n.rtp.find(a=>a.codec.toUpperCase()===t.toUpperCase()))===null||r===void 0?void 0:r.payload)!==null&&s!==void 0?s:0}function M0(n,e){if(n.maxbr<id)return;let t=Math.min(Math.round(n.maxbr*P0),n.maxbr);if(n.isScreenShare)return t;let i=Math.min(x0(e),O0());return Math.min(t,i)}function O0(){let n=typeof navigator<"u"?navigator.connection:void 0;switch(n?.effectiveType){case"slow-2g":case"2g":return id;case"3g":return I0;default:return Cr}}function x0(n){if(n===void 0)return Cr;let e=Math.min(Math.max((n-su)/(R0-su),0),1);return Math.round(Cr-e*(Cr-id))}function L0(n,e,t){let i;for(let r of n)if(!(r.type!=="video"||r.direction==="recvonly"||r.direction==="inactive"))for(let s of e){if(!s.cid)continue;let a=Ff(r,s.cid,s.codec);if(a===void 0)continue;let o=a>0?M0(s,t):void 0;o!==void 0&&(i===void 0||o>i)&&(i=o);break}return i}function D0(n,e,t){let i=n.fmtp.find(r=>r.payload===e);return i?i.config.includes("x-google-start-bitrate")||(i.config+=";x-google-start-bitrate=".concat(t)):n.fmtp.push({payload:e,config:"x-google-start-bitrate=".concat(t)}),!0}var gt={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",OfferAnswered:"offerAnswered",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"},Or=class extends Oe.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}createProbeOffer(){return g(this,void 0,void 0,function*(){var e,t,i;let r=yield this.offerLock.lock();try{return(i=(t=yield(e=this._pc)===null||e===void 0?void 0:e.createOffer())===null||t===void 0?void 0:t.sdp)!==null&&i!==void 0?i:""}finally{r()}})}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var r;super(),this.log=W,this.iceLog=W,this.ddExtID=0,this.latestOfferId=0,this.answeredOfferId=0,this.latestAcknowledgedOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.hasAppliedVideoStartBitrate=!1,this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=nd(s=>g(this,void 0,void 0,function*(){this.emit(gt.NegotiationStarted);try{yield this.createAndSendOffer()}catch(a){if(s)s(a);else throw a}}),A0),this.reservedSenders=new WeakSet,this.close=()=>{this._pc&&(this.log.debug("closing peer connection"),this.pendingInitialOffer=void 0,this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.offeredAudioNackMids=i.singlePeerConnection?["all"]:[],this.loggerOptions=t,this.log=we((r=t.loggerName)!==null&&r!==void 0?r:he.PCTransport,()=>this.logContext),this.iceLog=we(he.ICE,()=>this.logContext),this.config=e,this._pc=this.createPC(),this.offerLock=new ye}createPC(){let e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var i;t.candidate&&(this.iceLog.debug("local ICE candidate gathered",{candidate:t.candidate.candidate}),(i=this.onIceCandidate)===null||i===void 0||i.call(this,t.candidate))},e.onicecandidateerror=t=>{var i;this.iceLog.debug("ICE candidate error",{event:t}),(i=this.onIceCandidateError)===null||i===void 0||i.call(this,t)},e.oniceconnectionstatechange=()=>{var t;this.iceLog.debug("ICE connection state: ".concat(e.iceConnectionState)),(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;this.log.debug("signaling state: ".concat(e.signalingState)),(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;this.log.debug("connection state: ".concat(e.connectionState)),(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,e.connectionState)},e.ondatachannel=t=>{var i;this.log.debug("data channel opened by peer",{label:t.channel.label,id:t.channel.id}),(i=this.onDataChannel)===null||i===void 0||i.call(this,t)},e.ontrack=t=>{var i;(i=this.onTrack)===null||i===void 0||i.call(this,t)},e}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return g(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.iceLog.debug("queuing remote ICE candidate until remote description applied",{pendingCount:this.pendingCandidates.length+1}),this.pendingCandidates.push(e)})}isStaleAnswer(e){return this.latestOfferId>0&&e>0&&e!==this.latestOfferId}setRemoteDescription(e,t){return g(this,void 0,void 0,function*(){var i;if(e.type==="answer"&&this.isStaleAnswer(t))return this.log.warn("ignoring answer for old offer",{offerId:t,latestOfferId:this.latestOfferId}),!1;if(e.type==="answer"){if(j0(t,this.answerInFlight,this.answeredOfferId,(i=this._pc)===null||i===void 0?void 0:i.signalingState,this.pendingInitialOffer!==void 0))return this.log.warn("ignoring duplicate answer",{offerId:t}),!1;this.answerInFlight=t}try{return yield this.applyRemoteDescription(e,t)}finally{e.type==="answer"&&(this.answerInFlight=void 0)}})}applyRemoteDescription(e,t){return g(this,void 0,void 0,function*(){var i;let r;if(e.type==="offer"){let s=V0(e),a=s.stereoMids,o=s.nackMids;this.remoteStereoMids=a,this.remoteNackMids=o}else if(e.type==="answer"){if(this.pendingInitialOffer&&this._pc){let o=this.pendingInitialOffer,c=o.original,d=o.munged,l=o.appliedVideoStartBitrate;this.pendingInitialOffer=void 0,this.log.debug("setting pending initial offer before processing answer"),yield this.setMungedSDP(c,d),l&&c.sdp===d&&(this.hasAppliedVideoStartBitrate=!0)}let s=tt.parse((i=e.sdp)!==null&&i!==void 0?i:"");s.media.forEach(o=>{let c=yi(o.mid);o.type==="audio"&&this.trackBitrates.some(d=>{if(!d.transceiver||c!=d.transceiver.mid)return!1;let l=0;if(o.rtp.some(h=>h.codec.toUpperCase()===d.codec.toUpperCase()?(l=h.payload,!0):!1),l===0)return!0;let u=!1;for(let h of o.fmtp)if(h.payload===l){h.config=h.config.split(";").filter(f=>!f.includes("maxaveragebitrate")).join(";"),d.maxbr>0&&(h.config+=";maxaveragebitrate=".concat(d.maxbr*1e3)),u=!0;break}return u||d.maxbr>0&&o.fmtp.push({payload:l,config:"maxaveragebitrate=".concat(d.maxbr*1e3)}),!0})});let a=this.getPlaceholderMids();a.size>0&&cu(s.media,o=>a.has(yi(o.mid))),r=tt.write(s)}return yield this.setMungedSDP(e,r,!0),e.type==="answer"&&t>0&&(this.answeredOfferId=t),this.pendingCandidates.length>0&&this.iceLog.debug("flushing queued ICE candidates",{count:this.pendingCandidates.length}),this.pendingCandidates.forEach(s=>{this.pc.addIceCandidate(s)}),this.pendingCandidates=[],this.restartingIce=!1,e.type==="answer"&&(this.latestAcknowledgedOfferId=t,this.emit(gt.OfferAnswered,t)),this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(gt.NegotiationComplete),e.sdp&&tt.parse(e.sdp).media.forEach(a=>{a.type==="video"&&this.emit(gt.RTPVideoPayloadTypes,a.rtp)})),!0})}preparePublisherOffer(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,r=this.hasAppliedVideoStartBitrate?void 0:L0(e.media,this.trackBitrates,this.connectionSetupTimeEstimateMs()),s=!1;e.media.forEach(o=>{du(o),o.type==="audio"?au(o,t?["all"]:[],this.offeredAudioNackMids):o.type==="video"&&this.trackBitrates.some(c=>{if(!c.cid)return!1;let d=Ff(o,c.cid,c.codec);return d===void 0?!1:(d>0&&(r!==void 0&&(s=D0(o,d,r)),It(c.codec)&&!qe()&&(this.ddExtID=N0(o,e,this.ddExtID))),!0)})});let a=this.getPlaceholderMids();return(i||a.size>0)&&cu(e.media,o=>a.has(yi(o.mid))||i&&o.direction==="recvonly"),{connectionStartBitrate:r,appliedVideoStartBitrate:s}}createInitialOffer(){return g(this,void 0,void 0,function*(){var e;let t=yield this.offerLock.lock();try{if(this.pc.signalingState!=="stable"){this.log.warn("signaling state is not stable, cannot create initial offer");return}let i=this.latestOfferId+1;this.latestOfferId=i;let r=yield this.pc.createOffer(),s={sdp:r.sdp,type:r.type},a=tt.parse((e=r.sdp)!==null&&e!==void 0?e:""),o=this.preparePublisherOffer(a,!1,!0),c=o.appliedVideoStartBitrate;return r.sdp=tt.write(a),this.pendingInitialOffer={original:s,munged:r.sdp,appliedVideoStartBitrate:c},{offer:r,offerId:i}}finally{t()}})}createAndSendOffer(e){return g(this,void 0,void 0,function*(){var t;let i=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e?.iceRestart&&(this.iceLog.debug("restarting ICE"),this.restartingIce=!0),this._pc&&(this._pc.signalingState==="have-local-offer"||this.pendingInitialOffer)){let u=this._pc.remoteDescription;if(e?.iceRestart&&u)yield this._pc.setRemoteDescription(u);else{if(e?.iceRestart)throw new yt("ICE restart requested without a remote description, peer connection must be recreated");this.renegotiate=!0,this.log.debug("requesting renegotiation");return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection");return}this.log.debug("starting to negotiate");let r=this.latestOfferId+1;this.latestOfferId=r;let s=yield this.pc.createOffer(e);this.log.debug("original offer",{sdp:s.sdp});let a=tt.parse((t=s.sdp)!==null&&t!==void 0?t:""),o=this.preparePublisherOffer(a),c=o.connectionStartBitrate,d=o.appliedVideoStartBitrate;if(this.latestOfferId>r){this.log.warn("latestOfferId mismatch",{latestOfferId:this.latestOfferId,offerId:r});return}let l=tt.write(a);yield this.setMungedSDP(s,l),d&&s.sdp===l&&(this.hasAppliedVideoStartBitrate=!0,this.log.info("applied x-google-start-bitrate",{startBitrateKbps:c,connectionSetupTimeMs:this.connectionSetupTimeEstimateMs()})),this.onOffer(s,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return g(this,void 0,void 0,function*(){var e;let t=yield this.pc.createAnswer(),i=tt.parse((e=t.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(r=>{du(r),r.type==="audio"&&au(r,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,tt.write(i)),t})}reserveSender(e){this.reservedSenders.add(e)}releaseSender(e){this.reservedSenders.delete(e)}getPlaceholderMids(){var e,t;return q0((t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[],this.reservedSenders)}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new J("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConnectionSetupTime(e){this.connectionSetupTimeMs=e}setConnectionStartedAt(e){this.connectionStartedAt=e}connectionSetupTimeEstimateMs(){if(this.connectionSetupTimeMs!==void 0)return this.connectionSetupTimeMs;if(this.connectionStartedAt!==void 0)return Math.round(performance.now()-this.connectionStartedAt)}setConfiguration(e){var t;if(!this._pc)throw new J("PC closed, cannot configure");return(t=this._pc)===null||t===void 0?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;var i;(i=this._pc)===null||i===void 0||i.removeTrack(e),t&&this.stopTransceivers([e])}stopTransceivers(e){let t=!1,i=this.getTransceivers(),r=s=>s.direction!=="stopped"&&s.currentDirection!=="stopped";for(let s of i){if(!e.includes(s.sender)||typeof s.stop!="function")continue;let a=s.receiver.track.kind;if(i.some(o=>o!==s&&r(o)&&o.receiver.track.kind===a))try{s.stop(),t=!0}catch(o){this.log.warn("could not stop transceiver",{error:o})}}return t}getConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&t!==void 0?t:"closed"}getICEConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&t!==void 0?t:"closed"}getSignallingState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&t!==void 0?t:"closed"}getTransceivers(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[]}getSenders(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&t!==void 0?t:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){var e;return(e=this._pc)===null||e===void 0?void 0:e.getStats()}getMaxMessageSize(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.sctp)===null||t===void 0?void 0:t.maxMessageSize}getConnectedAddress(){return g(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="",i=new Map,r=new Map;if((yield this._pc.getStats()).forEach(o=>{switch(o.type){case"transport":t=o.selectedCandidatePairId;break;case"candidate-pair":t===""&&o.selected&&(t=o.id),i.set(o.id,o);break;case"remote-candidate":r.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;let a=(e=i.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(a!==void 0)return r.get(a)})}setMungedSDP(e,t,i){return g(this,void 0,void 0,function*(){var r,s;let a=e.sdp;if(t){e.sdp=t;try{this.log.debug("setting munged ".concat(i?"remote":"local"," description")),i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(o){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),{error:o,mungedSdp:t,originalSdp:a}),e.sdp=a}}try{i?yield(r=this._pc)===null||r===void 0?void 0:r.setRemoteDescription(e):yield(s=this._pc)===null||s===void 0?void 0:s.setLocalDescription(e)}catch(o){let c="unknown error";o instanceof Error?c=o.message:typeof o=="string"&&(c=o);let d={error:c,sdp:e.sdp};throw t&&t!==a&&(d.mungedSdp=t),!i&&this.pc.remoteDescription&&(d.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),{fields:d}),new yt(c)}})}};function N0(n,e,t){var i,r;let s=F0(e,t);return s===void 0?t:(!((i=n.ext)===null||i===void 0)&&i.some(a=>a.uri===Rn)||((r=n.ext)!==null&&r!==void 0||(n.ext=[]),n.ext.push({value:s,uri:Rn})),s)}function F0(n,e){let t=U0(n,Rn);return t!==void 0?ou(n,t,Rn)?void 0:t:e!==0&&!ou(n,e,Rn)?e:B0(n)}function U0(n,e){var t;for(let i of n.media){let r=(t=i.ext)===null||t===void 0?void 0:t.find(s=>s.uri===e);if(r)return r.value}}function ou(n,e,t){return n.media.some(i=>{var r;return(r=i.ext)===null||r===void 0?void 0:r.some(s=>s.value===e&&s.uri!==t)})}function B0(n){let e=0;return n.media.forEach(t=>{var i;(i=t.ext)===null||i===void 0||i.forEach(r=>{r.value>e&&(e=r.value)})}),e+1===15?16:e+1}function Uf(n,e){return n.split(";").some(t=>t.trim()===e)}function au(n,e,t){let i=yi(n.mid),r=a=>a.includes(i)||a.length===1&&a[0]==="all",s=0;n.rtp.some(a=>a.codec.toLowerCase()==="opus"?(s=a.payload,!0):!1),s>0&&(n.rtcpFb||(n.rtcpFb=[]),r(t)&&!n.rtcpFb.some(a=>a.payload===s&&a.type==="nack")&&n.rtcpFb.push({payload:s,type:"nack"}),r(e)&&n.fmtp.some(a=>a.payload===s?(Uf(a.config,"stereo=1")||(a.config+=";stereo=1"),!0):!1))}function q0(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:new WeakSet,t=new Set;for(let i of n)i.mid&&!i.sender.track&&!e.has(i)&&t.add(i.mid);return t}function cu(n,e){var t,i,r,s,a,o,c,d;let l=new Map;for(let u of n){let h=e(u);for(let f of(t=u.rtp)!==null&&t!==void 0?t:[]){let m=f.payload,p=(s=(r=(i=u.fmtp)===null||i===void 0?void 0:i.find(y=>y.payload===m))===null||r===void 0?void 0:r.config)!==null&&s!==void 0?s:"";(!h||!l.has(m))&&l.set(m,p)}}for(let u of n)if(e(u))for(let h of(a=u.rtp)!==null&&a!==void 0?a:[]){let f=h.payload,m=l.get(f),p=(o=u.fmtp)===null||o===void 0?void 0:o.find(y=>y.payload===f);m===""?u.fmtp=((c=u.fmtp)!==null&&c!==void 0?c:[]).filter(y=>y.payload!==f):p?p.config=m:u.fmtp=[...(d=u.fmtp)!==null&&d!==void 0?d:[],{payload:f,config:m}]}}function j0(n,e,t,i,r){return e===n?!0:n>0?n===t:i==="stable"&&!r}function V0(n){var e;let t=[],i=[],r=tt.parse((e=n.sdp)!==null&&e!==void 0?e:""),s=0;return r.media.forEach(a=>{var o;let c=yi(a.mid);a.type==="audio"&&(a.rtp.some(d=>d.codec.toLowerCase()==="opus"?(s=d.payload,!0):!1),!((o=a.rtcpFb)===null||o===void 0)&&o.some(d=>d.payload===s&&d.type==="nack")&&i.push(c),a.fmtp.some(d=>d.payload===s?(Uf(d.config,"sprop-stereo=1")&&t.push(c),!0):!1))}),{stereoMids:t,nackMids:i}}function du(n){if(n.connection){let e=n.connection.ip.indexOf(":")>=0;(n.connection.version===4&&e||n.connection.version===6&&!e)&&(n.connection.ip="0.0.0.0",n.connection.version=4)}}function yi(n){return typeof n=="number"?n.toFixed(0):n}var oi=7e3,W0=500,H0=[0,300,4*300,9*300,16*300,oi,oi,oi,oi,oi],Sa=class{constructor(e){this._retryDelays=e!==void 0?[...e]:H0}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;let t=this._retryDelays[e.retryCount];return e.retryCount===0&&t===0?Math.random()*W0:Math.round(t*(.5+Math.random()))}},xr="vp8",K0={audioPreset:Vo.music,dtx:!0,red:!0,forceStereo:!1,stopMicTrackOnMute:!1,preConnectBuffer:!1},Bf={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},z0={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Sa,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},rd={autoSubscribe:!0,disableIceLite:!1,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3},oe;(function(n){n[n.NEW=0]="NEW",n[n.CONNECTING=1]="CONNECTING",n[n.CONNECTED=2]="CONNECTED",n[n.FAILED=3]="FAILED",n[n.CLOSING=4]="CLOSING",n[n.CLOSED=5]="CLOSED"})(oe||(oe={}));var Lr=class{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r=i.rtcConfig,s=i.peerConnectionTimeout,a=s===void 0?rd.peerConnectionTimeout:s;var o;this.log=W,this.iceLog=W,this.updateState=()=>{var d,l;let u=this.state,h=this.requiredTransports.map(f=>f.getConnectionState());h.every(f=>f==="connected")?this.state=oe.CONNECTED:h.some(f=>f==="failed")?this.state=oe.FAILED:h.some(f=>f==="connecting")?this.state=oe.CONNECTING:h.every(f=>f==="closed")?this.state=oe.CLOSED:h.some(f=>f==="closed")?this.state=oe.CLOSING:h.every(f=>f==="new")&&(this.state=oe.NEW),u!==this.state&&(this.log.debug("pc state change: from ".concat(oe[u]," to ").concat(oe[this.state])),(d=this.onStateChange)===null||d===void 0||d.call(this,this.state,this.publisher.getConnectionState(),(l=this.subscriber)===null||l===void 0?void 0:l.getConnectionState()))},this.loggerOptions=t,this.peerConnectionTimeout=a,this.log=we((o=t.loggerName)!==null&&o!==void 0?o:he.PCManager,()=>this.logContext),this.iceLog=we(he.ICE,()=>this.logContext),this.isPublisherConnectionRequired=e!=="subscriber-primary",this.isSubscriberConnectionRequired=e==="subscriber-primary";let c=e==="publisher-only";this.publisher=new Or(r,t,{singlePeerConnection:c}),this._mode=e,c||(this.subscriber=new Or(r,t),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=d=>{var l;(l=this.onIceCandidate)===null||l===void 0||l.call(this,d,He.SUBSCRIBER)},this.subscriber.onDataChannel=d=>{var l;(l=this.onDataChannel)===null||l===void 0||l.call(this,d)},this.subscriber.onTrack=d=>{var l;(l=this.onTrack)===null||l===void 0||l.call(this,d)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=d=>{var l;(l=this.onIceCandidate)===null||l===void 0||l.call(this,d,He.PUBLISHER)},this.publisher.onTrack=d=>{var l;(l=this.onTrack)===null||l===void 0||l.call(this,d)},this.publisher.onOffer=(d,l)=>{var u;(u=this.onPublisherOffer)===null||u===void 0||u.call(this,d,l)},this.state=oe.NEW,this.connectionLock=new ye,this.remoteOfferLock=new ye}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e,t){return this.publisher.removeTrack(e,t)}close(){return g(this,void 0,void 0,function*(){var e;if(this.publisher&&this.publisher.getSignallingState()!=="closed"){let t=this.publisher;for(let i of t.getSenders())try{t.canRemoveTrack()&&t.removeTrack(i)}catch(r){this.log.warn("could not removeTrack",{error:r})}}yield Promise.all([this.publisher.close(),(e=this.subscriber)===null||e===void 0?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return g(this,void 0,void 0,function*(){this.iceLog.warn("triggering ICE restart"),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return g(this,void 0,void 0,function*(){var i;this.iceLog.debug("adding remote ICE candidate",{target:t,candidate:e}),t===He.PUBLISHER?yield this.publisher.addIceCandidate(e):yield(i=this.subscriber)===null||i===void 0?void 0:i.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return g(this,void 0,void 0,function*(){var i,r,s;this.log.debug("received server offer",{RTCSdpType:e.type,sdp:e.sdp,signalingState:(i=this.subscriber)===null||i===void 0?void 0:i.getSignallingState().toString()});let a=yield this.remoteOfferLock.lock();try{return(yield(r=this.subscriber)===null||r===void 0?void 0:r.setRemoteDescription(e,t))?yield(s=this.subscriber)===null||s===void 0?void 0:s.createAndSetAnswer():void 0}finally{a()}})}updateConfiguration(e,t){var i;this.log.debug("updating rtc configuration",{iceRestart:t}),this.publisher.setConfiguration(e),(i=this.subscriber)===null||i===void 0||i.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return g(this,void 0,void 0,function*(){var i;let r=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating"),this.publisher.negotiate().catch(s=>{this.log.error(s)})),yield Promise.all((i=this.requiredTransports)===null||i===void 0?void 0:i.map(s=>this.ensureTransportConnected(s,e,t)))}finally{r()}})}negotiate(e){return g(this,void 0,void 0,function*(){return new Pe((t,i)=>{let r=this.publisher.latestOfferId;if(this.publisher.latestAcknowledgedOfferId>r){this.log.debug("negotiation already handled in more recent acknowledged offer",this.logContext),t();return}let s=!1,a=()=>{s||(s=!0,clearTimeout(d),this.publisher.off(gt.OfferAnswered,o),e.signal.removeEventListener("abort",c))},o=l=>{(l===0||l>r)&&(a(),t())},c=()=>{a(),i(new yt("negotiation aborted"))},d=setTimeout(()=>{a(),i(new yt("negotiation timed out"))},this.peerConnectionTimeout);e.signal.addEventListener("abort",c),this.publisher.on(gt.OfferAnswered,o),this.publisher.negotiate(l=>{a(),l instanceof Error?i(l):i(new Error(String(l)))})})})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getTransceiverForReceiver(e){return(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(i=>i.receiver===e)}getMaxPublisherMessageSize(){return this.publisher.getMaxMessageSize()}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===He.PUBLISHER?this.publisher.getConnectedAddress():e===He.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){let e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return g(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return(function*(){if(i.getConnectionState()!=="connected")return new Promise((c,d)=>g(s,void 0,void 0,function*(){let l=()=>{this.log.warn("abort transport connection"),Y.clearTimeout(h),d(U.cancelled("room connection has been cancelled"))},u=!1,h=Y.setTimeout(()=>{u=!0,r?.signal.removeEventListener("abort",l),d(U.internal("could not establish pc connection"))},a);for(r?.signal.aborted&&l(),r?.signal.addEventListener("abort",l);this.state!==oe.CONNECTED;){if(yield Re(50),u)return;if(r?.signal.aborted){d(U.cancelled("room connection has been cancelled"));return}}Y.clearTimeout(h),r?.signal.removeEventListener("abort",l),c()}))})()})}},Dr=class{constructor(e){this.bufferStatusLow=!0,this.headroomLock=new ye,this.waiterAbortController=new AbortController,this.kind=e.kind,this.lowWaterMark=e.lowWaterMark,this.highWaterMark=e.highWaterMark,this.isEngineClosed=e.isEngineClosed,this.onBufferStatusChanged=e.onBufferStatusChanged}get channelHandle(){return this.handle}attach(e){let t=this.handle;this.handle=e,t&&t!==e&&this.release(t,"data channel replaced")}detach(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"data channel torn down",t=this.handle;this.handle=void 0,t&&this.release(t,e)}release(e,t){this.invalidateWaiters(t),e.close()}getChannel(){return this.handle}isBelowHighWaterMark(e){return e.bufferedAmount<=this.highWaterMark}isBelowLowWaterMark(e){return e.bufferedAmount<=e.bufferedAmountLowThreshold}lockHeadroom(){return this.headroomLock.lock()}waitForHeadroomWithLock(e){return g(this,void 0,void 0,function*(){let t=yield this.lockHeadroom();try{yield this.waitForHeadroomWithoutLock(e)}finally{t()}})}waitForHeadroomWithoutLock(e){return g(this,void 0,void 0,function*(){if(this.isEngineClosed())throw new J("engine closed");if(e.readyState!=="open")throw new J("DataChannel ".concat(this.kind," is ").concat(e.readyState));if(this.isBelowHighWaterMark(e))return;let t=this.waiterAbortController.signal;yield new Pe((i,r)=>{let s=()=>{c(),i()},a=()=>{c(),r(new J("DataChannel ".concat(this.kind," closed while draining the buffer")))},o=()=>{c(),r(new J("DataChannel ".concat(this.kind," was replaced or torn down while waiting for headroom")))},c=()=>{e.removeEventListener("bufferedamountlow",s),e.removeEventListener("close",a),t.removeEventListener("abort",o)};if(t.aborted){o();return}e.addEventListener("bufferedamountlow",s),e.addEventListener("close",a),t.addEventListener("abort",o)})})}invalidateWaiters(e){this.waiterAbortController.abort(e),this.waiterAbortController=new AbortController}refreshBufferStatus(){var e;let t=this.getChannel();if(!t)return;let i=this.isBelowLowWaterMark(t);i!==this.bufferStatusLow&&(this.bufferStatusLow=i,(e=this.onBufferStatusChanged)===null||e===void 0||e.call(this,i))}},Nr=class extends Dr{constructor(e){super(e),this.statCurrentBytes=0,this.statByterate=0,this.dropCount=0,this.bufferFullBehavior=e.bufferFullBehavior,this.shouldSkipSends=e.shouldSkipSends}send(e){return g(this,void 0,void 0,function*(){let t=this.getChannel();if(t){switch(this.bufferFullBehavior){case"wait":if(!this.isBelowHighWaterMark(t))try{yield this.waitForHeadroomWithLock(t)}catch(i){if(this.isEngineClosed())throw i;return}break;case"drop":if(!this.isBelowLowWaterMark(t)){this.dropCount+=1,this.dropCount%100===0&&W.warn("dropping lossy data channel messages, total dropped: ".concat(this.dropCount));return}}if(this.statCurrentBytes+=e.byteLength,!this.shouldSkipSends())try{t.send(e),this.refreshBufferStatus()}catch(i){if(i instanceof TypeError)W.error(i);else throw i}}})}startThresholdTuning(){this.stopThresholdTuning(),this.statInterval=Y.setInterval(()=>{this.statByterate=this.statCurrentBytes,this.statCurrentBytes=0;let e=this.getChannel();if(e){let t=this.statByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,this.lowWaterMark),this.highWaterMark)}},1e3)}stopThresholdTuning(){this.statByterate=0,this.statCurrentBytes=0,this.statInterval&&(Y.clearInterval(this.statInterval),this.statInterval=void 0),this.dropCount=0}},Fr=class{constructor(){this.buffer=[],this._totalSize=0,this._sentSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength,e.sent&&(this._sentSize+=e.data.byteLength)}pop(){let e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength,e.sent&&(this._sentSize-=e.data.byteLength)),e}getAll(){return this.buffer.slice()}getUnsent(){return this.buffer.filter(e=>!e.sent)}markSent(e){e.sent||(e.sent=!0,this._sentSize+=e.data.byteLength)}markAllUnsent(){for(let e of this.buffer)e.sent=!1;this._sentSize=0}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0;){let t=this.buffer[0];if(!t.sent||this._sentSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}},_a=class extends Dr{constructor(e){super(e),this.messageBuffer=new Fr,this.sequence=1,this.isDeferringSends=e.isDeferringSends}nextSequence(){let e=this.sequence;return this.sequence+=1,e}send(e,t){return g(this,void 0,void 0,function*(){if(this.isDeferringSends()){this.messageBuffer.push({data:e,sequence:t,sent:!1});return}let i=this.getChannel();if(i){try{yield this.waitForHeadroomWithLock(i)}catch(r){if(this.isEngineClosed())throw r;this.messageBuffer.push({data:e,sequence:t,sent:!1});return}if(this.isDeferringSends()){this.messageBuffer.push({data:e,sequence:t,sent:!1});return}this.messageBuffer.push({data:e,sequence:t,sent:!0}),i.send(e),this.refreshBufferStatus()}})}replay(e){return g(this,void 0,void 0,function*(){if(!this.getChannel())return;this.messageBuffer.popToSequence(e);let t=yield this.lockHeadroom();try{let i=this.getChannel();if(!i)throw new J("DataChannel not found, kind: ".concat(this.kind));this.messageBuffer.markAllUnsent();for(let r=this.messageBuffer.getUnsent();r.length>0;r=this.messageBuffer.getUnsent())for(let s of r)yield this.waitForHeadroomWithoutLock(i),i.send(s.data),this.messageBuffer.markSent(s)}finally{t()}this.refreshBufferStatus()})}refreshBufferStatus(){let e=this.channelHandle;e&&this.messageBuffer.alignBufferedAmount(e.bufferedAmount),super.refreshBufferStatus()}reset(){this.messageBuffer=new Fr,this.sequence=1}},z;(function(n){n[n.RELIABLE=0]="RELIABLE",n[n.LOSSY=1]="LOSSY",n[n.DATA_TRACK_LOSSY=2]="DATA_TRACK_LOSSY"})(z||(z={}));var G0=64*1024,J0=1024*1024,$0=8*1024,Q0=256*1024;function Y0(n){return n===z.RELIABLE?G0:$0}function X0(n){return n===z.RELIABLE?J0:Q0}var lu="_lossy",uu="_reliable",hu="_data_track";function Co(n){n.onbufferedamountlow=null,n.onclose=null,n.onclosing=null,n.onerror=null,n.onmessage=null,n.onopen=null}var Ca=class{constructor(e){this.negotiated=!1,this.opts=e;let t=i=>({kind:i,lowWaterMark:Y0(i),highWaterMark:X0(i),isEngineClosed:e.isEngineClosed,onBufferStatusChanged:r=>e.onBufferStatusChanged(i,r)});this.reliable=new _a(Object.assign(Object.assign({},t(z.RELIABLE)),{isDeferringSends:e.isReconnecting})),this.lossy=new Nr(Object.assign(Object.assign({},t(z.LOSSY)),{bufferFullBehavior:"drop",shouldSkipSends:e.isReconnecting})),this.dataTrack=new Nr(Object.assign(Object.assign({},t(z.DATA_TRACK_LOSSY)),{bufferFullBehavior:"wait",shouldSkipSends:e.isReconnecting}))}channelFor(e){switch(e){case z.RELIABLE:return this.reliable;case z.LOSSY:return this.lossy;case z.DATA_TRACK_LOSSY:return this.dataTrack}}getHandle(e){if(!(arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1))return this.channelFor(e).channelHandle;switch(e){case z.RELIABLE:return this.reliableSub;case z.LOSSY:return this.lossySub;case z.DATA_TRACK_LOSSY:return this.dataTrackSub}}get hasPublisherChannels(){return!!(this.reliable.channelHandle||this.lossy.channelHandle||this.dataTrack.channelHandle)}get publisherChannelsNegotiated(){return this.hasPublisherChannels&&this.negotiated}createPublisherChannels(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;for(let s of[this.lossy,this.reliable,this.dataTrack]){let a=s.channelHandle;a&&Co(a)}let i=(s,a,o)=>{a.onmessage=o,a.onerror=this.opts.onDataError,a.onclose=()=>this.opts.onChannelClose(s.kind),a.bufferedAmountLowThreshold=s.lowWaterMark,a.onbufferedamountlow=()=>s.refreshBufferStatus(),s.attach(a)},r=s=>t?{negotiated:t,id:s}:{};i(this.lossy,e.createPublisherDataChannel(lu,Object.assign({ordered:!1,maxRetransmits:0},r(so.NDCI_LOSSY))),this.opts.onDataMessage),i(this.reliable,e.createPublisherDataChannel(uu,Object.assign({ordered:!0},r(so.NDCI_RELIABLE))),this.opts.onDataMessage),i(this.dataTrack,e.createPublisherDataChannel(hu,Object.assign({ordered:!1,maxRetransmits:0},r(so.NDCI_DATA_TRACK))),this.opts.onDataTrackMessage),this.negotiated=t,this.lossy.startThresholdTuning()}adoptSubscriberChannel(e){let t;if(e.label===uu)this.reliableSub=e,t=this.opts.onDataMessage;else if(e.label===lu)this.lossySub=e,t=this.opts.onDataMessage;else if(e.label===hu)this.dataTrackSub=e,t=this.opts.onDataTrackMessage;else return!1;return e.onmessage=t,!0}teardown(){let e=[this.lossy,this.reliable,this.dataTrack],t=[this.lossySub,this.reliableSub,this.dataTrackSub];for(let i of e){let r=i.channelHandle;r&&Co(r),i.detach("peer connections cleaned up")}for(let i of t)i&&(Co(i),i.close());this.lossySub=void 0,this.reliableSub=void 0,this.dataTrackSub=void 0,this.reliable.reset()}},Z0=2*1e3,wo="leave-reconnect",eb=10*1e3,tb=3e4,nb=3,ib=3,$e;(function(n){n[n.New=0]="New",n[n.Connected=1]="Connected",n[n.Disconnected=2]="Disconnected",n[n.Reconnecting=3]="Reconnecting",n[n.Closed=4]="Closed"})($e||($e={}));var fu=64e3,wa=class extends Oe.EventEmitter{get isClosed(){return this._isClosed}get isNewlyCreated(){return this._isNewlyCreated}get pendingReconnect(){return!!this.reconnectTimeout}get serverVersion(){var e,t,i;return((t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.serverInfo)===null||t===void 0?void 0:t.version)||((i=this.latestJoinResponse)===null||i===void 0?void 0:i.serverVersion)||void 0}get serverProtocol(){var e,t;return(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.serverInfo)===null||t===void 0?void 0:t.protocol}get reliableChannel(){return this.dataChannels.reliable}get lossyChannel(){return this.dataChannels.lossy}get dataTrackChannel(){return this.dataChannels.dataTrack}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=rd.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=$e.New,this._isClosed=!0,this._isNewlyCreated=!0,this.preparedPublications=[],this.initialTrackRequests=[],this.reservations=Promise.resolve(),this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.shouldFailOnV1Path=!1,this.log=W,this.reliableReceivedState=new Ta(tb),this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.pendingNegotiationAborts=new Set,this.handleDataChannel=r=>g(this,[r],void 0,function(s){var a=this;let o=s.channel;return(function*(){o&&a.dataChannels.adoptSubscriberChannel(o)&&a.log.debug("on data channel ".concat(o.id,", ").concat(o.label))})()}),this.handleDataMessage=r=>g(this,void 0,void 0,function*(){var s,a,o,c;let d=yield this.dataProcessLock.lock();try{let l=yield this.decodeDataMessage(r);if(!l)return;let u=Fe.fromBinary(l);if(u.sequence>0&&u.participantSid!==""){let h=this.reliableReceivedState.get(u.participantSid);if(h&&u.sequence<=h)return;this.reliableReceivedState.set(u.participantSid,u.sequence)}if(((s=u.value)===null||s===void 0?void 0:s.case)==="speaker")this.emit(A.ActiveSpeakersUpdate,u.value.value.speakers);else if(((a=u.value)===null||a===void 0?void 0:a.case)==="encryptedPacket"){if(!this.e2eeManager){this.log.error("Received encrypted packet but E2EE not set up");return}let h;try{h=yield this.e2eeManager.handleEncryptedData(u.value.value.encryptedValue,u.value.value.iv,u.participantIdentity,u.value.value.keyIndex)}catch(p){this.log.debug("failed to decrypt data packet",{error:p,participantIdentity:u.participantIdentity});return}let f=zh.fromBinary(h.payload),m=new Fe({value:f.value,participantIdentity:u.participantIdentity,participantSid:u.participantSid});((o=m.value)===null||o===void 0?void 0:o.case)==="user"&&pu(m,m.value.value),this.emit(A.DataPacketReceived,m,u.value.value.encryptionType)}else((c=u.value)===null||c===void 0?void 0:c.case)==="user"&&pu(u,u.value.value),this.emit(A.DataPacketReceived,u,X.NONE)}finally{d()}}),this.handleDataTrackMessage=r=>g(this,void 0,void 0,function*(){let s=yield this.decodeDataMessage(r);s&&this.emit("dataTrackPacketReceived",s)}),this.handleDataError=r=>{if(this._isClosed)return;let a=r.currentTarget.maxRetransmits===0?"lossy":"reliable";if(typeof RTCErrorEvent<"u"&&r instanceof RTCErrorEvent&&r.error){let o=r.error;this.log.error("DataChannel error on ".concat(a,": ").concat(o.message),{error:o,errorDetail:o.errorDetail,sctpCauseCode:o.sctpCauseCode})}else this.log.error("Unknown DataChannel error on ".concat(a),{event:r})},this.handleDataChannelClose=r=>()=>{var s;!this._isClosed&&((s=this.pcManager)===null||s===void 0?void 0:s.publisher.getConnectionState())==="connected"&&this.log.error("publisher data channel '".concat(z[r],"' closed unexpectedly"),this.logContext)},this.handleDisconnect=(r,s)=>{if(this._isClosed)return;this.log.warn("".concat(r," disconnected")),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());let a=d=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(d,"ms. giving up")),this.emit(A.Disconnected),this.close("gave up reconnecting after ".concat(this.reconnectAttempts," attempts, ").concat(d,"ms"))},o=Date.now()-this.reconnectStart,c=this.getNextRetryDelay({elapsedMs:o,retryCount:this.reconnectAttempts});if(c===null){a(o);return}if(r===wo&&(c=this.getNextRetryDelay({elapsedMs:o,retryCount:0}),c===null)){a(o);return}this.log.debug("reconnecting in ".concat(c,"ms")),this.clearReconnectTimeout(),this.token&&this.emit(A.TokenRefreshed,this.token),this.reconnectTimeout=Y.setTimeout(()=>{this.reconnectTimeout=void 0,this.attemptReconnect(s)},c)},this.waitForRestarted=r=>new Promise(s=>{if(r.aborted){s(!1);return}let a=()=>{r.removeEventListener("abort",o),s(!0)},o=()=>{r.removeEventListener("abort",o),this.off(A.Restarted,a),s(!1)};this.once(A.Restarted,a),r.addEventListener("abort",o)}),this.onRtpMapAvailable=r=>{let s=new Map;r.forEach(a=>{let o=a.codec.toLowerCase();Af(o)&&s.set(a.payload,o)}),this.emit(A.RTPVideoMapUpdate,s)},this.handleBrowserOnLine=()=>g(this,void 0,void 0,function*(){!this.url||!(yield fetch(Ii(this.url),{method:"HEAD"}).then(s=>s.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===Me.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===Me.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(St.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>g(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(Ii(this.url),{method:"HEAD"}),Re(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=we((t=e.loggerName)!==null&&t!==void 0?t:he.Engine,()=>this.logContext),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new Oi(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new ye,this.dataProcessLock=new ye,this.dataChannels=new Ca({isEngineClosed:()=>this.isClosed,isReconnecting:()=>this.attemptingReconnect,onDataMessage:r=>this.handleDataMessage(r),onDataTrackMessage:r=>this.handleDataTrackMessage(r),onDataError:r=>this.handleDataError(r),onChannelClose:r=>this.handleDataChannelClose(r)(),onBufferStatusChanged:(r,s)=>this.emit(A.DCBufferStatusChanged,s,r)}),this.client.on(N.ParticipantUpdate,r=>this.emit(A.ParticipantUpdate,r)),this.client.on(N.ConnectionQuality,r=>{this.handleLocalConnectionQuality(r),this.emit(A.ConnectionQualityUpdate,r)}),this.client.on(N.RoomUpdate,r=>this.emit(A.RoomUpdate,r)),this.client.on(N.SubscriptionError,r=>this.emit(A.SubscriptionError,r)),this.client.on(N.SubscriptionPermissionUpdate,r=>this.emit(A.SubscriptionPermissionUpdate,r)),this.client.on(N.SpeakersChanged,r=>this.emit(A.SpeakersChanged,r)),this.client.on(N.StreamStateUpdate,r=>this.emit(A.StreamStateChanged,r)),this.client.on(N.RequestResponse,r=>this.emit(A.SignalRequestResponse,r)),this.client.on(N.Joined,r=>this.emit(A.Joined,r));let i=()=>{for(let r of Array.from(this.pendingNegotiationAborts))r()};this.on(A.Closing,i),this.on(A.Restarting,i)}get logContext(){var e,t,i,r,s,a;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(r=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.room)===null||r===void 0?void 0:r.sid,participant:(a=(s=this.latestJoinResponse)===null||s===void 0?void 0:s.participant)===null||a===void 0?void 0:a.identity,participantID:this.participantSid}}join(e,t,i,r){return g(this,arguments,void 0,function(s,a,o,c){var d=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){var u,h,f,m;d._isNewlyCreated=!1,d.url=s,d.token=a,d.signalOpts=o,d.maxJoinAttempts=o.maxRetries;try{d.joinAttempts+=1,d.joinStartedAt=performance.now(),d.setupSignalClientCallbacks();let p=!l&&Vy(),y;if(p){d.pcManager||(yield d.configure(),d.applyInitialPublisherLayout(!0)),d.initialTrackRequests=!d.e2eeManager&&!d.frameMetadataOptions&&!o.e2eeEnabled?yield d.reserveSenders(b=>d.waitForTrackPublished(b)):[];let P=yield(u=d.pcManager)===null||u===void 0?void 0:u.publisher.createInitialOffer();P&&(y=Xt(P.offer,P.offerId)),d.initialOfferId=P?.offerId}if(c?.aborted)throw U.cancelled("Connection aborted");if(!l&&d.shouldFailOnV1Path)throw d.shouldFailOnV1Path=!1,U.serviceNotFound("Simulated v1 path failure","v0-rtc");let v=yield d.client.join(s,a,o,c,l,y,d.initialTrackRequests);if(c?.aborted)throw d.log.info("join cancelled after the signal join response"),U.cancelled("Connection aborted");if(d._isClosed=!1,d.latestJoinResponse=v,d.participantSid=(h=v.participant)===null||h===void 0?void 0:h.sid,d.subscriberPrimary=v.subscriberPrimary,p)(f=d.pcManager)===null||f===void 0||f.updateConfiguration(d.makeRTCConfiguration(v)),d.dataChannels.publisherChannelsNegotiated&&!d.useNegotiatedDataChannels()&&(d.log.debug("server does not support negotiated data channels, using in-band ones"),d.createDataChannels(!1));else{if(!d.pcManager){if(yield d.configure(v,!l),c?.aborted)throw d.log.info("join cancelled after configuring peer connections"),U.cancelled("Connection aborted");l||d.applyInitialPublisherLayout()}(!d.subscriberPrimary||v.fastPublish)&&d.negotiate().catch(P=>{d.log.error(P)})}d.joinStartedAt!==void 0&&((m=d.pcManager)===null||m===void 0||m.publisher.setConnectionStartedAt(d.joinStartedAt)),d.registerOnLineListener(),d.clientConfiguration=v.clientConfiguration,d.emit(A.SignalConnected,v);let _=v.serverInfo;return _||(_={version:v.serverVersion,region:v.serverRegion}),d.log.info("connected to Livekit Server ".concat(Object.entries(_).map(P=>{let b=F(P,2),k=b[0],S=b[1];return"".concat(k,": ").concat(S)}).join(", "))),d.canReserve=p&&!d.e2eeManager&&!d.frameMetadataOptions&&!o.e2eeEnabled,d.reservePublications(),{joinResponse:v,serverInfo:_}}catch(p){if(d.initialTrackRequests.length&&(d.pcManager&&(d.pcManager.onStateChange=void 0),yield d.cleanupPeerConnections()),p instanceof U){if(p.reason===Z.ServerUnreachable){if(d.log.warn("Couldn't connect to server, attempt ".concat(d.joinAttempts," of ").concat(d.maxJoinAttempts)),d.joinAttempts<d.maxJoinAttempts)return d.join(s,a,o,c,l)}else if(p.reason===Z.ServiceNotFound)return d.log.warn("Initial connection failed: ".concat(p.message," \u2013 Retrying")),d.pcManager&&(d.pcManager.onStateChange=void 0,yield d.cleanupPeerConnections()),d.join(s,a,o,c,!0)}throw p}})()})}close(e){return g(this,void 0,void 0,function*(){var t,i;(t=this.reconnectAbortController)===null||t===void 0||t.abort(),this.reconnectAbortController=void 0,(i=this.restartAttemptController)===null||i===void 0||i.abort(),this.restartAttemptController=void 0;let r=yield this.closingLock.lock();if(this.isClosed){r();return}try{this._isClosed=!0,this.joinAttempts=0,this.joinStartedAt=void 0,this.emit(A.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.clearLostQualityTimeout(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient(e)}finally{r()}})}cleanupPeerConnections(){return g(this,void 0,void 0,function*(){var e;for(let t of this.preparedPublications)t.fallback();this.initialTrackRequests=[],this.initialOfferId=void 0,this.canReserve=void 0,this.dataChannels.teardown(),yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0,this.transportConnectingSince=void 0,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyChannel.stopThresholdTuning()}cleanupClient(e){return g(this,void 0,void 0,function*(){yield this.client.close(!0,e),this.removeSignalClientCallbacks();for(let t of Object.keys(this.pendingTrackResolvers))this.pendingTrackResolvers[t].reject();this.pendingTrackResolvers={}})}reservePublications(){return this.reservations=this.reservations.then(()=>this.reserveWaitingPublications()).catch(e=>{this.log.warn("publication reservation failed; publishing after capture",{error:e});for(let t of this.preparedPublications)t.isWaitingForSender&&t.skipReservation()}),this.reservations}reserveWaitingPublications(){return g(this,void 0,void 0,function*(){var e,t;let i=()=>[...this.preparedPublications].filter(a=>a.isWaitingForSender);if(this.canReserve===void 0||!i().length)return;let r=(e=this.pcManager)===null||e===void 0?void 0:e.publisher;if(!this.canReserve||!r||this.initialOfferId===void 0){for(let a of i())a.skipReservation();return}if(!(yield this.initialOfferAnswered())||((t=this.pcManager)===null||t===void 0?void 0:t.publisher)!==r)return;for(let a of i())a.canReserve||a.skipReservation();(yield this.reserveSenders(a=>this.addTrack(a))).length&&(yield this.negotiate())})}initialOfferAnswered(){return g(this,void 0,void 0,function*(){var e;let t=(e=this.pcManager)===null||e===void 0?void 0:e.publisher,i=this.initialOfferId;return!t||i===void 0?!1:t.latestAcknowledgedOfferId>=i?!0:new Promise(r=>{let s=setTimeout(()=>a(!1),this.peerConnectionTimeout),a=c=>{clearTimeout(s),t.off(gt.OfferAnswered,o),r(c)},o=c=>{c>=i&&a(!0)};t.on(gt.OfferAnswered,o)})})}reserveSenders(e){return g(this,void 0,void 0,function*(){var t,i;let r=yield this.addReservedSenders();if(!r.length)return[];let s="";try{s=(i=yield(t=this.pcManager)===null||t===void 0?void 0:t.publisher.createProbeOffer())!==null&&i!==void 0?i:""}catch(a){this.log.warn("could not read reserved senders from a probe offer",{error:a})}return this.claimReservations(r,s,e)})}addReservedSenders(){return g(this,void 0,void 0,function*(){var e;let t=[],i=(e=this.pcManager)===null||e===void 0?void 0:e.publisher;if(!this.pcManager||!i)return t;for(let r of this.preparedPublications){if(!r.isWaitingForSender||!r.canReserve)continue;let s;try{let a=new MediaStream;s=yield this.pcManager.addPublisherTransceiverOfKind(r.kind===C.Kind.Audio?"audio":"video",{direction:"sendonly",streams:[a],sendEncodings:r.encodings});let o="".concat(r.kind,"/").concat(r.codec).toLowerCase(),c=RTCRtpSender.getCapabilities(r.kind===C.Kind.Audio?"audio":"video").codecs.filter(d=>d.mimeType.toLowerCase()===o||(r.kind===C.Kind.Audio?!r.request.disableRed&&d.mimeType.toLowerCase()==="audio/red":d.mimeType.toLowerCase()==="video/rtx"));i.reserveSender(s),s.setCodecPreferences(c),t.push({plan:r,transceiver:s,stream:a.id})}catch(a){this.log.warn("publication reservation failed; publishing after capture",{error:a}),s&&(i.releaseSender(s),s.stop()),r.skipReservation()}}return t})}claimReservations(e,t,i){var r;let s=[],a=(r=this.pcManager)===null||r===void 0?void 0:r.publisher;if(!a)return s;for(let o of e){let c=o.plan,d=o.transceiver,l=o.stream;try{let u=a0(t,l);if(!u)throw new J("reserved sender has no CID in the offer");c.request.cid=u,c.request.simulcastCodecs[0]&&(c.request.simulcastCodecs[0].cid=u),c.startBitrate&&a.setTrackCodecBitrate({cid:u,codec:c.codec,maxbr:c.startBitrate/1e3}),c.reserve({engine:this,transport:a,transceiver:d,accepted:i(c.request)}),s.push(c.request)}catch(u){c.isCancelled||this.log.warn("publication reservation failed; publishing after capture",{error:u}),c.request.cid&&this.cancelPendingTrack(c.request.cid),a.releaseSender(d),d.stop(),c.isCancelled||c.skipReservation()}}return s}addTrack(e){let t=this.waitForTrackPublished(e);return this.client.sendAddTrack(e),t}cancelPendingTrack(e){let t=this.pendingTrackResolvers[e];delete this.pendingTrackResolvers[e],t?.reject()}waitForTrackPublished(e){if(this.pendingTrackResolvers[e.cid])throw new le("a track with the same ID has already been published");return new Promise((t,i)=>{let r=Y.setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(U.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:s=>{Y.clearTimeout(r),t(s)},reject:()=>{Y.clearTimeout(r),i(new Error("Cancelled publication by calling unpublish"))}}})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){let t=this.pendingTrackResolvers[e.track.id].reject;t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e,gy(this.serverProtocol)),!0}catch(t){this.log.warn("failed to remove track",{error:t})}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.dataChannelForKind(z.RELIABLE,!0))===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return g(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionStrategy(e){this.regionStrategy=e}configure(e,t){return g(this,void 0,void 0,function*(){var i;if(!(this.pcManager&&this.pcManager.currentState!==oe.NEW)){if(e){this.participantSid=(i=e.participant)===null||i===void 0?void 0:i.sid;let r=this.makeRTCConfiguration(e);this.pcManager=new Lr(t?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions,{rtcConfig:r,peerConnectionTimeout:this.peerConnectionTimeout})}else{let r=this.makeRTCConfiguration();this.pcManager=new Lr("publisher-only",this.loggerOptions,{rtcConfig:r,peerConnectionTimeout:this.peerConnectionTimeout})}this.emit(A.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(r,s)=>{this.client.sendIceCandidate(r,s)},this.pcManager.onPublisherOffer=(r,s)=>{this.client.sendOffer(r,s)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(r,s,a)=>g(this,void 0,void 0,function*(){var o;if(this.log.debug("primary PC state changed ".concat(r)),r===oe.CONNECTING?this.transportConnectingSince=Date.now():this.transportConnectingSince=void 0,["closed","disconnected","failed"].includes(s)&&(this.publisherConnectionPromise=void 0),r===oe.CONNECTED){if(this.joinStartedAt!==void 0){let u=Math.round(performance.now()-this.joinStartedAt);this.joinStartedAt=void 0,this.log.info("connection setup took ".concat(u," ms")),(o=this.pcManager)===null||o===void 0||o.publisher.setConnectionSetupTime(u)}let l=this.pcState===$e.New;this.pcState=$e.Connected,l&&this.emit(A.Connected,this.latestJoinResponse)}else r===oe.FAILED&&(this.pcState===$e.Connected||this.pcState===$e.Reconnecting)&&(this.pcState=$e.Disconnected,this.handleDisconnect("peerconnection failed",a==="failed"?St.RR_SUBSCRIBER_FAILED:St.RR_PUBLISHER_FAILED));let c=this.client.isDisconnected||this.client.currentState===Me.RECONNECTING,d=[oe.FAILED,oe.CLOSING,oe.CLOSED].includes(r);c&&d&&!this._isClosed&&this.emit(A.Offline)}),this.pcManager.onTrack=r=>{r.streams.length!==0&&this.emit(A.MediaTrackAdded,r.track,r.streams[0],r.receiver)}}})}setupSignalClientCallbacks(){this.removeSignalClientCallbacks(),this.client.on(N.Answer,(e,t,i)=>g(this,void 0,void 0,function*(){if(this.pcManager){if(this.pcManager.publisher.isStaleAnswer(t)){this.log.warn("ignoring answer for old offer",{offerId:t,latestOfferId:this.pcManager.publisher.latestOfferId});return}this.log.debug("received server answer",{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:i}),this.pcManager.mode==="publisher-only"&&Object.keys(i).length>0&&(this.midToTrackId=i),yield this.pcManager.setPublisherAnswer(e,t),this.emit(A.RequestSubscribedCodecRefresh)}})),this.client.on(N.Trickle,(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",{candidate:e,target:t}),this.pcManager.addIceCandidate(e,t))}),this.client.on(N.Offer,(e,t,i)=>g(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=i;let r=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);r&&this.client.sendAnswer(r,t)})),this.client.on(N.LocalTrackPublished,e=>{var t;if(this.log.debug("received trackPublishedResponse",{cid:e.cid,track:(t=e.track)===null||t===void 0?void 0:t.sid}),!this.pendingTrackResolvers[e.cid]){this.log.error("missing track resolver for ".concat(e.cid),{cid:e.cid});return}let i=this.pendingTrackResolvers[e.cid].resolve;delete this.pendingTrackResolvers[e.cid],i(e.track)}),this.client.on(N.LocalTrackUnpublished,e=>{this.emit(A.LocalTrackUnpublished,e)}),this.client.on(N.LocalTrackSubscribed,e=>{this.emit(A.LocalTrackSubscribed,e)}),this.client.on(N.TokenRefresh,e=>{this.token=e,this.emit(A.TokenRefreshed,e)}),this.client.on(N.RemoteMuteChanged,(e,t)=>{this.emit(A.RemoteMute,e,t)}),this.client.on(N.SubscribedQualityUpdate,e=>{this.emit(A.SubscribedQualityUpdate,e)}),this.client.on(N.RoomMoved,e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(A.RoomMoved,e)}),this.client.on(N.MediaSectionsRequirement,e=>{this.addMediaSections(e.numAudios,e.numVideos),this.negotiate().catch(t=>{this.log.error(t)})}),this.client.on(N.PublishDataTrackResponse,e=>{this.emit(A.PublishDataTrackResponse,e)}),this.client.on(N.UnpublishDataTrackResponse,e=>{this.emit(A.UnPublishDataTrackResponse,e)}),this.client.on(N.DataTrackSubscriberHandles,e=>{this.emit(A.DataTrackSubscriberHandles,e)}),this.client.on(N.Close,()=>{this.handleDisconnect("signal",St.RR_SIGNAL_DISCONNECTED)}),this.client.on(N.Leave,e=>{var t;switch(this.log.info("client leave request received (action=".concat(e?.action,")"),{reason:e?.reason}),e.regions&&(this.log.debug("updating regions"),this.emit(A.ServerRegionsReported,e.regions)),e.action){case En.DISCONNECT:this.emit(A.Disconnected,e?.reason),this.close("server leave: ".concat((t=Ke[e.reason])!==null&&t!==void 0?t:e.reason));break;case En.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(wo);break;case En.RESUME:this.handleDisconnect(wo)}})}removeSignalClientCallbacks(){this.client.removeAllListeners(N.Answer),this.client.removeAllListeners(N.Trickle),this.client.removeAllListeners(N.Offer),this.client.removeAllListeners(N.LocalTrackPublished),this.client.removeAllListeners(N.LocalTrackUnpublished),this.client.removeAllListeners(N.LocalTrackSubscribed),this.client.removeAllListeners(N.TokenRefresh),this.client.removeAllListeners(N.RemoteMuteChanged),this.client.removeAllListeners(N.SubscribedQualityUpdate),this.client.removeAllListeners(N.RoomMoved),this.client.removeAllListeners(N.MediaSectionsRequirement),this.client.removeAllListeners(N.PublishDataTrackResponse),this.client.removeAllListeners(N.UnpublishDataTrackResponse),this.client.removeAllListeners(N.DataTrackSubscriberHandles),this.client.removeAllListeners(N.Close),this.client.removeAllListeners(N.Leave)}makeRTCConfiguration(e){var t;let i=Object.assign({},this.rtcConfig);if((!((t=this.signalOpts)===null||t===void 0)&&t.e2eeEnabled||this.frameMetadataWorker&&!Ai())&&Xc()&&(this.log.debug("E2EE - setting up transports with insertable streams"),i.encodedInsertableStreams=!0),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",!e)return i;if(e.iceServers&&!i.iceServers){let s=[];e.iceServers.forEach(a=>{let o={urls:a.urls};a.username&&(o.username=a.username),a.credential&&(o.credential=a.credential),s.push(o)}),i.iceServers=s}return e.clientConfiguration&&e.clientConfiguration.forceRelay===wi.ENABLED&&(i.iceTransportPolicy="relay"),i}applyInitialPublisherLayout(e){this.createDataChannels(e),je()||this.addMediaSections(nb,ib)}addMediaSections(e,t){var i,r,s;let a={direction:"recvonly"};for(let c=0;c<e;c++)(i=this.pcManager)===null||i===void 0||i.addPublisherTransceiverOfKind("audio",a);let o=((r=this.pcManager)===null||r===void 0?void 0:r.mode)==="publisher-only";for(let c=0;c<t;c++){let d=(s=this.pcManager)===null||s===void 0?void 0:s.addPublisherTransceiverOfKind("video",a);if(o&&d){let l=hy(d);this.log.debug("dependency descriptor negotiated for received video",{negotiated:l})}}}useNegotiatedDataChannels(){var e,t,i,r;return((e=this.pcManager)===null||e===void 0?void 0:e.mode)==="publisher-only"&&((r=(i=(t=this.latestJoinResponse)===null||t===void 0?void 0:t.serverInfo)===null||i===void 0?void 0:i.protocol)!==null&&r!==void 0?r:0)>=kf}createDataChannels(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.useNegotiatedDataChannels();this.pcManager&&(this.dataChannels.hasPublisherChannels&&(this.publisherConnectionPromise=void 0),this.dataChannels.createPublisherChannels(this.pcManager,e))}decodeDataMessage(e){return g(this,void 0,void 0,function*(){if(e.data instanceof ArrayBuffer)return new Uint8Array(e.data);if(e.data instanceof Blob)return new Uint8Array(yield e.data.arrayBuffer());this.log.error("unsupported data type",{data:e.data})})}createSender(e,t,i){return g(this,void 0,void 0,function*(){let r;if(da())r=yield this.createTransceiverRTCRtpSender(e,t,i);else if(la())this.log.warn("using add-track fallback"),r=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new J("Required webRTC APIs not supported on this device");return this.setupFrameMetadataSender(r,t),r})}createSimulcastSender(e,t,i,r){return g(this,void 0,void 0,function*(){let s;if(da())s=yield this.createSimulcastTransceiverSender(e,t,i,r);else if(la())this.log.debug("using add-track fallback"),s=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new J("Cannot stream on this device");return s&&this.setupFrameMetadataSender(s,i),s})}get frameMetadataWorker(){var e;return(e=this.frameMetadataOptions)===null||e===void 0?void 0:e.worker}setupFrameMetadataSender(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;let r=this.frameMetadataWorker;if(!r||!((i=this.signalOpts)===null||i===void 0)&&i.e2eeEnabled)return;let s=Zc(t),a=Ar(s);if(Ai()){a&&(e.transform=new RTCRtpScriptTransform(r,{kind:"encode",packetTrailer:s}));return}if(!Mi(this.frameMetadataOptions)||!("createEncodedStreams"in e)){a&&this.log.warn("frame metadata transform not supported; skipping write",this.logContext);return}let o=e.createEncodedStreams(),c=o.readable,d=o.writable;a?r.postMessage({kind:"encode",data:{readableStream:c,writableStream:d,packetTrailer:s}},[c,d]):c.pipeTo(d)}createTransceiverRTCRtpSender(e,t,i){return g(this,void 0,void 0,function*(){if(!this.pcManager)throw new J("publisher is closed");let r=[];e.mediaStream&&r.push(e.mediaStream),Mt(e)&&(e.codec=t.videoCodec);let s={direction:"sendonly",streams:r};return i&&(s.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender})}createSimulcastTransceiverSender(e,t,i,r){return g(this,void 0,void 0,function*(){if(!this.pcManager)throw new J("publisher is closed");let s={direction:"sendonly"};r&&(s.sendEncodings=r);let a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s);if(i.videoCodec)return yield e.setSimulcastTrackSender(i.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return g(this,void 0,void 0,function*(){if(!this.pcManager)throw new J("publisher is closed");return this.pcManager.addPublisherTrack(e)})}handleLocalConnectionQuality(e){if(!this.participantSid)return;let t=e.updates.find(i=>i.participantSid===this.participantSid);t&&(t.quality===Tn.LOST?this.scheduleLostQualityReconnect():this.clearLostQualityTimeout())}scheduleLostQualityReconnect(){this.lostQualityTimeout||(this.lostQualityTimeout=Y.setTimeout(()=>{this.lostQualityTimeout=void 0,!(this._isClosed||this.pcState!==$e.Connected||this.attemptingReconnect)&&this.hasActivePublisherSenders()&&(this.log.warn("local connection quality lost while publishing, triggering full reconnect",this.logContext),this.fullReconnectOnNext=!0,this.handleDisconnect("connection quality lost",St.RR_PUBLISHER_FAILED))},eb))}clearLostQualityTimeout(){this.lostQualityTimeout&&(Y.clearTimeout(this.lostQualityTimeout),this.lostQualityTimeout=void 0)}hasActivePublisherSenders(){var e,t;return(t=(e=this.pcManager)===null||e===void 0?void 0:e.publisher.getSenders().some(i=>!!i.track&&i.track.readyState==="live"))!==null&&t!==void 0?t:!1}reconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:St.RR_UNKNOWN;this.fullReconnectOnNext=!0,this.handleDisconnect("reconcile",e)}attemptReconnect(e){return g(this,void 0,void 0,function*(){var t,i,r;if(this._isClosed)return;if(this.attemptingReconnect){this.log.warn("already attempting reconnect, returning early");return}this.clearLostQualityTimeout(),(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===wi.DISABLED||((r=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&r!==void 0?r:oe.NEW)===oe.NEW)&&(this.fullReconnectOnNext=!0);let s=this.fullReconnectOnNext;this.fullReconnectOnNext=!1;let a=!1,o=new AbortController;this.reconnectAbortController=o;try{if(this.attemptingReconnect=!0,s?yield this.restartConnection(o.signal):yield this.resumeConnection(e),o.signal.aborted){this.log.info("reconnect attempt cancelled, not marking it as succeeded");return}this.clearPendingReconnect(),a=!0}catch(c){if(o.signal.aborted){this.log.info("reconnect attempt cancelled, not retrying",{error:c});return}this.reconnectAttempts+=1;let d=!0;c instanceof J?(this.log.debug("received unrecoverable error",{error:c}),d=!1):(s||!(c instanceof Ft))&&(this.fullReconnectOnNext=!0),d?this.handleDisconnect("reconnect",St.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up")),this.emit(A.Disconnected),yield this.close("gave up reconnecting after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms")))}finally{this.reconnectAbortController===o&&(this.reconnectAbortController=void 0),this.attemptingReconnect=!1,a&&this.fullReconnectOnNext&&!this._isClosed&&(this.log.debug("full reconnect requested during in-progress attempt, dispatching"),this.handleDisconnect("reconnect"))}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",{error:t})}return null}restartConnection(e,t){return g(this,void 0,void 0,function*(){var i,r,s,a;try{if(e.aborted){this.log.info("full reconnect cancelled before starting",{regionUrl:t});return}if(!this.url||!this.token)throw new J("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts)),(i=this.restartAttemptController)===null||i===void 0||i.abort();let o=new AbortController;if(this.restartAttemptController=o,this.emit(A.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient(),e.aborted){this.log.info("full reconnect cancelled after cleaning up the previous session",{regionUrl:t});return}let c;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present"),new Ft;c=(yield this.join(t??this.url,this.token,this.signalOpts,e,!this.options.singlePeerConnection)).joinResponse}catch(d){throw d instanceof U&&d.reason===Z.NotAllowed?new J("could not reconnect, token might be expired"):new Ft}if(e.aborted){this.log.info("full reconnect cancelled after the signal join response",{regionUrl:t});return}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(A.SignalRestarted,c,o.signal),yield this.waitForPCReconnected(),e.aborted){this.log.info("full reconnect cancelled after peer connections reconnected",{regionUrl:t});return}if(this.client.currentState!==Me.CONNECTED)throw new Ft("Signal connection got severed during reconnect");(r=this.regionStrategy)===null||r===void 0||r.resetAttempts(),this.emit(A.Restarted)}catch(o){if(e.aborted){this.log.info("full reconnect cancelled after a failed attempt",{regionUrl:t});return}let c=yield(s=this.regionStrategy)===null||s===void 0?void 0:s.getNextUrl(e);if(e.aborted){this.log.info("full reconnect cancelled during region selection",{regionUrl:t});return}if(c){yield this.restartConnection(e,c);return}else throw(a=this.regionStrategy)===null||a===void 0||a.resetAttempts(),o}})}resumeConnection(e){return g(this,void 0,void 0,function*(){if(!this.url||!this.token)throw new J("could not reconnect, url or token not saved");if(!this.pcManager)throw new J("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts)),this.emit(A.Resuming);let t;try{this.setupSignalClientCallbacks(),t=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(r){let s="";throw r instanceof Error&&(s=r.message,this.log.error(r.message,{error:r})),r instanceof U&&r.reason===Z.NotAllowed?new J("could not reconnect, token might be expired"):r instanceof U&&r.reason===Z.LeaveRequest?r:new Ft(s)}if(this.emit(A.SignalResumed),t){let r=this.makeRTCConfiguration(t);this.pcManager.updateConfiguration(r),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=t.serverInfo)}else this.log.warn("Did not receive reconnect response");if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==Me.CONNECTED)throw new Ft("Signal connection got severed during reconnect");this.client.setReconnected();let i=this.dataChannelForKind(z.RELIABLE);i?.readyState==="open"&&i.id===null&&this.createDataChannels(),t?.lastMessageSeq&&this.resendReliableMessagesForResume(t.lastMessageSeq).catch(r=>{this.log.warn("failed to resend reliable messages after resume",Object.assign(Object.assign({},this.logContext),{error:r}))}),this.emit(A.Resumed)})}waitForPCInitialConnection(e,t){return g(this,void 0,void 0,function*(){if(!this.pcManager)throw new J("PC manager is closed");let i=!1,r=()=>{i=!0},s,a,o,c,d=new Promise((l,u)=>{s=l,a=()=>u(U.internal("could not establish pc connection")),o=()=>u(U.cancelled("room connection has been cancelled")),this.once(A.Restarted,s),this.once(A.Closing,a),t?.signal.addEventListener("abort",o),c=Y.setTimeout(a,e??this.peerConnectionTimeout)});this.once(A.Restarting,r);try{yield Promise.race([this.pcManager.ensurePCTransportConnection(t,e),d]),i&&(yield d)}finally{Y.clearTimeout(c),t?.signal.removeEventListener("abort",o),this.off(A.Restarting,r),this.off(A.Restarted,s),this.off(A.Closing,a)}})}waitForPCReconnected(){return g(this,void 0,void 0,function*(){this.pcState=$e.Reconnecting,this.log.debug("waiting for peer connection to reconnect");try{if(yield Re(Z0),!this.pcManager)throw new J("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=$e.Connected}catch(e){throw this.pcState=$e.Disconnected,U.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcAck(e,t){return g(this,void 0,void 0,function*(){let i=new Fe({destinationIdentities:[e],kind:qt.RELIABLE,value:{case:"rpcAck",value:new vs({requestId:t})}});yield this.sendDataPacket(i,z.RELIABLE)})}sendDataPacket(e,t){return g(this,void 0,void 0,function*(){var i,r;if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){let o=Zy(e);if(o){let c=yield this.e2eeManager.encryptData(o.toBinary());e.value={case:"encryptedPacket",value:new Kh({encryptedValue:c.payload,iv:c.iv,keyIndex:c.keyIndex})}}}t===z.RELIABLE&&(e.sequence=this.reliableChannel.nextSequence());let s=e.toBinary(),a=Math.min((r=(i=this.pcManager)===null||i===void 0?void 0:i.getMaxPublisherMessageSize())!==null&&r!==void 0?r:fu,fu);if(typeof a<"u"&&a!==0&&s.byteLength>a)throw new ra("cannot publish data packet larger than ".concat(a," bytes (got ").concat(s.byteLength,")"));t===z.RELIABLE?yield this.reliableChannel.send(s,e.sequence):yield this.lossyChannel.send(s)})}sendDataTrackFrame(e){return g(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(z.DATA_TRACK_LOSSY),yield this.dataTrackChannel.send(e)})}resendReliableMessagesForResume(e){return g(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(z.RELIABLE),yield this.reliableChannel.replay(e)})}flowControlFor(e){return this.dataChannels.channelFor(e)}waitForBufferHeadroom(e){return g(this,void 0,void 0,function*(){let t=this.dataChannelForKind(e);if(!t)throw new J("DataChannel not found, kind: ".concat(e));return this.flowControlFor(e).waitForHeadroomWithLock(t)})}ensureDataTransportConnected(e){return g(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return(function*(){var s;if(!i.pcManager)throw new J("PC manager is closed");let a=r?i.pcManager.subscriber:i.pcManager.publisher,o=r?"Subscriber":"Publisher";if(!a)throw U.internal("".concat(o," connection not set"));let c=!1;!r&&!i.dataChannelForKind(t,r)&&(i.createDataChannels(),c=!0),!c&&!r&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(c=!0),c&&i.negotiate().catch(u=>{i.log.error(u)});let d=i.dataChannelForKind(t,r);if(d?.readyState==="open")return;let l=new Date().getTime()+i.peerConnectionTimeout;for(;new Date().getTime()<l;){if(a.isICEConnected&&((s=i.dataChannelForKind(t,r))===null||s===void 0?void 0:s.readyState)==="open")return;yield Re(50)}throw U.internal("could not establish ".concat(o," connection, state: ").concat(a.getICEConnectionState()))})()})}ensurePublisherConnected(e){return g(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){if(!this.pcManager)return!1;let e=this.pcManager.currentState;return![oe.CONNECTING,oe.CONNECTED].includes(e)||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED?!1:e===oe.CONNECTING&&this.transportConnectingSince!==void 0&&Date.now()-this.transportConnectingSince>this.peerConnectionTimeout?(this.log.warn("transport stuck in connecting state",this.logContext),!1):!0}negotiate(){return g(this,void 0,void 0,function*(){return new Pe((e,t)=>g(this,void 0,void 0,function*(){if(!this.pcManager){t(new yt("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.dataChannels.hasPublisherChannels&&this.createDataChannels();let i=new AbortController,r=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing"),e()};this.isClosed&&t(new yt("cannot negotiate on closed engine")),this.pendingNegotiationAborts.add(r),this.pcManager.publisher.off(gt.RTPVideoPayloadTypes,this.onRtpMapAvailable),this.pcManager.publisher.once(gt.RTPVideoPayloadTypes,this.onRtpMapAvailable);try{yield this.pcManager.negotiate(i),e()}catch(s){if(i.signal.aborted){e();return}s instanceof yt&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",St.RR_UNKNOWN),s instanceof Error?t(s):t(new Error(String(s)))}finally{this.pendingNegotiationAborts.delete(r)}}))})}dataChannelForKind(e,t){return this.dataChannels.getHandle(e,t)}sendSyncState(e,t,i){var r,s,a,o;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup");return}let c=this.pcManager.publisher.getLocalDescription(),d=this.pcManager.publisher.getRemoteDescription(),l=(r=this.pcManager.subscriber)===null||r===void 0?void 0:r.getRemoteDescription(),u=(s=this.pcManager.subscriber)===null||s===void 0?void 0:s.getLocalDescription(),h=(o=(a=this.signalOpts)===null||a===void 0?void 0:a.autoSubscribe)!==null&&o!==void 0?o:!0,f=new Array,m=new Array;e.forEach(p=>{p.isDesired!==h&&f.push(p.trackSid),p.isEnabled||m.push(p.trackSid)}),this.client.sendSyncState(new Kc({answer:this.pcManager.mode==="publisher-only"?d?Xt({sdp:d.sdp,type:d.type}):void 0:u?Xt({sdp:u.sdp,type:u.type}):void 0,offer:this.pcManager.mode==="publisher-only"?c?Xt({sdp:c.sdp,type:c.type}):void 0:l?Xt({sdp:l.sdp,type:l.type}):void 0,subscription:new Ts({trackSids:f,subscribe:!h,participantTracks:[]}),publishTracks:ny(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:m,datachannelReceiveStates:this.reliableReceivedState.map((p,y)=>new pf({publisherSid:y,lastSeq:p})),publishDataTracks:i}))}failNext(){this.shouldFailNext=!0}failNextV1Path(){this.shouldFailOnV1Path=!0}dataChannelsInfo(){let e=[],t=(i,r)=>{i?.id!==void 0&&i.id!==null&&e.push(new mf({label:i.label,id:i.id,target:r}))};return t(this.dataChannelForKind(z.LOSSY),He.PUBLISHER),t(this.dataChannelForKind(z.RELIABLE),He.PUBLISHER),t(this.dataChannelForKind(z.LOSSY,!0),He.SUBSCRIBER),t(this.dataChannelForKind(z.RELIABLE,!0),He.SUBSCRIBER),t(this.dataChannelForKind(z.DATA_TRACK_LOSSY),He.PUBLISHER),t(this.dataChannelForKind(z.DATA_TRACK_LOSSY,!0),He.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&(Y.clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Le()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){Le()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t,i;let r=(i=(t=this.pcManager)===null||t===void 0?void 0:t.getTransceiverForReceiver(e))===null||i===void 0?void 0:i.mid;if(r){let s=Object.entries(this.midToTrackId).find(a=>F(a,1)[0]===r);if(s)return s[1]}}};function pu(n,e){let t=n.participantIdentity?n.participantIdentity:e.participantIdentity;n.participantIdentity=t,e.participantIdentity=t;let i=n.destinationIdentities.length!==0?n.destinationIdentities:e.destinationIdentities;n.destinationIdentities=i,e.destinationIdentities=i}var ai=we(he.Region),Ea=5e3,rb=3e4,ct=class n{static fetchRegionSettings(e,t,i){return g(this,void 0,void 0,function*(){let r=yield n.fetchLock.lock();try{let s=yield fetch("".concat(sb(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:i});if(s.ok){let a=qy(s.headers),o=a?a*1e3:Ea;return{regionSettings:yield s.json(),updatedAtInMs:Date.now(),maxAgeInMs:o}}else throw s.status===401?U.notAllowed("Could not fetch region settings: ".concat(s.statusText),s.status):U.internal("Could not fetch region settings: ".concat(s.statusText))}catch(s){throw s instanceof U?s:i?.aborted?U.cancelled("Region fetching was aborted"):U.serverUnreachable("Could not fetch region settings, ".concat(s instanceof Error?"".concat(s.name,": ").concat(s.message):s))}finally{r()}})}static scheduleRefetch(e,t,i){return g(this,void 0,void 0,function*(){let r=n.settingsTimeouts.get(e.hostname);clearTimeout(r),n.settingsTimeouts.set(e.hostname,setTimeout(()=>g(this,void 0,void 0,function*(){try{let s=yield n.fetchRegionSettings(e,t);n.updateCachedRegionSettings(e,t,s)}catch(s){if(s instanceof U&&s.reason===Z.NotAllowed){ai.debug("token is not valid, cancelling auto region refresh");return}ai.debug("auto refetching of region settings failed",{error:s}),n.scheduleRefetch(e,t,i)}}),i))})}static updateCachedRegionSettings(e,t,i){n.cache.set(e.hostname,i),n.scheduleRefetch(e,t,i.maxAgeInMs)}static stopRefetch(e){let t=n.settingsTimeouts.get(e);t&&(clearTimeout(t),n.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=n.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{let i=n.connectionTrackers.get(e);i&&i.connectionCount===0&&(ai.debug("stopping region refetch after disconnect delay",{hostname:e}),n.stopRefetch(e)),i&&(i.cleanupTimeout=void 0)},rb))}static cancelCleanup(e){let t=n.connectionTrackers.get(e);t?.cleanupTimeout&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){let e=this.serverUrl.hostname,t=n.connectionTrackers.get(e);t||(t={connectionCount:0},n.connectionTrackers.set(e,t)),t.connectionCount++,n.cancelCleanup(e)}notifyDisconnected(){let e=this.serverUrl.hostname,t=n.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),t.connectionCount===0&&n.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){var t;this.token=e;let i=this.getServerUrl(),r=n.cache.get(i.hostname);n.scheduleRefetch(this.serverUrl,this.token,(t=r?.maxAgeInMs)!==null&&t!==void 0?t:Ea)}isCloud(){return qn(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return g(this,void 0,void 0,function*(){return n.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return g(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=n.cache.get(this.serverUrl.hostname);if(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)try{let r=yield this.fetchRegionSettings(e);n.updateCachedRegionSettings(this.serverUrl,this.token,r),t=r}catch(r){if(!t||r instanceof U&&(r.reason===Z.Cancelled||r.reason===Z.NotAllowed))throw r;ai.warn("could not refresh region settings, using expired cache",{error:r})}let i=t.regionSettings.regions.filter(r=>!this.attemptedRegions.find(s=>s.url===r.url));if(i.length>0){let r=i[0];return this.attemptedRegions.push(r),ai.info("switching to region: ".concat(r.region),{region:r.region}),r.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){n.updateCachedRegionSettings(this.serverUrl,this.token,e)}};ct.cache=new Map;ct.settingsTimeouts=new Map;ct.connectionTrackers=new Map;ct.fetchLock=new ye;function sb(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}var ob=["e2eeManager","frameMetadataOptions","byteStreamOpener","videoPublisher"];function sd(n,e,t){let i=Symbol("lk.extension.".concat(n)),r=s=>({key:i,requires:e,install:(a,o)=>t(a,o,typeof s=="function"?s():s)});return Object.assign(s=>r(s),r())}function qf(n,e){let t=new Map;for(let a of e){if(t.has(a.key))throw new Error("extension '".concat(String(a.key),"' is listed twice"));t.set(a.key,a)}let i=[],r=new Set,s=(a,o)=>{var c,d;let l=(c=t.get(a.key))!==null&&c!==void 0?c:a;if(o.includes(l.key))throw new Error("extension '".concat(String(l.key),"' depends on itself"));r.has(l.key)||(r.add(l.key),(d=l.requires)===null||d===void 0||d.forEach(u=>s(u,[...o,l.key])),i.push(l))};e.forEach(a=>s(a,[])),n.installExtensions(i)}var od=2e3;function ws(n,e){if(!e)return 0;let t,i;return"bytesReceived"in n?(t=n.bytesReceived,i=e.bytesReceived):"bytesSent"in n&&(t=n.bytesSent,i=e.bytesSent),t===void 0||i===void 0||n.timestamp===void 0||e.timestamp===void 0?0:(t-i)*8*1e3/(n.timestamp-e.timestamp)}var ad=typeof MediaRecorder<"u",Pa=class{constructor(){throw new Error("MediaRecorder is not available in this environment")}},ab=ad?MediaRecorder:Pa,Ra=class extends ab{constructor(e,t){if(!ad)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),t);let i,r,s=()=>r===void 0,a=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",a),this.removeEventListener("error",o),r?.close(),r=void 0},o=c=>{r?.error(c),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",a),this.removeEventListener("error",o),r=void 0};this.byteStream=new ReadableStream({start:c=>{r=c,i=d=>g(this,void 0,void 0,function*(){let l;if(d.data.arrayBuffer){let u=yield d.data.arrayBuffer();l=new Uint8Array(u)}else if(d.data.byteArray)l=d.data.byteArray;else throw new Error("no data available!");s()||c.enqueue(l)}),this.addEventListener("dataavailable",i)},cancel:()=>{a()}}),this.addEventListener("stop",a),this.addEventListener("error",o)}};function cb(){return ad}var db=1e3,lb=1e4,Ur=class extends C{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,i){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,s=arguments.length>4?arguments[4]:void 0;super(e,t,s),this.manuallyStopped=!1,this.stopCount=0,this.pendingDeviceChange=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=nd(()=>g(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>g(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(M.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new ye,this.pauseUpstreamLock=new ye,this.trackChangeLock=new ye,this.trackChangeLock.lock().then(a=>g(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{a()}})),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==C.Kind.Video)return;let e=this._mediaStreamTrack.getSettings(),t=e.width,i=e.height;if(t&&i)return{width:t,height:i}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get isStopped(){return this.manuallyStopped}get mediaStreamTrack(){var e,t;return(t=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&t!==void 0?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t,i){return g(this,void 0,void 0,function*(){var r;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(a=>{Pn(this._mediaStreamTrack,a)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let s;if(this.processor&&e){if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(_n(e,this.processorElement),this.processorElement.muted=!0);let a=this.processor,o=this.stopCount;if(yield a.restart({track:e,kind:this.kind,element:this.processorElement,audioContext:this.audioContext,localTrack:this}),this.stopCount!==o)throw new le("track was stopped while its processor was restarting");s=a.processedTrack}this.sender&&((r=this.sender.transport)===null||r===void 0?void 0:r.state)!=="closed"&&(yield this.sender.replaceTrack(s??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=i?!0:!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(a=>{_n(s??e,a)})),yield this.onMediaStreamTrackChanged()})}onMediaStreamTrackChanged(){return g(this,void 0,void 0,function*(){})}waitForDimensions(){return g(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:db;return(function*(){if(e.kind===C.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");let i=Date.now();for((by()||Cs()&&e.source===C.Source.ScreenShare)&&(yield ay(e._mediaStreamTrack,t,e.attachedElements));;){let r=e.dimensions;if(r)return r;if(Date.now()-i>=t)break;yield Re(50)}throw new le("unable to get track dimensions after timeout")})()})}setDeviceId(e){return g(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===An(e)&&this._mediaStreamTrack.readyState==="live"?!0:(this._constraints.deviceId=e,this.isMuted?(this.pendingDeviceChange=!0,!0):(yield this.restartTrack(),An(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return g(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){if(e.source===C.Source.ScreenShare)return;let i=e._mediaStreamTrack.getSettings(),r=i.deviceId,s=i.groupId,a=e.kind===C.Kind.Audio?"audioinput":"videoinput";return t?Ne.getInstance().normalizeDeviceId(a,r,s):r})()})}mute(){return g(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return g(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return g(this,void 0,void 0,function*(){let i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new le("unable to replace an unpublished track");let r,s;typeof t=="boolean"?r=t:t!==void 0&&(r=t.userProvidedTrack,s=t.stopProcessor),this.providedByUser=r??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),s&&this.processor&&(yield this.internalStopProcessor())}finally{i()}return yield this.onSenderTrackSwapped(),this})}onSenderTrackSwapped(){return g(this,void 0,void 0,function*(){})}restart(e,t){return g(this,void 0,void 0,function*(){this.manuallyStopped=!1;let i=yield this.trackChangeLock.lock();try{e||(e=this._constraints);let r=e,s=r.deviceId,a=r.facingMode,o=jv(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));let c={audio:!1,video:!1};this.kind===C.Kind.Video?c.video=s||a?{deviceId:s,facingMode:a}:!0:c.audio=s?Object.assign({deviceId:s},o):!0,this.attachedElements.forEach(u=>{Pn(this.mediaStreamTrack,u)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();let d;try{d=yield navigator.mediaDevices.getUserMedia(c)}catch(u){throw My(u),u}let l=d.getTracks()[0];try{this.kind===C.Kind.Video&&(yield l.applyConstraints(o)),l.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(l,!1,t)}catch(u){throw this._mediaStreamTrack!==l&&l.stop(),u}return this._constraints=e,this.pendingDeviceChange=!1,this.emit(M.Restarted,this),this}finally{this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),i()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?M.Muted:M.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return g(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Pf()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,this.stopCount+=1,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(e=this.processor)===null||e===void 0||e.destroy().catch(t=>{this.log.error("failed to destroy processor",Object.assign(Object.assign({},this.logContext),{error:t}))}),this.processor=void 0}pauseUpstream(){return g(this,void 0,void 0,function*(){var e;let t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}if(this._isUpstreamPaused=!0,this.emit(M.UpstreamPaused,this),!_y())throw new Ri("pauseUpstream is not supported on Safari < 12.");((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return g(this,void 0,void 0,function*(){var e;let t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(M.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return g(this,void 0,void 0,function*(){var e;return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){return g(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var s;let a=yield i.trackChangeLock.lock(),o=i.stopCount;try{i.log.debug("setting up processor",i.logContext);let c=document.createElement(i.kind),d={kind:i.kind,track:i._mediaStreamTrack,element:c,audioContext:i.audioContext,localTrack:i};if(yield t.init(d),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.internalStopProcessor()),i.stopCount!==o)throw yield i.destroyUnusedProcessor(t),new le("track was stopped while its processor was being set");if(i.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(_n(i._mediaStreamTrack,c),c.muted=!0,c.play().catch(l=>{l instanceof DOMException&&l.name==="AbortError"?(i.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},i.logContext),{error:l})),setTimeout(()=>{c.play().catch(u=>{i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{err:u}))})},100)):i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:l}))}),i.processor=t,i.processorElement=c,i.processor.processedTrack){for(let l of i.attachedElements)l!==i.processorElement&&r&&(Pn(i._mediaStreamTrack,l),_n(i.processor.processedTrack,l));if(yield(s=i.sender)===null||s===void 0?void 0:s.replaceTrack(i.processor.processedTrack),i.stopCount!==o)throw new le("track was stopped while its processor was being set")}i.emit(M.TrackProcessorUpdate,i.processor)}finally{a()}yield i.onSenderTrackSwapped()})()})}destroyUnusedProcessor(e){return g(this,void 0,void 0,function*(){yield e.destroy().catch(t=>{this.log.error("failed to destroy processor",Object.assign(Object.assign({},this.logContext),{error:t}))})})}getProcessor(){return this.processor}stopProcessor(){return g(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){let i=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{i()}yield e.onSenderTrackSwapped()})()})}internalStopProcessor(){return g(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var i,r;e.processor&&(e.log.debug("stopping processor",e.logContext),(i=e.processor.processedTrack)===null||i===void 0||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||((r=e.processorElement)===null||r===void 0||r.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(M.TrackProcessorUpdate))})()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!cb()){this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext);return}if(this.localTrackRecorder){this.log.warn("preconnect buffer already started");return}else{let t="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(t)||(t="video/mp4"),this.localTrackRecorder=new Ra(this,{mimeType:t})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},lb)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.mimeType}},jn=class extends Ur{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;super(e,C.Kind.Audio,t,i,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>g(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let a;try{a=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}a&&this.prevStats&&(this._currentBitrate=ws(a,this.prevStats)),this.prevStats=a}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(M.AudioTrackFeatureUpdate,this,ge.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(M.AudioTrackFeatureUpdate,this,ge.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return g(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===C.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return g(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.source===C.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||this.pendingDeviceChange)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}restartTrack(e){return g(this,void 0,void 0,function*(){let t;if(e){let i=Jc({audio:e});typeof i.audio!="boolean"&&(t=i.audio)}yield this.restart(t)})}applyConstraints(e){return g(this,void 0,void 0,function*(){let t=yield this.trackChangeLock.lock();try{let i=yield this._mediaStreamTrack.applyConstraints(e);return this._constraints=Object.assign(Object.assign({},this._constraints),e),i}finally{t()}})}restart(e,t){let i=Object.create(null,{restart:{get:()=>super.restart}});return g(this,void 0,void 0,function*(){let r=yield i.restart.call(this,e,t);return this.checkForSilence(),r})}startMonitor(){Le()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},od)))}observeProcessedTrack(e){this.observedProcessedTrack!==e&&(this.observedProcessedTrack&&(this.observedProcessedTrack.removeEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.observedProcessedTrack.removeEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable),this.observedProcessedTrack=void 0,this.isKrispNoiseFilterEnabled&&this.handleKrispNoiseFilterDisable()),e&&(e.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),e.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable),this.observedProcessedTrack=e))}setProcessor(e){return g(this,void 0,void 0,function*(){var t;let i=yield this.trackChangeLock.lock(),r=this.stopCount;try{if(!je()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());let s={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext,localTrack:this};if(this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(s),this.stopCount!==r)throw yield this.destroyUnusedProcessor(e),new le("track was stopped while its processor was being set");if(this.processor=e,e.processedTrack){if(yield(t=this.sender)===null||t===void 0?void 0:t.replaceTrack(e.processedTrack),this.stopCount!==r)throw new le("track was stopped while its processor was being set");this.observeProcessedTrack(e.processedTrack)}this.emit(M.TrackProcessorUpdate,this.processor)}finally{i()}})}onMediaStreamTrackChanged(){return g(this,void 0,void 0,function*(){var e;this.observeProcessedTrack((e=this.processor)===null||e===void 0?void 0:e.processedTrack)})}internalStopProcessor(){let e=Object.create(null,{internalStopProcessor:{get:()=>super.internalStopProcessor}});return g(this,arguments,void 0,function(){var t=this;let i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){t.observeProcessedTrack(void 0),yield e.internalStopProcessor.call(t,i)})()})}stop(){this.observeProcessedTrack(void 0),super.stop()}setAudioContext(e){return g(this,void 0,void 0,function*(){var t;if(this.audioContext===e)return;let i=yield this.trackChangeLock.lock(),r=this.stopCount;try{if(this.audioContext=e,!this.processor||je())return;if(!e){this.log.debug("stopping audio processor, audio context has been removed",this.logContext),yield this.internalStopProcessor();return}this.log.debug("restarting audio processor on new audio context",this.logContext);let s=this.processor;if(yield s.restart({kind:this.kind,track:this._mediaStreamTrack,audioContext:e,localTrack:this}),this.stopCount!==r)return;s.processedTrack&&(yield(t=this.sender)===null||t===void 0?void 0:t.replaceTrack(s.processedTrack),this.observeProcessedTrack(s.processedTrack)),this.emit(M.TrackProcessorUpdate,this.processor)}finally{i()}})}getSenderStats(){return g(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;let t=yield this.sender.getStats(),i;return t.forEach(r=>{if(r.type==="outbound-rtp"){i={type:"audio",streamId:r.id,packetsSent:r.packetsSent,bytesSent:r.bytesSent,timestamp:r.timestamp};let s=t.get(r.remoteId);s&&(i.packetsLost=s.packetsLost,i.jitter=s.jitter,i.roundTripTime=s.roundTripTime)}}),i})}checkForSilence(){return g(this,void 0,void 0,function*(){let e=yield Sf(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(M.AudioSilenceDetected)),e})}},Br=class extends C{constructor(e,t,i,r,s){super(e,i,s),this.timeSyncLoop=()=>{var a;if(this.listenerCount(M.TimeSyncUpdate)===0){this.timeSyncHandle=void 0;return}this.timeSyncHandle=requestAnimationFrame(this.timeSyncLoop);let o=(a=this.receiver)===null||a===void 0?void 0:a.getSynchronizationSources()[0];if(o){let c=o.timestamp,d=o.rtpTimestamp;d&&this.rtpTimestamp!==d&&(this.emit(M.TimeSyncUpdate,{timestamp:c,rtpTimestamp:d}),this.rtpTimestamp=d)}},this.onTimeSyncListenerAdded=a=>{a===M.TimeSyncUpdate&&this.timeSyncHandle===void 0&&(this.timeSyncHandle=requestAnimationFrame(this.timeSyncLoop))},this.sid=t,this.receiver=r}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?M.Muted:M.Unmuted,this))}setMediaStream(e){this.mediaStream=e;let t=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(M.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return g(this,void 0,void 0,function*(){var e;return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),od)),iy()&&this.registerTimeSyncUpdate()}stopMonitor(){super.stopMonitor(),this.off("newListener",this.onTimeSyncListenerAdded)}registerTimeSyncUpdate(){let e=this;e.off("newListener",this.onTimeSyncListenerAdded),e.on("newListener",this.onTimeSyncListenerAdded),this.timeSyncHandle===void 0&&this.timeSyncLoop()}},Ia=class extends Br{constructor(e,t,i,r,s,a){super(e,t,C.Kind.Audio,i,a),this.connectedNodes=[],this.monitorReceiver=()=>g(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=ws(o,this.prevStats)),this.prevStats=o}),this.audioContext=r,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;if(this.audioContext)(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1);else for(let i of this.attachedElements)i.volume=e;je()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume!==void 0)return this.elementVolume;if(je())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return g(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(ua(t))return t.setSinkId(e)}))})}attach(e){let t=!this.sourceNode;return e?super.attach(e):e=super.attach(),this.sinkId&&ua(e)&&e.setSinkId(this.sinkId).catch(i=>{this.log.error("Failed to set sink id on remote audio track",i,this.logContext)}),this.audioContext&&(e.volume=0,e.muted=!0,t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e))),this.elementVolume!==void 0&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){var t;if(this.audioContext!==e)if(this.audioContext=e,e){for(let i of this.attachedElements)i.volume=0,i.muted=!0;this.attachedElements.length>0&&this.connectWebAudio(e,this.attachedElements[0])}else{this.disconnectWebAudio();for(let i of this.attachedElements)i.muted=!1,i.volume=(t=this.elementVolume)!==null&&t!==void 0?t:1}}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.connectedNodes=[this.sourceNode],this.webAudioPluginNodes.forEach(r=>{i.connect(r),i=r,this.connectedNodes.push(r)}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.connectedNodes.push(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume!==void 0&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(M.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(r=>{this.emit(M.AudioPlaybackFailed,r)})}disconnectWebAudio(){var e,t;for(let i=0;i<this.connectedNodes.length-1;i+=1)try{this.connectedNodes[i].disconnect(this.connectedNodes[i+1])}catch{}this.connectedNodes=[],(e=this.gainNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return g(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;let e=yield this.receiver.getStats(),t;return e.forEach(i=>{i.type==="inbound-rtp"&&(t={type:"audio",streamId:i.id,timestamp:i.timestamp,jitter:i.jitter,bytesReceived:i.bytesReceived,concealedSamples:i.concealedSamples,concealmentEvents:i.concealmentEvents,silentConcealedSamples:i.silentConcealedSamples,silentConcealmentEvents:i.silentConcealmentEvents,totalAudioEnergy:i.totalAudioEnergy,totalSamplesDuration:i.totalSamplesDuration})}),t})}},st=class extends Oe.EventEmitter{constructor(e,t,i,r){var s;super(),this.metadataMuted=!1,this.encryption=X.NONE,this.log=W,this.handleMuted=()=>{this.emit(M.Muted)},this.handleUnmuted=()=>{this.emit(M.Unmuted)},this.log=we((s=r?.loggerName)!==null&&s!==void 0?s:he.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=C.Source.Unknown}setTrack(e){this.track&&(this.track.off(M.Muted,this.handleMuted),this.track.off(M.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(M.Muted,this.handleMuted),e.on(M.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),K(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==X.NONE}get audioTrack(){if(bt(this.track))return this.track}get videoTrack(){if(Mt(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=C.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===C.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}};(function(n){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(n.SubscriptionStatus||(n.SubscriptionStatus={})),(function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"})(n.PermissionStatus||(n.PermissionStatus={}))})(st||(st={}));var xi=class extends st{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,i,r){super(e,t.sid,t.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(M.Ended)},this.handleCpuConstrained=()=>{this.track&&Mt(this.track)&&this.emit(M.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(M.Ended,this.handleTrackEnded),this.track.off(M.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(M.Ended,this.handleTrackEnded),e.on(M.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return g(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return g(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return g(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return g(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(bt(this.track)){let t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(ge.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(ge.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(ge.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(ge.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(ge.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(ge.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}},Aa;function ub(n){Aa=n}function qr(){if(!Aa)throw new le("video capture is not available in this build, add the video extension");return Aa}function Es(n,e){return g(this,void 0,void 0,function*(){n??(n={});let t=!1,i=Cf(n),r=i.audioProcessor,s=i.videoProcessor,a=i.optionsWithoutProcessor,o=a.audio,c=a.video;if(r&&typeof a.audio=="object"&&(a.audio.processor=r),s&&typeof a.video=="object"&&(a.video.processor=s),n.audio&&typeof a.audio=="object"&&typeof a.audio.deviceId=="string"){let h=a.audio.deviceId;a.audio.deviceId={exact:h},t=!0,o=Object.assign(Object.assign({},a.audio),{deviceId:{ideal:h}})}if(a.video&&typeof a.video=="object"&&typeof a.video.deviceId=="string"){let h=a.video.deviceId;a.video.deviceId={exact:h},t=!0,c=Object.assign(Object.assign({},a.video),{deviceId:{ideal:h}})}a.audio===!0?a.audio={deviceId:"default"}:typeof a.audio=="object"&&a.audio!==null&&(a.audio=Object.assign(Object.assign({},a.audio),{deviceId:a.audio.deviceId||"default"})),a.video===!0?a.video={deviceId:"default"}:typeof a.video=="object"&&!a.video.deviceId&&(a.video.deviceId="default");let d=Tf(a,Bf,a.video?qr().defaults:void 0),l=Jc(d),u=navigator.mediaDevices.getUserMedia(l);a.audio&&(Ne.userMediaPromiseMap.set("audioinput",u),u.catch(()=>Ne.userMediaPromiseMap.delete("audioinput"))),a.video&&(Ne.userMediaPromiseMap.set("videoinput",u),u.catch(()=>Ne.userMediaPromiseMap.delete("videoinput")));try{let h=yield u;return yield Promise.all(h.getTracks().map(f=>g(this,void 0,void 0,function*(){let m=f.kind==="audio",p,y=m?l.audio:l.video;typeof y!="boolean"&&(p=y);let v=f.getSettings().deviceId;p?.deviceId&&An(p.deviceId)!==v?p.deviceId=v:p||(p={deviceId:v});let _=f.kind==="audio"?new jn(f,p,!1,void 0,e):qr().createTrack(f,p,!1,e);return _.kind===C.Kind.Video?_.source=C.Source.Camera:_.kind===C.Kind.Audio&&(_.source=C.Source.Microphone),_.mediaStream=h,bt(_)&&r?yield _.setProcessor(r):Mt(_)&&s&&(yield _.setProcessor(s)),_})))}catch(h){if(!t)throw h;return Es(Object.assign(Object.assign({},n),{audio:o,video:c}),e)}})}function hb(n){return g(this,void 0,void 0,function*(){return(yield Es({audio:n??!0,video:!1}))[0]})}var Ut;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(Ut||(Ut={}));function fb(n){switch(n){case Tn.EXCELLENT:return Ut.Excellent;case Tn.GOOD:return Ut.Good;case Tn.POOR:return Ut.Poor;case Tn.LOST:return Ut.Lost;default:return Ut.Unknown}}var jr=class extends Oe.EventEmitter{get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return((e=this.permissions)===null||e===void 0?void 0:e.agent)||this.kind===Ei.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===wn.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,r,s,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Ei.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Ut.Unknown,this.log=W,this.loggerOptions=a,this.log=we((c=a?.loggerName)!==null&&c!==void 0?c:he.Participant,()=>this.logContext),this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=s??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(let i of this.trackPublications){var t=F(i,2);let r=t[1];if(r.source===e)return r}}getTrackPublicationByName(e){for(let i of this.trackPublications){var t=F(i,2);let r=t[1];if(r.trackName===e)return r}}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new Ce,this.once(L.Active,()=>{var e,t;(t=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||t===void 0||t.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;let t=this.getTrackPublication(C.Source.Camera);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;let t=this.getTrackPublication(C.Source.Microphone);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(C.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}isOlderSession(e){let t=this.participantInfo;return!t||t.sid===e.sid?!1:e.joinedAt!==t.joinedAt?e.joinedAt<t.joinedAt:e.joinedAtMs&&t.joinedAtMs&&e.joinedAtMs!==t.joinedAtMs?e.joinedAtMs<t.joinedAtMs:e.sid<t.sid}updateInfo(e){var t;return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===wn.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==wn.ACTIVE&&this.emit(L.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){let t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(L.ParticipantMetadataChanged,i)}_setName(e){let t=this.name!==e;this.name=e,t&&this.emit(L.ParticipantNameChanged,e)}_setAttributes(e){let t=ry(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(L.AttributesChanged,t)}setPermissions(e){var t,i,r,s,a,o;let c=this.permissions,d=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((i=this.permissions)===null||i===void 0?void 0:i.canSubscribe)||e.canPublishData!==((r=this.permissions)===null||r===void 0?void 0:r.canPublishData)||e.hidden!==((s=this.permissions)===null||s===void 0?void 0:s.hidden)||e.recorder!==((a=this.permissions)===null||a===void 0?void 0:a.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((l,u)=>{var h;return l!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[u])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,d&&this.emit(L.ParticipantPermissionsChanged,c),d}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(L.IsSpeakingChanged,e))}setConnectionQuality(e){let t=this._connectionQuality;this._connectionQuality=fb(e),t!==this._connectionQuality&&this.emit(L.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&((t=(e=this.activeFuture).reject)===null||t===void 0||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){return g(this,void 0,void 0,function*(){this.audioContext=e,yield Promise.all(Array.from(this.audioTrackPublications.values()).map(t=>t.track).filter(bt).map(t=>t.setAudioContext(e)))})}addTrackPublication(e){this.log.debug("adding track publication",{trackSid:e.trackSid,source:e.source,kind:e.kind}),e.on(M.Muted,()=>{this.emit(L.TrackMuted,e)}),e.on(M.Unmuted,()=>{this.emit(L.TrackUnmuted,e)});let t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case C.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case C.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}};function pb(n){var e,t,i;if(!n.participantSid&&!n.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new hf({participantIdentity:(e=n.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=n.participantSid)!==null&&t!==void 0?t:"",allTracks:(i=n.allowAll)!==null&&i!==void 0?i:!1,trackSids:n.allowedTrackSids||[]})}var Vr=class extends jr{constructor(e,t,i,r){let s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{};super(e,t,void 0,void 0,void 0,{loggerName:r.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.pendingReservations=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=X.NONE,this.e2eeStateMutex=new ye,this.enabledPublishVideoCodecs=[],this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Ce)},this.handleReconnected=()=>{var a,o;(o=(a=this.reconnectFuture)===null||a===void 0?void 0:a.resolve)===null||o===void 0||o.call(a),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var a,o,c,d,l,u;this.reconnectFuture&&(this.reconnectFuture.promise.catch(h=>this.log.warn(h.message)),(o=(a=this.reconnectFuture)===null||a===void 0?void 0:a.reject)===null||o===void 0||o.call(a,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&((d=(c=this.signalConnectedFuture).reject)===null||d===void 0||d.call(c,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),(u=(l=this.activeAgentFuture)===null||l===void 0?void 0:l.reject)===null||u===void 0||u.call(l,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=a=>{var o,c;a.participant&&this.updateInfo(a.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new Ce),(c=(o=this.signalConnectedFuture).resolve)===null||c===void 0||c.call(o)},this.handleSignalRequestResponse=a=>{let o=a.requestId,c=a.reason,d=a.message,l=this.pendingSignalRequests.get(o);l&&(c!==rn.OK&&l.reject(new Rr(d,c)),this.pendingSignalRequests.delete(o))},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions}),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(a=>pb(a)))},this.onTrackUnmuted=a=>{this.onTrackMuted(a,a.isUpstreamPaused)},this.onTrackMuted=(a,o)=>{if(o===void 0&&(o=!0),!a.sid){this.log.error("could not update mute status for unpublished track",K(a));return}this.engine.updateMuteStatus(a.sid,o)},this.onTrackUpstreamPaused=a=>{this.log.debug("upstream paused",K(a)),this.onTrackMuted(a,!0)},this.onTrackUpstreamResumed=a=>{this.log.debug("upstream resumed",K(a)),this.onTrackMuted(a,a.isMuted)},this.onTrackFeatureUpdate=a=>{let o=this.audioTrackPublications.get(a.sid);if(!o){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(a.sid));return}this.engine.client.sendUpdateLocalAudioTrack(o.trackSid,o.getTrackFeatures())},this.onTrackCpuConstrained=(a,o)=>{this.log.debug("track cpu constrained",K(o)),this.emit(L.LocalTrackCpuConstrained,a,o)},this.handleLocalTrackUnpublished=a=>{let o=this.trackPublications.get(a.trackSid);if(!o){this.log.warn("received unpublished event for unknown track",{trackSid:a.trackSid});return}this.unpublishTrack(o.track)},this.handleTrackEnded=a=>g(this,void 0,void 0,function*(){if(a.source===C.Source.ScreenShare||a.source===C.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",K(a)),this.unpublishTrack(a);else if(a.isUserProvided)yield a.mute();else if(ht(a)||We(a))try{if(Le())try{let o=yield navigator?.permissions.query({name:a.source===C.Source.Camera?"camera":"microphone"});if(o&&o.state==="denied")throw this.log.warn("user has revoked access to ".concat(a.source),K(a)),o.onchange=()=>{o.state!=="denied"&&(a.isMuted||a.restartTrack(),o.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}a.isMuted||(this.log.debug("track ended, attempting to use a different device",K(a)),ht(a)?yield this.restartOnDefaultAudioDevice(a):yield a.restartTrack())}catch{this.log.warn("could not restart track, muting instead",K(a)),yield a.mute()}}),this.slots=s,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=r,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==X.NONE}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(A.RemoteMute,(i,r)=>{let s=this.trackPublications.get(i);!s||!s.track||(r?s.mute():s.unmute())}),!((t=this.signalConnectedFuture)===null||t===void 0)&&t.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(A.Connected,this.handleReconnected).on(A.SignalConnected,this.handleSignalConnected).on(A.SignalRestarted,this.handleReconnected).on(A.SignalResumed,this.handleReconnected).on(A.Restarting,this.handleReconnecting).on(A.Resuming,this.handleReconnecting).on(A.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(A.Closing,this.handleClosing).on(A.SignalRequestResponse,this.handleSignalRequestResponse)}setMetadata(e){return g(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return g(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return g(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return g(this,arguments,void 0,function(t){var i=this;let r=t.metadata,s=t.name,a=t.attributes;return(function*(){return new Pe((o,c)=>g(i,void 0,void 0,function*(){var d,l;try{let u=!1,h=yield this.engine.client.sendUpdateLocalMetadata((d=r??this.metadata)!==null&&d!==void 0?d:"",(l=s??this.name)!==null&&l!==void 0?l:"",a),f=performance.now();for(this.pendingSignalRequests.set(h,{resolve:o,reject:m=>{c(m),u=!0},values:{name:s,metadata:r,attributes:a}});performance.now()-f<5e3&&!u;){if((!s||this.name===s)&&(!r||this.metadata===r)&&(!a||Object.entries(a).every(m=>{let p=F(m,2),y=p[0],v=p[1];return this.attributes[y]===v||v===""&&!this.attributes[y]}))){this.pendingSignalRequests.delete(h),o();return}yield Re(50)}c(new Rr("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error?c(u):c(new Error(String(u)))}}))})()})}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(C.Source.Microphone,e,t,i)}setE2EEEnabled(e){return g(this,void 0,void 0,function*(){let t=yield this.e2eeStateMutex.lock();try{if(this.encryptionType=e?X.GCM:X.NONE,yield Promise.all(this.pendingPublishPromises.values()),this.trackPublications.size===0||Array.from(this.trackPublications.values()).every(i=>i.isEncrypted===e))return;yield this.republishAllTracks(void 0,!1)}finally{t()}})}setTrackEnabled(e,t,i,r){return g(this,void 0,void 0,function*(){var s,a,o;this.log.debug("setTrackEnabled",{source:e,enabled:t}),this.republishPromise&&(yield this.republishPromise);let c=this.getTrackPublication(e);if(t)if(c)yield c.unmute();else{let h;if(this.pendingPublishing.has(e)){let p=yield this.waitForPendingPublicationOfSource(e);return p||this.log.info("waiting for pending publication promise timed out",{source:e}),yield p?.unmute(),p}this.pendingPublishing.add(e);let f,m;try{switch(e){case C.Source.Camera:h=yield this.createTracks({video:(s=i)!==null&&s!==void 0?s:!0});break;case C.Source.Microphone:{f=(a=this.reservePublication)===null||a===void 0?void 0:a.call(this,{source:C.Source.Microphone,publishOptions:Object.assign({},r)}),m=f&&this.limitRegistration(f),h=yield this.createTracks({audio:(o=i)!==null&&o!==void 0?o:!0});break}case C.Source.ScreenShare:h=yield this.requireVideoPublisher().createScreenTracks(Object.assign({},i));break;default:throw new le(e)}}catch(p){throw h?.forEach(y=>{y.stop()}),p instanceof Error&&this.emit(L.MediaDevicesError,p,ca(e)),f?.cancel().catch(()=>{}),this.pendingPublishing.delete(e),p}for(let p of h){let y=Object.assign(Object.assign({},this.roomOptions.publishDefaults),r);e===C.Source.Microphone&&bt(p)&&y.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone"),p.startPreConnectBuffer())}try{let p=[];for(let v of h)this.log.info("publishing track",K(v)),p.push(f&&v.kind===C.Kind.Audio?f.attachTrack(v):this.publishTrack(v,r));let y=yield Promise.all(p);var d=F(y,1);c=d[0]}catch(p){throw h?.forEach(y=>{y.stop()}),m?m(p):p}finally{this.pendingPublishing.delete(e)}}else if(!c?.track&&this.pendingPublishing.has(e)&&(c=yield this.waitForPendingPublicationOfSource(e),c||this.log.info("waiting for pending publication promise timed out",{source:e})),c&&c.track)if(e===C.Source.ScreenShare){let h=[this.unpublishTrack(c.track)],f=this.getTrackPublication(C.Source.ScreenShareAudio);f&&f.track&&h.push(this.unpublishTrack(f.track));var l=yield Promise.all(h),u=F(l,1);c=u[0]}else yield c.mute();return c})}createTracks(e){return g(this,void 0,void 0,function*(){var t,i;e??(e={});let r=Tf(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(i=this.roomOptions)===null||i===void 0?void 0:i.videoCaptureDefaults);try{let s=yield Es(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return yield Promise.all(s.map(o=>g(this,void 0,void 0,function*(){return bt(o)&&(this.microphoneError=void 0,yield o.setAudioContext(this.audioContext),o.source=C.Source.Microphone,this.emit(L.AudioStreamAcquired)),Mt(o)&&(this.cameraError=void 0,o.source=C.Source.Camera),o})))}catch(s){throw s instanceof Error&&(e.audio&&(this.microphoneError=s),e.video&&(this.cameraError=s)),s}})}get trackLoggerOptions(){return{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext}}requireVideoPublisher(){if(!this.slots.videoPublisher)throw new le("video publishing is not available in this build, add the video extension");return this.slots.videoPublisher}preparePublication(e,t){var i,r,s,a,o,c,d,l,u,h,f,m,p,y;let v=Gc(e);e.publishOptions&&(v.publishOptions=eu(e.publishOptions));let _=eu(Object.assign(Object.assign(Object.assign({},this.roomOptions.publishDefaults),v.publishOptions),{source:v.source}));if(v.source!==C.Source.Microphone&&v.source!==C.Source.Camera)throw new le("only microphone and camera publications can be prepared");if(v.source===C.Source.Microphone){if(v.format&&((i=v.publishOptions)===null||i===void 0?void 0:i.forceStereo)!==void 0&&v.publishOptions.forceStereo!==(v.format.channelCount===2))throw new le("audio format and forceStereo disagree");_.forceStereo=v.format?v.format.channelCount===2:(r=_.forceStereo)!==null&&r!==void 0?r:!1,_.forceStereo&&((s=_.dtx)!==null&&s!==void 0||(_.dtx=!1),(a=_.red)!==null&&a!==void 0||(_.red=!1))}let P=new dn,b=v.source===C.Source.Camera;if(b&&(![v.format.width,v.format.height].every(D=>Number.isFinite(D)&&D>0)||v.format.frameRate!==void 0&&(!Number.isFinite(v.format.frameRate)||v.format.frameRate<=0)))throw new le("video format must have positive finite dimensions and frame rate");let k=v.source===C.Source.Camera?(c=(o=this.slots.videoPublisher)===null||o===void 0?void 0:o.prepareInitial)===null||c===void 0?void 0:c.call(o,v.format,_,P):void 0,S=b?k?.encodings:[{maxBitrate:(d=_.audioPreset)===null||d===void 0?void 0:d.maxBitrate,priority:(u=(l=_.audioPreset)===null||l===void 0?void 0:l.priority)!==null&&u!==void 0?u:"high",networkPriority:(f=(h=_.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&f!==void 0?f:"high"}],E=b?(m=_.videoCodec)!==null&&m!==void 0?m:"vp8":"opus",q=!!(typeof RTCRtpSender<"u"&&((y=(p=RTCRtpSender.getCapabilities)===null||p===void 0?void 0:p.call(RTCRtpSender,b?"video":"audio"))===null||y===void 0?void 0:y.codecs.some(D=>D.mimeType.toLowerCase()==="".concat(b?"video":"audio","/").concat(E))))&&!!S&&!je()&&!this.slots.e2eeManager&&!this.slots.frameMetadataOptions&&!_.frameMetadata,x=new ga(v.source===C.Source.Camera?Object.assign(Object.assign({},v),{format:Object.assign({},v.format)}):Object.assign({},v),_,S??[],E,q,(D,B)=>this.publishOrRepublishTrack(D,_,!1,!1,B),t);return v.source===C.Source.Camera?(x.startBitrate=k?.startBitrate,x.request.width=P.width,x.request.height=P.height,x.request.layers=P.layers,x.request.simulcastCodecs=P.simulcastCodecs):(_.forceStereo&&x.request.audioFeatures.push(ge.TF_STEREO),_.dtx===!1&&x.request.audioFeatures.push(ge.TF_NO_DTX),_.preConnectBuffer&&x.request.audioFeatures.push(ge.TF_PRECONNECT_BUFFER)),x}toLocalTrack(e){let t;if(e instanceof MediaStreamTrack)t=e.getConstraints();else{t=e.constraints;let i;switch(e.source){case C.Source.Microphone:i="audioinput";break;case C.Source.Camera:i="videoinput"}i&&this.activeDeviceMap.has(i)&&(t=Object.assign(Object.assign({},t),{deviceId:this.activeDeviceMap.get(i)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new jn(e,t,!0,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});break;case"video":e=qr().createTrack(e,t,!0,this.trackLoggerOptions);break;default:throw new le("unsupported MediaStreamTrack kind ".concat(e.kind))}else e.updateLoggerOptions({loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return e}publishOptionsFor(e,t){var i,r,s;let a=Object.assign(Object.assign({},this.roomOptions.publishDefaults),t),o="channelCount"in e.mediaStreamTrack.getSettings()&&e.mediaStreamTrack.getSettings().channelCount===2||e.mediaStreamTrack.getConstraints().channelCount===2,c=(i=a.forceStereo)!==null&&i!==void 0?i:o;return c&&(a.dtx===void 0&&this.log.debug("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",K(e)),a.red===void 0&&this.log.debug("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(r=a.dtx)!==null&&r!==void 0||(a.dtx=!1),(s=a.red)!==null&&s!==void 0||(a.red=!1)),a.source&&(e.source=a.source),{opts:a,isStereo:c}}reserveTrack(e,t,i){var r;let s=e.getSourceTrackSettings(),a=e.kind===C.Kind.Audio,o=a?C.Source.Microphone:C.Source.Camera;if(e.source!==o)return;let c;if(a)c={source:C.Source.Microphone,publishOptions:Object.assign(Object.assign({},t),{forceStereo:i})};else{let h=s.width,f=s.height,m=s.frameRate;if(!h||!f)return;c={source:C.Source.Camera,format:Object.assign({width:h,height:f},m?{frameRate:m}:{}),publishOptions:t}}let d=(r=this.reservePublication)===null||r===void 0?void 0:r.call(this,c);if(!d)return;d.request.muted=e.isMuted;let l=this.limitRegistration(d,()=>e.stop()),u=d.attachTrack(e).catch(h=>{throw l(h)}).finally(()=>this.pendingReservations.delete(e));return this.pendingReservations.set(e,{prepared:d,publishing:u}),u}limitRegistration(e,t){let i=!1,r=setTimeout(()=>{i=!0,t?.(),e.cancel().catch(()=>{})},15e3);return e.registration.then(()=>clearTimeout(r),()=>clearTimeout(r)),s=>i?new pi("publishing rejected as engine not connected within timeout",408):s}publishTrack(e,t){return g(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}waitForNextEngineRestart(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:15e3;return new Promise((t,i)=>{let r=()=>{clearTimeout(o),this.engine.off(A.Restarted,s),this.engine.off(A.Closing,a)},s=()=>{r(),t()},a=()=>{r(),i(new Error("engine closed before restart completed"))},o=setTimeout(()=>{r(),i(new Error("timed out waiting for engine restart"))},e);this.engine.once(A.Restarted,s),this.engine.once(A.Closing,a)})}publishOrRepublishTrack(e,t){return g(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,o=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,c=arguments.length>4?arguments[4]:void 0;return(function*(){var d;if(!c&&!a&&s.engine.client.currentState!==Me.CONNECTED){i=s.toLocalTrack(i);let p=s.pendingReservations.get(i);if(p)return p.publishing;if(!(s.pendingPublishPromises.has(i)||[...s.trackPublications.values()].some(v=>v.track===i))){let v=s.publishOptionsFor(i,r),_=v.opts,P=v.isStereo,b=s.reserveTrack(i,_,P);if(b)return b}}ht(i)&&(yield i.setAudioContext(s.audioContext)),yield(d=s.reconnectFuture)===null||d===void 0?void 0:d.promise,s.republishPromise&&!a&&(yield s.republishPromise),Mn(i)&&s.pendingPublishPromises.has(i)&&(yield s.pendingPublishPromises.get(i)),i=s.toLocalTrack(i);let l;if(s.trackPublications.forEach(p=>{p.track&&p.track===i&&(l=p)}),l)return s.log.warn("track has already been published, skipping",K(l)),l;let u=s.publishOptionsFor(i,r),h=u.opts,f=u.isStereo,m=new Promise((p,y)=>g(s,void 0,void 0,function*(){try{if(this.engine.client.currentState!==Me.CONNECTED){this.log.debug("deferring track publication until signal is connected",{track:K(i)});let v=!1,_=setTimeout(()=>{v=!0,c||i.stop(),y(new pi("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(_),v)return;let P=yield this.publish(i,h,f,c);p(P)}else try{let v=yield this.publish(i,h,f,c);p(v)}catch(v){y(v)}}catch(v){y(v)}}));s.pendingPublishPromises.set(i,m);try{return yield m}catch(p){if(!c&&!o&&p instanceof yt)return s.log.warn("negotiation due to track publish failed, retrying after reconnect",{error:p}),s.pendingPublishPromises.delete(i),yield s.waitForNextEngineRestart(),yield s.publishOrRepublishTrack(i,r,a,!0);throw p}finally{s.pendingPublishPromises.delete(i)}})()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Ce),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",K(e)),!1;let t=this.permissions,i=t.canPublish,r=t.canPublishSources;return i&&(r.length===0||r.map(s=>sy(s)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",K(e)),!1)}publish(e,t,i,r){return g(this,void 0,void 0,function*(){let s=this.engine;try{return yield this.publishImpl(e,t,i,r)}catch(a){if(r&&!r.isCommitted){e.off(M.Muted,this.onTrackMuted),e.off(M.Unmuted,this.onTrackUnmuted),e.off(M.Ended,this.handleTrackEnded),e.off(M.UpstreamPaused,this.onTrackUpstreamPaused),e.off(M.UpstreamResumed,this.onTrackUpstreamResumed),e.off(M.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),s.cancelPendingTrack(e.mediaStreamTrack.id),s.cancelPendingTrack(r.request.cid);let o=e.sender;if(e.sender=void 0,o&&!s.isClosed)try{s.removeTrack(o),yield s.negotiate()}catch(c){this.log.warn("failed to reconcile cancelled publication",{error:c})}}throw a}})}publishImpl(e,t,i,r){return g(this,void 0,void 0,function*(){var s,a,o,c,d,l,u,h;let f=this.engine,m=r?yield r.senderFor(e,f):void 0;if(!this.hasPermissionsToPublish(e))throw new pi("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(x=>Mn(e)&&x.source===e.source)&&e.source!==C.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),K(e)),t.stopMicTrackOnMute&&bt(e)&&(e.stopOnMute=!0),e.on(M.Muted,this.onTrackMuted),e.on(M.Unmuted,this.onTrackUnmuted),e.on(M.Ended,this.handleTrackEnded),e.on(M.UpstreamPaused,this.onTrackUpstreamPaused),e.on(M.UpstreamResumed,this.onTrackUpstreamResumed),e.on(M.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);let y=[],v=!(!((s=t.dtx)!==null&&s!==void 0)||s),_=e.getSourceTrackSettings();_.autoGainControl&&y.push(ge.TF_AUTO_GAIN_CONTROL),_.echoCancellation&&y.push(ge.TF_ECHO_CANCELLATION),_.noiseSuppression&&y.push(ge.TF_NOISE_SUPPRESSION),_.channelCount&&_.channelCount>1&&y.push(ge.TF_STEREO),v&&y.push(ge.TF_NO_DTX),ht(e)&&e.hasPreConnectBuffer&&y.push(ge.TF_PRECONNECT_BUFFER);let P=this.normalizeRequestedFrameMetadataOptions(e,t),b=m?r.request:new dn({cid:e.mediaStreamTrack.id,name:t.name,type:C.kindToProto(e.kind),muted:e.isMuted,source:C.sourceToProto(e.source),disableDtx:v,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(!((a=t.red)!==null&&a!==void 0)||a),stream:t?.stream,backupCodecPolicy:t?.backupCodecPolicy,audioFeatures:y,packetTrailerFeatures:P}),k;if(m?k=r.encodings:We(e)?k=yield this.requireVideoPublisher().prepare(e,t,b):e.kind===C.Kind.Audio&&(k=[{maxBitrate:(o=t.audioPreset)===null||o===void 0?void 0:o.maxBitrate,priority:(d=(c=t.audioPreset)===null||c===void 0?void 0:c.priority)!==null&&d!==void 0?d:"high",networkPriority:(u=(l=t.audioPreset)===null||l===void 0?void 0:l.priority)!==null&&u!==void 0?u:"high"}]),!f||f.isClosed)throw new J("cannot publish track when not connected");let S=()=>g(this,void 0,void 0,function*(){var x,D;if(!f.pcManager)throw new J("pcManager is not ready");if(m){r.assertActive();let B=yield m.accepted,H=B.sid;if(e.isMuted!==r.request.muted&&f.updateMuteStatus(H,e.isMuted),yield m.transceiver.sender.replaceTrack(e.mediaStreamTrack),r.assertActive(),f!==m.engine||f.isClosed||((x=f.pcManager)===null||x===void 0?void 0:x.publisher)!==m.transport)throw new J("connection changed while attaching prepared media");e.sender=m.transceiver.sender,We(e)&&(e.codec=r.codec)}else e.sender=yield f.createSender(e,t,k);if(We(e)&&(e.publishOptions=t),this.emit(L.LocalSenderCreated,e.sender,e),We(e)&&this.requireVideoPublisher().senderCreated(e,t,k,b),k&&fn()&&e.kind===C.Kind.Audio){let B;for(let H of f.pcManager.publisher.getTransceivers())if(H.sender===e.sender){B=H;break}B&&f.pcManager.publisher.setTrackCodecBitrate({transceiver:B,codec:"opus",maxbr:!((D=k[0])===null||D===void 0)&&D.maxBitrate?k[0].maxBitrate/1e3:0})}m||(yield f.negotiate())}),E,O=new Promise((x,D)=>g(this,void 0,void 0,function*(){var B;try{E=yield m?m.accepted:f.addTrack(b),x(E)}catch(H){if(e.sender&&(!((B=f.pcManager)===null||B===void 0)&&B.publisher)){try{f.removeTrack(e.sender)}catch($){this.log.error($)}e.sender=void 0,yield f.negotiate().catch($=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign({},K(e)),{error:$}))})}D(H)}}));if(m||this.enabledPublishVideoCodecs.length>0&&P.length===0)if(r){let x=xe=>xe.then(V=>({ok:!0,value:V}),V=>({ok:!1,error:V})),D=yield Promise.all([x(O),x(S())]),B=F(D,2),H=B[0],$=B[1];if(!H.ok)throw H.error;if(!$.ok)throw $.error;E=H.value}else E=(yield Promise.all([O,S()]))[0];else E=yield O,We(e)&&(k=(h=this.requireVideoPublisher().serverCodecChanged(e,t,E,b))!==null&&h!==void 0?h:k),yield S();if(r?.assertActive(),r&&(this.engine!==f||f.isClosed))throw new J("connection changed while publishing prepared media");let q=new xi(e.kind,E,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(q.on(M.CpuConstrained,x=>this.onTrackCpuConstrained(x,q)),q.options=t,e.sid=E.sid,m&&e.kind===C.Kind.Audio&&f.client.sendUpdateLocalAudioTrack(E.sid,y),We(e)&&(e.publishOptions=t,b.width&&b.height&&(e.lastEncodedDimensions={width:b.width,height:b.height})),this.log.debug("publishing ".concat(e.kind," with encodings"),{encodings:k,trackInfo:E}),We(e)?e.startMonitor(f.client):ht(e)&&e.startMonitor(),r?.commit(),this.addTrackPublication(q),ht(e)&&E.audioFeatures.includes(ge.TF_PRECONNECT_BUFFER)){let x=e.getPreConnectBuffer(),D=e.getPreConnectBufferMimeType(),B=()=>{this.off(L.LocalTrackSubscribed,H),this.off(L.LocalTrackUnpublished,$),e.stopPreConnectBuffer()},H=xe=>{xe.trackSid===E.sid&&B()},$=xe=>{xe.trackSid===E.sid&&B()};this.on(L.LocalTrackSubscribed,H),this.on(L.LocalTrackUnpublished,$),x&&new Promise((V,se)=>g(this,void 0,void 0,function*(){var Q,De,Qn,Yn,xt,zi;try{this.log.debug("waiting for agent",K(e));let js=setTimeout(()=>{se(new Error("agent not active within 10 seconds"))},1e4),hm=yield this.waitUntilActiveAgentPresent();if(clearTimeout(js),this.log.debug("sending preconnect buffer",K(e)),!this.slots.byteStreamOpener)throw new Error("the dataStreams extension is required to send the preconnect buffer");let Ud=yield this.slots.byteStreamOpener({name:"preconnect-buffer",mimeType:D,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[hm.identity],attributes:{trackId:q.trackSid,sampleRate:String((xt=_.sampleRate)!==null&&xt!==void 0?xt:"48000"),channels:String((zi=_.channelCount)!==null&&zi!==void 0?zi:"1")}});try{for(var Xn=!0,Bs=ze(x),qs;qs=yield Bs.next(),Q=qs.done,!Q;Xn=!0){Yn=qs.value,Xn=!1;let Vs=Yn;yield Ud.write(Vs)}}catch(Vs){De={error:Vs}}finally{try{!Xn&&!Q&&(Qn=Bs.return)&&(yield Qn.call(Bs))}finally{if(De)throw De.error}}yield Ud.close(),V()}catch(js){se(js)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",K(e))}).catch(V=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign({},K(e)),{error:V}))})}return this.emit(L.LocalTrackPublished,q),q})}canPublishFrameMetadata(){return!!this.engine.e2eeManager||Mi(this.engine.frameMetadataOptions)}normalizeRequestedFrameMetadataOptions(e,t){let i=Zc(t);if(e.kind!==C.Kind.Video||!Ar(i))return go(t,void 0),[];if(!this.canPublishFrameMetadata())return this.log.warn("frame metadata transform not supported; not advertising features",Object.assign(Object.assign({},this.logContext),K(e))),go(t,void 0),[];let r=e0(i),s=t0(r);return go(t,s),r}get isLocal(){return!0}unpublishTrack(e,t){return g(this,void 0,void 0,function*(){var i,r;if(Mn(e)){let l=this.pendingReservations.get(e);l&&(yield l.prepared.cancel(),yield l.publishing.catch(()=>{}));let u=this.pendingPublishPromises.get(e);u&&(this.log.debug("awaiting publish promise before attempting to unpublish",K(e)),yield u)}let s=this.getPublicationForTrack(e),a=s?K(s):void 0;if(this.log.info("unpublishing track",a),!s||!s.track){this.log.warn("track was not unpublished because no publication was found",a);return}e=s.track,e.off(M.Muted,this.onTrackMuted),e.off(M.Unmuted,this.onTrackUnmuted),e.off(M.Ended,this.handleTrackEnded),e.off(M.UpstreamPaused,this.onTrackUpstreamPaused),e.off(M.UpstreamResumed,this.onTrackUpstreamResumed),e.off(M.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(r=(i=this.roomOptions)===null||i===void 0?void 0:i.stopLocalTrackOnUnpublish)!==null&&r!==void 0?r:!0),t?e.stop():e.stopMonitor();let o=!1,c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<oe.FAILED&&c)try{for(let l of this.engine.pcManager.publisher.getTransceivers())l.sender===c&&(l.direction="inactive",o=!0);try{o=this.engine.removeTrack(c)}catch(l){this.log.warn(l),o=!0}if(We(e)){for(let l of e.simulcastCodecs){var d=F(l,2);let u=d[1];if(u.sender){try{o=this.engine.removeTrack(u.sender)}catch(h){this.log.warn(h),o=!0}u.sender=void 0}}e.simulcastCodecs.clear()}}catch(l){this.log.warn("failed to unpublish track",Object.assign(Object.assign({},a),{error:l}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case C.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case C.Kind.Video:this.videoTrackPublications.delete(s.trackSid);break}return this.emit(L.LocalTrackUnpublished,s),s.setTrack(void 0),o&&(yield this.engine.negotiate()),s})}unpublishTracks(e){return g(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return g(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){i.republishPromise&&(yield i.republishPromise),i.republishPromise=new Pe((s,a)=>g(i,void 0,void 0,function*(){try{let o=[];this.trackPublications.forEach(c=>{c.track&&(t&&(c.options=Object.assign(Object.assign({},c.options),t)),o.push(c))}),yield Promise.all(o.map(c=>g(this,void 0,void 0,function*(){let d=c.track;yield this.unpublishTrack(d,!1),r&&!d.isMuted&&d.source!==C.Source.ScreenShare&&d.source!==C.Source.ScreenShareAudio&&(ht(d)||We(d))&&!d.isUserProvided&&(this.log.debug("restarting existing track",{track:c.trackSid}),yield d.restartTrack()),yield this.publishOrRepublishTrack(d,c.options,!0)}))),s()}catch(o){o instanceof Error?a(o):a(new Error(String(o)))}finally{this.republishPromise=void 0}})),yield i.republishPromise})()})}publishData(e){return g(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return(function*(){let s=r.reliable?z.RELIABLE:z.LOSSY,a=r.reliable?qt.RELIABLE:qt.LOSSY,o=r.destinationIdentities,c=r.topic,d=new Oc({participantIdentity:i.identity,payload:t,destinationIdentities:o,topic:c}),l=new Fe({kind:a,value:{case:"user",value:d}});yield i.engine.sendDataPacket(l,s)})()})}publishDtmf(e,t){return g(this,void 0,void 0,function*(){let i=new Fe({kind:qt.RELIABLE,value:{case:"sipDtmf",value:new Jh({code:e,digit:t})}});yield this.engine.sendDataPacket(i,z.RELIABLE)})}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(t=>{var i,r;let s=this.trackPublications.get(t.sid);if(s){let a=s.isMuted||((r=(i=s.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&r!==void 0?r:!1);a!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign({},K(s)),{mutedOnServer:a})),this.engine.client.sendMuteTrack(t.sid,a))}}),!0):!1}setActiveAgent(e){var t,i,r,s;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(i=(t=this.activeAgentFuture)===null||t===void 0?void 0:t.resolve)===null||i===void 0||i.call(t,e):(s=(r=this.activeAgentFuture)===null||r===void 0?void 0:r.reject)===null||s===void 0||s.call(r,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Ce),this.activeAgentFuture.promise)}restartOnDefaultAudioDevice(e){return g(this,void 0,void 0,function*(){var t,i;try{Cs()?yield e.setDeviceId({exact:"default"}):yield e.restartTrack()}catch(r){if(!Oy(r)||Ay(r)||e.isStopped)throw r;this.log.debug("could not reacquire the audio device, retrying with an enumerated device",K(e));let s=yield Ne.getInstance().getDevices("audioinput",!1);yield e.setDeviceId((i=(t=s?.[0])===null||t===void 0?void 0:t.deviceId)!==null&&i!==void 0?i:"default")}})}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{let r=i.track;r&&(e instanceof MediaStreamTrack?(ht(r)||We(r))&&r.mediaStreamTrack===e&&(t=i):e===r&&(t=i))}),t}waitForPendingPublicationOfSource(e){return g(this,void 0,void 0,function*(){let i=Date.now();for(;Date.now()<i+1e4;){let r=Array.from(this.pendingPublishPromises.entries()).find(s=>F(s,1)[0].source===e);if(r)return r[1];yield Re(20)}})}},Wr=class extends DOMException{constructor(e,t){super(e,"AbortError"),this.reason=t}},Ma=class extends Map{constructor(){super(...arguments),this.pending=new Map}set(e,t){var i,r;super.set(e,t);let s=(i=this.pending)===null||i===void 0?void 0:i.get(e);if(s){for(let a of s)a.isResolved||(r=a.resolve)===null||r===void 0||r.call(a,t);this.pending.delete(e)}return this}get[Symbol.toStringTag](){return"DeferrableMap"}getDeferred(e,t){return g(this,void 0,void 0,function*(){let i=this.get(e);if(typeof i<"u")return i;if(t?.aborted)throw new Wr("The operation was aborted.",t.reason);let r=new Ce(void 0,()=>{let a=this.pending.get(e);if(!a)return;let o=a.indexOf(r);o!==-1&&a.splice(o,1),a.length===0&&this.pending.delete(e)}),s=this.pending.get(e);if(s?s.push(r):this.pending.set(e,[r]),t){let a=()=>{var c;r.isResolved||(c=r.reject)===null||c===void 0||c.call(r,new Wr("The operation was aborted.",t.reason))};t.addEventListener("abort",a,{once:!0});let o=()=>{t.removeEventListener("abort",a)};r.promise.then(o,o)}return r.promise})}},Oa=class extends st{constructor(e,t,i,r){super(e,t.sid,t.name,r),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=s=>{this.setTrack(void 0),this.emit(M.Ended,s)},this.handleVisibilityChange=s=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(s),this.logContext),this.visible=s,this.emitTrackUpdate()},this.handleVideoDimensionsChange=s=>{this.log.debug("adaptivestream video dimensions ".concat(s.width,"x").concat(s.height),this.logContext),this.videoDimensionsAdaptiveStream=s,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){let t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);let r=new Ts({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Xh({participantSid:"",trackSids:[this.trackSid]})]});this.emit(M.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?st.SubscriptionStatus.Unsubscribed:super.isSubscribed?st.SubscriptionStatus.Subscribed:st.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?st.PermissionStatus.Allowed:st.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled!==void 0?!this.requestedDisabled:this.isAdaptiveStream?this.visible:!0}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.requestedDisabled===!e||(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.requestedMaxQuality===e||(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&(((t=this.requestedVideoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((i=this.requestedVideoDimensions)===null||i===void 0?void 0:i.height)===e.height||(po(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&po(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:Ge.HIGH}setTrack(e){let t=this.subscriptionStatus,i=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(M.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(M.VisibilityChanged,this.handleVisibilityChange),r.off(M.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(M.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(M.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(M.VisibilityChanged,this.handleVisibilityChange),e.on(M.Ended,this.handleEnded),this.emit(M.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){let t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(M.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);let t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?M.Muted:M.Unmuted)}emitSubscriptionUpdateIfChanged(e){let t=this.subscriptionStatus;e!==t&&this.emit(M.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(M.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return po(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){let e=new cf({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===C.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)jl(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){let i=oy(this.trackInfo,this.requestedMaxQuality);i&&jl(this.videoDimensionsAdaptiveStream,i)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream;t?(e.width=Math.ceil(t.width),e.height=Math.ceil(t.height)):this.requestedMaxQuality!==void 0?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:Ge.HIGH})),e.quality=Ge.HIGH)}this.emit(M.UpdateSettings,e)}},Eo=100,Li=class extends Br{constructor(e,t,i,r,s){super(e,t,C.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>g(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=ws(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=nd(()=>{this.updateDimensions()},Eo),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}lookupFrameMetadata(e){let t=e.rtpTimestamp;var i;return(i=this.frameMetadataExtractor)===null||i===void 0?void 0:i.lookupMetadata(t)}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===C.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?Pn(this._mediaStreamTrack,t):_n(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){let t=new xa(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}let t=this.elementInfos.filter(i=>i===e);for(let i of t)i.stopObserving();this.elementInfos=this.elementInfos.filter(i=>i!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){if(e)return this.stopObservingElement(e),super.detach(e);let t=super.detach();for(let i of t)this.stopObservingElement(i);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return g(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;let e=yield this.receiver.getStats(),t,i="",r=new Map;return e.forEach(s=>{s.type==="inbound-rtp"?(i=s.codecId,t={type:"video",streamId:s.id,framesDecoded:s.framesDecoded,framesDropped:s.framesDropped,framesReceived:s.framesReceived,packetsReceived:s.packetsReceived,packetsLost:s.packetsLost,frameWidth:s.frameWidth,frameHeight:s.frameHeight,pliCount:s.pliCount,firCount:s.firCount,nackCount:s.nackCount,jitter:s.jitter,timestamp:s.timestamp,bytesReceived:s.bytesReceived,decoderImplementation:s.decoderImplementation}):s.type==="codec"&&r.set(s.id,s)}),t&&i!==""&&r.get(i)&&(t.mimeType=r.get(i).mimeType),t})}stopObservingElement(e){let t=this.elementInfos.filter(i=>i.element===e);for(let i of t)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return g(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,i;let r=this.elementInfos.reduce((c,d)=>Math.max(c,d.visibilityChangedAt||0),0),s=!((i=(t=this.adaptiveStreamSettings)===null||t===void 0?void 0:t.pauseVideoInBackground)!==null&&i!==void 0)||i?this.isInBackground:!1,a=this.elementInfos.some(c=>c.pictureInPicture),o=this.elementInfos.some(c=>c.visible)&&!s||a;if(!(this.lastVisible===o&&!e)){if(!o&&Date.now()-r<Eo){Y.setTimeout(()=>{this.updateVisibility()},Eo);return}this.lastVisible=o,this.emit(M.VisibilityChanged,o,this)}}updateDimensions(){var e,t;let i=0,r=0,s=this.getPixelDensity();for(let a of this.elementInfos){let o=a.width()*s,c=a.height()*s;o+c>i+r&&(i=o,r=c)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===i&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===r||(this.lastDimensions={width:i,height:r},this.emit(M.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;let t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?Vl():t||(Vl()>2?2:1)}},xa=class{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=i=>{var r;let s=i.target,a=i.isIntersecting;s===this.element&&(this.isIntersecting=a,this.isPiP=ci(this.element),this.visibilityChangedAt=Date.now(),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this))},this.onEnterPiP=()=>{var i,r;(r=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||r===void 0||r.addEventListener("pagehide",this.onLeavePiP),queueMicrotask(()=>{requestAnimationFrame(()=>{var s;this.isPiP=ci(this.element),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this)})})},this.onLeavePiP=()=>{var i;this.isPiP=ci(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=t??La(e),this.isPiP=Le()&&ci(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=La(this.element),this.isPiP=ci(this.element),this.element.handleResize=()=>{var r;(r=this.handleResize)===null||r===void 0||r.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Hl().observe(this.element),Wl().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(i=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,r,s;(e=Hl())===null||e===void 0||e.unobserve(this.element),(t=Wl())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(i=window.documentPictureInPicture)===null||i===void 0||i.removeEventListener("enter",this.onEnterPiP),(s=(r=window.documentPictureInPicture)===null||r===void 0?void 0:r.window)===null||s===void 0||s.removeEventListener("pagehide",this.onLeavePiP)}};function ci(n){var e;if(document.pictureInPictureElement===n)return!0;let t=(e=window.documentPictureInPicture)===null||e===void 0?void 0:e.window;return t?mb(n.ownerDocument,t)&&La(n,t):!1}function mb(n,e){var t,i,r;if(((t=n.defaultView)===null||t===void 0?void 0:t.top)===e)return!0;let s=n;for(;s;){if(s===e.document)return!0;try{s=(r=(i=s.defaultView)===null||i===void 0?void 0:i.frameElement)===null||r===void 0?void 0:r.ownerDocument}catch{return!1}}return!1}function La(n,e){let t=e||window,i=n.offsetTop,r=n.offsetLeft,s=n.offsetWidth,a=n.offsetHeight,o=n,c=o.hidden,d=getComputedStyle(n),l=d.display;for(;n.offsetParent;)n=n.offsetParent,i+=n.offsetTop,r+=n.offsetLeft;return i<t.pageYOffset+t.innerHeight&&r<t.pageXOffset+t.innerWidth&&i+a>t.pageYOffset&&r+s>t.pageXOffset&&!c&&l!=="none"}var Hr=class n extends jr{static fromParticipantInfo(e,t,i){return new n(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind,[],t.clientProtocol,t.capabilities)}get logContext(){return Object.assign(Object.assign({},super.logContext),{remoteParticipantID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,r,s,a,o){let c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Ei.STANDARD,d=arguments.length>8&&arguments[8]!==void 0?arguments[8]:[],l=arguments.length>9&&arguments[9]!==void 0?arguments[9]:zc,u=arguments.length>10&&arguments[10]!==void 0?arguments[10]:[];super(t,i||"",r,s,a,o,c),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.dataTracks=new Ma(d.map(h=>[h.info.name,h])),this.volumeMap=new Map,this.clientProtocol=l,this.capabilities=u}addTrackPublication(e){super.addTrackPublication(e),e.on(M.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),K(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(M.UpdateSubscription,t=>{t.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(M.SubscriptionPermissionChanged,t=>{this.emit(L.TrackSubscriptionPermissionChanged,e,t)}),e.on(M.SubscriptionStatusChanged,t=>{this.emit(L.TrackSubscriptionStatusChanged,e,t)}),e.on(M.Subscribed,t=>{this.emit(L.TrackSubscribed,t,e)}),e.on(M.Unsubscribed,t=>{this.emit(L.TrackUnsubscribed,t,e)}),e.on(M.SubscriptionFailed,t=>{this.emit(L.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:C.Source.Microphone;this.volumeMap.set(t,e);let i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:C.Source.Microphone,t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,r,s,a){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(l=>{!o&&e.kind===l.kind.toString()&&(o=l)}),!o){if(a===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(L.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,r,s,a-1)},150);return}if(e.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),K(o))),this.emit(L.TrackSubscriptionFailed,t);return}let c=e.kind==="video",d;return c?d=new Li(e,t,r,s):d=new Ia(e,t,r,this.audioContext,this.audioOutput),d.source=o.source,d.isMuted=o.isMuted,d.setMediaStream(i),d.start(),o.setTrack(d),this.volumeMap.has(o.source)&&ma(d)&&bt(d)&&d.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;let t=new Map,i=new Map;return e.tracks.forEach(r=>{var s,a;let o=this.getTrackPublicationBySid(r.sid);if(o)o.updateInfo(r);else{let c=C.kindFromProto(r.type);if(!c)return;o=new Oa(c,r,(s=this.signalClient.connectOptions)===null||s===void 0?void 0:s.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(a=this.loggerOptions)===null||a===void 0?void 0:a.loggerName}),o.updateInfo(r),i.set(r.sid,o);let d=Array.from(this.trackPublications.values()).find(l=>l.source===o?.source);d&&o.source!==C.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(o.source),Object.assign(Object.assign({},this.logContext),{oldTrack:K(d),newTrack:K(o)})),this.addTrackPublication(o)}t.set(r.sid,o)}),this.trackPublications.forEach(r=>{t.has(r.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),K(r))),this.unpublishTrack(r.trackSid,!0))}),i.forEach(r=>{this.emit(L.TrackPublished,r)}),!0}unpublishTrack(e,t){let i=this.trackPublications.get(e);if(!i)return;let r=i.track;switch(r&&(r.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case C.Kind.Audio:this.audioTrackPublications.delete(e);break;case C.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(L.TrackUnpublished,i)}setAudioOutput(e){return g(this,void 0,void 0,function*(){this.audioOutput=e;let t=[];this.audioTrackPublications.forEach(i=>{var r;bt(i.track)&&ma(i.track)&&t.push(i.track.setSinkId((r=e.deviceId)!==null&&r!==void 0?r:"default"))}),yield Promise.all(t)})}addRemoteDataTrack(e){this.dataTracks.set(e.info.name,e)}removeRemoteDataTrack(e){for(let i of this.dataTracks.entries()){var t=F(i,2);let r=t[0],s=t[1];e===s.info.sid&&this.dataTracks.delete(r)}}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}},G;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(G||(G={}));var gb=4*1e3,vb=30*1e3,yb="livekit-dummy-audio-el",ar;function bb(){let n=document.createElement("audio");n.id=yb,n.autoplay=!0,n.hidden=!0;let e=If();e.enabled=!0;let t=new MediaStream([e]);return n.srcObject=t,document.body.append(n),{element:n,stream:t,track:e,refCount:0}}var Di=class n extends Oe.EventEmitter{get hasE2EESetup(){return this.slots.e2eeManager!==void 0}constructor(e){var t,i,r,s,a;if(super(),t=this,this.state=G.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.ownsAudioContext=!1,this.audioContextReleased=!1,this.audioContextMutex=new ye,this.acquiredEmptyAudioTracks=new Set,this.isVideoPlaybackBlocked=!1,this.log=W,this.statsLog=W,this.bufferedEvents=[],this.isResuming=!1,this.pendingTrackAddedCallbacks=new Map,this.installedExtensions=new Map,this.slots={},this.extensionDisposers=[],this.dataPacketHandlers=new Map,this.disposed=!1,this.preparedPublications=new Set,this.pendingInitialTrackSubscriptions=new Map,this.reservePublication=o=>{var c;if(this.disposed)return;let d;try{d=this.prepareSessionPublication(o)}catch(l){this.log.debug("publication cannot be prepared",Object.assign(Object.assign({},this.logContext),{error:l}));return}return(c=this.engine)===null||c===void 0||c.reservePublications(),d},this.connect=(o,c,d)=>g(this,void 0,void 0,function*(){var l;if(this.disposed)throw new J("room has been disposed");if(!vy())throw je()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");let u=yield this.disconnectLock.lock();if(this.disposed)throw u(),new J("room has been disposed");if(this.state===G.Connected)return this.log.info("already connected to room ".concat(this.name)),u(),Promise.resolve();if(this.connectFuture)return u(),this.connectFuture.promise;this.setAndEmitConnectionState(G.Connecting),((l=this.regionUrlProvider)===null||l===void 0?void 0:l.getServerUrl().toString())!==xf(o)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),qn(new URL(o))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new ct(o,c):this.regionUrlProvider.updateToken(c),this.regionUrlProvider.fetchRegionSettings().then(m=>{var p;(p=this.regionUrlProvider)===null||p===void 0||p.setServerReportedRegions(m)}).catch(m=>{this.log.warn("could not fetch region settings",{error:m})}));let h=(m,p,y)=>g(this,void 0,void 0,function*(){this.abortController&&this.abortController.abort();let v=new AbortController;this.abortController=v,u?.();let _=(P,b)=>{this.abortController===v&&this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,b),p(P)};try{if(yield xn.getInstance().getBackOffPromise(o),v.signal.aborted)throw U.cancelled("Connection attempt aborted");yield this.attemptConnection(y??o,c,d,v),this.abortController=void 0,m()}catch(P){if(this.regionUrlProvider&&P instanceof U&&Yv(P)){let b=null;try{this.log.debug("Fetching next region"),b=yield this.regionUrlProvider.getNextBestRegionUrl(v.signal)}catch(k){if(k instanceof U&&(k.status===401||k.reason===Z.Cancelled)){_(k);return}}[Z.InternalError,Z.ServerUnreachable,Z.Timeout].includes(P.reason)&&(this.log.debug("Adding failed connection attempt to back off"),xn.getInstance().addFailedConnectionAttempt(o)),b&&!v.signal.aborted?(this.log.info("Initial connection failed with ConnectionError: ".concat(P.message,". Retrying with another region: ").concat(b)),this.recreateEngine(!0),yield h(m,p,b)):_(P,Gl(P))}else{let b=Ke.UNKNOWN_REASON;P instanceof U&&(b=Gl(P)),_(P,b)}}}),f=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Ce((m,p)=>{h(m,p,f)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(o,c,d,l,u,h)=>g(this,void 0,void 0,function*(){let f=yield d.join(o,c,{autoSubscribe:l.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,disableIceLite:l.disableIceLite,subscriberAllowPause:l.subscriberAllowPause,clientInfoCapabilities:this.getClientInfoCapabilities(),maxRetries:l.maxRetries,e2eeEnabled:!!this.slots.e2eeManager,websocketTimeout:l.websocketTimeout},h.signal,!u.singlePeerConnection),m=f.joinResponse,p=f.serverInfo;if(this.serverInfo=p,!p.version)throw new ia("unknown server version");return p.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version"),u.dynacast=!1),m}),this.applyJoinResponse=o=>{let c=o.participant;if(this.localParticipant.sid=c.sid,this.localParticipant.identity=c.identity,this.localParticipant.setEnabledPublishCodecs(o.enabledPublishCodecs),this.slots.e2eeManager)try{this.slots.e2eeManager.setSifTrailer(o.sifTrailer)}catch(d){this.log.error(d instanceof Error?d.message:"Could not set SifTrailer",{error:d})}this.handleParticipantUpdates([c,...o.otherParticipants]),o.room&&this.handleRoomUpdate(o.room)},this.attemptConnection=(o,c,d,l)=>g(this,void 0,void 0,function*(){var u,h;this.state===G.Reconnecting||this.isResuming||!((u=this.engine)===null||u===void 0)&&u.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt"),this.recreateEngine(!0)):this.maybeCreateEngine();let f=this.engine;!((h=this.regionUrlProvider)===null||h===void 0)&&h.isCloud()&&f.setRegionStrategy(this.createRegionStrategy()),this.acquireAudioContext(!0).catch(m=>this.log.warn("Could not acquire audio context",Object.assign(Object.assign({},this.logContext),{error:m}))),this.connOptions=Object.assign(Object.assign({},rd),d),this.connOptions.rtcConfig&&(f.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(f.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{let m=yield this.connectSignal(o,c,f,this.connOptions,this.options,l);this.applyJoinResponse(m),this.setupLocalParticipantEvents(),this.emit(R.SignalConnected)}catch(m){yield f.close(),this.recreateEngine(!1,f);let p=l.signal.aborted?U.cancelled("Signal connection aborted"):U.serverUnreachable("could not establish signal connection");throw m instanceof Error&&(p.message="".concat(p.message,": ").concat(m.message)),m instanceof U&&(p.reason=m.reason,p.status=m.status),this.log.debug("error trying to establish signal connection",{error:m}),p}if(l.signal.aborted)throw yield f.close(),this.recreateEngine(!1,f),U.cancelled("Connection attempt aborted");try{yield f.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,l)}catch(m){throw yield f.close(),this.recreateEngine(!1,f),m}Le()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Le()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(G.Connected),this.emit(R.Connected),xn.getInstance().resetFailedConnectionAttempts(o),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var o=arguments.length,c=new Array(o),d=0;d<o;d++)c[d]=arguments[d];return g(t,[...c],void 0,function(){var l=this;let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var h,f,m;let p=yield l.disconnectLock.lock();try{if(l.state===G.Disconnected){for(let y of l.preparedPublications)y.disconnected();l.log.debug("already disconnected");return}if(l.log.info("disconnect from room"),l.state===G.Connecting||l.state===G.Reconnecting||l.isResuming){let y="Abort connection attempt due to user initiated disconnect";l.log.warn(y),(h=l.abortController)===null||h===void 0||h.abort(y),(m=(f=l.connectFuture)===null||f===void 0?void 0:f.reject)===null||m===void 0||m.call(f,U.cancelled("Client initiated disconnect")),l.connectFuture=void 0}l.engine&&(l.engine.client.isDisconnected||(yield l.engine.client.sendLeave()),yield l.engine.close()),l.handleDisconnect(u,Ke.CLIENT_INITIATED),l.engine=void 0}finally{p()}})()})},this.onPageLeave=()=>g(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting"),yield this.disconnect()}),this.startAudio=()=>g(this,void 0,void 0,function*(){let o=[],c=Ue();c&&c.os==="iOS"&&!this.audioContextReleased&&o.push(this.acquireDummyAudioElement()),this.remoteParticipants.forEach(d=>{d.audioTrackPublications.forEach(l=>{l.track&&l.track.attachedElements.forEach(u=>{o.push(u)})})});try{yield Promise.all([...this.audioContextReleased?[]:[this.acquireAudioContext()],...o.map(d=>(this.options.webAudioMix||(d.muted=!1),d.play()))]),this.handleAudioPlaybackStarted()}catch(d){throw this.handleAudioPlaybackFailed(d),d}}),this.startVideo=()=>g(this,void 0,void 0,function*(){let o=[];for(let c of this.remoteParticipants.values())c.videoTrackPublications.forEach(d=>{var l;(l=d.track)===null||l===void 0||l.attachedElements.forEach(u=>{o.includes(u)||o.push(u)})});yield Promise.all(o.map(c=>c.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(c=>{c.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler")})}),this.handleRestarting=()=>{var o;this.clearConnectionReconcile(),this.isResuming=!1,(o=this.roomInfoBeforeRestart)!==null&&o!==void 0||(this.roomInfoBeforeRestart=this.roomInfo),this.roomInfo=this.roomInfoBeforeRestart,this.bufferedEvents=[];for(let c of this.remoteParticipants.values())this.handleParticipantDisconnected(c.identity,c);!this.connectFuture&&this.setAndEmitConnectionState(G.Reconnecting)&&this.emit(R.Reconnecting)},this.handleSignalRestarted=(o,c)=>g(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(o.serverRegion),{region:o.serverRegion}),this.bufferedEvents=[];let d=this.connectFuture!==void 0,l=this.engine.waitForRestarted(c);this.applyJoinResponse(o);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(u){this.log.error("error trying to re-publish tracks after reconnection",{error:u})}if(!(!(yield l)||c.aborted)){if(this.log.debug("fully reconnected to server",{region:o.serverRegion}),this.roomInfoBeforeRestart=void 0,d){this.bufferedEvents=[];return}this.setAndEmitConnectionState(G.Connected),this.emit(R.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}}),this.handleParticipantUpdates=o=>{var c;let d=[];for(let l of o){if(l.identity===this.localParticipant.identity){this.localParticipant.updateInfo(l),d.push(l);continue}l.identity===""&&(l.identity=(c=this.sidToIdentity.get(l.sid))!==null&&c!==void 0?c:"");let u=this.remoteParticipants.get(l.identity);if(u?.isOlderSession(l)){this.log.debug("ignoring update from an older participant session",{remoteIdentity:l.identity,staleSid:l.sid,currentSid:u.sid});continue}l.state===wn.DISCONNECTED?this.handleParticipantDisconnected(l.identity,u,l.disconnectReason===Ke.UNKNOWN_REASON?void 0:l.disconnectReason):this.getOrCreateParticipant(l.identity,l),d.push(l)}this.extensionResults.forEach(l=>{var u;return(u=l.onParticipantUpdates)===null||u===void 0?void 0:u.call(l,d)})},this.handleActiveSpeakersUpdate=o=>{let c=[],d={};o.forEach(l=>{if(d[l.sid]=!0,l.sid===this.localParticipant.sid)this.localParticipant.audioLevel=l.level,this.localParticipant.setIsSpeaking(!0),c.push(this.localParticipant);else{let u=this.getRemoteParticipantBySid(l.sid);u&&(u.audioLevel=l.level,u.setIsSpeaking(!0),c.push(u))}}),d[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(l=>{d[l.sid]||(l.audioLevel=0,l.setIsSpeaking(!1))}),this.activeSpeakers=c,this.emitWhenConnected(R.ActiveSpeakersChanged,c)},this.handleSpeakersChanged=o=>{let c=new Map;this.activeSpeakers.forEach(l=>{let u=this.remoteParticipants.get(l.identity);u&&u.sid!==l.sid||c.set(l.sid,l)}),o.forEach(l=>{let u=this.getRemoteParticipantBySid(l.sid);l.sid===this.localParticipant.sid&&(u=this.localParticipant),u&&(u.audioLevel=l.level,u.setIsSpeaking(l.active),l.active?c.set(l.sid,u):c.delete(l.sid))});let d=Array.from(c.values());d.sort((l,u)=>u.audioLevel-l.audioLevel),this.activeSpeakers=d,this.emitWhenConnected(R.ActiveSpeakersChanged,d)},this.handleStreamStateUpdate=o=>{o.streamStates.forEach(c=>{let d=this.getRemoteParticipantBySid(c.participantSid);if(!d)return;let l=d.getTrackPublicationBySid(c.trackSid);if(!l||!l.track)return;let u=C.streamStateFromProto(c.state),h=l.track.streamState;l.track.setStreamState(u),u!==h&&(d.emit(L.TrackStreamStateChanged,l,l.track.streamState),this.emitWhenConnected(R.TrackStreamStateChanged,l,l.track.streamState,d))})},this.handleSubscriptionPermissionUpdate=o=>{let c=this.getRemoteParticipantBySid(o.participantSid);if(!c)return;let d=c.getTrackPublicationBySid(o.trackSid);d&&d.setAllowed(o.allowed)},this.handleSubscriptionError=o=>{this.cancelPendingTrackAdded(o.trackSid);let c=Array.from(this.remoteParticipants.values()).find(l=>l.trackPublications.has(o.trackSid));if(!c)return;let d=c.getTrackPublicationBySid(o.trackSid);d&&d.setSubscriptionError(o.err)},this.handleDataPacket=(o,c)=>{var d;let l=this.remoteParticipants.get(o.participantIdentity);o.value.case==="user"?this.handleUserPacket(l,o.value.value,o.kind,c,o.participantIdentity):o.value.case==="transcription"?this.log.debug("ignoring legacy transcription data packet",this.logContext):o.value.case==="sipDtmf"?this.handleSipDtmf(l,o.value.value):o.value.case==="metrics"?this.handleMetrics(o.value.value,l):o.value.case&&((d=this.dataPacketHandlers.get(o.value.case))===null||d===void 0||d(o,c,l))},this.handleUserPacket=(o,c,d,l,u)=>{this.emit(R.DataReceived,c.payload,o,d,c.topic,l,u),o?.emit(L.DataReceived,c.payload,d,l)},this.handleSipDtmf=(o,c)=>{this.emit(R.SipDTMFReceived,c,o),o?.emit(L.SipDTMFReceived,c)},this.handleTranscription=o=>{let c=o.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(o.transcribedParticipantIdentity),d=c?.trackPublications.get(o.trackId),l=Ly(o,this.transcriptionReceivedTimes);d?.emit(M.TranscriptionReceived,l),c?.emit(L.TranscriptionReceived,l,d),this.emit(R.TranscriptionReceived,l,c,d)},this.handleMetrics=(o,c)=>{this.emit(R.MetricsReceived,o,c)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(R.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=o=>{this.log.warn("could not playback audio",{error:o}),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(R.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(R.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(R.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>g(this,void 0,void 0,function*(){var o;((o=Ue())===null||o===void 0?void 0:o.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(R.MediaDevicesChanged)}),this.handleRoomUpdate=o=>{let c=this.roomInfo;this.roomInfo=o,c&&c.metadata!==o.metadata&&this.emitWhenConnected(R.RoomMetadataChanged,o.metadata),c?.activeRecording!==o.activeRecording&&this.emitWhenConnected(R.RecordingStatusChanged,o.activeRecording)},this.handleConnectionQualityUpdate=o=>{o.updates.forEach(c=>{if(c.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(c.quality);return}let d=this.getRemoteParticipantBySid(c.participantSid);d&&d.setConnectionQuality(c.quality)})},this.logWebRTCStats=()=>g(this,void 0,void 0,function*(){var o,c,d,l;let u=(o=this.engine)===null||o===void 0?void 0:o.pcManager;if(u)try{let h=yield Promise.all([u.publisher.getStats(),(c=u.subscriber)===null||c===void 0?void 0:c.getStats()]),f=F(h,2),m=f[0],p=f[1],y=m&&oa(m),v=p&&oa(p);this.statsLog.info("webrtc stats",{publisher:y?.connection,subscriber:v?.connection,inbound:[...(d=y?.inbound)!==null&&d!==void 0?d:[],...(l=v?.inbound)!==null&&l!==void 0?l:[]],outbound:y?.outbound})}catch(h){this.statsLog.debug("could not collect webrtc stats",{error:h})}}),this.onLocalParticipantMetadataChanged=o=>{this.emit(R.ParticipantMetadataChanged,o,this.localParticipant)},this.onLocalParticipantNameChanged=o=>{this.emit(R.ParticipantNameChanged,o,this.localParticipant)},this.onLocalAttributesChanged=o=>{this.emit(R.ParticipantAttributesChanged,o,this.localParticipant)},this.onLocalTrackMuted=o=>{this.emit(R.TrackMuted,o,this.localParticipant)},this.onLocalTrackUnmuted=o=>{this.emit(R.TrackUnmuted,o,this.localParticipant)},this.onTrackProcessorUpdate=o=>{var c;(c=o?.onPublish)===null||c===void 0||c.call(o,this)},this.onLocalTrackPublished=o=>g(this,void 0,void 0,function*(){var c,d,l,u,h,f;(c=o.track)===null||c===void 0||c.on(M.TrackProcessorUpdate,this.onTrackProcessorUpdate),(d=o.track)===null||d===void 0||d.on(M.Restarted,this.onLocalTrackRestarted),(h=(u=(l=o.track)===null||l===void 0?void 0:l.getProcessor())===null||u===void 0?void 0:u.onPublish)===null||h===void 0||h.call(u,this),this.emit(R.LocalTrackPublished,o,this.localParticipant),this.pendingInitialTrackSubscriptions.delete(o.trackSid)&&this.emitLocalTrackSubscribed(o),ht(o.track)&&(yield o.track.checkForSilence())&&this.emit(R.LocalAudioSilenceDetected,o);let m=yield(f=o.track)===null||f===void 0?void 0:f.getDeviceId(!1),p=ca(o.source);p&&m&&m!==this.localParticipant.activeDeviceMap.get(p)&&(this.localParticipant.activeDeviceMap.set(p,m),this.emit(R.ActiveDeviceChanged,p,m))}),this.onLocalTrackUnpublished=o=>{var c,d;(c=o.track)===null||c===void 0||c.off(M.TrackProcessorUpdate,this.onTrackProcessorUpdate),(d=o.track)===null||d===void 0||d.off(M.Restarted,this.onLocalTrackRestarted),this.emit(R.LocalTrackUnpublished,o,this.localParticipant)},this.onLocalTrackRestarted=o=>g(this,void 0,void 0,function*(){let c=yield o.getDeviceId(!1),d=ca(o.source);d&&c&&c!==this.localParticipant.activeDeviceMap.get(d)&&(this.log.debug("local track restarted, setting ".concat(d," ").concat(c," active")),this.localParticipant.activeDeviceMap.set(d,c),this.emit(R.ActiveDeviceChanged,d,c))}),this.onLocalConnectionQualityChanged=o=>{this.emit(R.ConnectionQualityChanged,o,this.localParticipant)},this.onMediaDevicesError=(o,c)=>{this.emit(R.MediaDevicesError,o,c)},this.onLocalParticipantPermissionsChanged=o=>{this.emit(R.ParticipantPermissionsChanged,o,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},z0),e),this.log=we((i=this.options.loggerName)!==null&&i!==void 0?i:he.Room,()=>this.logContext),this.statsLog=we(he.Stats,()=>this.logContext),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Bf),e?.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign({},e?.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},K0),e?.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new ye,this.localParticipant=new Vr("","",this.engine,this.options,this.slots),this.localParticipant.reservePublication=this.reservePublication,this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",An(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",An(this.options.audioCaptureDefaults.deviceId)),!((r=this.options.audioOutput)===null||r===void 0)&&r.deviceId&&this.switchActiveDevice("audiooutput",An(this.options.audioOutput.deviceId)).catch(o=>this.log.warn("Could not set audio output: ".concat(o.message))),Le()){let o=new AbortController;this.cleanupController=o;let c,d=this.constructor.cleanupRegistry;d?(c=n.createWeakDeviceChangeListener(new WeakRef(this)),d.register(this,o)):c=this.handleDeviceChange,(a=(s=navigator.mediaDevices)===null||s===void 0?void 0:s.addEventListener)===null||a===void 0||a.call(s,"devicechange",c,{signal:o.signal})}}installExtensions(e){var t;let i={log:this.log,get:a=>{let o=this.installedExtensions.get(a.key);if(!o)throw new Error("extension '".concat(String(a.key),"' is not installed"));return o},slot:a=>this.slots[a],getOrCreateParticipant:(a,o)=>this.getOrCreateParticipant(a,o),simulateConnected:(a,o)=>this.simulateConnected(a,o),acquireEmptyAudioStreamTrack:()=>this.acquireEmptyAudioStreamTrack(),handleTranscription:a=>this.handleTranscription(a)},r=[];for(let a of e){if(this.installedExtensions.has(a.key))throw new Error("extension '".concat(String(a.key),"' is already installed"));let o=a.install(this,i);this.installedExtensions.set(a.key,o),r.push(o);for(let c of Object.entries((t=o.dataPackets)!==null&&t!==void 0?t:{})){var s=F(c,2);let d=s[0],l=s[1];if(this.dataPacketHandlers.has(d))throw new Error("data packet case '".concat(d,"' is already handled by another extension"));this.dataPacketHandlers.set(d,(u,h,f)=>l(u.value.value,u,h,f))}for(let c of ob)o[c]!==void 0&&(this.slots[c]=o[c]);mu(this,n.prototype,o.room,a),mu(this.localParticipant,Vr.prototype,o.localParticipant,a),o.dispose&&this.extensionDisposers.push(o.dispose)}this.applySlotsToEngine(),r.forEach(a=>{var o;return(o=a.onEngineCreated)===null||o===void 0?void 0:o.call(a,this.engine)})}applySlotsToEngine(){this.engine.e2eeManager=this.slots.e2eeManager,this.engine.frameMetadataOptions=this.slots.frameMetadataOptions}get extensionResults(){return Array.from(this.installedExtensions.values())}dispose(){return g(this,void 0,void 0,function*(){var e;if(!this.disposed){this.disposed=!0;for(let t of this.preparedPublications)t.disconnected();this.state!==G.Disconnected&&(yield this.disconnect());for(let t of this.extensionDisposers.reverse())t();(e=this.cleanupController)===null||e===void 0||e.abort()}})}get logContext(){var e,t,i;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:(t=this.localParticipant)===null||t===void 0?void 0:t.identity,participantID:(i=this.localParticipant)===null||i===void 0?void 0:i.sid}}get isRecording(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&t!==void 0?t:!1}getSid(){return this.state===G.Disconnected?Pe.resolve(""):this.roomInfo&&this.roomInfo.sid!==""?Pe.resolve(this.roomInfo.sid):new Pe((e,t)=>{let i=r=>{r.sid!==""&&(this.engine.off(A.RoomUpdate,i),e(r.sid))};this.engine.on(A.RoomUpdate,i),this.once(R.Disconnected,()=>{this.engine.off(A.RoomUpdate,i),t(new J("Room disconnected before room server id was available"))})})}get name(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&t!==void 0?t:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&t!==void 0?t:0}get numPublishers(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&t!==void 0?t:0}maybeCreateEngine(){this.engine&&(this.engine.isNewlyCreated||!this.engine.isClosed)||(this.engine=new wa(this.options),this.engine.preparedPublications=this.preparedPublications,this.applySlotsToEngine(),this.engine.on(A.ParticipantUpdate,this.handleParticipantUpdates).on(A.RoomUpdate,this.handleRoomUpdate).on(A.SpeakersChanged,this.handleSpeakersChanged).on(A.StreamStateChanged,this.handleStreamStateUpdate).on(A.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(A.SubscriptionError,this.handleSubscriptionError).on(A.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(A.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(A.Disconnected,e=>{var t;(t=this.abortController)===null||t===void 0||t.abort("room disconnected by the server during connection attempt"),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(A.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(A.DataPacketReceived,this.handleDataPacket).on(A.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.debug("Resuming signal connection"),!this.connectFuture&&this.setAndEmitConnectionState(G.SignalReconnecting)&&this.emit(R.SignalReconnecting)}).on(A.Resumed,()=>{if(this.registerConnectionReconcile(),this.isResuming=!1,this.log.debug("Resumed signal connection"),this.updateSubscriptions(),this.connectFuture){this.bufferedEvents=[];return}this.setAndEmitConnectionState(G.Connected)&&this.emit(R.Reconnected),this.emitBufferedEvents()}).on(A.SignalResumed,()=>{(this.state===G.Reconnecting||this.isResuming)&&this.sendSyncState(),this.emitBufferedEvents()}).on(A.Restarting,this.handleRestarting).on(A.SignalRestarted,this.handleSignalRestarted).on(A.Restarted,()=>{this.state===G.Connected&&this.emitBufferedEvents()}).on(A.Offline,()=>{!this.connectFuture&&this.setAndEmitConnectionState(G.Reconnecting)&&this.emit(R.Reconnecting)}).on(A.DCBufferStatusChanged,(e,t)=>{this.emit(R.DCBufferStatusChanged,e,t)}).on(A.LocalTrackSubscribed,e=>{this.handleLocalTrackSubscribed(e)}).on(A.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,i)=>{this.handleParticipantDisconnected(i,t)}),this.emit(R.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}).on(A.TokenRefreshed,e=>{var t;(t=this.regionUrlProvider)===null||t===void 0||t.updateToken(e)}).on(A.ServerRegionsReported,e=>{var t;(t=this.regionUrlProvider)===null||t===void 0||t.setServerReportedRegions({regionSettings:e,updatedAtInMs:Date.now(),maxAgeInMs:Ea})}).on(A.RequestSubscribedCodecRefresh,()=>{for(let e of this.localParticipant.videoTrackPublications.values())We(e.track)&&e.track.refreshSubscribedCodecs()}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.slots.e2eeManager&&this.slots.e2eeManager.setupEngine(this.engine),this.extensionResults.forEach(e=>{var t;return(t=e.onEngineCreated)===null||t===void 0?void 0:t.call(e,this.engine)}))}createRegionStrategy(){return{getNextUrl:e=>g(this,void 0,void 0,function*(){return this.regionUrlProvider?this.regionUrlProvider.getNextBestRegionUrl(e):null}),resetAttempts:()=>{var e;return(e=this.regionUrlProvider)===null||e===void 0?void 0:e.resetAttempts()}}}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return Ne.getInstance().getDevices(e,t)}static createWeakDeviceChangeListener(e){return()=>{var t;(t=e.deref())===null||t===void 0||t.handleDeviceChange()}}prepareConnection(e,t){return g(this,void 0,void 0,function*(){if(this.state===G.Disconnected){this.log.debug("prepareConnection to ".concat(e));try{if(qn(new URL(e))&&t){this.regionUrlProvider=new ct(e,t);let i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===G.Disconnected&&(this.regionUrl=i,yield fetch(Ii(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i)))}else yield fetch(Ii(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",{error:i})}}})}prepareSessionPublication(e){if(this.disposed)throw new J("room has been disposed");let t=this.localParticipant.preparePublication(e,i=>{this.preparedPublications.delete(i);for(let s of this.pendingInitialTrackSubscriptions){var r=F(s,2);let a=r[0];r[1]===i&&this.pendingInitialTrackSubscriptions.delete(a)}});return this.preparedPublications.add(t),t}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return g(this,void 0,void 0,function*(){let i=()=>g(this,void 0,void 0,function*(){}),r;switch(e){case"signal-reconnect":let s=typeof t=="number"?t:0;yield this.engine.client.handleOnClose("simulate disconnect",void 0,s);break;case"fail-on-v1-path":this.engine.failNextV1Path();break;case"speaker":r=new ut({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":r=new ut({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":r=new ut({scenario:{case:"serverLeave",value:!0}});break;case"migration":r=new ut({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":i=()=>g(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new ut({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>g(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new ut({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":r=new ut({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>g(this,void 0,void 0,function*(){this.engine.client.emit("leave",new Ss({reason:Ke.CLIENT_INITIATED,action:En.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");r=new ut({scenario:{case:"subscriberBandwidth",value:at(t)}});break;case"leave-full-reconnect":r=new ut({scenario:{case:"leaveRequestFullReconnect",value:!0}})}r&&(yield this.engine.client.sendSimulateScenario(r),yield i())})}acquireDummyAudioElement(){ar||(ar=bb());let e=ar;if(this.releaseDummyAudioElement)return e.element;e.refCount+=1;let t=()=>{e.element.srcObject=document.hidden?null:e.stream,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status"),this.startAudio().catch(i=>this.log.warn("Could not restart audio on page becoming visible",Object.assign(Object.assign({},this.logContext),{error:i}))))};return document.addEventListener("visibilitychange",t),this.releaseDummyAudioElement=()=>{this.releaseDummyAudioElement=void 0,document.removeEventListener("visibilitychange",t),e.refCount-=1,!(e.refCount>0)&&(e.element.srcObject=null,e.element.remove(),ar=void 0,zl(e.track).catch(i=>this.log.warn("Could not release the dummy audio element track",Object.assign(Object.assign({},this.logContext),{error:i}))))},e.element}acquireEmptyAudioStreamTrack(){let e=If();return this.acquiredEmptyAudioTracks.add(e),e}releaseAcquiredEmptyAudioTrack(e){this.acquiredEmptyAudioTracks.delete(e)&&zl(e).catch(t=>this.log.warn("Could not release empty audio stream track",Object.assign(Object.assign({},this.logContext),{error:t})))}releaseAcquiredEmptyAudioTracks(){for(let e of this.acquiredEmptyAudioTracks)this.releaseAcquiredEmptyAudioTrack(e)}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return g(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return(function*(){var o,c,d,l,u,h,f;let m=!0,p=!1,y=a?{exact:r}:r;if(i==="audioinput"){p=s.localParticipant.audioTrackPublications.size===0;let v=(o=s.getActiveDevice(i))!==null&&o!==void 0?o:s.options.audioCaptureDefaults.deviceId;s.options.audioCaptureDefaults.deviceId=y;let _=Array.from(s.localParticipant.audioTrackPublications.values()).filter(b=>b.source===C.Source.Microphone);try{m=(yield Promise.all(_.map(b=>{var k;return(k=b.audioTrack)===null||k===void 0?void 0:k.setDeviceId(y)}))).every(b=>b===!0)}catch(b){throw s.options.audioCaptureDefaults.deviceId=v,b}let P=_.some(b=>{var k,S;return(S=(k=b.track)===null||k===void 0?void 0:k.isMuted)!==null&&S!==void 0?S:!1});m&&P&&(p=!0)}else if(i==="videoinput"){p=s.localParticipant.videoTrackPublications.size===0;let v=(c=s.getActiveDevice(i))!==null&&c!==void 0?c:s.options.videoCaptureDefaults.deviceId;s.options.videoCaptureDefaults.deviceId=y;let _=Array.from(s.localParticipant.videoTrackPublications.values()).filter(b=>b.source===C.Source.Camera);try{m=(yield Promise.all(_.map(b=>{var k;return(k=b.videoTrack)===null||k===void 0?void 0:k.setDeviceId(y)}))).every(b=>b===!0)}catch(b){throw s.options.videoCaptureDefaults.deviceId=v,b}let P=_.some(b=>{var k,S;return(S=(k=b.track)===null||k===void 0?void 0:k.isMuted)!==null&&S!==void 0?S:!1});m&&P&&(p=!0)}else if(i==="audiooutput"){if(p=!0,!ua()&&!s.options.webAudioMix||s.options.webAudioMix&&s.audioContext&&!("setSinkId"in s.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");s.options.webAudioMix&&(r=(d=yield Ne.getInstance().normalizeDeviceId("audiooutput",r))!==null&&d!==void 0?d:""),(l=(f=s.options).audioOutput)!==null&&l!==void 0||(f.audioOutput={});let v=(u=s.getActiveDevice(i))!==null&&u!==void 0?u:s.options.audioOutput.deviceId;s.options.audioOutput.deviceId=r;try{s.options.webAudioMix&&(yield(h=s.audioContext)===null||h===void 0?void 0:h.setSinkId(r)),yield Promise.all(Array.from(s.remoteParticipants.values()).map(_=>_.setAudioOutput({deviceId:r})))}catch(_){throw s.options.audioOutput.deviceId=v,_}}return p&&(s.localParticipant.activeDeviceMap.set(i,r),s.emit(R.ActiveDeviceChanged,i,r)),m})()})}setupLocalParticipantEvents(){this.localParticipant.on(L.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(L.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(L.AttributesChanged,this.onLocalAttributesChanged).on(L.TrackMuted,this.onLocalTrackMuted).on(L.TrackUnmuted,this.onLocalTrackUnmuted).on(L.LocalTrackPublished,this.onLocalTrackPublished).on(L.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(L.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(L.MediaDevicesError,this.onMediaDevicesError).on(L.AudioStreamAcquired,this.startAudio).on(L.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.engine;e&&t&&!t.client.isDisconnected?t.client.sendLeave().finally(()=>t.close()):t?.close(),t===this.engine&&(this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine())}onTrackAdded(e,t,i){var r,s;if([G.Connecting,G.Reconnecting].includes(this.state)){let f=Jl(e,t);this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(y=>y.id)});let m=()=>{if(p(),!t.getTracks().includes(e)){this.log.debug("skipping deferred track, the server no longer sends it",{mediaTrackId:e.id,mediaStreamId:t.id});return}this.onTrackAdded(e,t,i)},p=()=>{if(this.off(R.Reconnected,m),this.off(R.Connected,m),this.off(R.Disconnected,p),f){let y=this.pendingTrackAddedCallbacks.get(f);y?.delete(p),y?.size===0&&this.pendingTrackAddedCallbacks.delete(f)}};if(this.once(R.Reconnected,m),this.once(R.Connected,m),this.once(R.Disconnected,p),f){let y=(r=this.pendingTrackAddedCallbacks.get(f))!==null&&r!==void 0?r:new Set;y.add(p),this.pendingTrackAddedCallbacks.set(f,y)}return}if(this.state===G.Disconnected){this.log.warn("skipping incoming track after Room disconnected");return}if(e.readyState==="ended"){this.log.debug("skipping incoming track as it already ended");return}let a=wf(t.id),o=a[0],c=a[1],d=(s=Jl(e,t))!==null&&s!==void 0?s:e.id;if(o===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant");return}let l=Array.from(this.remoteParticipants.values()).find(f=>f.sid===o);if(!l){o.startsWith("PA")&&this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(o));return}if(!d.startsWith("TR")){let f=this.engine.getTrackIdForReceiver(i);if(!f){this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(o));return}d=f}d.startsWith("TR")||this.log.warn("Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ".concat(o,", streamId: ").concat(c,", trackId: ").concat(d),{remoteParticipantID:o,streamId:c,trackId:d});let u;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?u=this.options.adaptiveStream:u={});let h=l.addSubscribedMediaTrack(e,d,t,i,u);h?.isEncrypted&&!this.slots.e2eeManager&&this.emit(R.EncryptionError,new Error("Encrypted ".concat(h.source," track received from participant ").concat(l.sid,", but room does not have encryption enabled!")))}cancelPendingTrackAdded(e){var t;(t=this.pendingTrackAddedCallbacks.get(e))===null||t===void 0||t.forEach(i=>i())}handleLocalTrackSubscribed(e){let t=()=>this.localParticipant.getTrackPublications().find(d=>d.trackSid===e),i=t();if(i){this.emitLocalTrackSubscribed(i);return}let r=Array.from(this.preparedPublications).find(d=>!d.isCancelled&&d.initialTrackSid===e);if(r){this.pendingInitialTrackSubscriptions.set(e,r);return}this.log.debug("deferring LocalTrackSubscribed, publication not yet available",{subscribedSid:e});let s=1e4,a,o=d=>{d.trackSid===e&&(c(),this.emitLocalTrackSubscribed(d))},c=()=>{clearTimeout(a),this.localParticipant.off(L.LocalTrackPublished,o),this.off(R.Disconnected,c)};this.localParticipant.on(L.LocalTrackPublished,o),this.once(R.Disconnected,c),a=setTimeout(()=>{c();let d=t();d?this.emitLocalTrackSubscribed(d):this.log.warn("could not find local track publication for LocalTrackSubscribed event after timeout",{subscribedSid:e})},s)}emitLocalTrackSubscribed(e){this.localParticipant.emit(L.LocalTrackSubscribed,e),this.emitWhenConnected(R.LocalTrackSubscribed,e,this.localParticipant)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var i,r,s;this.pendingInitialTrackSubscriptions.clear();for(let a of this.preparedPublications)a.disconnected();if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.roomInfoBeforeRestart=void 0,this.transcriptionReceivedTimes.clear(),this.extensionResults.forEach(a=>{var o;return(o=a.onDisconnect)===null||o===void 0?void 0:o.call(a)}),this.state!==G.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{let a=e?[]:Array.from(this.localParticipant.audioTrackPublications.values()).map(o=>o.track).filter(ht);this.remoteParticipants.forEach(o=>{o.trackPublications.forEach(c=>{o.unpublishTrack(c.trackSid)})}),this.localParticipant.trackPublications.forEach(o=>{var c,d,l;o.track&&this.localParticipant.unpublishTrack(o.track,e),e?((c=o.track)===null||c===void 0||c.detach(),(d=o.track)===null||d===void 0||d.stop()):(l=o.track)===null||l===void 0||l.stopMonitor()}),this.localParticipant.off(L.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(L.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(L.AttributesChanged,this.onLocalAttributesChanged).off(L.TrackMuted,this.onLocalTrackMuted).off(L.TrackUnmuted,this.onLocalTrackUnmuted).off(L.LocalTrackPublished,this.onLocalTrackPublished).off(L.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(L.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(L.MediaDevicesError,this.onMediaDevicesError).off(L.AudioStreamAcquired,this.startAudio).off(L.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],(i=this.releaseDummyAudioElement)===null||i===void 0||i.call(this),this.releaseAcquiredEmptyAudioTracks(),this.releaseAudioContext(a).catch(o=>this.log.warn("Could not release audio context",Object.assign(Object.assign({},this.logContext),{error:o}))),Le()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(s=(r=navigator.mediaDevices)===null||r===void 0?void 0:r.removeEventListener)===null||s===void 0||s.call(r,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(G.Disconnected),this.emit(R.Disconnected,t)}}}handleParticipantDisconnected(e,t,i){this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach(r=>{t.unpublishTrack(r.trackSid,!0)}),this.emit(R.ParticipantDisconnected,t,i),t.setDisconnected())}selectDefaultDevices(){return g(this,void 0,void 0,function*(){var e,t,i;let r=Ne.getInstance().previousDevices,s=yield Ne.getInstance().getDevices(void 0,!1),a=Ue();if(a?.name==="Chrome"&&a.os!=="iOS")for(let c of s){let d=r.find(l=>l.deviceId===c.deviceId);d&&d.label!==""&&d.kind===c.kind&&d.label!==c.label&&this.getActiveDevice(c.kind)==="default"&&this.emit(R.ActiveDeviceChanged,c.kind,c.deviceId)}let o=["audiooutput","audioinput","videoinput"];for(let c of o){let d=ey(c),l=this.localParticipant.getTrackPublication(d);if(l&&(!((e=l.track)===null||e===void 0)&&e.isUserProvided))continue;let u=s.filter(f=>f.kind===c),h=this.getActiveDevice(c);if(h===((t=r.filter(f=>f.kind===c)[0])===null||t===void 0?void 0:t.deviceId)&&u.length>0&&((i=u[0])===null||i===void 0?void 0:i.deviceId)!==h){yield this.switchActiveDevice(c,u[0].deviceId);continue}c==="audioinput"&&!qe()||c==="videoinput"||u.length>0&&!u.find(f=>f.deviceId===this.getActiveDevice(c))&&(c!=="audiooutput"||!qe())&&(yield this.switchActiveDevice(c,u[0].deviceId))}})}acquireAudioContext(){return g(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;return(function*(){var i,r;let s=yield e.audioContextMutex.lock();try{if(e.audioContextReleased&&!t)return;e.audioContextReleased=!1;let a=typeof e.options.webAudioMix!="boolean"?e.options.webAudioMix.audioContext:void 0;if(a?yield e.setRoomAudioContext(a,!1):(!e.audioContext||e.audioContext.state==="closed")&&(yield e.setRoomAudioContext((i=_f())!==null&&i!==void 0?i:void 0,!0)),e.audioContext&&e.audioContext.state==="suspended")try{yield Promise.race([e.audioContext.resume(),Re(200)])}catch(c){e.log.warn("Could not resume audio context",{error:c})}let o=((r=e.audioContext)===null||r===void 0?void 0:r.state)==="running";o!==e.canPlaybackAudio&&(e.audioEnabled=o,e.emit(R.AudioPlaybackStatusChanged,o))}finally{s()}})()})}setRoomAudioContext(e,t){return g(this,void 0,void 0,function*(){let i=!!e&&t;if(this.audioContext===e){this.ownsAudioContext=i;return}let r=this.ownsAudioContext?this.audioContext:void 0;this.audioContext=e,this.ownsAudioContext=i;try{this.options.webAudioMix&&(yield Promise.all(Array.from(this.remoteParticipants.values()).map(s=>s.setAudioContext(e)))),yield this.localParticipant.setAudioContext(e)}catch(s){this.log.warn("Could not move audio tracks to the new audio context",Object.assign(Object.assign({},this.logContext),{error:s}))}finally{if(r&&r.state!=="closed")try{yield r.close()}catch(s){this.log.warn("Could not close audio context",Object.assign(Object.assign({},this.logContext),{error:s}))}}})}releaseAudioContext(){return g(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return(function*(){e.audioContextReleased=!0;let i=e.audioContext,r=yield e.audioContextMutex.lock();try{if(!e.audioContextReleased||e.audioContext!==i||!e.ownsAudioContext)return;try{yield Promise.all(t.map(s=>s.setAudioContext(void 0)))}catch(s){e.log.warn("Could not detach retained audio tracks from the audio context",Object.assign(Object.assign({},e.logContext),{error:s}))}yield e.setRoomAudioContext(void 0,!1)}finally{r()}})()})}createParticipant(e,t){var i;let r;return t?(r=Hr.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.extensionResults.forEach(s=>{var a;return(a=s.onParticipantCreated)===null||a===void 0?void 0:a.call(s,r,t)})):r=new Hr(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&r.setAudioContext(this.audioContext).catch(s=>this.log.warn("Could not set audio context",Object.assign(Object.assign({},this.logContext),{error:s}))),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&r.setAudioOutput(this.options.audioOutput).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message))),r}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){let r=this.remoteParticipants.get(e);return t&&r.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),r}let i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(R.ParticipantConnected,i),i.on(L.TrackPublished,r=>{this.emitWhenConnected(R.TrackPublished,r,i)}).on(L.TrackSubscribed,(r,s)=>{r.kind===C.Kind.Audio?(r.on(M.AudioPlaybackStarted,this.handleAudioPlaybackStarted),r.on(M.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):r.kind===C.Kind.Video&&(r.on(M.VideoPlaybackFailed,this.handleVideoPlaybackFailed),r.on(M.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emitWhenConnected(R.TrackSubscribed,r,s,i)}).on(L.TrackUnpublished,r=>{this.cancelPendingTrackAdded(r.trackSid),this.emit(R.TrackUnpublished,r,i)}).on(L.TrackUnsubscribed,(r,s)=>{this.emit(R.TrackUnsubscribed,r,s,i)}).on(L.TrackMuted,r=>{this.emitWhenConnected(R.TrackMuted,r,i)}).on(L.TrackUnmuted,r=>{this.emitWhenConnected(R.TrackUnmuted,r,i)}).on(L.ParticipantMetadataChanged,r=>{this.emitWhenConnected(R.ParticipantMetadataChanged,r,i)}).on(L.ParticipantNameChanged,r=>{this.emitWhenConnected(R.ParticipantNameChanged,r,i)}).on(L.AttributesChanged,r=>{this.emitWhenConnected(R.ParticipantAttributesChanged,r,i)}).on(L.ConnectionQualityChanged,r=>{this.emitWhenConnected(R.ConnectionQualityChanged,r,i)}).on(L.ParticipantPermissionsChanged,r=>{this.emitWhenConnected(R.ParticipantPermissionsChanged,r,i)}).on(L.TrackSubscriptionStatusChanged,(r,s)=>{this.emitWhenConnected(R.TrackSubscriptionStatusChanged,r,s,i)}).on(L.TrackSubscriptionFailed,(r,s)=>{this.emit(R.TrackSubscriptionFailed,r,i,s)}).on(L.TrackSubscriptionPermissionChanged,(r,s)=>{this.emitWhenConnected(R.TrackSubscriptionPermissionChanged,r,s,i)}).on(L.Active,()=>{this.emitWhenConnected(R.ParticipantActive,i),i.kind===Ei.AGENT&&this.localParticipant.setActiveAgent(i)}),t&&i.updateInfo(t),i}sendSyncState(){let e=Array.from(this.remoteParticipants.values()).reduce((r,s)=>(r.push(...s.getTrackPublications()),r),[]),t=this.localParticipant.getTrackPublications(),i=[].concat(...this.extensionResults.map(r=>{var s,a;return(a=(s=r.syncState)===null||s===void 0?void 0:s.call(r))!==null&&a!==void 0?a:[]}));this.engine.sendSyncState(e,t,i)}updateSubscriptions(){for(let e of this.remoteParticipants.values())for(let t of e.videoTrackPublications.values())t.isSubscribed&&Ny(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){let t=this.sidToIdentity.get(e);if(t){let i=this.remoteParticipants.get(t);if(i?.sid===e)return i}}getClientInfoCapabilities(){let e=[];return(Mi(this.slots.frameMetadataOptions)||this.slots.e2eeManager)&&e.push(Pi.CAP_PACKET_TRAILER),On()&&e.push(Pi.CAP_COMPRESSION_DEFLATE_RAW),e}setStatsLogging(e){e?this.statsLogInterval||(this.statsLogInterval=Y.setInterval(()=>{this.logWebRTCStats()},vb)):this.statsLogInterval&&(Y.clearInterval(this.statsLogInterval),this.statsLogInterval=void 0)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Y.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnectedOrConnecting:this.engine.verifyTransport()}:void 0}),e>=3&&(this.clearConnectionReconcile(),this.engine&&!this.engine.isClosed?(this.log.warn("detected connection state mismatch, attempting full reconnect"),this.engine.reconnect()):(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Ke.STATE_MISMATCH)))):e=0},gb)}clearConnectionReconcile(){this.connectionReconcileInterval&&Y.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.log.info("connection state changed: ".concat(this.state," -> ").concat(e)),this.state=e,this.setStatsLogging(e===G.Connected),this.emit(R.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let t=F(e,2),i=t[0],r=t[1];this.emit(i,...r)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];if(this.state===G.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===G.Connected)return this.emit(e,...i);return!1}simulateConnected(e,t){this.handleDisconnect(),this.roomInfo=e,this.localParticipant.updateInfo(t),this.setupLocalParticipantEvents(),this.emit(R.SignalConnected),this.emit(R.Connected),this.setAndEmitConnectionState(G.Connected)}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];if(e!==R.ActiveSpeakersChanged&&e!==R.TranscriptionReceived){let s=jf(i).filter(a=>a!==void 0);(e===R.TrackSubscribed||e===R.TrackUnsubscribed)&&this.log.trace("subscribe trace: ".concat(e),{event:e,args:s}),this.log.debug("room event ".concat(e),{event:e,args:s})}return super.emit(e,...i)}};Di.cleanupRegistry=typeof FinalizationRegistry<"u"&&typeof WeakRef<"u"&&new FinalizationRegistry(n=>{n.abort()});function jf(n){return n.map(e=>{if(e)return Array.isArray(e)?jf(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}function mu(n,e,t,i){if(!t)return;let r=Object.getOwnPropertyDescriptors(t);for(let s of Object.keys(r)){if(Object.getOwnPropertyDescriptor(n,s)||s in e)throw new Error("extension '".concat(String(i.key),"' redefines '").concat(s,"'"));s in n&&delete r[s]}Object.defineProperties(n,r)}var cd=65535,Vf=4294967295,jt=class n{static u16(e){return new n(e,cd)}static u32(e){return new n(e,Vf)}constructor(e,t){if(this.value=e,e<0)throw new Error("WrapAroundUnsignedInt: cannot faithfully represent an integer smaller than 0");if(t>Number.MAX_SAFE_INTEGER)throw new Error("WrapAroundUnsignedInt: cannot faithfully represent an integer bigger than MAX_SAFE_INTEGER.");this.maxSize=t,this.clamp()}clamp(){for(;this.value>this.maxSize;)this.value-=this.maxSize+1;for(;this.value<0;)this.value+=this.maxSize+1}clone(){return new n(this.value,this.maxSize)}update(e){this.value=e(this.value),this.clamp()}increment(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.update(t=>t+e)}decrement(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.update(t=>t-e)}getThenIncrement(){let e=this.value;return this.increment(),new n(e,this.maxSize)}isBefore(e){let t=this.value>>>0,r=(e.value>>>0)-t>>>0;return r!==0&&r<this.maxSize+1}},Kr=class n{static fromRtpTicks(e){return new n(e,9e4)}static rtpRandom(){let e=Math.round(Math.random()*Vf);return n.fromRtpTicks(e)}constructor(e,t){this.timestamp=jt.u32(e),this.rateInHz=t}asTicks(){return this.timestamp.value}clone(){return new n(this.timestamp.value,this.rateInHz)}wrappingAdd(e){this.timestamp.increment(e)}isBefore(e){return this.timestamp.isBefore(e.timestamp)}},Da=class n{constructor(e,t,i){this.epoch=t,this.base=i,this.previous=i.clone(),this.rateInHz=e}static startingNow(e,t){return new n(t,new Date,e)}static startingAtTime(e,t,i){return new n(i,e,t)}static rtpStartingNow(e){return n.startingNow(e,9e4)}static rtpStartingAtTime(e,t){return n.startingAtTime(e,t,9e4)}now(){return this.at(new Date)}at(e){let t=e.getTime()-this.epoch.getTime(),i=n.durationInMsToTicks(t,this.rateInHz),r=this.base.clone();return r.wrappingAdd(i),r.isBefore(this.previous)&&(r=this.previous),this.previous=r.clone(),r.clone()}static durationInMsToTicks(e,t){let r=(e*1e6*t+5e8)/1e9;return Math.round(r)}};function dd(n){if(n instanceof DataView)return n;if(n instanceof ArrayBuffer)return new DataView(n);if(n instanceof Uint8Array)return new DataView(n.buffer,n.byteOffset,n.byteLength);throw new Error("Error coercing ".concat(n," to DataView - input was not DataView, ArrayBuffer, or Uint8Array."))}var me=1,Tt=2,gu=4,kb=8,vu=0,yu=12,bu=5,Tb=7,ku=3,Sb=3,Tu=2,Su=1,_u=0,Cu=3,cr=2,wu=2,_b=1,Cb=0,_t;(function(n){n[n.TooShort=0]="TooShort",n[n.HeaderOverrun=1]="HeaderOverrun",n[n.MissingExtWords=2]="MissingExtWords",n[n.UnsupportedVersion=3]="UnsupportedVersion",n[n.InvalidHandle=4]="InvalidHandle",n[n.MalformedExt=5]="MalformedExt"})(_t||(_t={}));var mt=class n extends Be{constructor(e,t,i){super(19,e,i),this.name="DataTrackDeserializeError",this.reason=t,this.reasonName=_t[t]}static tooShort(){return new n("Too short to contain a valid header",_t.TooShort)}static headerOverrun(){return new n("Header exceeds total packet length",_t.HeaderOverrun)}static missingExtWords(){return new n("Extension word indicator is missing",_t.MissingExtWords)}static unsupportedVersion(e){return new n("Unsupported version ".concat(e),_t.UnsupportedVersion)}static invalidHandle(e){return new n("invalid track handle: ".concat(e.message),_t.InvalidHandle,{cause:e})}static malformedExt(e){return new n("Extension with tag ".concat(e," is malformed"),_t.MalformedExt)}},bi;(function(n){n[n.TooSmallForHeader=0]="TooSmallForHeader",n[n.TooSmallForPayload=1]="TooSmallForPayload"})(bi||(bi={}));var zr=class n extends Be{constructor(e,t,i){super(19,e,i),this.name="DataTrackSerializeError",this.reason=t,this.reasonName=bi[t]}static tooSmallForHeader(){return new n("Buffer cannot fit header",bi.TooSmallForHeader)}static tooSmallForPayload(){return new n("Buffer cannot fit payload",bi.TooSmallForPayload)}},Vn=class{toBinary(){let e=this.toBinaryLengthBytes(),t=new ArrayBuffer(e),i=new DataView(t),r=this.toBinaryInto(i);if(e!==r)throw new Error("".concat(this.constructor.name,".toBinary: written bytes (").concat(r," bytes) not equal to allocated array buffer length (").concat(e," bytes)."));return new Uint8Array(t)}},Wn;(function(n){n[n.UserTimestamp=2]="UserTimestamp",n[n.E2ee=1]="E2ee"})(Wn||(Wn={}));var Gr=class extends Vn{},ln=class n extends Gr{constructor(e){super(),this.timestamp=e}toBinaryLengthBytes(){return me+me+n.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,n.tag),t+=me,e.setUint8(t,n.lengthBytes),t+=me,e.setBigUint64(t,this.timestamp),t+=kb;let i=this.toBinaryLengthBytes();if(t!==i)throw new Error("DataTrackUserTimestampExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(i," bytes"));return t}toJSON(){return{tag:n.tag,lengthBytes:n.lengthBytes,timestamp:this.timestamp}}};ln.tag=Wn.UserTimestamp;ln.lengthBytes=8;var un=class n extends Gr{constructor(e,t){super(),this.keyIndex=e,this.iv=t}toBinaryLengthBytes(){return me+me+n.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,n.tag),t+=me,e.setUint8(t,n.lengthBytes),t+=me,e.setUint8(t,this.keyIndex),t+=me;for(let r=0;r<this.iv.length;r+=1)e.setUint8(t,this.iv[r]),t+=me;let i=this.toBinaryLengthBytes();if(t!==i)throw new Error("DataTrackE2eeExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(i," bytes"));return t}toJSON(){return{tag:n.tag,lengthBytes:n.lengthBytes,keyIndex:this.keyIndex,iv:this.iv}}};un.tag=Wn.E2ee;un.lengthBytes=13;var Dn=class n extends Vn{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.userTimestamp=e.userTimestamp,this.e2ee=e.e2ee}toBinaryLengthBytes(){let e=0;return this.userTimestamp&&(e+=this.userTimestamp.toBinaryLengthBytes()),this.e2ee&&(e+=this.e2ee.toBinaryLengthBytes()),e}toBinaryInto(e){let t=0;if(this.e2ee){let r=this.e2ee.toBinaryInto(e);t+=r}if(this.userTimestamp){let r=this.userTimestamp.toBinaryInto(new DataView(e.buffer,e.byteOffset+t));t+=r}let i=this.toBinaryLengthBytes();if(t!==i)throw new Error("DataTrackExtensions.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(i," bytes"));return t}static fromBinary(e){let t=dd(e),i,r,s=0;for(;t.byteLength-s>=me+me;){let a=t.getUint8(s);s+=me;let o=t.getUint8(s);if(s+=me,a!==Cb)switch(a){case Wn.UserTimestamp:if(t.byteLength-s<ln.lengthBytes)throw mt.malformedExt(a);i=new ln(t.getBigUint64(s)),s+=o;break;case Wn.E2ee:if(t.byteLength-s<un.lengthBytes)throw mt.malformedExt(a);let c=t.getUint8(s),d=new Uint8Array(12);for(let l=0;l<d.length;l+=1){let u=s;u+=me,u+=l*me,d[l]=t.getUint8(u)}r=new un(c,d),s+=o;break;default:if(t.byteLength-s<o)throw mt.malformedExt(a);s+=o;break}}return[new n({userTimestamp:i,e2ee:r}),t.byteLength]}toJSON(){var e,t,i,r;return{userTimestamp:(t=(e=this.userTimestamp)===null||e===void 0?void 0:e.toJSON())!==null&&t!==void 0?t:null,e2ee:(r=(i=this.e2ee)===null||i===void 0?void 0:i.toJSON())!==null&&r!==void 0?r:null}}},Wf={from(n){return{payload:n.payload,extensions:new Dn({userTimestamp:n.userTimestamp?new ln(n.userTimestamp):void 0})}},lossyIntoFrame(n){var e;return{payload:n.payload,userTimestamp:(e=n.extensions.userTimestamp)===null||e===void 0?void 0:e.timestamp}}},an;(function(n){n[n.Reserved=0]="Reserved",n[n.TooLarge=1]="TooLarge"})(an||(an={}));var Ni=class n extends Be{constructor(e,t){super(19,e),this.name="DataTrackHandleError",this.reason=t,this.reasonName=an[t]}isReason(e){return this.reason===e}static tooLarge(){return new n("Value too large to be a valid track handle",an.TooLarge)}static reserved(e){return new n("0x".concat(e.toString(16)," is a reserved value."),an.Reserved)}},wb={fromNumber(n){if(n===0)throw Ni.reserved(n);if(n>cd)throw Ni.tooLarge();return n}},Na=class{constructor(){this.value=0}get(){return this.value+=1,this.value>cd?null:this.value}reset(){this.value=0}},Fi=class n extends Vn{constructor(e){var t;super(),this.marker=e.marker,this.trackHandle=e.trackHandle,this.sequence=e.sequence,this.frameNumber=e.frameNumber,this.timestamp=e.timestamp,this.extensions=(t=e.extensions)!==null&&t!==void 0?t:new Dn}extensionsMetrics(){let e=this.extensions.toBinaryLengthBytes(),t=Math.ceil((cr+e)/4),i=t*4-cr-e;return{lengthBytes:e,lengthWords:t,paddingLengthBytes:i}}toBinaryLengthBytes(){let e=this.extensionsMetrics(),t=e.lengthBytes,i=e.paddingLengthBytes,r=yu;return t>0&&(r+=cr+t+i),r}toBinaryInto(e){if(e.byteLength<this.toBinaryLengthBytes())throw zr.tooSmallForHeader();let t=vu<<bu,i;switch(this.marker){case ce.Inter:i=_u;break;case ce.Final:i=Su;break;case ce.Start:i=Tu;break;case ce.Single:i=Cu;break}t|=i<<ku;let r=this.extensionsMetrics(),s=r.lengthBytes,a=r.lengthWords,o=r.paddingLengthBytes;s>0&&(t|=1<<wu);let c=0;if(e.setUint8(c,t),c+=me,e.setUint8(c,0),c+=me,e.setUint16(c,this.trackHandle),c+=Tt,e.setUint16(c,this.sequence.value),c+=Tt,e.setUint16(c,this.frameNumber.value),c+=Tt,e.setUint32(c,this.timestamp.asTicks()),c+=gu,s>0){let l=a-1;e.setUint16(c,l),c+=Tt;let u=this.extensions.toBinaryInto(new DataView(e.buffer,e.byteOffset+c));c+=u;for(let h=0;h<o;h+=1)e.setUint8(c,0),c+=me}let d=this.toBinaryLengthBytes();if(c!==d)throw new Error("DataTrackPacketHeader.toBinaryInto: Wrote ".concat(c," bytes but expected length was ").concat(d," bytes"));return d}static fromBinary(e){let t=dd(e);if(t.byteLength<yu)throw mt.tooShort();let i=0,r=t.getUint8(i);i+=me;let s=r>>bu&Tb;if(s>vu)throw mt.unsupportedVersion(s);let a;switch(r>>ku&Sb){case Tu:a=ce.Start;break;case Su:a=ce.Final;break;case Cu:a=ce.Single;break;case _u:default:a=ce.Inter;break}let o=(r>>wu&_b)>0;i+=me;let c;try{c=wb.fromNumber(t.getUint16(i))}catch(f){throw f instanceof Ni&&(f.isReason(an.Reserved)||f.isReason(an.TooLarge))?mt.invalidHandle(f):f}i+=Tt;let d=jt.u16(t.getUint16(i));i+=Tt;let l=jt.u16(t.getUint16(i));i+=Tt;let u=Kr.fromRtpTicks(t.getUint32(i));i+=gu;let h=new Dn;if(o){if(t.byteLength-i<Tt)throw mt.missingExtWords();let f=t.getUint16(i);i+=Tt;let p=4*(f+1)-cr;if(i+p>t.byteLength)throw mt.headerOverrun();let y=new DataView(t.buffer,t.byteOffset+i,p),v=Dn.fromBinary(y),_=F(v,2),P=_[0],b=_[1];h=P,i+=b}return[new n({marker:a,trackHandle:c,sequence:d,frameNumber:l,timestamp:u,extensions:h}),i]}toJSON(){return{marker:this.marker,trackHandle:this.trackHandle,sequence:this.sequence.value,frameNumber:this.frameNumber.value,timestamp:this.timestamp.asTicks(),extensions:this.extensions.toJSON()}}},ce;(function(n){n[n.Start=0]="Start",n[n.Inter=1]="Inter",n[n.Final=2]="Final",n[n.Single=3]="Single"})(ce||(ce={}));var Jr=class n extends Vn{constructor(e,t){super(),this.header=e,this.payload=t}toBinaryLengthBytes(){return this.header.toBinaryLengthBytes()+this.payload.byteLength}toBinaryInto(e){let t=0,i=this.header.toBinaryInto(e);if(t+=i,e.byteLength-t<this.payload.byteLength)throw zr.tooSmallForPayload();for(let s=0;s<this.payload.length;s+=1)e.setUint8(t,this.payload[s]),t+=me;let r=this.toBinaryLengthBytes();if(t!==r)throw new Error("DataTrackPacket.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(r," bytes"));return r}static fromBinary(e){let t=dd(e),i=Fi.fromBinary(t),r=F(i,2),s=r[0],a=r[1],o=t.buffer.slice(t.byteOffset+a,t.byteOffset+t.byteLength);return[new n(s,new Uint8Array(o)),t.byteLength]}toJSON(){return{header:this.header.toJSON(),payload:this.payload}}},$r=class n extends Be{constructor(e,t,i){super(19,e,i),this.name="DataTrackPacketizerError",this.reason=t,this.reasonName=Qr[t]}static mtuTooShort(){return new n("MTU is too short to send frame",Qr.MtuTooShort)}},Qr;(function(n){n[n.MtuTooShort=0]="MtuTooShort"})(Qr||(Qr={}));var Fa=class n{constructor(e,t){this.sequence=jt.u16(0),this.frameNumber=jt.u16(0),this.clock=Da.rtpStartingNow(Kr.rtpRandom()),this.handle=e,this.mtuSizeBytes=t}static computeFrameMarker(e,t){return t<=1?ce.Single:e===0?ce.Start:e===t-1?ce.Final:ce.Inter}*packetize(e,t){var i;let r=this.frameNumber.getThenIncrement(),s={marker:ce.Inter,trackHandle:this.handle,sequence:jt.u16(0),frameNumber:r,timestamp:(i=t?.now)!==null&&i!==void 0?i:this.clock.now(),extensions:e.extensions},a=new Fi(s).toBinaryLengthBytes();if(a>=this.mtuSizeBytes)throw $r.mtuTooShort();let o=this.mtuSizeBytes-a,c=Math.ceil(e.payload.byteLength/o);for(let l=0,u=0;u<e.payload.byteLength;d=[l+1,u+o],l=d[0],u=d[1],d){var d;let h=this.sequence.getThenIncrement(),f=new Fi(Object.assign(Object.assign({},s),{marker:n.computeFrameMarker(l,c),sequence:h})),m=Math.min(o,e.payload.byteLength-u),p=new Uint8Array(e.payload.buffer,e.payload.byteOffset+u,m);yield new Jr(f,p)}}},nt;(function(n){n[n.NotAllowed=0]="NotAllowed",n[n.DuplicateName=1]="DuplicateName",n[n.Timeout=2]="Timeout",n[n.LimitReached=3]="LimitReached",n[n.Disconnected=4]="Disconnected",n[n.Cancelled=5]="Cancelled",n[n.InvalidName=6]="InvalidName",n[n.Unknown=7]="Unknown"})(nt||(nt={}));var Qe=class n extends Be{constructor(e,t,i){super(21,e,i),this.name="DataTrackPublishError",this.reason=t,this.reasonName=nt[t],this.rawMessage=i?.rawMessage}static notAllowed(e){return new n("Data track publishing unauthorized",nt.NotAllowed,{rawMessage:e})}static duplicateName(e){return new n("Track name already taken",nt.DuplicateName,{rawMessage:e})}static invalidName(e){return new n("Track name is invalid",nt.InvalidName,{rawMessage:e})}static timeout(){return new n("Publish data track timed-out. Does the LiveKit server support data tracks?",nt.Timeout)}static limitReached(e){return new n("Data track publication limit reached",nt.LimitReached,{rawMessage:e})}static unknown(e,t){return new n("Received RequestResponse for publishDataTrack, but reason was unrecognised (".concat(e,", ").concat(t,")"),nt.Unknown)}static disconnected(){return new n("Room disconnected",nt.Disconnected)}static cancelled(){return new n("Publish data track cancelled by caller",nt.Cancelled)}},ki;(function(n){n[n.TrackUnpublished=0]="TrackUnpublished",n[n.Dropped=1]="Dropped"})(ki||(ki={}));var sn=class n extends Be{constructor(e,t,i){super(22,e,i),this.name="DataTrackPushFrameError",this.reason=t,this.reasonName=ki[t]}static trackUnpublished(){return new n("Track is no longer published",ki.TrackUnpublished)}static dropped(e){return new n("Frame was dropped",ki.Dropped,{cause:e})}},Ti;(function(n){n[n.Packetizer=0]="Packetizer",n[n.Encryption=1]="Encryption"})(Ti||(Ti={}));var Yr=class n extends Be{constructor(e,t,i){super(21,e,i),this.name="DataTrackOutgoingPipelineError",this.reason=t,this.reasonName=Ti[t]}static packetizer(e){return new n("Error packetizing frame",Ti.Packetizer,{cause:e})}static encryption(e){return new n("Error encrypting frame",Ti.Encryption,{cause:e})}},Hf=Symbol.for("lk.track"),Kf=Symbol.for("lk.data-track"),Xr=class n{constructor(e,t){this.trackSymbol=Hf,this.isLocal=!0,this.typeSymbol=Kf,this.handle=null,this.log=W,this.flushedFuture=new Ce,this.isFlushed=!0,this.handleManagerReset=()=>{var i,r;(r=(i=this.flushedFuture).resolve)===null||r===void 0||r.call(i),this.manager.off("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.off("reset",this.handleManagerReset)},this.handleManagerPacketsFlushedChange=i=>{var r,s;this.isFlushed=i.isFlushed,i.isFlushed&&((s=(r=this.flushedFuture).resolve)===null||s===void 0||s.call(r),this.flushedFuture=new Ce)},this.options=e,this.manager=t,this.log=we(he.DataTracks),this.manager.on("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.on("reset",this.handleManagerReset)}static withExplicitHandle(e,t,i){let r=new n(e,t);return r.handle=i,r}get info(){let e=this.descriptor;if(e?.type==="active")return e.info}get descriptor(){return this.handle?this.manager.getDescriptor(this.handle):null}publish(e){return g(this,void 0,void 0,function*(){try{this.handle=yield this.manager.publishRequest(this.options,e)}catch(t){throw t}})}isPublished(){var e;return((e=this.descriptor)===null||e===void 0?void 0:e.type)==="active"&&this.descriptor.publishState!=="unpublished"}tryPush(e){if(!this.handle)throw sn.trackUnpublished();let t=Wf.from(e);try{return this.manager.tryProcessAndSend(this.handle,t)}catch(i){throw i}}flush(){return g(this,void 0,void 0,function*(){if(!this.isFlushed)return this.flushedFuture.promise})}unpublish(){return g(this,void 0,void 0,function*(){if(!this.handle){W.warn('Data track "'.concat(this.options.name,'" is not published, so unpublishing has no effect.'));return}try{yield this.manager.unpublishRequest(this.handle)}catch(e){throw e}})}},Ua={from(n){return{sid:n.sid,pubHandle:n.pubHandle,name:n.name,usesE2ee:n.encryption!==X.NONE}},toProtobuf(n){return new gs({sid:n.sid,pubHandle:n.pubHandle,name:n.name,encryption:n.usesE2ee?X.GCM:X.NONE})}},Zr=class{constructor(e,t,i){this.trackSymbol=Hf,this.isLocal=!1,this.typeSymbol=Kf,this.info=e,this.manager=t,this.publisherIdentity=i.publisherIdentity}subscribe(e){try{let t=this.manager.openSubscriptionStream(this.info.sid,e?.signal,e?.bufferSize),i=F(t,2),r=i[0];return i[1].catch(()=>{}),r}catch(t){throw t}}setPipelineOptions(e){this.manager.setPipelineOptions(this.info.sid,e)}},Eb=Object.values(_i),Pb=Object.values(Wo),Rb=Object.values(Ec),Ib=[_i.h180,_i.h360],Ab=[Wo.h180,Wo.h360],Mb=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var i,r;return new ee(Math.floor(n.width/t.scaleResolutionDownBy),Math.floor(n.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(n.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((i=n.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((r=t.fps)!==null&&r!==void 0?r:30))))),t.fps,n.encoding.priority)}),Ba=["q","h","f"];function Si(n,e,t,i){var r,s;let a=i?.videoEncoding;n&&(a=i?.screenShareEncoding);let o=i?.simulcast,c=i?.scalabilityMode,d=i?.videoCodec,l=In(d,i);if(!a&&!o&&!c||!e||!t)return[{}];a||(a=Ob(n,e,t,d),W.debug("using video encoding",a));let u=a.maxFramerate,h=new ee(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(c&&It(d)&&!l){let _=new es(c),P=[];if(_.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));if(Ef()){let b=_.suffix=="h"?2:3,k=Cy();for(let S=0;S<_.spatial;S+=1)P.push({rid:Ba[2-S],maxBitrate:a.maxBitrate/Math.pow(b,S),maxFramerate:h.encoding.maxFramerate,scaleResolutionDownBy:k?Math.pow(2,S):void 0});P[0].scalabilityMode=c}else P.push({maxBitrate:a.maxBitrate,maxFramerate:h.encoding.maxFramerate,scalabilityMode:c});return h.encoding.priority&&(P[0].priority=h.encoding.priority,P[0].networkPriority=h.encoding.priority),W.debug("using svc encoding",{encodings:P}),P}if(!o)return[a];let f=_=>(l&&_.forEach(P=>{P.scalabilityMode=c}),_),m;n?m=(r=Ru(i?.screenShareSimulcastLayers))!==null&&r!==void 0?r:Pu(n,h):m=(s=Ru(i?.videoSimulcastLayers))!==null&&s!==void 0?s:Pu(n,h);let p;if(m.length>0){let _=m[0];if(m.length>1){var y=m,v=F(y,2);p=v[1]}let P=Math.max(e,t);if(P>=960&&p)return f(Po(e,t,[_,p,h],u));if(P>=480)return f(Po(e,t,[_,h],u))}return f(Po(e,t,[h]))}function Eu(n,e,t){var i,r;return It(n)&&!In(n,e)?(r=(i=t[0])===null||i===void 0?void 0:i.maxBitrate)!==null&&r!==void 0?r:0:t.reduce((s,a)=>{var o;return s+((o=a.maxBitrate)!==null&&o!==void 0?o:0)},0)}function zf(n,e,t){var i,r,s,a;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&W.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;let o=n.mediaStreamTrack.getSettings(),c=(i=o.width)!==null&&i!==void 0?i:(r=n.dimensions)===null||r===void 0?void 0:r.width,d=(s=o.height)!==null&&s!==void 0?s:(a=n.dimensions)===null||a===void 0?void 0:a.height;return n.source===C.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),Si(n.source===C.Source.ScreenShare,c,d,t)}function Ob(n,e,t,i){let r=xb(n,e,t),s=r[0].encoding,a=Math.max(e,t);for(let o=0;o<r.length;o+=1){let c=r[o];if(s=c.encoding,c.width>=a)break}if(i)switch(i){case"av1":case"h265":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.7;break;case"vp9":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.85;break}return s}function xb(n,e,t){if(n)return Rb;let i=e>t?e/t:t/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?Eb:Pb}function Pu(n,e){if(n)return Mb(e);let t=e.width,i=e.height,r=t>i?t/i:i/t;return Math.abs(r-16/9)<Math.abs(r-4/3)?Ib:Ab}function Po(n,e,t,i){let r=[];if(t.forEach((s,a)=>{if(a>=Ba.length)return;let o=Math.min(n,e),d={rid:Ba[a],scaleResolutionDownBy:Math.max(1,o/Math.min(s.width,s.height)),maxBitrate:s.encoding.maxBitrate},l=i&&s.encoding.maxFramerate?Math.min(i,s.encoding.maxFramerate):s.encoding.maxFramerate;l&&(d.maxFramerate=l);let u=Ue(),h=u?.name==="Firefox"&&u.os!=="iOS"||a===0;s.encoding.priority&&h&&(d.priority=s.encoding.priority,d.networkPriority=s.encoding.priority),r.push(d)}),je()&&Rf()==="ios"){let s;r.forEach(o=>{s?o.maxFramerate&&o.maxFramerate>s&&(s=o.maxFramerate):s=o.maxFramerate});let a=!0;r.forEach(o=>{var c;o.maxFramerate!=s&&(a&&(a=!1,W.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),W.info('Setting framerate of encoding "'.concat((c=o.rid)!==null&&c!==void 0?c:"",'" to ').concat(s)),o.maxFramerate=s)})}return r}function Ru(n){if(n)return n.slice().sort((e,t)=>{let i=e.encoding,r=t.encoding;return i.maxBitrate>r.maxBitrate?1:i.maxBitrate<r.maxBitrate?-1:i.maxBitrate===r.maxBitrate&&i.maxFramerate&&r.maxFramerate?i.maxFramerate>r.maxFramerate?1:-1:0})}var es=class{constructor(e){let t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}};function Lb(n){switch(n.source){case C.Source.Camera:return"maintain-framerate";case C.Source.ScreenShare:return"maintain-resolution";default:return"balanced"}}var Db=5e3,ts=class extends Ur{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(e,C.Kind.Video,t,i,r),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>g(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let s;try{s=yield this.getSenderStats()}catch(c){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:c}));return}let a=new Map(s.map(c=>[c.rid,c])),o=s.some(c=>c.qualityLimitationReason==="cpu");if(o!==this.isCpuConstrained&&(this.isCpuConstrained=o,this.isCpuConstrained&&this.emit(M.CpuConstrained)),this.prevStats){let c=0;a.forEach((d,l)=>{var u;let h=(u=this.prevStats)===null||u===void 0?void 0:u.get(l);c+=ws(d,h)}),this._currentBitrate=c}this.prevStats=a}),this.senderLock=new ye}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;this.signalClient=e;let i=(t=this.sender)===null||t===void 0?void 0:t.getParameters();i&&(this.encodings=i.encodings),Le()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},od)))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){let e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return g(this,void 0,void 0,function*(){var t,i,r,s,a;yield e.pauseUpstream.call(this);try{for(var o=!0,c=ze(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;o=!0)s=d.value,o=!1,yield(a=s.sender)===null||a===void 0?void 0:a.replaceTrack(null)}catch(l){i={error:l}}finally{try{!o&&!t&&(r=c.return)&&(yield r.call(c))}finally{if(i)throw i.error}}})}resumeUpstream(){let e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return g(this,void 0,void 0,function*(){var t,i,r,s,a;yield e.resumeUpstream.call(this);try{for(var o=!0,c=ze(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;o=!0){s=d.value,o=!1;let l=s;yield(a=l.sender)===null||a===void 0?void 0:a.replaceTrack(l.mediaStreamTrack)}}catch(l){i={error:l}}finally{try{!o&&!t&&(r=c.return)&&(yield r.call(c))}finally{if(i)throw i.error}}})}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return g(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===C.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return g(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.source===C.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(let t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return g(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];let t=[],i=yield this.sender.getStats();return i.forEach(r=>{var s;if(r.type==="outbound-rtp"){let a={type:"video",streamId:r.id,frameHeight:r.frameHeight,frameWidth:r.frameWidth,framesPerSecond:r.framesPerSecond,framesSent:r.framesSent,firCount:r.firCount,pliCount:r.pliCount,nackCount:r.nackCount,packetsSent:r.packetsSent,bytesSent:r.bytesSent,qualityLimitationReason:r.qualityLimitationReason,qualityLimitationDurations:r.qualityLimitationDurations,qualityLimitationResolutionChanges:r.qualityLimitationResolutionChanges,rid:(s=r.rid)!==null&&s!==void 0?s:r.id,retransmittedPacketsSent:r.retransmittedPacketsSent,targetBitrate:r.targetBitrate,timestamp:r.timestamp},o=i.get(r.remoteId);o&&(a.jitter=o.jitter,a.packetsLost=o.packetsLost,a.roundTripTime=o.roundTripTime),t.push(a)}}),t.sort((r,s)=>{var a,o;return((a=s.frameWidth)!==null&&a!==void 0?a:0)-((o=r.frameWidth)!==null&&o!==void 0?o:0)}),t})}isSvcPublish(e){return It(e)&&!In(e,this.publishOptions)}setPublishingQuality(e){let t=[];for(let i=Ge.LOW;i<=Ge.HIGH;i+=1)t.push(new Hc({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(this.isSvcPublish(this.codec),t)}restartTrack(e){return g(this,void 0,void 0,function*(){var t,i,r,s,a;let o;if(e){let u=Jc({video:e});typeof u.video!="boolean"&&(o=u.video)}yield this.restart(o),this.isCpuConstrained=!1;try{for(var c=!0,d=ze(this.simulcastCodecs.values()),l;l=yield d.next(),t=l.done,!t;c=!0){s=l.value,c=!1;let u=s;u.sender&&((a=u.sender.transport)===null||a===void 0?void 0:a.state)!=="closed"&&(u.mediaStreamTrack=this.mediaStreamTrack.clone(),yield u.sender.replaceTrack(u.mediaStreamTrack))}}catch(u){i={error:u}}finally{try{!c&&!t&&(r=d.return)&&(yield r.call(d))}finally{if(i)throw i.error}}yield this.onSenderTrackSwapped()})}onSenderTrackSwapped(){return g(this,void 0,void 0,function*(){yield this.refreshSenderEncodings()})}refreshSenderEncodings(){return g(this,void 0,void 0,function*(){var e;if(!this.sender||!this.publishOptions||this.optimizeForPerformance)return;let t=yield this.senderLock.lock();try{let r;try{r=yield this.waitForDimensions()}catch(o){this.log.warn("could not determine new track dimensions, skipping encoding recompute",Object.assign(Object.assign({},this.logContext),{error:o}));return}if(this.lastEncodedDimensions&&this.lastEncodedDimensions.width===r.width&&this.lastEncodedDimensions.height===r.height)return;let s=this.source===C.Source.ScreenShare,a=Si(s,r.width,r.height,Object.assign({},this.publishOptions));yield this.applyEncodingsToSender(this.sender,a),this.encodings=a,this.lastEncodedDimensions=r;for(let o of this.simulcastCodecs){var i=F(o,2);let c=i[0],d=i[1];if(!d.sender||((e=d.sender.transport)===null||e===void 0?void 0:e.state)==="closed"||!kh(c))continue;let l=Object.assign({},this.publishOptions),u=zf(this,c,l);u&&(yield this.applyEncodingsToSender(d.sender,u),d.encodings=u)}}catch(r){this.log.warn("failed to apply recomputed encodings",Object.assign(Object.assign({},this.logContext),{error:r}))}finally{t()}})}applyEncodingsToSender(e,t){return g(this,void 0,void 0,function*(){let i=e.getParameters();!i.encodings||i.encodings.length!==t.length||(i.encodings.forEach((r,s)=>{if(r.active===!1)return;let a=t[s];a.scaleResolutionDownBy!==void 0&&(r.scaleResolutionDownBy=a.scaleResolutionDownBy),a.maxBitrate!==void 0&&(r.maxBitrate=a.maxBitrate),a.maxFramerate!==void 0&&(r.maxFramerate=a.maxFramerate),a.priority!==void 0&&(r.priority=a.priority,r.networkPriority=a.priority)}),this.log.debug("updating sender encodings after track restart",Object.assign(Object.assign({},this.logContext),{encodings:i.encodings})),yield e.setParameters(i))})}setProcessor(e){let t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return g(this,arguments,void 0,function(i){var r=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var a,o,c,d,l,u;if(yield t.setProcessor.call(r,i,s),!((l=r.processor)===null||l===void 0)&&l.processedTrack)try{for(var h=!0,f=ze(r.simulcastCodecs.values()),m;m=yield f.next(),a=m.done,!a;h=!0)d=m.value,h=!1,yield(u=d.sender)===null||u===void 0?void 0:u.replaceTrack(r.processor.processedTrack)}catch(p){o={error:p}}finally{try{!h&&!a&&(c=f.return)&&(yield c.call(f))}finally{if(o)throw o.error}}})()})}setDegradationPreference(e){return g(this,void 0,void 0,function*(){this.degradationPreference=e,yield this.applyDegradationPreference(this.sender);for(let t of this.simulcastCodecs.values())yield this.applyDegradationPreference(t.sender)})}applyDegradationPreference(e){return g(this,void 0,void 0,function*(){if(e)try{this.log.debug("setting degradationPreference to ".concat(this.degradationPreference),this.logContext);let t=e.getParameters();t.degradationPreference=this.degradationPreference,yield e.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}let i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){return g(this,void 0,void 0,function*(){let i=this.simulcastCodecs.get(e);i&&(i.sender=t,yield this.applyDegradationPreference(t),setTimeout(()=>{this.refreshSubscribedCodecs()},Db))})}refreshSubscribedCodecs(){return g(this,void 0,void 0,function*(){if(this.subscribedCodecs)return this.setPublishingCodecs(this.subscribedCodecs).catch(e=>this.log.warn("failed to refresh codec for track",Object.assign(Object.assign({},this.logContext),{error:e})))})}setPublishingCodecs(e){return g(this,void 0,void 0,function*(){var t,i,r,s,a,o,c;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(this.isSvcPublish(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;let d=[];try{for(t=!0,i=ze(e);r=yield i.next(),s=r.done,!s;t=!0){c=r.value,t=!1;let l=c;if(!this.codec||this.codec===l.codec)yield this.setPublishingLayers(this.isSvcPublish(l.codec),l.qualities);else{let u=this.simulcastCodecs.get(l.codec);if(this.log.debug("try setPublishingCodec for ".concat(l.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:u})),!u||!u.sender){for(let h of l.qualities)if(h.enabled){d.push(l.codec);break}}else u.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(l.codec),this.logContext),yield Iu(u.sender,u.encodings,l.qualities,this.senderLock,this.isSvcPublish(l.codec),this.log,this.logContext))}}}catch(l){a={error:l}}finally{try{!t&&!s&&(o=i.return)&&(yield o.call(i))}finally{if(a)throw a.error}}return d})}setPublishingLayers(e,t){return g(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:t}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),!(!this.sender||!this.encodings)&&(yield Iu(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return g(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");let e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;let t=this.sender.getParameters();t.encodings=t.encodings.map((i,r)=>{var s;return Object.assign(Object.assign({},i),{active:r===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((s=this.mediaStreamTrack.getSettings().height)!==null&&s!==void 0?s:360)/360)),scalabilityMode:r===0&&It(this.codec)?"L1T3":void 0,maxFramerate:r===0?15:0,maxBitrate:r===0?i.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:t.encodings})),this.encodings=t.encodings,yield this.sender.setParameters(t)}catch(t){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:t})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return g(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Pf()&&this.isInBackground&&this.source===C.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}};function Iu(n,e,t,i,r,s,a){return g(this,void 0,void 0,function*(){let o=yield i.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},a),{sender:n,qualities:t,senderEncodings:e}));try{let c=n.getParameters(),d=c.encodings;if(!d)return;if(d.length!==e.length){s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},a),{encodings:d,senderEncodings:e}));return}let l=!1;!1&&d[0].scalabilityMode||(r&&t.some(f=>f.enabled)&&t.forEach(f=>f.enabled=!0),d.forEach((h,f)=>{var m;let p=(m=h.rid)!==null&&m!==void 0?m:"";p===""&&(p="q");let y=Gf(p),v=t.find(_=>_.quality===y);v&&h.active!==v.enabled&&(l=!0,h.active=v.enabled,s.debug("setting layer ".concat(v.quality," to ").concat(h.active?"enabled":"disabled"),a),fn()&&(v.enabled?(h.scaleResolutionDownBy=e[f].scaleResolutionDownBy,h.maxBitrate=e[f].maxBitrate,h.maxFrameRate=e[f].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))})),l&&(c.encodings=d,s.debug("setting encodings",Object.assign(Object.assign({},a),{encodings:c.encodings})),yield n.setParameters(c))}finally{o()}})}function Gf(n){switch(n){case"f":return Ge.HIGH;case"h":return Ge.MEDIUM;case"q":return Ge.LOW;default:return Ge.HIGH}}function qa(n,e,t,i){if(!t)return[new Bt({quality:Ge.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(i){let r=t[0].scalabilityMode,s=new es(r),a=[],o=s.suffix=="h"?1.5:2,c=s.suffix=="h"?2:3;for(let d=0;d<s.spatial;d+=1)a.push(new Bt({quality:Math.min(Ge.HIGH,s.spatial-1)-d,width:Math.ceil(n/Math.pow(o,d)),height:Math.ceil(e/Math.pow(o,d)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(c,d)):0,ssrc:0}));return a}return t.map(r=>{var s,a,o;let c=(s=r.scaleResolutionDownBy)!==null&&s!==void 0?s:1,d=Gf((a=r.rid)!==null&&a!==void 0?a:"");return new Bt({quality:d,width:Math.ceil(n/c),height:Math.ceil(e/c),bitrate:(o=r.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}var ns=class{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!(typeof this.totalByteSize!="number"||this.totalByteSize===0)){if(e&&this.bytesReceived<this.totalByteSize)throw new fe("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),de.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new fe("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),de.LengthExceeded)}}constructor(e,t,i){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0}handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();let i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,i)}},is=class extends ns{[Symbol.asyncIterator](){let e=this.reader.getReader();e.closed.catch(()=>{});let t=i=>{e.cancel(i).catch(()=>{}),e.releaseLock(),this.signal=void 0};return{next:()=>g(this,void 0,void 0,function*(){var i;try{let r=this.signal;if(r?.aborted)throw r.reason;let s=yield new Promise((a,o)=>{if(r){let c=()=>o(r.reason);r.addEventListener("abort",c,{once:!0}),e.read().then(a,o).finally(()=>{r.removeEventListener("abort",c)})}else e.read().then(a,o)});return s.done?(this.validateBytesReceived(!0),typeof this.totalByteSize=="number"&&((i=this.onProgress)===null||i===void 0||i.call(this,1)),{done:!0,value:void 0}):(this.handleChunkReceived(s.value),{done:!1,value:s.value.content})}catch(r){throw t(r),r}}),return(){return g(this,void 0,void 0,function*(){return t(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return g(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,r,s,a;let o=new Set,c=t.signal?e.withAbortSignal(t.signal):e;try{for(var d=!0,l=ze(c),u;u=yield l.next(),i=u.done,!i;d=!0){a=u.value,d=!1;let h=a;o.add(h)}}catch(h){r={error:h}}finally{try{!d&&!i&&(s=l.return)&&(yield s.call(l))}finally{if(r)throw r.error}}return Array.from(o)})()})}},rs=class extends ns{[Symbol.asyncIterator](){let e=this.reader.getReader();e.closed.catch(()=>{});let t=new TextDecoder("utf-8"),i=this.signal,r=s=>{e.cancel(s).catch(()=>{}),e.releaseLock(),this.signal=void 0};return{next:()=>g(this,void 0,void 0,function*(){var s;try{if(i?.aborted)throw i.reason;let a=yield new Promise((o,c)=>{if(i){let d=()=>c(i.reason);i.addEventListener("abort",d,{once:!0}),e.read().then(o,c).finally(()=>{i.removeEventListener("abort",d)})}else e.read().then(o,c)});if(a.done)return this.validateBytesReceived(!0),typeof this.totalByteSize=="number"&&((s=this.onProgress)===null||s===void 0||s.call(this,1)),{done:!0,value:void 0};{this.handleChunkReceived(a.value);let o;try{o=t.decode(a.value.content)}catch(c){throw new fe("Cannot decode datastream chunk ".concat(a.value.chunkIndex," as text: ").concat(c),de.DecodeFailed)}return{done:!1,value:o}}}catch(a){throw r(a),a}}),return(){return g(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return g(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,r,s,a;let o="",c=t.signal?e.withAbortSignal(t.signal):e;try{for(var d=!0,l=ze(c),u;u=yield l.next(),i=u.done,!i;d=!0)a=u.value,d=!1,o+=a}catch(h){r={error:h}}finally{try{!d&&!i&&(s=l.return)&&(yield s.call(l))}finally{if(r)throw r.error}}return o})()})}},ae=class n extends Error{constructor(e,t,i,r){super(t),this.code=e,this.message=Au(t,n.MAX_MESSAGE_BYTES),this.data=i?Au(i,n.MAX_DATA_BYTES):void 0,typeof r?.cause<"u"&&(this.cause=r?.cause)}static fromProto(e){return new n(e.code,e.message,e.data)}toProto(){return new Yh({code:this.code,message:this.message,data:this.data})}static builtIn(e,t,i){return new n(n.ErrorCode[e],n.ErrorMessage[e],t,i)}};ae.MAX_MESSAGE_BYTES=256;ae.MAX_DATA_BYTES=15360;ae.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,CONNECTION_CLOSED:1506,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404};ae.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",CONNECTION_CLOSED:"Connection closed",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};var Jf=15360,$f="lk.rpc_request",Qf="lk.rpc_response",Ee;(function(n){n.RPC_REQUEST_ID="lk.rpc_request_id",n.RPC_REQUEST_METHOD="lk.rpc_request_method",n.RPC_REQUEST_RESPONSE_TIMEOUT_MS="lk.rpc_request_response_timeout_ms",n.RPC_REQUEST_VERSION="lk.rpc_request_version"})(Ee||(Ee={}));var Nb=1,Yf=2;function ld(n){return new TextEncoder().encode(n).length}function Au(n,e){if(ld(n)<=e)return n;let t=0,i=n.length,r=new TextEncoder;for(;t<i;){let a=Math.floor((t+i+1)/2);r.encode(n.slice(0,a)).length<=e?t=a:i=a-1}let s=t>0?n.charCodeAt(t-1):0;return s>=55296&&s<=56319&&(t-=1),n.slice(0,t)}var ja=class extends Oe.EventEmitter{constructor(e,t,i,r){super(),this.pendingAcks=new Map,this.pendingResponses=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=i,this.getServerVersion=r}performRpc(e){return g(this,arguments,void 0,function(t){var i=this;let r=t.destinationIdentity,s=t.method,a=t.payload,o=t.responseTimeout,c=o===void 0?15e3:o;return(function*(){let u=i.getRemoteParticipantClientProtocol(r);if(ld(a)>Jf&&u<na)throw ae.builtIn("REQUEST_PAYLOAD_TOO_LARGE");let f=i.getServerVersion();if(f&&on(f,"1.8.0")<0)throw ae.builtIn("UNSUPPORTED_SERVER");let m=Math.max(c,8e3),p=pt(),y=new Ce,v=null,_=setTimeout(()=>{var b;i.pendingAcks.delete(p),(b=y.reject)===null||b===void 0||b.call(y,ae.builtIn("CONNECTION_TIMEOUT")),i.pendingResponses.delete(p),v!==null&&clearTimeout(v)},7e3);i.pendingAcks.set(p,{resolve:()=>{clearTimeout(_)},participantIdentity:r}),i.pendingResponses.set(p,{completionFuture:y,participantIdentity:r});let P=y.promise.finally(()=>{v!==null&&clearTimeout(v),i.pendingAcks.has(p)&&(i.log.warn("RPC response received before ack",p),i.pendingAcks.delete(p),clearTimeout(_))});P.catch(()=>{});try{yield i.publishRpcRequest(r,p,s,a,m,u)}catch(b){throw clearTimeout(_),i.pendingAcks.delete(p),i.pendingResponses.delete(p),b}return i.pendingResponses.has(p)&&(v=setTimeout(()=>{var b;i.pendingResponses.delete(p),(b=y.reject)===null||b===void 0||b.call(y,ae.builtIn("RESPONSE_TIMEOUT"))},c)),[p,P]})()})}publishRpcRequest(e,t,i,r,s,a){return g(this,void 0,void 0,function*(){if(a>=na){yield this.outgoingDataStreamManager.sendText(r,{topic:$f,destinationIdentities:[e],attributes:{[Ee.RPC_REQUEST_ID]:t,[Ee.RPC_REQUEST_METHOD]:i,[Ee.RPC_REQUEST_RESPONSE_TIMEOUT_MS]:"".concat(s),[Ee.RPC_REQUEST_VERSION]:"".concat(Yf)}});return}this.emit("sendDataPacket",{packet:new Fe({destinationIdentities:[e],kind:qt.RELIABLE,value:{case:"rpcRequest",value:new Lc({id:t,method:i,payload:r,responseTimeoutMs:s,version:Nb})}})})})}handleIncomingDataStream(e,t,i){return g(this,void 0,void 0,function*(){let r=i[Ee.RPC_REQUEST_ID];if(!r){this.log.warn("RPC data stream malformed: ".concat(Ee.RPC_REQUEST_ID," not set."));return}let s=this.pendingResponses.get(r);if(s&&s.participantIdentity!==t){this.log.warn("RPC response stream for ".concat(r," arrived from unexpected sender ").concat(t,", expected ").concat(s.participantIdentity,". Ignoring."));return}let a;try{a=yield e.readAll()}catch(o){this.log.warn("Error reading RPC response payload: ".concat(o)),this.handleIncomingRpcResponseFailure(r,ae.builtIn("APPLICATION_ERROR","Error reading RPC response payload",{cause:o}));return}this.handleIncomingRpcResponseSuccess(r,a)})}handleIncomingRpcResponseSuccess(e,t){var i,r;let s=this.pendingResponses.get(e);s?((r=(i=s.completionFuture).resolve)===null||r===void 0||r.call(i,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcResponseFailure(e,t){var i,r;let s=this.pendingResponses.get(e);s?((r=(i=s.completionFuture).reject)===null||r===void 0||r.call(i,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcAck(e){let t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):this.log.error("Ack received for unexpected RPC request: ".concat(e))}handleParticipantDisconnected(e){var t;for(let a of this.pendingAcks){var i=F(a,2);let o=i[0];i[1].participantIdentity===e&&this.pendingAcks.delete(o)}for(let a of this.pendingResponses){var r=F(a,2);let o=r[0];var s=r[1];let c=s.participantIdentity,d=s.completionFuture;c===e&&((t=d.reject)===null||t===void 0||t.call(d,ae.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(o))}}handleRoomDisconnected(){var e;for(let t of this.pendingAcks.values()){let i=t.resolve;i()}this.pendingAcks.clear();for(let t of this.pendingResponses.values()){let i=t.completionFuture;(e=i.reject)===null||e===void 0||e.call(i,ae.builtIn("CONNECTION_CLOSED"))}this.pendingResponses.clear()}},Va=class extends Oe.EventEmitter{constructor(e,t,i){super(),this.rpcHandlers=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=i}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}handleIncomingRpcRequest(e,t){return g(this,void 0,void 0,function*(){var i;if(this.publishRpcAck(e,t.id),t.version!==1){this.publishRpcResponsePacket(e,t.id,null,ae.builtIn("UNSUPPORTED_VERSION"));return}let r=this.rpcHandlers.get(t.method);if(!r){this.publishRpcResponsePacket(e,t.id,null,ae.builtIn("UNSUPPORTED_METHOD"));return}let s;try{s=yield r({requestId:t.id,callerIdentity:e,payload:t.payload,responseTimeout:t.responseTimeoutMs})}catch(a){let o;a instanceof ae?o=a:(this.log.warn("Uncaught error returned by RPC handler for ".concat(t.method,". Returning APPLICATION_ERROR instead."),a),o=ae.builtIn("APPLICATION_ERROR","Uncaught error: ".concat((i=a?.message)!==null&&i!==void 0?i:a),{cause:a})),this.publishRpcResponsePacket(e,t.id,null,o);return}yield this.publishRpcResponse(e,t.id,s??"")})}handleIncomingDataStream(e,t,i){return g(this,void 0,void 0,function*(){let r=i[Ee.RPC_REQUEST_ID],s=i[Ee.RPC_REQUEST_METHOD],a=parseInt(i[Ee.RPC_REQUEST_RESPONSE_TIMEOUT_MS],10),o=parseInt(i[Ee.RPC_REQUEST_VERSION],10);if(!r||!s||Number.isNaN(a)||Number.isNaN(o)){this.log.warn("RPC data stream malformed: ".concat(Ee.RPC_REQUEST_ID," / ").concat(Ee.RPC_REQUEST_METHOD," / ").concat(Ee.RPC_REQUEST_RESPONSE_TIMEOUT_MS," / ").concat(Ee.RPC_REQUEST_VERSION," not set.")),this.publishRpcResponsePacket(t,r,null,ae.builtIn("APPLICATION_ERROR","RPC data stream malformed"));return}if(this.publishRpcAck(t,r),o!==Yf){this.publishRpcResponsePacket(t,r,null,ae.builtIn("UNSUPPORTED_VERSION"));return}let c;try{c=yield e.readAll()}catch(u){this.log.warn("Error reading RPC request payload: ".concat(u)),this.publishRpcResponsePacket(t,r,null,ae.builtIn("APPLICATION_ERROR","Error reading RPC request payload",{cause:u}));return}let d=this.rpcHandlers.get(s);if(!d){this.publishRpcResponsePacket(t,r,null,ae.builtIn("UNSUPPORTED_METHOD"));return}let l;try{l=yield d({requestId:r,callerIdentity:t,payload:c,responseTimeout:a})}catch(u){let h;u instanceof ae?h=u:(this.log.warn("Uncaught error returned by RPC handler for ".concat(s,". Returning APPLICATION_ERROR instead."),u),h=ae.builtIn("APPLICATION_ERROR")),this.publishRpcResponsePacket(t,r,null,h);return}yield this.publishRpcResponse(t,r,l??"")})}publishRpcAck(e,t){this.emit("sendDataPacket",{packet:new Fe({destinationIdentities:[e],kind:qt.RELIABLE,value:{case:"rpcAck",value:new vs({requestId:t})}})})}publishRpcResponsePacket(e,t,i,r){this.emit("sendDataPacket",{packet:new Fe({destinationIdentities:[e],kind:qt.RELIABLE,value:{case:"rpcResponse",value:new Dc({requestId:t,value:r?{case:"error",value:r.toProto()}:{case:"payload",value:i??""}})}})})}publishRpcResponse(e,t,i){return g(this,void 0,void 0,function*(){if(this.getRemoteParticipantClientProtocol(e)>=na){yield this.outgoingDataStreamManager.sendText(i,{topic:Qf,destinationIdentities:[e],attributes:{[Ee.RPC_REQUEST_ID]:t}});return}if(ld(i)>Jf){this.log.warn("RPC Response payload too large for request ".concat(t,". To send larger responses, consider updating the sending client.")),this.publishRpcResponsePacket(e,t,null,ae.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"));return}this.publishRpcResponsePacket(e,t,i,null)})}},Fb=300,Wa=class{constructor(){this.metadataMap=new Map,this.activeSsrc=0}storeMetadata(e,t,i){for(this.activeSsrc!==0&&this.activeSsrc!==t&&this.metadataMap.clear(),this.activeSsrc=t;this.metadataMap.size>=Fb;){let r=this.metadataMap.keys().next().value;this.metadataMap.delete(r)}this.metadataMap.set(e,i)}lookupMetadata(e){return this.metadataMap.get(e)}dispose(){this.metadataMap.clear(),this.activeSsrc=0}},Ha=class{constructor(e){this.extractors=new Map,this.workerPipelines=new Map,this.onWorkerMessage=t=>{let i=t.data;if(i.kind==="metadata"){let r=this.extractors.get(i.data.trackId);r&&r.storeMetadata(i.data.rtpTimestamp,i.data.ssrc,i.data.metadata)}},this.onWorkerError=t=>{W.error("frame metadata worker encountered an error:",{error:t.error})},this.worker=e?.worker}setup(e){e!==this.room&&(this.room=e,this.worker&&(this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage({kind:"init"})),e.on(R.TrackSubscribed,(t,i,r)=>{t.kind==="video"&&this.setupReceiver(t,i.trackInfo)}).on(R.TrackUnsubscribed,t=>{this.teardownTrack(t)}).on(R.Disconnected,()=>{this.cleanup()}))}setupReceiver(e,t){var i,r,s;let a=e.receiver;if(!a)return;if(!(!!t?.packetTrailerFeatures&&t.packetTrailerFeatures.length>0)){!((i=this.room)===null||i===void 0)&&i.hasE2EESetup||this.setupPassthroughReceiver(a,e.mediaStreamID);return}if(!Mi(this.worker?{worker:this.worker}:void 0)&&!(!((r=this.room)===null||r===void 0)&&r.hasE2EESetup)){W.warn("frame metadata transform not supported; skipping extraction");return}let c=new Wa,d=e.mediaStreamID;this.extractors.set(d,c),e.frameMetadataExtractor=c,!(!((s=this.room)===null||s===void 0)&&s.hasE2EESetup)&&this.setupWorkerReceiver(a,d,!0)}setupPassthroughReceiver(e,t){if(Ai()){"transform"in e&&(e.transform=null);return}if(this.worker&&Mi({worker:this.worker})&&!this.workerPipelines.has(e)){this.setupWorkerReceiver(e,t,!1);return}this.worker&&this.workerPipelines.has(e)&&this.setupWorkerReceiver(e,t,!1)}setupWorkerReceiver(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=this.worker;if(!r)return;if(Ai()){e.transform=new RTCRtpScriptTransform(r,{kind:"decode",trackId:t});return}let s=this.workerPipelines.get(e);if(s){let c={kind:"updateTrackId",data:{oldTrackId:s,newTrackId:t,hasPacketTrailer:i}};r.postMessage(c),this.workerPipelines.set(e,t);return}if(!("createEncodedStreams"in e)){W.warn("createEncodedStreams not supported");return}let a;try{a=e.createEncodedStreams()}catch(c){W.warn("failed to create encoded streams",{error:c});return}let o={kind:"decode",data:{readableStream:a.readable,writableStream:a.writable,trackId:t,hasPacketTrailer:i}};r.postMessage(o,[a.readable,a.writable]),this.workerPipelines.set(e,t)}teardownTrack(e){let t=e.mediaStreamID,i=this.extractors.get(t);i&&(i.dispose(),this.extractors.delete(t)),e instanceof Li&&(e.frameMetadataExtractor=void 0)}cleanup(){for(let e of this.extractors.values())e.dispose();this.extractors.clear(),this.workerPipelines.clear()}dispose(){var e;this.cleanup(),(e=this.worker)===null||e===void 0||e.terminate()}};function Ub(n,e){let t=new Di(n);return qf(t,e??[]),t}var Nn;(function(n){n.AgentState="lk.agent.state",n.PublishOnBehalf="lk.publish_on_behalf",n.TranscriptionFinal="lk.transcription_final",n.TranscriptionSegmentId="lk.segment_id",n.TranscribedTrackId="lk.transcribed_track_id",n.Expression="lk.expression"})(Nn||(Nn={}));var Ka=class{constructor(e){this.log=W,this.partials=new Map,this.handleTextStream=(t,i)=>g(this,void 0,void 0,function*(){var r,s,a,o,c,d,l,u,h,f;let m=((u=t.info.attributes)===null||u===void 0?void 0:u[Nn.TranscriptionSegmentId])||t.info.id,p=Bb(i,m),y=this.partials.get(p);(!y||y.streamId!==t.info.id)&&this.partials.set(p,{streamId:t.info.id,text:""});let v=new za,_;try{try{for(r=!0,s=ze(t);a=yield s.next(),o=a.done,!o;r=!0){l=a.value,r=!1;let P=l,b=this.partials.get(p);if(!b||b.streamId!==t.info.id)return;b.text+=v.push(P),this.emitSegment(b,m,i,t,(h=this.isFinal(t))!==null&&h!==void 0?h:!1)}}catch(P){c={error:P}}finally{try{!r&&!o&&(d=s.return)&&(yield d.call(s))}finally{if(c)throw c.error}}_=(f=this.isFinal(t))!==null&&f!==void 0?f:!0}catch(P){this.log.debug("lk.transcription stream ended abnormally",P),_=!0}this.closeSegment(p,m,i,t,_,v.flush())}),this.options=e}reset(){this.partials.clear()}closeSegment(e,t,i,r,s,a){let o=this.partials.get(e);!o||o.streamId!==r.info.id||(o.text+=a,this.emitSegment(o,t,i,r,s),s&&this.partials.delete(e))}resolveSpeaker(e,t){var i;let r=this.options.getDelegatingPublisherIdentity(e)||e,s=((i=t.info.attributes)===null||i===void 0?void 0:i[Nn.TranscribedTrackId])||this.options.getMicrophoneTrackSid(r)||this.options.getMicrophoneTrackSid(e)||"";return{identity:r,trackId:s}}emitSegment(e,t,i,r,s){if(typeof e.emittedText>"u"&&e.text===""||e.emittedText===e.text&&e.emittedFinal===s)return;e.emittedText=e.text,e.emittedFinal=s;let a=this.resolveSpeaker(i,r),o=a.identity,c=a.trackId;this.options.onTranscription(new $h({transcribedParticipantIdentity:o,trackId:c,segments:[new Qh({id:t,text:e.text,startTime:BigInt(0),endTime:BigInt(0),final:s,language:""})]}))}isFinal(e){var t;let i=(t=e.info.attributes)===null||t===void 0?void 0:t[Nn.TranscriptionFinal];if(!(typeof i>"u"))return i==="true"||i==="1"||i===!0}};function Bb(n,e){return"".concat(n,"/").concat(e)}var za=class{constructor(){this.buffered=""}push(e){var t,i;if((t=this.json)!==null&&t!==void 0||(this.json=e.trim()===""?void 0:e.trim().startsWith('{"')),!this.json)return e;this.buffered+=e;let r=this.buffered.split(`
47
47
  `);return this.buffered=(i=r.pop())!==null&&i!==void 0?i:"",r.map(s=>{var a;return(a=Mu(s))!==null&&a!==void 0?a:"".concat(s,`
48
- `)}).join("")}flush(){var e;let t=this.buffered;return this.buffered="",(e=Mu(t))!==null&&e!==void 0?e:t}};function Mu(n){let e=n.trim();if(!(!e.startsWith("{")||!e.endsWith("}")))try{let t=JSON.parse(e);if(t!==null&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{}}function Ro(){return new CompressionStream("deflate-raw")}function Xf(){return new DecompressionStream("deflate-raw")}function Ou(n,e){return g(this,void 0,void 0,function*(){let t=new DecompressionStream("deflate-raw"),i=t.writable.getWriter();return i.write(n).catch(()=>{}),i.close().catch(()=>{}),Zf(t.readable,e)})}function Zf(n,e){return g(this,void 0,void 0,function*(){let t=n.getReader(),i=[],r=0;for(;;){let o=yield t.read(),c=o.done,d=o.value;if(c)break;if(i.push(d),r+=d.byteLength,typeof e=="number"&&r>e)throw yield t.cancel(),new fe("Decompressed payload exceeds the maximum payload size of ".concat(e," bytes"),de.PayloadTooLarge)}let s=new Uint8Array(r),a=0;for(let o of i)s.set(o,a),a+=o.byteLength;return s})}var Zt=15e3,qb=5e9,jb=500,Vb="lk.transcription",Ga=class extends Oe.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=e.maxPayloadByteLength,i=t===void 0?qb:t,r=e.maxOpenStreamsPerParticipant,s=r===void 0?jb:r;super(),this.log=W,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.isConnected=!1,this.bufferedPackets=[],this.maxPayloadByteLength=i,this.maxOpenStreamsPerParticipant=s}setConnected(e){this.isConnected=e,e&&this.flushBufferedPackets()}flushBufferedPackets(){let e=this.bufferedPackets;this.bufferedPackets=[];for(let t of e){let i=t.packet,r=t.encryptionType;this.handleDataStreamPacket(i,r)}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new fe('A text stream handler for topic "'.concat(e,'" has already been set.'),de.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new fe('A byte stream handler for topic "'.concat(e,'" has already been set.'),de.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){let e=new fe("Room disconnected in the middle of receiving data",de.AbnormalEnd);for(let t of this.byteStreamControllers.values())t.controller.error(e);for(let t of this.textStreamControllers.values())for(let i of t.controllers)i.error(e);this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.bufferedPackets=[]}validateParticipantHasNoActiveDataStreams(e){let t=Array.from(this.textStreamControllers.entries()).filter(a=>F(a,2)[1].sendingParticipantIdentity===e),i=Array.from(this.byteStreamControllers.entries()).filter(a=>a[1].sendingParticipantIdentity===e);if(t.length>0||i.length>0){let a=new fe("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),de.AbnormalEnd);for(let o of i){var r=F(o,2);let c=r[0];r[1].controller.error(a),this.byteStreamControllers.delete(c)}for(let o of t){var s=F(o,2);let c=s[0],d=s[1];for(let l of d.controllers)l.error(a);this.textStreamControllers.delete(c)}}}handleDataStreamPacket(e,t){if(!this.isConnected){this.bufferedPackets.push({packet:e,encryptionType:t});return}switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case"streamChunk":return this.handleStreamChunk(e.value.value,t);case"streamTrailer":return this.handleStreamTrailer(e.value.value,t);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}}hasTooManyOpenStreams(e){let t=0;for(let i of[this.byteStreamControllers,this.textStreamControllers])for(let r of i.values())r.sendingParticipantIdentity===e&&(t+=1);return t>=this.maxOpenStreamsPerParticipant}handleStreamHeader(e,t,i){var r;if(this.hasTooManyOpenStreams(t)){this.log.error("Participant ".concat(t," already has ").concat(this.maxOpenStreamsPerParticipant," data streams open, dropping stream ").concat(e.streamId));return}switch(e.contentHeader.case){case"byteHeader":{let s=this.byteStreamHandlers.get(e.topic);if(!s){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let a,o={id:e.streamId,name:(r=e.contentHeader.value.name)!==null&&r!==void 0?r:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:kn(e.timestamp),attributes:e.attributes,encryptionType:i},c;switch(e.compression){case Ae.DEFLATE_RAW:if(!On()){W.warn("Data stream ".concat(e.streamId," received with deflate-raw compression, but this browser does not support deflate-raw decompression. Dropping..."));return}c=!0;break;case Ae.NONE:c=!1;break;default:W.warn("Data stream ".concat(e.streamId," received with unknown compression type ").concat(e.compression,", dropping..."));return}let d=e.inlineContent;if(typeof d<"u"){s(new is(o,xu(e.streamId,c?Ou(d,this.maxPayloadByteLength):d),kn(e.totalLength)),{identity:t});return}let l=new ReadableStream({start:u=>{if(a=u,this.byteStreamControllers.has(e.streamId))throw new fe("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),de.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:o,controller:a,startTime:Date.now(),sendingParticipantIdentity:t})},cancel:()=>{var u;((u=this.byteStreamControllers.get(e.streamId))===null||u===void 0?void 0:u.controller)===a&&this.byteStreamControllers.delete(e.streamId)}});s(new is(o,c?Kb(l,e.streamId,this.maxPayloadByteLength):l.pipeThrough(ss(e.streamId)),kn(e.totalLength)),{identity:t});return}case"textHeader":{let s=[];e.topic===Vb&&this.listenerCount("transcriptionStreamArrived")>0&&s.push((u,h)=>{let f=h.identity;this.emit("transcriptionStreamArrived",{reader:u,participantIdentity:f})});let a=this.textStreamHandlers.get(e.topic);if(a&&s.push(a),s.length===0){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let o={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:i,attachedStreamIds:e.contentHeader.value.attachedStreamIds},c;switch(e.compression){case Ae.DEFLATE_RAW:if(!On()){W.warn("Data stream ".concat(e.streamId," received with deflate-raw compression, but this browser does not support deflate-raw decompression. Dropping..."));return}c=!0;break;case Ae.NONE:c=!1;break;default:W.warn("Data stream ".concat(e.streamId," received with unknown compression type ").concat(e.compression,", dropping..."));return}let d=e.inlineContent;if(typeof d<"u"){let u=c?Ou(d,this.maxPayloadByteLength):d;for(let h of s)h(new rs(o,xu(e.streamId,u),kn(e.totalLength)),{identity:t});return}if(this.textStreamControllers.has(e.streamId))throw new fe("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),de.AlreadyOpened);let l={info:o,sendingParticipantIdentity:t,controllers:[]};this.textStreamControllers.set(e.streamId,l);for(let u of s){let h,f=new ReadableStream({start:m=>{h=m,l.controllers.push(m)},cancel:()=>{let m=l.controllers.indexOf(h);m!==-1&&l.controllers.splice(m,1),l.controllers.length===0&&this.textStreamControllers.get(e.streamId)===l&&this.textStreamControllers.delete(e.streamId)}});u(new rs(o,c?zb(f,e.streamId,this.maxPayloadByteLength):f.pipeThrough(ss(e.streamId)),kn(e.totalLength)),{identity:t})}return}}}handleStreamChunk(e,t){let i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?(i.controller.error(new fe("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),de.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):i.controller.enqueue(e));let r=this.textStreamControllers.get(e.streamId);if(r)if(r.info.encryptionType!==t){let s=new fe("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(r.info.encryptionType),de.EncryptionTypeMismatch);for(let a of r.controllers)a.error(s);this.textStreamControllers.delete(e.streamId)}else for(let s of r.controllers)s.enqueue(e)}handleStreamTrailer(e,t){let i=this.textStreamControllers.get(e.streamId);if(i){if(i.info.encryptionType!==t){let s=new fe("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),de.EncryptionTypeMismatch);for(let a of i.controllers)a.error(s)}else if(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),e.reason){let s=new fe("Data stream ".concat(e.streamId," closed abnormally: ").concat(e.reason),de.AbnormalEnd);for(let a of i.controllers)a.error(s)}else for(let s of i.controllers)s.close();this.textStreamControllers.delete(e.streamId)}let r=this.byteStreamControllers.get(e.streamId);r&&(r.info.encryptionType!==t?r.controller.error(new fe("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(r.info.encryptionType),de.EncryptionTypeMismatch)):(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),e.attributes),e.reason?r.controller.error(new fe("Data stream ".concat(e.streamId," closed abnormally: ").concat(e.reason),de.AbnormalEnd)):r.controller.close()),this.byteStreamControllers.delete(e.streamId))}};function xu(n,e){return new ReadableStream({start:t=>g(this,void 0,void 0,function*(){let i=yield e;t.enqueue(new Pt({streamId:n,chunkIndex:BigInt(0),content:i})),t.close()})})}function ss(n){let e=-1;return new TransformStream({transform:(t,i)=>{let r=kn(t.chunkIndex);if(r<=e){W.warn("ignoring duplicate chunk ".concat(r," ").concat(t.version>0?"(version ".concat(t.version,")"):""," for data stream ").concat(n," (last processed: ").concat(e,")"));return}if(r>e+1)throw new fe("Missing chunk(s) ".concat(e+1,"..").concat(r-1," for data stream ").concat(n," - cannot reassemble payload"),de.Incomplete);e=r,t.content.length!==0&&i.enqueue(t)}})}function ep(){return new TransformStream({transform:(n,e)=>{e.enqueue(n.content)}})}function Wb(n){let e=0;return new TransformStream({transform:(t,i)=>{t.byteLength>0&&(i.enqueue(new Pt({streamId:n,chunkIndex:at(e),content:t})),e+=1)}})}function Hb(n){let e=new TextDecoder("utf-8"),t=new TextEncoder,i=0,r=s=>{try{return s?e.decode(s,{stream:!0}):e.decode()}catch(a){throw new fe("Cannot decode compressed data stream ".concat(n," as text: ").concat(a),de.DecodeFailed)}};return new TransformStream({transform:(s,a)=>{let o=r(s);o.length>0&&(a.enqueue(new Pt({streamId:n,chunkIndex:at(i),content:t.encode(o)})),i+=1)},flush:s=>{let a=r();a.length>0&&(s.enqueue(new Pt({streamId:n,chunkIndex:at(i),content:t.encode(a)})),i+=1)}})}function Kb(n,e,t){return n.pipeThrough(ss(e)).pipeThrough(ep()).pipeThrough(Xf()).pipeThrough(tp(e,t)).pipeThrough(Wb(e))}function zb(n,e,t){return n.pipeThrough(ss(e)).pipeThrough(ep()).pipeThrough(Xf()).pipeThrough(tp(e,t)).pipeThrough(Hb(e))}function tp(n,e){let t=0;return new TransformStream({transform:(i,r)=>{if(t+=i.byteLength,t>e)throw new fe("Data stream ".concat(n," exceeds the maximum payload size of ").concat(e," bytes"),de.PayloadTooLarge);r.enqueue(i)}})}var os=class{constructor(e,t,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return g(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)===null||e===void 0||e.call(this)})}},Ja=class extends os{},$a=class extends os{};function Io(n,e,t){var i;return new ys({streamId:n.id,mimeType:n.mimeType,topic:n.topic,timestamp:at(n.timestamp),totalLength:at(n.size),attributes:n.attributes,compression:(i=t?.compression)!==null&&i!==void 0?i:Ae.NONE,inlineContent:t?.inlineContent,contentHeader:{case:"textHeader",value:new sf({version:e?.version,attachedStreamIds:n.attachedStreamIds,replyToStreamId:e?.replyToStreamId,operationType:e?.type==="update"?Qo.UPDATE:Qo.CREATE})}})}function dr(n,e){var t;return new ys({streamId:n.id,mimeType:n.mimeType,topic:n.topic,timestamp:at(n.timestamp),totalLength:at(n.size),attributes:n.attributes,compression:(t=e?.compression)!==null&&t!==void 0?t:Ae.NONE,inlineContent:e?.inlineContent,contentHeader:{case:"byteHeader",value:new of({name:n.name})}})}function Yt(n,e){return new Fe({destinationIdentities:e,value:{case:"streamHeader",value:n}})}var Gb=new TextEncoder,Qa=class{constructor(e,t,i,r,s){this.engine=e,this.log=t,this.getRemoteParticipantClientProtocol=i,this.getRemoteParticipantCapabilities=r,this.getAllRemoteParticipantIdentities=s}setupEngine(e){this.engine=e}sendText(e,t){return g(this,void 0,void 0,function*(){var i,r,s,a,o;let c=pt(),d=Gb.encode(e),l=d.byteLength,u=(i=t?.compress)!==null&&i!==void 0?i:!0,h={id:c,mimeType:"text/plain",timestamp:Date.now(),topic:(r=t?.topic)!==null&&r!==void 0?r:"",size:l,attributes:t?.attributes,encryptionType:!((s=this.engine.e2eeManager)===null||s===void 0)&&s.isDataChannelEncryptionEnabled?X.GCM:X.NONE},m=u&&On()&&this.allRecipientsSupportV2(t?.destinationIdentities)&&this.allRecipientsSupportCompression(t?.destinationIdentities)?as.fromStream(_r(d).pipeThrough(Ro())):null;if((!t?.attachments||t.attachments.length===0)&&this.allRecipientsSupportV2(t?.destinationIdentities)){let b=d,k=Ae.NONE;if(m){let O=yield m.collect();O.byteLength<d.byteLength&&(b=O,k=Ae.DEFLATE_RAW)}let S=Io(h,void 0,{compression:k,inlineContent:b}),E=Yt(S,t?.destinationIdentities);if(E.toBinary().byteLength<=Zt)return yield this.engine.sendDataPacket(E,z.RELIABLE),(a=t?.onProgress)===null||a===void 0||a.call(t,1),h}let y=(o=t?.attachments)===null||o===void 0?void 0:o.map(()=>pt()),v=y?y.length+1:1,_=new Array(v).fill(0),P=(b,k)=>{var S;_[k]=b,(S=t?.onProgress)===null||S===void 0||S.call(t,_.reduce((E,O)=>E+O,0)/v)};if(m){h.attachedStreamIds=y;let b=Io(h,void 0,{compression:Ae.DEFLATE_RAW}),k=Yt(b,t?.destinationIdentities);yield this.sendChunkedByteStream(k,c,t?.destinationIdentities,m.stream().pipeThrough(Ao(d.length,S=>P(S,0)))),d.length===0&&P(1,0)}else{let b=yield this.streamText({streamId:c,totalSize:l,destinationIdentities:t?.destinationIdentities,topic:t?.topic,attachedStreamIds:y,attributes:t?.attributes});yield b.write(e),P(1,0),yield b.close(),h=b.info}return t?.attachments&&y&&(yield Promise.all(t.attachments.map((b,k)=>g(this,void 0,void 0,function*(){return this._sendFile(y[k],b,{topic:t.topic,mimeType:b.type,destinationIdentities:t.destinationIdentities,compress:t.compress,onProgress:S=>{P(S,k+1)}})})))),h})}sendBytes(e,t){return g(this,void 0,void 0,function*(){var i,r,s,a,o,c,d;let l=pt(),u=t?.destinationIdentities,h=(i=t?.compress)!==null&&i!==void 0?i:!0,f={id:l,name:(r=t?.name)!==null&&r!==void 0?r:"unknown",mimeType:(s=t?.mimeType)!==null&&s!==void 0?s:"application/octet-stream",timestamp:Date.now(),topic:(a=t?.topic)!==null&&a!==void 0?a:"",size:e.byteLength,attributes:t?.attributes,encryptionType:!((o=this.engine.e2eeManager)===null||o===void 0)&&o.isDataChannelEncryptionEnabled?X.GCM:X.NONE},m=Ao(e.length,t?.onProgress),y=h&&On()&&this.allRecipientsSupportV2(u)&&this.allRecipientsSupportCompression(u)?as.fromStream(_r(e).pipeThrough(m).pipeThrough(Ro())):null;if(this.allRecipientsSupportV2(u)){let b=e,k=Ae.NONE;if(y){let O=yield y.collect();O.byteLength<e.byteLength&&(b=O,k=Ae.DEFLATE_RAW)}let S=dr(f,{compression:k,inlineContent:b}),E=Yt(S,u);if(E.toBinary().byteLength<=Zt)return yield this.engine.sendDataPacket(E,z.RELIABLE),(c=t?.onProgress)===null||c===void 0||c.call(t,1),f}let v=dr(f,{compression:y?Ae.DEFLATE_RAW:Ae.NONE}),_=Yt(v,u),P=y?y.stream():_r(e).pipeThrough(m);return yield this.sendChunkedByteStream(_,l,u,P),e.length===0&&((d=t?.onProgress)===null||d===void 0||d.call(t,1)),f})}allRecipientsSupportV2(e){return(e&&e.length>0?e:this.getAllRemoteParticipantIdentities()).every(i=>this.getRemoteParticipantClientProtocol(i)>=Jv)}allRecipientsSupportCompression(e){return(e&&e.length>0?e:this.getAllRemoteParticipantIdentities()).every(i=>this.getRemoteParticipantCapabilities(i).includes(Pi.CAP_COMPRESSION_DEFLATE_RAW))}sendChunkedByteStream(e,t,i,r){return g(this,void 0,void 0,function*(){var s,a,o,c;let d=this.engine;yield Mo(d,e);let l=0;try{for(var u=!0,h=ze(By(r,Zt)),f;f=yield h.next(),s=f.done,!s;u=!0){c=f.value,u=!1;let m=c,p=new Fe({destinationIdentities:i,value:{case:"streamChunk",value:new Pt({content:m,streamId:t,chunkIndex:at(l)})}});yield d.sendDataPacket(p,z.RELIABLE),l+=1}}catch(m){a={error:m}}finally{try{!u&&!s&&(o=h.return)&&(yield o.call(h))}finally{if(a)throw a.error}}yield Oo(t,i,d)})}streamText(e){return g(this,void 0,void 0,function*(){var t,i,r;let s=(t=e?.streamId)!==null&&t!==void 0?t:pt(),a=e?.destinationIdentities,o={id:s,mimeType:"text/plain",timestamp:Date.now(),topic:(i=e?.topic)!==null&&i!==void 0?i:"",size:e?.totalSize,attributes:e?.attributes,encryptionType:!((r=this.engine.e2eeManager)===null||r===void 0)&&r.isDataChannelEncryptionEnabled?X.GCM:X.NONE,attachedStreamIds:e?.attachedStreamIds},c=Io(o,e),d=Yt(c,a);yield Mo(this.engine,d);let l=0,u=this.engine,h=new WritableStream({write(p){return g(this,void 0,void 0,function*(){for(let y of Uy(p,Zt)){let v=new Pt({content:y,streamId:s,chunkIndex:at(l)}),_=new Fe({destinationIdentities:a,value:{case:"streamChunk",value:v}});yield u.sendDataPacket(_,z.RELIABLE),l+=1}})},close(){return g(this,void 0,void 0,function*(){yield Oo(s,a,u)})},abort(p){console.log("Sink error:",p)}}),f=()=>g(this,void 0,void 0,function*(){yield m.close()});u.once(A.Closing,f);let m=new Ja(h,o,()=>this.engine.off(A.Closing,f));return m})}sendFile(e,t){return g(this,void 0,void 0,function*(){let i=pt();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return g(this,void 0,void 0,function*(){var r,s,a,o,c;let d=i?.destinationIdentities,l=((r=i?.compress)!==null&&r!==void 0?r:!0)&&On()&&this.allRecipientsSupportV2(d)&&this.allRecipientsSupportCompression(d),u={id:e,name:t.name,mimeType:(s=i?.mimeType)!==null&&s!==void 0?s:t.type,topic:(a=i?.topic)!==null&&a!==void 0?a:"",timestamp:Date.now(),size:t.size,encryptionType:!((o=this.engine.e2eeManager)===null||o===void 0)&&o.isDataChannelEncryptionEnabled?X.GCM:X.NONE},h=dr(u,{compression:l?Ae.DEFLATE_RAW:Ae.NONE}),f=Yt(h,d),m=t.stream().pipeThrough(Ao(t.size,i?.onProgress)),p=l?m.pipeThrough(Ro()):m;return yield this.sendChunkedByteStream(f,e,d,p),t.size===0&&((c=i?.onProgress)===null||c===void 0||c.call(i,1)),u})}streamBytes(e){return g(this,void 0,void 0,function*(){var t,i,r,s,a;let o=(t=e?.streamId)!==null&&t!==void 0?t:pt(),c=e?.destinationIdentities,d={id:o,mimeType:(i=e?.mimeType)!==null&&i!==void 0?i:"application/octet-stream",topic:(r=e?.topic)!==null&&r!==void 0?r:"",timestamp:Date.now(),attributes:e?.attributes,size:e?.totalSize,name:(s=e?.name)!==null&&s!==void 0?s:"unknown",encryptionType:!((a=this.engine.e2eeManager)===null||a===void 0)&&a.isDataChannelEncryptionEnabled?X.GCM:X.NONE},l=dr(d),u=Yt(l,c);yield Mo(this.engine,u);let h=0,f=new ye,m=this.engine,p=this.log,y=new WritableStream({write(_){return g(this,void 0,void 0,function*(){let P=yield f.lock(),b=0;try{for(;b<_.byteLength;){let k=_.slice(b,b+Zt),S=new Fe({destinationIdentities:c,value:{case:"streamChunk",value:new Pt({content:k,streamId:o,chunkIndex:at(h)})}});yield m.sendDataPacket(S,z.RELIABLE),h+=1,b+=k.byteLength}}finally{P()}})},close(){return g(this,void 0,void 0,function*(){yield Oo(o,c,m)})},abort(_){p.error("Sink error:",_)}});return new $a(y,d)})}},as=class n{constructor(e){this.state=e}static fromStream(e){return new n({type:"stream",stream:e})}collect(){return g(this,void 0,void 0,function*(){switch(this.state.type){case"stream":let e=yield Zf(this.state.stream);return this.state={type:"collected",bytes:e},e;case"collected":return this.state.bytes}})}stream(){switch(this.state.type){case"stream":return this.state.stream;case"collected":return _r(this.state.bytes)}}};function Ao(n,e){let t=0;return new TransformStream({transform(i,r){t+=i.byteLength,e&&typeof n=="number"&&n>0&&e(Math.min(t/n,1)),r.enqueue(i)}})}function Mo(n,e){return g(this,void 0,void 0,function*(){if(e.toBinary().byteLength>Zt)throw new fe("data stream header exceeds the ".concat(Zt,"-byte limit; reduce attribute size"),de.HeaderTooLarge);yield n.sendDataPacket(e,z.RELIABLE)})}function Oo(n,e,t){return g(this,void 0,void 0,function*(){let i=new Fe({destinationIdentities:e,value:{case:"streamTrailer",value:new Nc({streamId:n})}});yield t.sendDataPacket(i,z.RELIABLE)})}var cs=sd("dataStreams",[],(n,e,t)=>{let i=new Ga(t??n.options.dataStream),r=new Qa(n.engine,e.log,d=>{var l,u;return(u=(l=n.remoteParticipants.get(d))===null||l===void 0?void 0:l.clientProtocol)!==null&&u!==void 0?u:zc},d=>{var l,u;return(u=(l=n.remoteParticipants.get(d))===null||l===void 0?void 0:l.capabilities)!==null&&u!==void 0?u:[]},()=>Array.from(n.remoteParticipants.keys())),s=d=>{var l;let u=n.getParticipantByIdentity(d);for(let h of(l=u?.trackPublications.values())!==null&&l!==void 0?l:[])if(h.source===C.Source.Microphone)return h.trackSid},a=d=>{for(let l of n.remoteParticipants.values())if(l.attributes[Nn.PublishOnBehalf]===d)return l.identity},o=new Ka({onTranscription:d=>e.handleTranscription(d),getMicrophoneTrackSid:s,getDelegatingPublisherIdentity:a});i.on("transcriptionStreamArrived",d=>{let l=d.reader,u=d.participantIdentity;o.handleTextStream(l,u)});let c=(d,l,u)=>i.handleDataStreamPacket(l,u);return n.on(R.ConnectionStateChanged,d=>i.setConnected(d===G.Connected)).on(R.ParticipantDisconnected,d=>i.validateParticipantHasNoActiveDataStreams(d.identity)),{incoming:i,outgoing:r,byteStreamOpener:d=>r.streamBytes(d),dataPackets:{streamHeader:c,streamChunk:c,streamTrailer:c},onEngineCreated:d=>r.setupEngine(d),onDisconnect:()=>{o.reset(),i.clearControllers()},room:{registerTextStreamHandler:(d,l)=>i.registerTextStreamHandler(d,l),unregisterTextStreamHandler:d=>i.unregisterTextStreamHandler(d),registerByteStreamHandler:(d,l)=>i.registerByteStreamHandler(d,l),unregisterByteStreamHandler:d=>i.unregisterByteStreamHandler(d)},localParticipant:{sendText:(d,l)=>r.sendText(d,l),streamText:d=>r.streamText(d),sendFile:(d,l)=>r.sendFile(d,l),sendBytes:(d,l)=>r.sendBytes(d,l),streamBytes:d=>r.streamBytes(d)}}}),np={deviceId:{ideal:"default"},resolution:_i.h720.resolution},Jb={simulcast:!0,screenShareEncoding:Ec.h1080fps15.encoding,videoCodec:xr,backupCodec:!0},$b={defaults:np,createTrack:(n,e,t,i)=>new ts(n,e,t,i)};function ud(){ub($b)}function Qb(n){return g(this,void 0,void 0,function*(){return ud(),(yield Es({audio:!1,video:n??!0}))[0]})}function Yb(n,e){let t=n.localParticipant,i=n.options;return{prepareInitial(r,s,a){var o,c,d;if((o=s.videoCodec)!==null&&o!==void 0||(s.videoCodec=xr),s.backupCodec=Lu(s.backupCodec),!["vp8","h264"].includes(s.videoCodec)||s.scalabilityMode||typeof s.backupCodec=="object"&&s.backupCodec.codec!==s.videoCodec)return;a.width=r.width,a.height=r.height,r.frameRate&&s.videoEncoding&&(s.videoEncoding=Object.assign(Object.assign({},s.videoEncoding),{maxFramerate:(c=s.videoEncoding.maxFramerate)!==null&&c!==void 0?c:r.frameRate}));let l=Si(!1,r.width,r.height,s);if(r.frameRate)for(let u of l)u.maxFramerate=Math.min((d=u.maxFramerate)!==null&&d!==void 0?d:r.frameRate,r.frameRate);return a.layers=qa(r.width,r.height,l),a.simulcastCodecs=[new kr({codec:s.videoCodec,layers:a.layers})],{encodings:l,startBitrate:Eu(s.videoCodec,s,l)}},prepare(r,s,a){return g(this,void 0,void 0,function*(){var o,c,d,l;!wy()&&n.hasE2EESetup&&(e.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2"),s.simulcast=!1),r.source===C.Source.ScreenShare&&fn()&&(s.simulcast=!1),s.videoCodec==="av1"&&!ly()&&(s.videoCodec=void 0),s.videoCodec==="vp9"&&!uy()&&(s.videoCodec=void 0),s.videoCodec===void 0&&(s.videoCodec=xr),t.enabledPublishVideoCodecs.length>0&&(t.enabledPublishVideoCodecs.some(y=>s.videoCodec===mi(y.mime))||(s.videoCodec=mi(t.enabledPublishVideoCodecs[0].mime)));let u=s.videoCodec,h;try{h=yield r.waitForDimensions()}catch{let v=(c=(o=i.videoCaptureDefaults)===null||o===void 0?void 0:o.resolution)!==null&&c!==void 0?c:_i.h720.resolution;h={width:v.width,height:v.height},e.error("could not determine track dimensions, using defaults",Object.assign(Object.assign({},K(r)),{dims:h}))}a.width=h.width,a.height=h.height,It(u)&&r.source===C.Source.ScreenShare&&(s.scalabilityMode="L1T3","contentHint"in r.mediaStreamTrack&&(r.mediaStreamTrack.contentHint="motion",e.debug("forcing contentHint to motion for screenshare with SVC codecs",K(r)))),In(u,s)&&(Ef()||!py((d=n.engine)===null||d===void 0?void 0:d.serverVersion))&&(s.simulcast=!1,e.info("SVC simulcast is not supported, disabling simulcast.",K(r)));let f=In(u,s);It(u)&&!f&&(s.scalabilityMode=(l=s.scalabilityMode)!==null&&l!==void 0?l:"L3T3_KEY");let m=new kr({codec:u,cid:r.mediaStreamTrack.id});f&&(m.videoLayerMode=Mc.ONE_SPATIAL_LAYER_PER_STREAM),a.simulcastCodecs=[m],s.backupCodec=Lu(s.backupCodec),s.backupCodec&&u!==s.backupCodec.codec&&a.encryption===X.NONE&&(i.dynacast||(i.dynacast=!0),a.simulcastCodecs.push(new kr({codec:s.backupCodec.codec,cid:""})));let p=Si(r.source===C.Source.ScreenShare,a.width,a.height,s);return a.layers=qa(a.width,a.height,p,It(s.videoCodec)&&!In(s.videoCodec,s)),p})},senderCreated(r,s,a,o){var c,d;if((c=s.degradationPreference)!==null&&c!==void 0||(s.degradationPreference=Lb(r)),r.setDegradationPreference(s.degradationPreference),a&&r.codec&&Af(r.codec)){let l=Eu(r.codec,s,a);l>0&&((d=n.engine.pcManager)===null||d===void 0||d.publisher.setTrackCodecBitrate({cid:o.cid,codec:r.codec,maxbr:l/1e3,isScreenShare:r.source===C.Source.ScreenShare}))}},serverCodecChanged(r,s,a,o){let c;if(a.codecs.forEach(l=>{c===void 0&&(c=l.mimeType)}),!c)return;let d=mi(c);if(d!==s.videoCodec)return e.debug("falling back to server selected codec",Object.assign(Object.assign({},K(r)),{codec:d})),s.videoCodec=d,Si(r.source===C.Source.ScreenShare,o.width,o.height,s)},createScreenTracks:r=>ip(n,r)}}function ip(n,e){return g(this,void 0,void 0,function*(){let t=n.localParticipant;if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Ri("getDisplayMedia not supported");e.resolution===void 0&&!ky()&&(e.resolution=Ec.h1080fps30.resolution);let i=ty(e),r=yield navigator.mediaDevices.getDisplayMedia(i),s=r.getVideoTracks();if(s.length===0)throw new le("no video track found");let a=new ts(s[0],void 0,!1,t.trackLoggerOptions);a.source=C.Source.ScreenShare,e.contentHint&&(a.mediaStreamTrack.contentHint=e.contentHint);let o=[a];if(r.getAudioTracks().length>0){t.emit(L.AudioStreamAcquired);let c=new jn(r.getAudioTracks()[0],void 0,!1,t.audioContext,t.trackLoggerOptions);c.source=C.Source.ScreenShareAudio,o.push(c)}return o})}function Xb(n){return g(this,void 0,void 0,function*(){let e=n.localParticipant;if(!(e.pendingPublishing.has(C.Source.Camera)||e.pendingPublishing.has(C.Source.Microphone))){e.pendingPublishing.add(C.Source.Camera),e.pendingPublishing.add(C.Source.Microphone);try{let t=yield e.createTracks({audio:!0,video:!0});yield Promise.all(t.map(i=>e.publishTrack(i)))}finally{e.pendingPublishing.delete(C.Source.Camera),e.pendingPublishing.delete(C.Source.Microphone)}}})}function rp(n,e,t,i,r){return g(this,void 0,void 0,function*(){var s;let a=n.localParticipant;if(a.isE2EEEnabled)return;let o;if(a.trackPublications.forEach(S=>{S.track&&S.track===t&&(o=S)}),!o)throw new le("track is not published");if(!We(t))throw new le("track is not a video track");let c=Object.assign(Object.assign({},(s=n.options)===null||s===void 0?void 0:s.publishDefaults),r),d=zf(t,i,c);if(!d){e.info("backup codec has been disabled, ignoring request to add additional codec for track",K(t));return}let l=t.addSimulcastTrack(i,d);if(!l)return;let u=a.normalizeRequestedFrameMetadataOptions(t,c),h=t.mediaStreamTrack.getSettings(),f=h.width,m=h.height,p=f&&m?{width:f,height:m}:void 0;p||e.warn("could not determine track dimensions, publishing backup codec without layers",K(t));let y=p?qa(p.width,p.height,d):[],v=new dn({cid:l.mediaStreamTrack.id,type:C.kindToProto(t.kind),muted:t.isMuted,source:C.sourceToProto(t.source),sid:t.sid,width:p?.width,height:p?.height,packetTrailerFeatures:u,layers:y,simulcastCodecs:[{codec:c.videoCodec,cid:l.mediaStreamTrack.id,layers:y}]}),_=n.engine;if(!_||_.isClosed)throw new J("cannot publish track when not connected");let P=()=>g(this,void 0,void 0,function*(){yield _.createSimulcastSender(t,l,c,d),yield _.negotiate()}),k=(yield Promise.all([_.addTrack(v),P()]))[0];e.debug("published ".concat(i," for track ").concat(t.sid),{encodings:d,trackInfo:k})})}function Zb(n,e,t){return g(this,void 0,void 0,function*(){var i,r,s,a,o;if(!(!((o=n.options)===null||o===void 0)&&o.dynacast))return;let c=n.localParticipant.videoTrackPublications.get(t.trackSid);if(!c){e.warn("received subscribed quality update for unknown track",{trackSid:t.trackSid});return}if(!c.videoTrack)return;let d=yield c.videoTrack.setPublishingCodecs(t.subscribedCodecs);try{for(var l=!0,u=ze(d),h;h=yield u.next(),i=h.done,!i;l=!0){a=h.value,l=!1;let f=a;kh(f)&&(e.debug("publish ".concat(f," for ").concat(c.videoTrack.sid),K(c)),yield rp(n,e,c.videoTrack,f,c.options))}}catch(f){r={error:f}}finally{try{!l&&!i&&(s=u.return)&&(yield s.call(u))}finally{if(r)throw r.error}}})}function Lu(n){return n===!0?{codec:xr}:n}var sp={key:Symbol("lk.extension.video"),install(n,e){ud(),n.options.videoCaptureDefaults=Object.assign(Object.assign({},np),n.options.videoCaptureDefaults),n.options.publishDefaults=Object.assign(Object.assign({},Jb),n.options.publishDefaults);let t=n.localParticipant;return{videoPublisher:Yb(n,e.log),onEngineCreated:i=>{i.on(A.SubscribedQualityUpdate,r=>Zb(n,e.log,r))},localParticipant:{setCameraEnabled:(i,r,s)=>t.setTrackEnabled(C.Source.Camera,i,r,s),setScreenShareEnabled:(i,r,s)=>t.setTrackEnabled(C.Source.ScreenShare,i,r,s),enableCameraAndMicrophone:()=>Xb(n),createScreenTracks:i=>ip(n,i),publishAdditionalCodecForTrack:(i,r,s)=>rp(n,e.log,i,r,s)}}}},ek=n=>Ub(n,[cs,sp]),rt;(function(n){n[n.IDLE=0]="IDLE",n[n.RUNNING=1]="RUNNING",n[n.SKIPPED=2]="SKIPPED",n[n.SUCCESS=3]="SUCCESS",n[n.FAILED=4]="FAILED"})(rt||(rt={}));var kt=class extends Oe.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=rt.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=ek(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return g(this,void 0,void 0,function*(){if(this.status!==rt.IDLE)throw Error("check is running already");this.setStatus(rt.RUNNING);try{yield this.perform()}catch(t){t instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(t.message):this.appendError(t.message))}return yield this.disconnect(),yield new Promise(t=>setTimeout(t,500)),this.status!==rt.SKIPPED&&this.setStatus(this.isSuccess()?rt.SUCCESS:rt.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return g(this,void 0,void 0,function*(){return this.room.state===G.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return g(this,void 0,void 0,function*(){this.room&&this.room.state!==G.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(rt.SKIPPED)}switchProtocol(e){return g(this,void 0,void 0,function*(){let t=!1,i=!1;if(this.room.on(R.Reconnecting,()=>{t=!0}),this.room.once(R.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(s=>setTimeout(s,1e3)),!t)return;let r=Date.now()+1e4;for(;Date.now()<r;){if(i)return;yield Re(100)}throw new Error("Could not reconnect using ".concat(e," protocol after 10 seconds"))})}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return(e=this.room)===null||e===void 0?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}},Ya=class extends kt{get description(){return"Cloud regions"}perform(){return g(this,void 0,void 0,function*(){let e=new ct(this.url,this.token);if(!e.isCloud()){this.skip();return}let t=[],i=new Set;for(let s=0;s<3;s++){let a=yield e.getNextBestRegionUrl();if(!a)break;if(i.has(a))continue;i.add(a);let o=yield this.checkCloudRegion(a);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),t.push(o)}t.sort((s,a)=>(s.duration-a.duration)*.5+(s.rtt-a.rtt)*.5);let r=t[0];this.bestStats=r,this.appendMessage("best Cloud region: ".concat(r.region))})}getInfo(){let e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return g(this,void 0,void 0,function*(){var t,i;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));let r=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!r)throw new Error("Region not found");let s=yield this.room.localParticipant.streamText({topic:"test"}),a=1e3,c=1e6/a,d="A".repeat(a),l=Date.now();for(let m=0;m<c;m++)yield s.write(d);yield s.close();let u=Date.now(),h=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),f={region:r,rtt:1e4,duration:u-l};return h?.forEach(m=>{m.type==="candidate-pair"&&m.nominated&&(f.rtt=m.currentRoundTripTime*1e3)}),yield this.disconnect(),f})}},xo=1e4,Xa=class extends kt{get description(){return"Connection via UDP vs TCP"}perform(){return g(this,void 0,void 0,function*(){let e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):this.appendMessage("best connection quality via udp");let i=this.bestStats;this.appendMessage("upstream bitrate: ".concat((i.bitrateTotal/i.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((i.rttTotal/i.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((i.jitterTotal/i.count*1e3).toFixed(2)," ms")),i.packetsLost>0&&this.appendWarning("packets lost: ".concat((i.packetsLost/i.packetsSent*100).toFixed(2),"%")),i.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((i.qualityLimitationDurations.bandwidth/(xo/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(xo/1e3)*100).toFixed(2),"%"))})}getInfo(){let e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return g(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");let t=document.createElement("canvas");t.width=1280,t.height=720;let i=t.getContext("2d");if(!i)throw new Error("Could not get canvas context");let r=0,s=()=>{r=(r+1)%360,i.fillStyle="hsl(".concat(r,", 100%, 50%)"),i.fillRect(0,0,t.width,t.height),requestAnimationFrame(s)};s();let o=t.captureStream(30).getVideoTracks()[0],d=(yield this.room.localParticipant.publishTrack(o,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,l={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},u=setInterval(()=>g(this,void 0,void 0,function*(){let h=yield d.getRTCStatsReport();h?.forEach(f=>{f.type==="outbound-rtp"?(l.packetsSent=f.packetsSent,l.qualityLimitationDurations=f.qualityLimitationDurations,l.bitrateTotal+=f.targetBitrate,l.count++):f.type==="remote-inbound-rtp"&&(l.packetsLost=f.packetsLost,l.rttTotal+=f.roundTripTime,l.jitterTotal+=f.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,xo)),clearInterval(u),o.stop(),t.remove(),yield this.disconnect(),l})}},Za=class extends kt{get description(){return"Can publish audio"}perform(){return g(this,void 0,void 0,function*(){var e;let t=yield this.connect(),i=yield hb();if(yield Sf(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,3e3));let s=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let a=0;if(s.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="audio"||!o.kind&&o.mediaType==="audio")&&(a=o.packetsSent)}),a===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(a," audio packets"))})}},ec=class extends kt{get description(){return"Can publish video"}perform(){return g(this,void 0,void 0,function*(){var e;let t=yield this.connect(),i=yield Qb();yield this.checkForVideo(i.mediaStreamTrack),t.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,5e3));let r=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let s=0;if(r.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="video"||!a.kind&&a.mediaType==="video")&&(s+=a.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," video packets"))})}checkForVideo(e){return g(this,void 0,void 0,function*(){let t=new MediaStream;t.addTrack(e.clone());let i=document.createElement("video");i.srcObject=t,i.muted=!0,i.autoplay=!0,i.playsInline=!0,i.setAttribute("playsinline","true"),document.body.appendChild(i),yield new Promise(r=>{i.onplay=()=>{setTimeout(()=>{var s,a,o,c;let d=document.createElement("canvas"),l=e.getSettings(),u=(a=(s=l.width)!==null&&s!==void 0?s:i.videoWidth)!==null&&a!==void 0?a:1280,h=(c=(o=l.height)!==null&&o!==void 0?o:i.videoHeight)!==null&&c!==void 0?c:720;d.width=u,d.height=h;let f=d.getContext("2d");f.drawImage(i,0,0);let p=f.getImageData(0,0,d.width,d.height).data,y=!0;for(let v=0;v<p.length;v+=4)if(p[v]!==0||p[v+1]!==0||p[v+2]!==0){y=!1;break}y?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),r()},1e3)},i.play()}),t.getTracks().forEach(r=>r.stop()),i.remove()})}},tc=class extends kt{get description(){return"Resuming connection after interruption"}perform(){return g(this,void 0,void 0,function*(){var e;let t=yield this.connect(),i=!1,r=!1,s,a=new Promise(c=>{setTimeout(c,5e3),s=c}),o=()=>{i=!0};if(t.on(R.SignalReconnecting,o).on(R.Reconnecting,o).on(R.Reconnected,()=>{r=!0,s(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close(),t.engine.client.emit(N.Close,""),yield a,i){if(!r||t.state!==G.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}else throw new Error("Did not attempt to reconnect")})}},nc=class extends kt{get description(){return"Can connect via TURN"}perform(){return g(this,void 0,void 0,function*(){var e,t,i;qn(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(e=yield new ct(this.url,this.token).getNextBestRegionUrl())!==null&&e!==void 0?e:this.url);let r=new Oi,s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0),a=!1,o=!1,c=!1;for(let d of s.iceServers)for(let l of d.urls)l.startsWith("turn:")?(o=!0,c=!0):l.startsWith("turns:")&&(o=!0,c=!0,a=!0),l.startsWith("stun:")&&(c=!0);c?o&&!a&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield r.close(),!((i=(t=this.connectOptions)===null||t===void 0?void 0:t.rtcConfig)===null||i===void 0)&&i.iceServers||o?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(d=>setTimeout(d,0)))})}},ic=class extends kt{get description(){return"Establishing WebRTC connection"}perform(){return g(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(R.SignalConnected,()=>{var i;this.room.engine.client.on(N.Trickle,r=>{if(r.candidate){let s=new RTCIceCandidate(r),a="".concat(s.protocol," ").concat(s.address,":").concat(s.port," ").concat(s.type);s.address&&(tk(s.address)?a+=" (private)":s.protocol==="tcp"&&s.tcpType==="passive"?(e=!0,a+=" (passive)"):s.protocol==="udp"&&(t=!0)),this.appendMessage(a)}}),!((i=this.room.engine.pcManager)===null||i===void 0)&&i.subscriber&&(this.room.engine.pcManager.subscriber.onIceCandidateError=r=>{r instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(r.errorCode," ").concat(r.errorText," ").concat(r.url))})});try{yield this.connect(),W.info("now the room is connected")}catch(i){throw this.appendWarning("ports need to be open on firewall in order to connect."),i}e||this.appendWarning("Server is not configured for ICE/TCP"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}};function tk(n){let e=n.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){let t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}var rc=class extends kt{get description(){return"Connecting to signal connection via WebSocket"}perform(){return g(this,void 0,void 0,function*(){var e,t,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let r=new Oi,s;try{s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(a){if(qn(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(a.message,". Retrying with region fallback"));let c=yield new ct(this.url,this.token).getNextBestRegionUrl();c&&(s=yield r.join(c,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0),this.appendMessage("Fallback to region worked. To avoid initial connections failing, ensure you're calling room.prepareConnection() ahead of time"))}}s?(this.appendMessage("Connected to server, version ".concat(s.serverVersion,".")),((e=s.serverInfo)===null||e===void 0?void 0:e.edition)===ef.Cloud&&(!((t=s.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=s.serverInfo)===null||i===void 0?void 0:i.region))):this.appendError("Websocket connection could not be established"),yield r.close()})}},Du=class extends Oe.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=i}getNextCheckId(){let e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:rt.IDLE,name:"",description:""}),e}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==rt.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return g(this,void 0,void 0,function*(){let t=this.getNextCheckId(),i=new e(this.url,this.token,this.options),r=a=>{this.updateCheck(t,a)};i.on("update",r);let s=yield i.run();return i.off("update",r),s})}checkWebsocket(){return g(this,void 0,void 0,function*(){return this.createAndRunCheck(rc)})}checkWebRTC(){return g(this,void 0,void 0,function*(){return this.createAndRunCheck(ic)})}checkTURN(){return g(this,void 0,void 0,function*(){return this.createAndRunCheck(nc)})}checkReconnect(){return g(this,void 0,void 0,function*(){return this.createAndRunCheck(tc)})}checkPublishAudio(){return g(this,void 0,void 0,function*(){return this.createAndRunCheck(Za)})}checkPublishVideo(){return g(this,void 0,void 0,function*(){return this.createAndRunCheck(ec)})}checkConnectionProtocol(){return g(this,void 0,void 0,function*(){let e=yield this.createAndRunCheck(Xa);if(e.data&&"protocol"in e.data){let t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return g(this,void 0,void 0,function*(){return this.createAndRunCheck(Ya)})}},Vt;(function(n){n.SetKey="setKey",n.RatchetRequest="ratchetRequest",n.KeyRatcheted="keyRatcheted"})(Vt||(Vt={}));var Nu;(function(n){n.KeyRatcheted="keyRatcheted"})(Nu||(Nu={}));var vt;(function(n){n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError"})(vt||(vt={}));var Fu;(function(n){n.Error="cryptorError"})(Fu||(Fu={}));var Uu=class extends Oe.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.latestManuallySetKeyIndex=0,this.onKeyRatcheted=(t,i,r)=>{W.debug("key ratcheted event received",{participantId:i,keyIndex:r})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},Qy),e),this.on(Vt.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,i){let r={key:e,participantIdentity:t,keyIndex:i};if(!this.options.sharedKey&&!t)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(t??"shared","-").concat(i??0),r),i!==void 0&&(this.latestManuallySetKeyIndex=i),this.emit(Vt.SetKey,r,i!==void 0)}getKeys(){return Array.from(this.keyInfoMap.values())}getLatestManuallySetKeyIndex(){return this.latestManuallySetKeyIndex}getOptions(){return this.options}ratchetKey(e,t){this.emit(Vt.RatchetRequest,e,t)}};var ds;(function(n){n[n.InvalidKey=0]="InvalidKey",n[n.MissingKey=1]="MissingKey",n[n.InternalError=2]="InternalError"})(ds||(ds={}));var sc=class extends Ye{constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:ds.InternalError,i=arguments.length>2?arguments[2]:void 0;super(40,e),this.reason=t,this.participantIdentity=i}};new TextEncoder;var DT=new TextDecoder,NT=new TextDecoder("utf-8",{fatal:!0});var Ie=class extends Error{constructor(e,t){var i;super(e,t),j(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,(i=Error.captureStackTrace)===null||i===void 0||i.call(Error,this,this.constructor)}};j(Ie,"code","ERR_JOSE_GENERIC");var oc=class extends Ie{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:r,payload:t}}),j(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),j(this,"claim",void 0),j(this,"reason",void 0),j(this,"payload",void 0),this.claim=i,this.reason=r,this.payload=t}};j(oc,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");var ac=class extends Ie{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:r,payload:t}}),j(this,"code","ERR_JWT_EXPIRED"),j(this,"claim",void 0),j(this,"reason",void 0),j(this,"payload",void 0),this.claim=i,this.reason=r,this.payload=t}};j(ac,"code","ERR_JWT_EXPIRED");var cc=class extends Ie{constructor(){super(...arguments),j(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}};j(cc,"code","ERR_JOSE_ALG_NOT_ALLOWED");var dc=class extends Ie{constructor(){super(...arguments),j(this,"code","ERR_JOSE_NOT_SUPPORTED")}};j(dc,"code","ERR_JOSE_NOT_SUPPORTED");var lc=class extends Ie{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"decryption operation failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),j(this,"code","ERR_JWE_DECRYPTION_FAILED")}};j(lc,"code","ERR_JWE_DECRYPTION_FAILED");var uc=class extends Ie{constructor(){super(...arguments),j(this,"code","ERR_JWE_INVALID")}};j(uc,"code","ERR_JWE_INVALID");var hc=class extends Ie{constructor(){super(...arguments),j(this,"code","ERR_JWS_INVALID")}};j(hc,"code","ERR_JWS_INVALID");var fc=class extends Ie{constructor(){super(...arguments),j(this,"code","ERR_JWT_INVALID")}};j(fc,"code","ERR_JWT_INVALID");var pc=class extends Ie{constructor(){super(...arguments),j(this,"code","ERR_JWK_INVALID")}};j(pc,"code","ERR_JWK_INVALID");var mc=class extends Ie{constructor(){super(...arguments),j(this,"code","ERR_JWKS_INVALID")}};j(mc,"code","ERR_JWKS_INVALID");var gc=class extends Ie{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"no applicable key found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),j(this,"code","ERR_JWKS_NO_MATCHING_KEY")}};j(gc,"code","ERR_JWKS_NO_MATCHING_KEY");var vc=class extends Ie{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"multiple matching keys found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),j(this,Symbol.asyncIterator,pg(function*(){})),j(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};j(vc,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");var yc=class extends Ie{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"request timed out",t=arguments.length>1?arguments[1]:void 0;super(e,t),j(this,"code","ERR_JWKS_TIMEOUT")}};j(yc,"code","ERR_JWKS_TIMEOUT");var bc=class extends Ie{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"signature verification failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),j(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}};j(bc,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");var nk=1e3,FT=60*nk;var ls=class n extends Oe.EventEmitter{get logContext(){var e,t;return{room:(e=this.room)===null||e===void 0?void 0:e.name,participant:(t=this.room)===null||t===void 0?void 0:t.localParticipant.identity}}constructor(e,t){super(),this.keysPostedToWorker=new WeakSet,this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.log=we(he.E2EE,()=>this.logContext),this.onWorkerMessage=i=>{var r;let s=i.data,a=s.kind,o=s.data;switch(a){case"error":{let l=new Error(o.error.message);if(l.name=o.error.name,o.error.stack&&(l.stack=o.error.stack),o.uuid){let u=this.decryptDataRequests.get(o.uuid);if(u?.reject){u.reject(l);break}let h=this.encryptDataRequests.get(o.uuid);if(h?.reject){h.reject(l);break}}this.log.error(l.message),this.emit(vt.EncryptionError,l,o.participantIdentity);break}case"initAck":o.enabled&&this.keyProvider.getKeys().forEach(l=>{this.postKey(l,!1)});break;case"enable":if(o.local)this.encryptionEnabled!==o.enabled&&(this.emit(vt.ParticipantEncryptionStatusChanged,o.enabled,this.room.localParticipant),this.encryptionEnabled=o.enabled);else if(o.participantIdentity){let l=(r=this.room)===null||r===void 0?void 0:r.getParticipantByIdentity(o.participantIdentity);if(!l)throw TypeError("couldn't set encryption status, participant not found".concat(o.participantIdentity));this.emit(vt.ParticipantEncryptionStatusChanged,o.enabled,l)}break;case"ratchetKey":this.keyProvider.emit(Vt.KeyRatcheted,o.ratchetResult,o.participantIdentity,o.keyIndex);break;case"decryptDataResponse":let c=this.decryptDataRequests.get(o.uuid);c?.resolve&&c.resolve(o);break;case"encryptDataResponse":let d=this.encryptDataRequests.get(o.uuid);d?.resolve&&d.resolve(o);break;case"packetTrailerMetadata":this.handleFrameMetadata(o.trackId,o.rtpTimestamp,o.ssrc,o.metadata);break;case"log":Bn[o.level](o.msg,o.context);break}},this.onWorkerError=i=>{this.log.error("e2ee worker encountered an error:",{error:i.error}),this.emit(vt.EncryptionError,i.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!Yy())throw new Ri("tried to setup end-to-end encryption on an unsupported browser");if(this.log.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);let t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:Bn.getLevel()}};this.worker&&(this.log.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t),this.subscribeToLogLevelChanges())}}subscribeToLogLevelChanges(){var e;(e=this.unsubscribeLogLevel)===null||e===void 0||e.call(this);let t;if(n.disposeRegistry){let i=new WeakRef(this.worker);t=Fl(r=>{let s=i.deref();if(!s){t?.();return}s.postMessage({kind:"setLogLevel",data:{level:r}})}),n.disposeRegistry.register(this,t,this)}else{let i=this.worker;t=Fl(r=>{i.postMessage({kind:"setLogLevel",data:{level:r}})})}this.unsubscribeLogLevel=t}dispose(){var e,t,i;(e=this.unsubscribeLogLevel)===null||e===void 0||e.call(this),this.unsubscribeLogLevel=void 0,n.disposeRegistry&&n.disposeRegistry.unregister(this);let r=new sc("E2EEManager disposed",ds.InternalError);for(let s of[...this.encryptDataRequests.values()])(t=s.reject)===null||t===void 0||t.call(s,r);for(let s of[...this.decryptDataRequests.values()])(i=s.reject)===null||i===void 0||i.call(s,r);this.worker&&(this.worker.onmessage=null,this.worker.onerror=null),this.removeAllListeners()}setLocalParticipantCryptorEnabled(e){var t,i;this.log.debug("set e2ee to ".concat(e," for the local participant")),this.postEnable(e,(i=(t=this.room)===null||t===void 0?void 0:t.localParticipant.identity)!==null&&i!==void 0?i:"",!0)}setParticipantCryptorEnabled(e,t){this.setLocalParticipantCryptorEnabled(e)}setSifTrailer(e){!e||e.length===0?this.log.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}handleFrameMetadata(e,t,i,r){if(this.room){for(let s of[this.room.localParticipant,...this.room.remoteParticipants.values()])for(let a of s.trackPublications.values())if(a.track&&a.track.mediaStreamID===e&&a.track instanceof Li&&a.track.frameMetadataExtractor){a.track.frameMetadataExtractor.storeMetadata(t,i,r);return}}}setupEngine(e){e.on(A.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(R.TrackPublished,(i,r)=>this.setParticipantCryptorEnabledForPublication(i,r.identity)),e.on(R.ConnectionStateChanged,i=>{i===G.Connected&&e.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{this.setParticipantCryptorEnabledForPublication(s,r.identity)})})}).on(R.TrackUnsubscribed,(i,r,s)=>{var a;let o={kind:"removeTransform",data:{participantIdentity:s.identity,trackId:i.mediaStreamID}};(a=this.worker)===null||a===void 0||a.postMessage(o)}).on(R.TrackSubscribed,(i,r,s)=>{this.setupE2EEReceiver(i,s.identity,r.trackInfo)}).on(R.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");let i=t.getLatestManuallySetKeyIndex();t.getKeys().filter(r=>!this.keysPostedToWorker.has(r)).forEach(r=>{var s;this.postKey(r,i===((s=r.keyIndex)!==null&&s!==void 0?s:0))}),this.setLocalParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled)}),e.localParticipant.on(L.LocalSenderCreated,(i,r)=>g(this,void 0,void 0,function*(){this.setupE2EESender(r,i)})),e.localParticipant.on(L.LocalTrackPublished,i=>{if(!Mt(i.track)||!qe())return;let r={kind:"updateCodec",data:{trackId:i.track.mediaStreamID,codec:mi(i.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity,hasPacketTrailer:!1,operation:"encode"}};this.worker.postMessage(r)}),t.on(Vt.SetKey,(i,r)=>this.postKey(i,r??!0)).on(Vt.RatchetRequest,(i,r)=>this.postRatchetRequest(i,r))}encryptData(e){return g(this,void 0,void 0,function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");let t=pt(),i={kind:"encryptDataRequest",data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},r=new Ce;return r.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,r),this.worker.postMessage(i),r.promise})}handleEncryptedData(e,t,i,r){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");let s=pt(),a={kind:"decryptDataRequest",data:{uuid:s,payload:e,iv:t,participantIdentity:i,keyIndex:r}},o=new Ce;return o.onFinally=()=>{this.decryptDataRequests.delete(s)},this.decryptDataRequests.set(s,o),this.worker.postMessage(a),o.promise}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");let i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(i)}postKey(e,t){var i;if(!this.worker)throw Error("could not set key, worker is missing");let r=e.key,s=e.participantIdentity,a=e.keyIndex,o={kind:"setKey",data:{participantIdentity:s,isPublisher:s===((i=this.room)===null||i===void 0?void 0:i.localParticipant.identity),key:r,keyIndex:a,updateCurrentKeyIndex:t}};this.worker.postMessage(o),this.keysPostedToWorker.add(e)}postEnable(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;if(this.worker){let r={kind:"enable",data:{enabled:e,participantIdentity:t,local:i}};this.worker.postMessage(r)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((t=this.room)===null||t===void 0)&&t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");let i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");let t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setParticipantCryptorEnabledForPublication(e,t){if(!e.trackInfo){this.log.warn("skipping e2ee enabled update for publication without trackInfo",{trackSid:e.trackSid});return}this.postEnable(e.trackInfo.encryption!==X.NONE,t)}setupE2EEReceiver(e,t,i){if(!e.receiver)return;if(!i?.mimeType||i.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");let r=e.kind==="video"&&!!i.packetTrailerFeatures&&i.packetTrailerFeatures.length>0;this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?mi(i.mimeType):void 0,r,i.encryption!==X.NONE)}setupE2EESender(e,t){var i;if(!Mn(e)||!t){t||this.log.warn("early return because sender is not ready");return}let r=Mt(e),s=r?(i=e.publishOptions)===null||i===void 0?void 0:i.videoCodec:void 0;this.handleSender(t,e.mediaStreamID,s==="h264"||s==="h265"?s:void 0,r?Zc(e.publishOptions):void 0)}handleReceiver(e,t,i,r,s,a){return g(this,void 0,void 0,function*(){if(this.worker){if(ha()){let o={kind:"decode",participantIdentity:i,trackId:t,codec:r,hasPacketTrailer:s,encrypted:a};e.transform=new RTCRtpScriptTransform(this.worker,o)}else{if(sr in e&&or in e){let l={kind:"updateCodec",data:{trackId:t,previousTrackId:e[or],codec:r,participantIdentity:i,hasPacketTrailer:s,encrypted:a}};this.worker.postMessage(l),e[or]=t;return}let o=e.writableStream,c=e.readableStream;if(!o||!c){let l=e.createEncodedStreams();e.writableStream=l.writable,o=l.writable,e.readableStream=l.readable,c=l.readable}let d={kind:"decode",data:{readableStream:c,writableStream:o,trackId:t,codec:r,participantIdentity:i,hasPacketTrailer:s,encrypted:a}};this.worker.postMessage(d,[c,o])}e[sr]=!0,e[or]=t}})}handleSender(e,t,i,r){var s;if(!(sr in e||!this.worker)){if(!(!((s=this.room)===null||s===void 0)&&s.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(ha()){this.log.info("initialize script transform");let a={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i,hasPacketTrailer:Ar(r),packetTrailer:r};e.transform=new RTCRtpScriptTransform(this.worker,a)}else{this.log.info("initialize encoded streams");let a=e.createEncodedStreams(),o={kind:"encode",data:{readableStream:a.readable,writableStream:a.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity,hasPacketTrailer:Ar(r),packetTrailer:r}};this.worker.postMessage(o,[a.readable,a.writable])}e[sr]=!0}}};ls.disposeRegistry=typeof FinalizationRegistry<"u"&&typeof WeakRef<"u"&&new FinalizationRegistry(n=>{n()});var ik=sd("e2ee",[],(n,e,t)=>{let i=!n.options.e2ee,r=t??(n.options.encryption||n.options.e2ee),s,a=()=>{};if(r){if("e2eeManager"in r)s=r.e2eeManager,s.isDataChannelEncryptionEnabled=i;else{let l=new ls(r,i);s=l,a=()=>{l.dispose(),r.worker.terminate()}}let c=(l,u)=>{Fy(u)&&(n.isE2EEEnabled=l),n.emit(R.ParticipantEncryptionStatusChanged,l,u)},d=(l,u)=>{let h=u?n.getParticipantByIdentity(u):void 0;n.emit(R.EncryptionError,l,h)};if(s.on(vt.ParticipantEncryptionStatusChanged,c),s.on(vt.EncryptionError,d),"e2eeManager"in r){let l=s;a=()=>{l.off(vt.ParticipantEncryptionStatusChanged,c),l.off(vt.EncryptionError,d)}}s.setup(n),s.setupEngine(n.engine)}let o=new ye;return{manager:s,e2eeManager:s,room:{setE2EEEnabled:c=>g(void 0,void 0,void 0,function*(){let d=yield o.lock();try{if(s)n.isE2EEEnabled!==c&&(yield n.localParticipant.setE2EEEnabled(c),s.setLocalParticipantCryptorEnabled?s.setLocalParticipantCryptorEnabled(c):n.localParticipant.identity!==""&&s.setParticipantCryptorEnabled(c,n.localParticipant.identity));else throw Error("e2ee not configured, please set e2ee settings within the room options")}finally{d()}})},dispose:a}}),rk=sd("frameMetadata",[],(n,e,t)=>{var i;let r=(i=t??n.options.frameMetadata)!==null&&i!==void 0?i:n.options.packetTrailer,s=new Ha(r);return s.setup(n),{manager:s,frameMetadataOptions:r,dispose:()=>s.dispose()}}),sk={key:Symbol("lk.extension.chat"),install(n,e){let t=n.localParticipant;t.on(L.ChatMessage,r=>{n.emit(R.ChatMessage,r,t)});let i=r=>g(this,void 0,void 0,function*(){let s=new Fe({value:{case:"chatMessage",value:new xc(Object.assign(Object.assign({},r),{timestamp:ue.parse(r.timestamp),editTimestamp:r.editTimestamp!==void 0?ue.parse(r.editTimestamp):void 0}))}});return yield n.engine.sendDataPacket(s,z.RELIABLE),t.emit(L.ChatMessage,r),r});return{dataPackets:{chatMessage:(r,s,a,o)=>{n.emit(R.ChatMessage,Dy(r),o)}},localParticipant:{sendChatMessage:(r,s)=>i({id:pt(),message:r,timestamp:Date.now(),attachedFiles:s?.attachments}),editChatMessage:(r,s)=>i(Object.assign(Object.assign({},s),{message:r,editTimestamp:Date.now()}))}}}},Lo=we(he.DataTracks),en=class n extends Be{constructor(e,t,i,r){super(19,"Frame ".concat(i," dropped: ").concat(e),r),this.name="DataTrackDepacketizerDropError",this.reason=t,this.reasonName=tn[t],this.frameNumber=i}static interrupted(e,t){return new n("Interrupted by the start of a new frame ".concat(t),tn.Interrupted,e)}static unknownFrame(e){return new n("Initial packet was never received.",tn.UnknownFrame,e)}static bufferFull(e){return new n("Reorder buffer is full.",tn.BufferFull,e)}static incomplete(e,t,i){return new n("Not all packets received before final packet. Received ".concat(t," packets, expected ").concat(i," packets."),tn.Incomplete,e)}},tn;(function(n){n[n.Interrupted=0]="Interrupted",n[n.UnknownFrame=1]="UnknownFrame",n[n.BufferFull=2]="BufferFull",n[n.Incomplete=3]="Incomplete"})(tn||(tn={}));var us=class n{constructor(){this.partials=new Map}push(e,t){switch(e.header.marker){case ce.Single:return this.frameFromSingle(e,t);case ce.Start:return this.beginPartial(e,t);case ce.Inter:case ce.Final:return this.pushToPartial(e)}}reset(){this.partials.clear()}peekOldestPartialFrameNumber(){let e=this.partials.keys().next();return e.done?null:e.value}frameFromSingle(e,t){var i;if(e.header.marker!==ce.Single)throw new Error("Depacketizer.frameFromSingle: packet.header.marker was not FrameMarker.Single, found ".concat(e.header.marker,"."));let r=(i=t?.maxPartialFrames)!==null&&i!==void 0?i:1;if(this.partials.size>=r){let s=this.peekOldestPartialFrameNumber();if(typeof s!="number")throw new Error("Depacketizer.frameFromSingle: no oldest frame number found, but partials.size is ".concat(this.partials.size,"."));if(this.partials.delete(s),t?.throwOnInterruption)throw en.interrupted(s,e.header.frameNumber.value);Lo.warn("Data track frame ".concat(s," was interrupted by single-packet frame ").concat(e.header.frameNumber.value,", dropping."))}return{payload:e.payload,extensions:e.header.extensions}}beginPartial(e,t){var i;if(e.header.marker!==ce.Start)throw new Error("Depacketizer.beginPartial: packet.header.marker was not FrameMarker.Start, found ".concat(e.header.marker,"."));let r=e.header.sequence,s=e.header.frameNumber.value,a={startSequence:r,extensions:e.header.extensions,payloads:new Map([[r.value,e.payload]])},o=(i=t?.maxPartialFrames)!==null&&i!==void 0?i:1;for(;this.partials.size>=o;){let c=this.peekOldestPartialFrameNumber();if(typeof c!="number")break;if(this.partials.delete(c),t?.throwOnInterruption)throw en.interrupted(c,s);Lo.warn("Data track partials full (max ".concat(o,"), evicted oldest frame ").concat(c," to make room for new frame ").concat(s,"."))}return this.partials.set(s,a),null}pushToPartial(e){if(e.header.marker!==ce.Inter&&e.header.marker!==ce.Final)throw new Error("Depacketizer.pushToPartial: packet.header.marker was not FrameMarker.Inter or FrameMarker.Final, found ".concat(e.header.marker,"."));let t=e.header.frameNumber.value,i=this.partials.get(t);if(!i)throw this.partials.delete(t),en.unknownFrame(t);if(i.payloads.size>=n.MAX_BUFFER_PACKETS)throw this.partials.delete(t),en.bufferFull(t);return i.payloads.has(e.header.sequence.value)&&Lo.warn("Data track frame ".concat(t," received duplicate packet for sequence ").concat(e.header.sequence.value,", so replacing with newly received packet.")),i.payloads.set(e.header.sequence.value,e.payload),e.header.marker===ce.Final?this.finalize(t,i,e.header.sequence.value):null}finalize(e,t,i){let r=t.payloads.size,s=0;for(let d of t.payloads.values())s+=d.length;let a=new Uint8Array(s),o=t.startSequence.clone(),c=0;for(;;){let d=t.payloads.get(o.value);if(!d)break;t.payloads.delete(o.value);let l=a.length-c;if(d.length>l)throw new Error("Depacketizer.finalize: Expected at least ".concat(d.length," more bytes left in the payload buffer, only got ").concat(l," bytes."));if(a.set(d,c),c+=d.length,o.value!=i){o.increment();continue}return this.partials.delete(e),{payload:a,extensions:t.extensions}}throw this.partials.delete(e),en.incomplete(e,r,i-t.startSequence.value+1)}};us.MAX_BUFFER_PACKETS=128;var nn;(function(n){n[n.Unpublished=0]="Unpublished",n[n.Timeout=1]="Timeout",n[n.Disconnected=2]="Disconnected",n[n.Cancelled=4]="Cancelled"})(nn||(nn={}));var it=class n extends Be{constructor(e,t,i){super(22,e,i),this.name="DataTrackSubscribeError",this.reason=t,this.reasonName=nn[t]}static unpublished(){return new n("The track has been unpublished and is no longer available",nn.Unpublished)}static timeout(){return new n("Request to subscribe to data track timed-out",nn.Timeout)}static disconnected(){return new n("Cannot subscribe to data track when disconnected",nn.Disconnected)}static cancelled(){return new n("Subscription to data track cancelled by caller",nn.Cancelled)}},Do=we(he.DataTracks),kc=class{constructor(e){var t,i;let r=e.e2eeManager!==null;if(e.info.usesE2ee!==r)throw new Error("IncomingDataTrackPipeline: DataTrackInfo.usesE2ee must match presence of decryptionProvider");let s=new us;this.publisherIdentity=e.publisherIdentity,this.e2eeManager=(t=e.e2eeManager)!==null&&t!==void 0?t:null,this.depacketizer=s,this.options=(i=e.pipelineOptions)!==null&&i!==void 0?i:{}}updateE2eeManager(e){this.e2eeManager=e}setOptions(e){this.options=e}processPacket(e){return g(this,void 0,void 0,function*(){let t=this.depacketize(e);if(!t)return null;let i=yield this.decryptIfNeeded(t);return i||null})}depacketize(e){let t;try{t=this.depacketizer.push(e,{throwOnInterruption:!1,maxPartialFrames:this.options.maxPartialFrames})}catch(i){return Do.warn("Data frame depacketize error: ".concat(i)),null}return t}decryptIfNeeded(e){return g(this,void 0,void 0,function*(){var t,i;let r=this.e2eeManager;if(!r)return e;let s=(i=(t=e.extensions)===null||t===void 0?void 0:t.e2ee)!==null&&i!==void 0?i:null;if(!s)return Do.error("Missing E2EE meta"),null;let a;try{a=yield r.handleEncryptedData(e.payload,s.iv,this.publisherIdentity,s.keyIndex)}catch(o){return Do.error("Error decrypting packet: ".concat(o)),null}return e.payload=a.payload,e})}},ke=we(he.DataTracks),ok=1e4,ak=16,Tc=class extends Oe.EventEmitter{constructor(e){var t;super(),this.descriptors=new Map,this.subscriptionHandles=new Map,this.e2eeManager=(t=e?.e2eeManager)!==null&&t!==void 0?t:null}updateE2eeManager(e){this.e2eeManager=e;for(let t of this.descriptors.values())t.subscription.type==="active"&&t.subscription.pipeline.updateE2eeManager(e)}setPipelineOptions(e,t){let i=this.descriptors.get(e);if(!i){ke.warn("Unknown track ".concat(e,", cannot set pipeline options."));return}i.pipelineOptions=t,i.subscription.type==="active"&&i.subscription.pipeline.setOptions(t)}openSubscriptionStream(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ak,r=null,s=new Ce,a=this.descriptors.get(e),o=()=>{t?.removeEventListener("abort",d)},c=()=>{if(o(),!r){ke.warn("ReadableStream subscribed to ".concat(e," was not started."));return}if(!a||this.descriptors.get(a.info.sid)!==a){ke.warn("Unknown track ".concat(e,", skipping cancel..."));return}if(a.subscription.type!=="active"){ke.warn("Subscription for track ".concat(e," is not active, skipping cancel..."));return}a.subscription.streamControllers.delete(r),a.subscription.streamControllers.size===0&&this.unSubscribeRequest(a.info.sid)},d=()=>{var u;r&&(a?.subscription.type==="active"&&a.subscription.streamControllers.delete(r),r.error(it.cancelled()),(u=s.reject)===null||u===void 0||u.call(s,it.cancelled()),c())};return[new ReadableStream({start:u=>{r=u,this.subscribeRequest(e,t).then(()=>g(this,void 0,void 0,function*(){var h,f,m;if(!a||this.descriptors.get(a.info.sid)!==a){ke.error("Unknown track ".concat(e));let p=it.disconnected();u.error(p),(h=s.reject)===null||h===void 0||h.call(s,p);return}if(a.subscription.type!=="active"){ke.error("Subscription for track ".concat(e," is not active"));let p=it.disconnected();u.error(p),(f=s.reject)===null||f===void 0||f.call(s,p);return}if(t?.aborted){d();return}t?.addEventListener("abort",d),a.subscription.streamControllers.set(u,o),(m=s.resolve)===null||m===void 0||m.call(s)})).catch(h=>{var f;u.error(h),(f=s.reject)===null||f===void 0||f.call(s,h)})},cancel:()=>{c()}},new CountQueuingStrategy({highWaterMark:i})),s.promise]}subscribeRequest(e,t){return g(this,void 0,void 0,function*(){let i=this.descriptors.get(e);if(!i)throw new Error("Cannot subscribe to unknown track");let r=(s,a,o)=>g(this,void 0,void 0,function*(){if(s.subscription.type==="active")return;if(s.subscription.type!=="pending")throw new Error("Descriptor for track ".concat(e," is not pending, found ").concat(s.subscription.type));let c=Lf([a,o].filter(u=>typeof u<"u")),d=new Ce;s.subscription.completionFuture.promise.then(()=>{var u;return(u=d.resolve)===null||u===void 0?void 0:u.call(d)}).catch(u=>{var h;return(h=d.reject)===null||h===void 0?void 0:h.call(d,u)});let l=()=>{var u;if(s.subscription.type==="pending"){if(s.subscription.pendingRequestCount-=1,o?.aborted){s.subscription.cancel();return}if(s.subscription.pendingRequestCount<=0){s.subscription.cancel();return}(u=d.reject)===null||u===void 0||u.call(d,it.cancelled())}};c.aborted&&l(),c.addEventListener("abort",l),yield d.promise,c.removeEventListener("abort",l)});switch(i.subscription.type){case"none":{i.subscription={type:"pending",completionFuture:new Ce,pendingRequestCount:1,cancel:()=>{var a,o;let c=i.subscription;i.subscription={type:"none"},this.emit("sfuUpdateSubscription",{sid:i.info.sid,subscribe:!1}),c.type==="pending"&&((o=(a=c.completionFuture).reject)===null||o===void 0||o.call(a,s.aborted?it.timeout():it.cancelled()))}},this.emit("sfuUpdateSubscription",{sid:e,subscribe:!0});let s=td(ok);yield r(i,t,s);return}case"pending":{i.subscription.pendingRequestCount+=1,yield r(i,t);return}case"active":return}})}querySubscribed(){return g(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).filter(t=>t.subscription.type==="active").map(t=>[t.info,t.publisherIdentity])})}unSubscribeRequest(e){var t;let i=this.descriptors.get(e);if(!i)throw new Error("Cannot subscribe to unknown track");if(i.subscription.type!=="active"){ke.warn("Unexpected descriptor state in unSubscribeRequest, expected active, found ".concat((t=i.subscription)===null||t===void 0?void 0:t.type));return}this.closeStreamControllers(i.subscription.streamControllers,e);let r=i.subscription;i.subscription={type:"none"},this.subscriptionHandles.delete(r.subcriptionHandle),this.emit("sfuUpdateSubscription",{sid:e,subscribe:!1})}closeStreamControllers(e,t){for(let r of e){var i=F(r,2);let s=i[0],a=i[1];a();try{s.close()}catch(o){ke.warn("Failed to close readable stream for track ".concat(t,": ").concat(o))}}}receiveSfuPublicationUpdates(e){return g(this,void 0,void 0,function*(){if(e.size===0)return;let t=new Map;for(let s of e.entries()){var i=F(s,2);let a=i[0],o=i[1],c=new Set;for(let d of o)c.add(d.sid),!this.descriptors.has(d.sid)&&(this.handleSidReassigned(a,d)||(yield this.handleTrackPublished(a,d)));t.set(a,c)}for(let s of t.entries()){var r=F(s,2);let a=r[0],o=r[1],d=Array.from(this.descriptors.entries()).filter(l=>{let u=F(l,2);return u[0],u[1].publisherIdentity===a}).map(l=>F(l,1)[0]).filter(l=>!o.has(l));for(let l of d)this.handleTrackUnpublished(l)}})}queryPublications(){return g(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).map(e=>e.info)})}handleTrackPublished(e,t){return g(this,void 0,void 0,function*(){if(this.descriptors.has(t.sid)){ke.error("Existing descriptor for track ".concat(t.sid));return}let i={info:t,publisherIdentity:e,subscription:{type:"none"},pipelineOptions:{}};this.descriptors.set(i.info.sid,i);let r=new Zr(i.info,this,{publisherIdentity:e});this.emit("trackPublished",{track:r})})}handleSidReassigned(e,t){let i=Array.from(this.descriptors.entries()).find(u=>{let h=F(u,2);h[0];let f=h[1];return f.publisherIdentity===e&&f.info.pubHandle===t.pubHandle});if(!i)return!1;let r=F(i,2),s=r[0],a=r[1],o=a.info,c=o.name,d=o.usesE2ee;if(c!==t.name||d!==t.usesE2ee)return ke.warn("Info mismatch for ".concat(s,", treating as new publication")),!1;let l=t.sid;if(ke.debug("SID reassigned: ".concat(s," -> ").concat(l)),!this.descriptors.delete(s))return!1;switch(a.info.sid=l,a.subscription.type){case"none":break;case"pending":case"active":this.emit("sfuUpdateSubscription",{sid:l,subscribe:!0});break}return a.subscription.type==="active"&&this.subscriptionHandles.set(a.subscription.subcriptionHandle,l),this.descriptors.set(l,a),!0}handleTrackUnpublished(e){let t=this.descriptors.get(e);if(!t){ke.error("Unknown track ".concat(e));return}this.descriptors.delete(e),t.subscription.type==="active"&&(this.closeStreamControllers(t.subscription.streamControllers,e),this.subscriptionHandles.delete(t.subscription.subcriptionHandle)),this.emit("trackUnpublished",{sid:e,publisherIdentity:t.publisherIdentity})}receivedSfuSubscriberHandles(e){for(let i of e.entries()){var t=F(i,2);let r=t[0],s=t[1];this.registerSubscriberHandle(r,s)}}registerSubscriberHandle(e,t){var i,r;let s=this.descriptors.get(t);if(!s){ke.error("Unknown track ".concat(t));return}switch(s.subscription.type){case"none":{ke.warn("No subscription for ".concat(t));return}case"active":{this.subscriptionHandles.delete(s.subscription.subcriptionHandle),s.subscription.subcriptionHandle=e,this.subscriptionHandles.set(e,t);return}case"pending":{ke.debug("data track subscription activated",{sid:t,handle:e});let a=new kc({info:s.info,publisherIdentity:s.publisherIdentity,e2eeManager:this.e2eeManager,pipelineOptions:s.pipelineOptions}),o=s.subscription;s.subscription={type:"active",subcriptionHandle:e,pipeline:a,streamControllers:new Map},this.subscriptionHandles.set(e,t),(r=(i=o.completionFuture).resolve)===null||r===void 0||r.call(i)}}}packetReceived(e){return g(this,void 0,void 0,function*(){let t;try{var i=Jr.fromBinary(e),r=F(i,1);t=r[0]}catch(c){ke.error("Failed to deserialize packet: ".concat(c));return}let s=this.subscriptionHandles.get(t.header.trackHandle);if(!s){ke.warn("Unknown subscriber handle ".concat(t.header.trackHandle));return}let a=this.descriptors.get(s);if(!a){ke.error("Missing descriptor for track ".concat(s));return}if(a.subscription.type!=="active"){ke.warn("Received packet for track ".concat(s," without active subscription"));return}let o=yield a.subscription.pipeline.processPacket(t);if(o)for(let c of a.subscription.streamControllers.keys()){if(c.desiredSize!==null&&c.desiredSize<=0){ke.warn("Cannot send frame to subscribers: readable stream is full (desiredSize is ".concat(c.desiredSize,"). To increase this threshold, set a higher 'options.highWaterMark' when calling .subscribe()."));continue}let d=Wf.lossyIntoFrame(o);c.enqueue(d)}})}resendSubscriptionUpdates(){for(let t of this.descriptors){var e=F(t,2);let i=e[0];e[1].subscription.type!=="none"&&this.emit("sfuUpdateSubscription",{sid:i,subscribe:!0})}}handleRemoteParticipantDisconnected(e){var t,i;for(let r of this.descriptors.values())if(r.publisherIdentity===e)switch(r.subscription.type){case"none":break;case"pending":(i=(t=r.subscription.completionFuture).reject)===null||i===void 0||i.call(t,it.disconnected());break;case"active":this.unSubscribeRequest(r.info.sid);break}}reset(){var e,t;for(let i of this.descriptors.values())this.emit("trackUnpublished",{sid:i.info.sid,publisherIdentity:i.publisherIdentity}),i.subscription.type==="pending"&&((t=(e=i.subscription.completionFuture).reject)===null||t===void 0||t.call(e,it.disconnected())),i.subscription.type==="active"&&this.closeStreamControllers(i.subscription.streamControllers,i.info.sid);this.descriptors.clear(),this.subscriptionHandles.clear()}},hs=class n{constructor(e){this.e2eeManager=e.e2eeManager,this.packetizer=new Fa(e.info.pubHandle,n.TRANSPORT_MTU_BYTES)}updateE2eeManager(e){this.e2eeManager=e}processFrame(e){return yf(this,arguments,function*(){let i=yield Rt(this.encryptIfNeeded(e));try{yield Rt(yield*Vv(ze(this.packetizer.packetize(i))))}catch(r){throw r instanceof $r?Yr.packetizer(r):r}})}encryptIfNeeded(e){return g(this,void 0,void 0,function*(){if(!this.e2eeManager)return e;let t;try{t=yield this.e2eeManager.encryptData(e.payload)}catch(i){throw Yr.encryption(i)}return e.payload=t.payload,e.extensions.e2ee=new un(t.keyIndex,t.iv),e})}};hs.TRANSPORT_MTU_BYTES=16e3;var Je=we(he.DataTracks),Bu={pending(){return{type:"pending",completionFuture:new Ce}},active(n,e){return{type:"active",info:n,publishState:"published",pipeline:new hs({info:n,e2eeManager:e}),unpublishingFuture:new Ce}}},ck=1e4,Sc=class n extends Oe.EventEmitter{constructor(e){var t;super(),this.handleAllocator=new Na,this.descriptors=new Map,this.inFlightPacketCounter=new Map,this.e2eeManager=(t=e?.e2eeManager)!==null&&t!==void 0?t:null}static withDescriptors(e){let t=new n;return t.descriptors=e,t}updateE2eeManager(e){this.e2eeManager=e;for(let t of this.descriptors.values())t.type==="active"&&t.pipeline.updateE2eeManager(e)}getDescriptor(e){var t;return(t=this.descriptors.get(e))!==null&&t!==void 0?t:null}tryProcessAndSend(e,t){return g(this,void 0,void 0,function*(){var i,r,s,a,o;let c=this.getDescriptor(e);if(c?.type!=="active"||c.publishState==="unpublished")throw sn.trackUnpublished();if(c.publishState==="republishing")throw sn.dropped("Data track republishing");try{try{for(var d=!0,l=ze(c.pipeline.processFrame(t)),u;u=yield l.next(),i=u.done,!i;d=!0){a=u.value,d=!1;let h=a,f=(o=this.inFlightPacketCounter.get(e))!==null&&o!==void 0?o:0;this.inFlightPacketCounter.set(e,f+1),f===0&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!1}),this.emit("packetAvailable",{handle:e,bytes:h.toBinary()})}}catch(h){r={error:h}}finally{try{!d&&!i&&(s=l.return)&&(yield s.call(l))}finally{if(r)throw r.error}}}catch(h){throw sn.dropped(h)}})}handlePacketSendComplete(e){var t;let r=((t=this.inFlightPacketCounter.get(e))!==null&&t!==void 0?t:0)-1;r<0&&(Je.warn("OutgoingDataTrackManager.handlePacketSendComplete: inFlightPacketCounter was decremented below 0 (got ".concat(this.inFlightPacketCounter," - resetting to 0. Were more packets send than were emitted?")),r=0),this.inFlightPacketCounter.set(e,r),r===0&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!0})}publishRequest(e,t){return g(this,void 0,void 0,function*(){let i=this.handleAllocator.get();if(!i)throw Qe.limitReached();let r=td(ck),s=t?Lf([t,r]):r;if(this.descriptors.has(i))throw new Error("Descriptor for handle already exists");let a=Bu.pending();this.descriptors.set(i,a);let o=()=>{var c,d;let l=this.descriptors.get(i);if(!l){Je.warn("No descriptor for ".concat(i));return}this.descriptors.delete(i),this.emit("sfuUnpublishRequest",{handle:i}),l.type==="pending"&&((d=(c=l.completionFuture).reject)===null||d===void 0||d.call(c,r.aborted?Qe.timeout():Qe.cancelled()))};return s.aborted?(o(),a.completionFuture.promise.then(()=>i)):(s.addEventListener("abort",o),this.emit("sfuPublishRequest",{handle:i,name:e.name,usesE2ee:this.e2eeManager!==null}),yield a.completionFuture.promise,s.removeEventListener("abort",o),this.emit("trackPublished",{track:Xr.withExplicitHandle(e,this,i)}),i)})}queryPublished(){return Array.from(this.descriptors.values()).filter(t=>t.type==="active").map(t=>t.info)}unpublishRequest(e){return g(this,void 0,void 0,function*(){let t=this.descriptors.get(e);if(!t){Je.warn("No descriptor for ".concat(e));return}if(t.type!=="active"){Je.warn("Track ".concat(e," not active"));return}this.emit("sfuUnpublishRequest",{handle:e}),yield t.unpublishingFuture.promise,this.inFlightPacketCounter.delete(e),this.emit("trackUnpublished",{sid:t.info.sid})})}receivedSfuPublishResponse(e,t){var i,r,s,a;let o=this.descriptors.get(e);if(!o){Je.warn("No descriptor for ".concat(e));return}switch(this.descriptors.delete(e),o.type){case"pending":{if(t.type==="ok"){let c=t.data;Je.debug("SFU accepted publish request for handle ".concat(e),{sid:c.sid});let d=c.usesE2ee?this.e2eeManager:null;this.descriptors.set(c.pubHandle,Bu.active(c,d)),(r=(i=o.completionFuture).resolve)===null||r===void 0||r.call(i)}else Je.debug("SFU rejected publish request for handle ".concat(e),{error:t.error}),(a=(s=o.completionFuture).reject)===null||a===void 0||a.call(s,t.error);return}case"active":{if(o.publishState!=="republishing"){Je.warn("Track ".concat(e," already active"));return}if(t.type==="error"){Je.warn("Republish failed for track ".concat(e,": ").concat(t.error)),o.publishState="unpublished";return}Je.debug("Track ".concat(e," republished")),o.info.sid=t.data.sid,o.publishState="published",this.descriptors.set(o.info.pubHandle,o)}}}receivedSfuUnpublishResponse(e){var t,i;let r=this.descriptors.get(e);if(!r){Je.warn("No descriptor for ".concat(e));return}if(this.descriptors.delete(e),r.type!=="active"){Je.warn("Track ".concat(e," not active"));return}r.publishState="unpublished",(i=(t=r.unpublishingFuture).resolve)===null||i===void 0||i.call(t)}sfuWillRepublishTracks(){var e,t;for(let r of this.descriptors.entries()){var i=F(r,2);let s=i[0],a=i[1];switch(a.type){case"pending":this.descriptors.delete(s),(t=(e=a.completionFuture).reject)===null||t===void 0||t.call(e,Qe.disconnected());break;case"active":a.publishState="republishing",this.emit("sfuPublishRequest",{handle:a.info.pubHandle,name:a.info.name,usesE2ee:a.info.usesE2ee})}}}reset(){return g(this,void 0,void 0,function*(){var e,t,i,r;this.handleAllocator.reset();for(let s of this.descriptors.values())switch(s.type){case"pending":(t=(e=s.completionFuture).reject)===null||t===void 0||t.call(e,Qe.disconnected());break;case"active":(r=(i=s.unpublishingFuture).resolve)===null||r===void 0||r.call(i),yield this.unpublishRequest(s.info.pubHandle);break}this.descriptors.clear(),this.inFlightPacketCounter.clear(),this.emit("reset")})}},qu=n=>n.map(e=>Ua.from(e)),dk={key:Symbol("lk.extension.dataTracks"),install(n,e){let t=new Tc,i=new Sc;t.on("sfuUpdateSubscription",d=>{n.engine.client.sendUpdateDataSubscription(d.sid,d.subscribe)}).on("trackPublished",d=>{var l;d.track.publisherIdentity!==n.localParticipant.identity&&(n.emit(R.DataTrackPublished,d.track),(l=n.remoteParticipants.get(d.track.publisherIdentity))===null||l===void 0||l.addRemoteDataTrack(d.track))}).on("trackUnpublished",d=>{var l;d.publisherIdentity!==n.localParticipant.identity&&(n.emit(R.DataTrackUnpublished,d.sid),(l=n.remoteParticipants.get(d.publisherIdentity))===null||l===void 0||l.removeRemoteDataTrack(d.sid))}),i.on("sfuPublishRequest",d=>{n.engine.client.sendPublishDataTrackRequest(d.handle,d.name,d.usesE2ee)}).on("sfuUnpublishRequest",d=>{n.engine.client.sendUnPublishDataTrackRequest(d.handle)}).on("trackPublished",d=>{n.emit(R.LocalDataTrackPublished,d.track)}).on("trackUnpublished",d=>{n.emit(R.LocalDataTrackUnpublished,d.sid)}).on("packetAvailable",d=>{let l=d.handle,u=d.bytes;n.engine.sendDataTrackFrame(u).finally(()=>i.handlePacketSendComplete(l))});let r=d=>{var l;let u=(l=e.slot("e2eeManager"))!==null&&l!==void 0?l:null;t.updateE2eeManager(u),i.updateE2eeManager(u),d.on(A.PublishDataTrackResponse,h=>{if(!h.info){e.log.warn("received PublishDataTrackResponse, but event.info was ".concat(h.info,", so skipping."));return}i.receivedSfuPublishResponse(h.info.pubHandle,{type:"ok",data:{sid:h.info.sid,pubHandle:h.info.pubHandle,name:h.info.name,usesE2ee:h.info.encryption!==X.NONE}})}).on(A.UnPublishDataTrackResponse,h=>{if(!h.info){e.log.warn("received UnPublishDataTrackResponse, but event.info was ".concat(h.info,", so skipping."));return}i.receivedSfuUnpublishResponse(h.info.pubHandle)}).on(A.DataTrackSubscriberHandles,h=>{let f=new Map(Object.entries(h.subHandles).map(m=>{let p=F(m,2),y=p[0],v=p[1];return[parseInt(y,10),v.trackSid]}));t.receivedSfuSubscriberHandles(f)}).on(A.DataTrackPacketReceived,h=>{try{t.packetReceived(h)}catch(f){throw f}}).on(A.Joined,h=>{t.receiveSfuPublicationUpdates(new Map(h.otherParticipants.map(f=>[f.identity,qu(f.dataTracks)])))}).on(A.Restarted,()=>{i.sfuWillRepublishTracks(),t.resendSubscriptionUpdates()}).on(A.SignalRequestResponse,h=>{if(h.request.case!=="publishDataTrack")return;let f;switch(h.reason){case rn.NOT_ALLOWED:f=Qe.notAllowed(h.message);break;case rn.DUPLICATE_NAME:f=Qe.duplicateName(h.message);break;case rn.INVALID_NAME:f=Qe.invalidName(h.message);break;case rn.LIMIT_EXCEEDED:f=Qe.limitReached(h.message);break;default:f=Qe.unknown(h.reason,h.message);break}i.receivedSfuPublishResponse(h.request.value.pubHandle,{type:"error",error:f})})},s=()=>{t.reset(),i.reset()},a=(d,l)=>{for(let u of l.dataTracks)d.addRemoteDataTrack(new Zr(Ua.from(u),t,{publisherIdentity:l.identity}))},o=d=>{t.receiveSfuPublicationUpdates(new Map(d.filter(l=>l.identity!==n.localParticipant.identity).map(l=>[l.identity,qu(l.dataTracks)])))},c=()=>i.queryPublished().map(d=>new Uc({info:Ua.toProtobuf(d)}));return n.on(R.ParticipantDisconnected,d=>t.handleRemoteParticipantDisconnected(d.identity)),{incoming:t,outgoing:i,onEngineCreated:r,onDisconnect:s,onParticipantCreated:a,onParticipantUpdates:o,syncState:c,localParticipant:{publishDataTrack:d=>g(this,void 0,void 0,function*(){let l=new Xr(d,i);return yield l.publish(),l})}}}},_c={key:Symbol("lk.extension.rpc"),requires:[cs],install(n,e){let t=e.get(cs),i=t.incoming,r=t.outgoing,s=l=>{var u,h;return(h=(u=n.remoteParticipants.get(l))===null||u===void 0?void 0:u.clientProtocol)!==null&&h!==void 0?h:zc},a=new ja(e.log,r,s,()=>{var l;return(l=n.engine)===null||l===void 0?void 0:l.serverVersion});a.on("sendDataPacket",l=>{let u=l.packet;var h;(h=n.engine)===null||h===void 0||h.sendDataPacket(u,z.RELIABLE)});let o=new Va(e.log,r,s);return o.on("sendDataPacket",l=>{let u=l.packet;var h;(h=n.engine)===null||h===void 0||h.sendDataPacket(u,z.RELIABLE)}),i.registerTextStreamHandler($f,(l,u)=>g(this,[l,u],void 0,function(h,f){let m=f.identity;return(function*(){var p;yield o.handleIncomingDataStream(h,m,(p=h.info.attributes)!==null&&p!==void 0?p:{})})()})),i.registerTextStreamHandler(Qf,(l,u)=>g(this,[l,u],void 0,function(h,f){let m=f.identity;return(function*(){var p;yield a.handleIncomingDataStream(h,m,(p=h.info.attributes)!==null&&p!==void 0?p:{})})()})),n.on(R.ParticipantDisconnected,l=>a.handleParticipantDisconnected(l.identity)),{dataPackets:{rpcRequest:(l,u)=>{o.handleIncomingRpcRequest(u.participantIdentity,l)},rpcResponse:l=>{switch(l.value.case){case"payload":a.handleIncomingRpcResponseSuccess(l.requestId,l.value.value);break;case"error":a.handleIncomingRpcResponseFailure(l.requestId,ae.fromProto(l.value.value));break;default:e.log.warn("Unknown rpcResponse.value.case: ".concat(l.value.case));break}},rpcAck:l=>a.handleIncomingRpcAck(l.requestId)},onDisconnect:()=>a.handleRoomDisconnected(),room:{registerRpcMethod:(l,u)=>o.registerRpcMethod(l,u),unregisterRpcMethod:l=>o.unregisterRpcMethod(l)},localParticipant:{performRpc:l=>a.performRpc(l).then(u=>{let h=F(u,2);return h[0],h[1]})}}}},lk={key:Symbol("lk.extension.rpcLegacy"),requires:[_c],install(n,e){let t=e.get(_c).room,i=t.registerRpcMethod,r=t.unregisterRpcMethod;return{localParticipant:{registerRpcMethod:i,unregisterRpcMethod:r}}}},uk={key:Symbol("lk.extension.simulatedParticipants"),install(n,e){return{room:{simulateParticipants:t=>hk(n,e,t)}}}};function hk(n,e,t){return g(this,void 0,void 0,function*(){var i,r,s,a;let o=Object.assign({audio:!0,video:!0,useRealTracks:!1},t.publish),c=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},t.participants),d=n.localParticipant,l=d.trackLoggerOptions;if(e.simulateConnected(new ms({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:ue.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),new cn({identity:"simulated-local",name:"local-name"})),o.video){let u=new xi(C.Kind.Video,new Sn({source:Te.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:ot.AUDIO,name:"video-dummy"}),qr().createTrack(o.useRealTracks&&(!((i=window.navigator.mediaDevices)===null||i===void 0)&&i.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Kl(160*((r=c.aspectRatios[0])!==null&&r!==void 0?r:1),160,!0,!0),void 0,!1,l),l);d.addTrackPublication(u),d.emit(L.LocalTrackPublished,u)}if(o.audio){let u=new xi(C.Kind.Audio,new Sn({source:Te.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:ot.AUDIO}),new jn(o.useRealTracks&&(!((s=navigator.mediaDevices)===null||s===void 0)&&s.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:e.acquireEmptyAudioStreamTrack(),void 0,!1,d.audioContext,l),l);d.addTrackPublication(u),d.emit(L.LocalTrackPublished,u)}for(let u=0;u<c.count-1;u+=1){let h=new cn({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(u),state:wn.ACTIVE,tracks:[],joinedAt:ue.parse(Date.now())}),f=e.getOrCreateParticipant(h.identity,h);if(c.video){let m=Kl(160*((a=c.aspectRatios[u%c.aspectRatios.length])!==null&&a!==void 0?a:1),160,!1,!0),p=new Sn({source:Te.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:ot.AUDIO});f.addSubscribedMediaTrack(m,p.sid,new MediaStream([m]),new RTCRtpReceiver),h.tracks=[...h.tracks,p]}if(c.audio){let m=e.acquireEmptyAudioStreamTrack(),p=new Sn({source:Te.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:ot.AUDIO});f.addSubscribedMediaTrack(m,p.sid,new MediaStream([m]),new RTCRtpReceiver),h.tracks=[...h.tracks,p]}f.updateInfo(h)}})}var fk=[cs,_c,lk,dk,rk,ik,sp,uk,sk],fs=class extends Di{constructor(e){super(e),qf(this,fk)}};ud();var pk=Symbol.for("pv"),mk=0;function w(n,e,t,i,r,s){e||(e={});var a,o,c=e;if("ref"in c&&typeof n!="function")for(o in c={},e)o=="ref"?a=e[o]:c[o]=e[o];var d={type:n,props:c,key:t,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:pk,__v:--mk,__i:-1,__u:0};return(r||s)&&(d.__source=r,d.__self=s),ne.vnode&&ne.vnode(d),d}var lt={body:"var(--fl-peek-body, #8b7ba4)",grey:"var(--fl-peek-grey, #6b645c)",muzzle:"var(--fl-peek-muzzle, #f1eaf6)",ink:"var(--fl-peek-ink, #2b2338)",blush:"var(--fl-peek-blush, #e9a99a)",moon:"var(--fl-peek-moon, #dccfe9)"},gk="M38.5 117 C36 104 37 90 40 78 C45 55 61 40 80 40 C99 40 115 55 120 78 C123 90 124 104 121.5 117 Z",vk="M52 58 Q60 47 72 44",yk="M74 89 Q80 86 86 89 Q83.5 95 80 95 Q76.5 95 74 89 Z",bk="M80 95 v3 M74.2 100 q2.9 2.8 5.8 0 q2.9 2.8 5.8 0",kk=[[64,95],[62.5,101],[68.5,102.5],[96,95],[97.5,101],[91.5,102.5]],Tk="M 18 116 A 62 15 0 0 1 142 116",Sk="M 142 116 A 62 15 0 0 1 30.2 124.8",_k="M 146 131 A 76 18 0 0 1 40 142",Ck="M 44 116 A 60 60 0 1 1 116 116 Z",hd=[[61,72],[99,72]],wk={resting:7e3,listening:3600,awake:2400,thinking:3e3},fd={transformBox:"fill-box",transformOrigin:"center"},dt=n=>Math.round(n*100)/100;function Ek({state:n,small:e}){if(n==="awake"||n==="listening"||n==="thinking"){let[r,s]=n==="listening"?[5.4,7.2]:[5,6.6];e&&([r,s]=[r*1.35,s*1.25]);let[a,o]=n==="thinking"?[3.8,-4.8]:[0,0];return w(Ze,{children:hd.map(([c,d])=>w("g",{children:[w("ellipse",{cx:dt(c+a),cy:dt(d+o),rx:dt(r),ry:dt(s),style:{fill:lt.ink}}),e?null:w("circle",{cx:dt(c+a+r*.34),cy:dt(d+o-s*.4),r:1.8,fill:"#ffffff"})]},c))})}if(n==="glad")return w(Ze,{children:hd.map(([r,s])=>w("path",{d:`M${dt(r-6.3)} ${dt(s+2.4)} q6.3 -8.6 12.6 0`,fill:"none",strokeWidth:e?6.2:4.4,strokeLinecap:"round",style:{stroke:lt.ink}},r))});let[t,i]=e?[7.2,6.6]:[6.8,4.6];return w(Ze,{children:hd.map(([r,s])=>w("path",{d:`M${dt(r-t)} ${dt(s-1.4)} q${t} 6.8 ${dt(2*t)} 0`,fill:"none",strokeWidth:i,strokeLinecap:"round",style:{stroke:lt.ink}},r))})}function Hn({state:n="resting",size:e=32,live:t,pro:i=!1,label:r}){let s=e<=32,a=n==="grey"?lt.grey:lt.body,o=t??(n==="listening"||n==="thinking")?wk[n]:void 0,c=o?{animationDuration:`${o}ms`}:void 0;return w("svg",{viewBox:"0 0 160 160",width:e,height:e,role:r?"img":void 0,"aria-label":r,"aria-hidden":r?void 0:!0,style:{display:"block",flexShrink:0,overflow:"visible"},children:[i?w("path",{d:Ck,style:{fill:lt.moon}}):null,n==="listening"?w("ellipse",{cx:80,cy:116,rx:74,ry:18,fill:"none",strokeWidth:3.5,opacity:.32,style:{stroke:a}}):null,o&&n!=="thinking"?[0,o/2].map(d=>w("ellipse",{cx:80,cy:116,rx:62,ry:15,fill:"none",strokeWidth:s?6:3.5,opacity:0,class:"peek-anim-ripple",style:{...fd,...c,animationDelay:`${d}ms`,stroke:a}},d)):null,w("path",{d:Tk,fill:"none",strokeWidth:s?7:5,strokeLinecap:"round",opacity:.5,style:{stroke:a}}),w("g",{class:o?"peek-anim-bob":void 0,style:c,children:[w("path",{d:gk,style:{fill:a}}),s?null:w("path",{d:vk,fill:"none",stroke:"#ffffff",strokeWidth:4,strokeLinecap:"round",opacity:.3}),w("ellipse",{cx:80,cy:96,rx:25,ry:15,style:{fill:lt.muzzle}}),w("path",{d:yk,style:{fill:lt.ink}}),s?null:w(Ze,{children:[w("path",{d:bk,fill:"none",strokeWidth:2.1,strokeLinecap:"round",style:{stroke:lt.ink}}),kk.map(([d,l])=>w("circle",{cx:d,cy:l,r:1.6,opacity:.4,style:{fill:lt.ink}},`${d}-${l}`))]}),w("g",{style:fd,children:[w("g",{class:!o||n==="resting"?void 0:n==="thinking"?"peek-anim-look":"peek-anim-blink",style:fd,children:w(Ek,{state:n,small:s})}),n==="glad"?[54.5,105.5].map(d=>w("ellipse",{cx:d,cy:82.5,rx:6.2,ry:3.6,opacity:.85,style:{fill:lt.blush}},d)):null]},n)]}),w("path",{d:Sk,fill:"none",strokeWidth:s?8:6,strokeLinecap:"round",opacity:.8,style:{stroke:a}}),s?null:w("path",{d:_k,fill:"none",strokeWidth:3,strokeLinecap:"round",opacity:.3,style:{stroke:a}})]})}function op({size:n=132,stroke:e=3.5,fraction:t,breathScale:i,label:r,children:s}){let a=50-e/2,o=2*Math.PI*a,c=Math.min(1,Math.max(0,t));return w("div",{class:"fl-ring-wrap",style:{width:`${n}px`,height:`${n}px`},role:r?"timer":void 0,"aria-label":r,children:[typeof i=="number"?w("div",{class:"fl-breath-halo",style:{transform:`scale(${i.toFixed(3)})`},"aria-hidden":"true"}):null,w("svg",{viewBox:"0 0 100 100",width:n,height:n,"aria-hidden":"true",children:[w("circle",{cx:"50",cy:"50",r:a,fill:"none","stroke-width":e,style:{stroke:"var(--fl-track-strong)"}}),w("circle",{cx:"50",cy:"50",r:a,fill:"none","stroke-width":e,"stroke-linecap":"round","stroke-dasharray":o,"stroke-dashoffset":o*(1-c),transform:"rotate(-90 50 50)",style:{stroke:"var(--fl-accent)",transition:"stroke-dashoffset 220ms linear"}})]}),s?w("div",{class:"fl-ring-center",children:s}):null]})}var am=bm(om(),1);function Fd({value:n,size:e=96}){let t="",i=21;try{let r=am.default.create(n,{errorCorrectionLevel:"M"});i=r.modules.size;let s=r.modules.data,a=[];for(let o=0;o<i;o++)for(let c=0;c<i;c++)s[o*i+c]&&a.push(`M${c},${o}h1v1h-1z`);t=a.join("")}catch{t=""}return w("div",{class:"fl-qr-tile","aria-label":`QR code for ${n}`,children:w("svg",{viewBox:`0 0 ${i} ${i}`,width:e,height:e,shapeRendering:"crispEdges",role:"img","aria-label":"Scan to open in Flowe",children:[w("rect",{width:i,height:i,fill:"#ffffff"}),w("path",{d:t,fill:"#1a1611"})]})})}var kT="2026-01-26";function Us(n){let e=n==="dark"||!n&&window.matchMedia?.("(prefers-color-scheme: dark)").matches;document.documentElement.dataset.theme=e?"dark":"light"}function cm(n){if(n.structuredContent&&typeof n.structuredContent=="object")return n.structuredContent;let e=n.content?.find(t=>t.type==="text"&&typeof t.text=="string");if(e?.text)try{let t=JSON.parse(e.text);if(t&&typeof t=="object")return t}catch{return{message:e.text}}return null}function dm(n,e){Us(void 0);let t=window.matchMedia?.("(prefers-color-scheme: dark)"),i,r=()=>{i||Us(void 0)};t?.addEventListener?.("change",r);let s=null,a=e??null,o=1,c=new Map,d=k=>{a=k,s?.(k)},l=typeof window<"u"&&window.parent&&window.parent!==window;function u(k){l&&window.parent.postMessage(k,"*")}function h(k,S,E=15e3){if(!l)return Promise.reject(new Error("MCP host not connected"));let O=o++;return new Promise((q,x)=>{let D=window.setTimeout(()=>{c.delete(O),x(new Error(`MCP host timeout (${k})`))},E);c.set(O,{resolve:B=>{clearTimeout(D),q(B)},reject:B=>{clearTimeout(D),x(B)}}),u({jsonrpc:"2.0",id:O,method:k,params:S})})}function f(k,S={}){u({jsonrpc:"2.0",method:k,params:S})}let m=k=>{let S=k.data;if(!(!S||typeof S!="object"||S.jsonrpc!=="2.0")){if(typeof S.id=="number"&&!S.method&&c.has(S.id)){let E=c.get(S.id);c.delete(S.id),S.error?E.reject(new Error(S.error.message||"MCP host error")):E.resolve(S.result??{});return}if(S.method==="ui/resource-teardown"&&S.id!==void 0){u({jsonrpc:"2.0",id:S.id,result:{}});return}if(S.method==="ui/notifications/host-context-changed"){let E=S.params?.theme;E&&(i=E,Us(E));return}if(S.method==="ui/notifications/tool-result"&&S.params){let E=cm(S.params);E&&d(E)}}};window.addEventListener("message",m);let p=null,y=0,v=0;function _(){let k=document.documentElement,S=Math.ceil(k.scrollWidth),E=Math.ceil(document.body.scrollHeight||k.scrollHeight);E>0&&(S!==y||E!==v)&&(y=S,v=E,f("ui/notifications/size-changed",{width:S,height:E}))}typeof ResizeObserver<"u"&&(p=new ResizeObserver(()=>_()),p.observe(document.body));let P=!1,b=l?h("ui/initialize",{protocolVersion:kT,appInfo:{name:n,version:"0.3.1"},appCapabilities:{}},4e3).then(k=>{P=!0;let S=k.hostContext;S?.theme&&(i=S.theme,Us(S.theme)),f("ui/notifications/initialized",{}),_()}).catch(()=>{}):Promise.resolve();return{callTool:async(k,S={})=>{if(await b,!P)throw new Error("MCP host not connected");let E=await h("tools/call",{name:k,arguments:S}),O=cm(E);if(E.isError){let q=O?.message||(E.content?.[0]?.text??"Tool call failed");throw new Error(q)}return O??{}},openLink:async k=>{if(await b,P)try{await h("ui/open-link",{url:k},4e3);return}catch{}window.open(k,"_blank","noopener,noreferrer")},updateContext:async k=>{if(await b,!!P)try{await h("ui/update-model-context",{content:[{type:"text",text:k}]},4e3)}catch{}},onPayload:k=>{s=k,a&&k(a)},destroy:()=>{window.removeEventListener("message",m),t?.removeEventListener?.("change",r),p?.disconnect()}}}var TT={welcome:"Settling in",body_scan:"Body scan",yoga_nidra:"Deep rest",awakening:"Awakening",acute:"Reset",intake:"Check-in",identify:"Identify",investigate:"Explore",interrupt:"Shift",install:"Integrate"};function ST(n){return n?TT[n]??n.replace(/_/g," "):"Guided session"}function lm(n){let e=Math.max(0,Math.floor(n)),t=Math.floor(e/60),i=e%60;return`${t}:${String(i).padStart(2,"0")}`}function _T({payload:n,bridge:e,onReady:t}){let i=n.auth,[r,s]=Ve("pending"),[a,o]=Ve(!1),[c,d]=Ve(null);ni(()=>{if(!i||r!=="pending")return;let u=Math.max(2e3,(i.interval||3)*1e3),h=!1,f=window.setInterval(async()=>{if(!h)try{let m=await e.callTool("flowe_auth_poll",{device_code:i.device_code});if(m.status==="authorized"){h=!0,clearInterval(f),s("launching");let p=n.pending_tier??"quick",y=n.pending_session_type??(p==="deep"?"ht_stress":"quick_reset"),v=p==="deep"?"flowe_deep_reset":"flowe_quick_reset";try{let _=await e.callTool(v,{session_type:y,voice:n.voice,ambient:n.ambient});t({..._,account:m.account??_.account})}catch(_){d(_.message)}}else m.status==="expired"&&(h=!0,clearInterval(f),s("expired"))}catch{}},u);return()=>{h=!0,clearInterval(f)}},[i?.device_code,r]);let l=n.pending_tier==="deep"?"Deep Reset":"Quick Reset";return w("div",{class:"fl-stack",children:[w("div",{class:"fl-header",children:w("div",{class:"fl-brand-row",children:[w(Hn,{state:r==="launching"?"glad":"awake",size:34,live:r==="launching"}),w("div",{children:[w("div",{class:"fl-mono",children:"FLOWE ACCOUNT REQUIRED"}),w("h2",{class:"fl-title",children:r==="launching"?`Signed in \u2014 starting your ${l}\u2026`:`Sign in to start your ${l}`})]})]})}),w("p",{class:"fl-body",children:"Real Flowe Quick and Deep Resets use your account for live AI voice guidance and sync directly to your Journey."}),i&&r!=="launching"?w("div",{class:"fl-runner-stage",style:{alignItems:"center"},children:[w(Fd,{value:i.verification_uri_complete,size:96}),w("div",{class:"fl-stack",style:{gap:"10px",flex:1},children:[w("div",{class:"fl-row",children:[w("span",{class:"fl-code-box",children:i.user_code}),w("button",{type:"button",class:"fl-btn-link",onClick:()=>{navigator.clipboard?.writeText(i.user_code),o(!0),setTimeout(()=>o(!1),1800)},children:a?"Copied":"Copy code"})]}),w("div",{class:"fl-row",children:[w("button",{type:"button",class:"fl-btn-primary",onClick:()=>e.openLink(i.verification_uri_complete),children:"Continue in browser"}),w("span",{class:"fl-mono",children:r==="expired"?"EXPIRED \u2014 RETRY":"WAITING FOR APPROVAL\u2026"})]})]})]}):null,c?w("p",{class:"fl-error",children:c}):null]})}function CT({payload:n,bridge:e,onComplete:t}){let i=n.tier==="deep",r=Math.max(60,(n.estimated_duration??(i?20:10))*60),s=n.phases&&n.phases.length>0?n.phases:[n.current_phase??"yoga_nidra"],[a,o]=Ve(n.livekit_url&&n.livekit_token?"ready":"handoff"),[c,d]=Ve(i?"Ready to join two-way voice session.":"Ready when you are. Listen-only."),[l,u]=Ve(n.current_phase??s[0]),[h,f]=Ve(!i),[m,p]=Ve(!1),[y,v]=Ve(0),[_,P]=Ve(!1),[b,k]=Ve(null),S=nr(null),E=nr(null),O=nr(null);ni(()=>{if(a!=="connected")return;O.current||(O.current=Date.now());let V=window.setInterval(()=>{document.hidden||!O.current||v(Math.floor((Date.now()-O.current)/1e3))},1e3);return()=>clearInterval(V)},[a]),ni(()=>()=>{let V=S.current;S.current=null,V&&V.disconnect()},[]);async function q(){if(!n.livekit_url||!n.livekit_token){o("handoff");return}o("connecting"),d("Connecting to your Flowe guide\u2026"),k(null);try{let V=new fs({adaptiveStream:!0,dynacast:!0});if(S.current=V,V.on(R.TrackSubscribed,se=>{if(se.kind===C.Kind.Audio&&E.current){let Q=se.attach();Q.autoplay=!0,E.current.appendChild(Q),d("Flowe is guiding you.")}}),V.on(R.TrackUnsubscribed,se=>{se.detach().forEach(Q=>Q.remove())}),V.on(R.ActiveSpeakersChanged,se=>{let Q=se.some(De=>!De.isLocal);p(Q)}),V.on(R.DataReceived,se=>{try{let Q=JSON.parse(new TextDecoder().decode(se)),De=Q.phase??Q.current_phase;typeof De=="string"&&De.length>0&&u(De),Q.type==="session_complete"&&D()}catch{}}),V.on(R.Disconnected,()=>{p(!1)}),await V.connect(n.livekit_url,n.livekit_token),i)try{await V.localParticipant.setMicrophoneEnabled(!0),f(!1)}catch{k("Microphone access was blocked by this host \u2014 continue in Flowe Desktop or your browser."),await V.disconnect(),S.current=null,o("handoff");return}O.current=Date.now(),o("connected"),d(i?"Connected \u2014 speak naturally when prompted.":"Flowe is guiding you.")}catch{S.current=null,k("This host sandbox restricts inline audio streaming \u2014 open in Flowe or scan to continue seamlessly."),o("handoff")}}async function x(){let V=S.current;if(!V)return;let se=!h;try{await V.localParticipant.setMicrophoneEnabled(!se),f(se)}catch{}}async function D(){if(_)return;P(!0);let V=S.current;S.current=null,V&&await V.disconnect().catch(()=>{});let se=Math.max(1,Math.round(y/60)),Q={};if(n.session_id)try{Q=await e.callTool("flowe_session_complete",{session_id:n.session_id,duration_minutes:se})}catch{}await e.updateContext(`User finished their ${i?"Deep Reset":"Quick Reset"} (${n.session_type_name??"Flowe session"}).`),t({...n,...Q,view:"complete"})}let B=Math.max(0,r-y),H=Math.min(1,y/r),$=Math.max(0,s.indexOf(l));return w("div",{class:"fl-stack",children:[w("div",{ref:E,style:{display:"none"}}),w("div",{class:"fl-header",children:[w("div",{class:"fl-brand-row",children:[w(Hn,{state:a==="connecting"?"thinking":a==="connected"?i&&!h&&!m?"listening":m?"awake":"resting":"awake",size:36,live:a==="connected"||a==="connecting",pro:!!n.account?.is_pro,label:n.session_type_name??"Flowe session"}),w("div",{children:[w("div",{class:"fl-mono",children:[i?"DEEP RESET \xB7 INTERACTIVE VOICE":"QUICK RESET \xB7 LISTEN ONLY",n.ambient&&n.ambient!=="none"?` \xB7 ${n.ambient.replace(/_/g," ").toUpperCase()}`:""]}),w("h2",{class:"fl-title",children:n.session_type_name||"Flowe Session"})]})]}),w("span",{class:"fl-badge",children:[n.estimated_duration??(i?20:10)," min"]})]}),a==="ready"?w("div",{class:"fl-stack",children:[w("p",{class:"fl-body",children:i?"Your interactive Flowe voice room is ready. Uses your microphone for guided dialogue, or open on Flowe Desktop / mobile.":`Your live ${(n.voice??"ada").replace(/^\w/,V=>V.toUpperCase())} voice room is ready. Sit back and listen \u2014 no microphone needed.`}),w("div",{class:"fl-row",children:[w("button",{type:"button",class:"fl-btn-primary",onClick:q,children:i?"Join live voice session":"Begin Quick Reset"}),n.web_url?w("button",{type:"button",class:"fl-btn-secondary",onClick:()=>e.openLink(n.web_url),children:"Open in browser"}):null,w("button",{type:"button",class:"fl-btn-link",onClick:()=>o("handoff"),children:"Show phone QR"})]})]}):null,a==="connecting"||a==="connected"?w("div",{class:"fl-runner-stage",children:[w(op,{size:128,stroke:3.5,fraction:H,breathScale:m?1.1:.96,label:`${lm(B)} remaining`,children:[w("span",{class:"fl-ring-time",children:lm(B)}),w("span",{class:"fl-mono",children:ST(l)})]}),w("div",{class:"fl-stack",style:{gap:"10px",flex:1},children:[w("p",{class:"fl-body","aria-live":"polite",children:c}),s.length>1?w("div",{class:"fl-pips","aria-label":`Phase ${$+1} of ${s.length}`,children:s.map((V,se)=>w("span",{class:"fl-pip","data-state":se<$?"done":se===$?"active":"todo"},V))}):null,w("div",{class:"fl-row",children:[i&&a==="connected"?w("button",{type:"button",class:"fl-btn-secondary",onClick:x,children:h?"Unmute mic":"Mute mic"}):null,w("button",{type:"button",class:"fl-btn-secondary",disabled:_,onClick:D,children:_?"Finishing\u2026":"End session"}),w("button",{type:"button",class:"fl-btn-link",onClick:()=>o("handoff"),children:"Move to phone"})]})]})]}):null,a==="handoff"?w("div",{class:"fl-stack",children:[b?w("p",{class:"fl-body",children:b}):null,w("div",{class:"fl-runner-stage",style:{alignItems:"center"},children:[n.join_url?w(Fd,{value:n.join_url,size:96}):null,w("div",{class:"fl-stack",style:{gap:"10px",flex:1},children:[w("p",{class:"fl-body",children:"Scan with your phone to join in the Flowe app, or launch on desktop. Your session is already queued."}),w("div",{class:"fl-row",children:[n.web_url?w("button",{type:"button",class:"fl-btn-primary",onClick:()=>e.openLink(n.web_url),children:"Open in Flowe"}):null,n.livekit_url&&n.livekit_token?w("button",{type:"button",class:"fl-btn-secondary",onClick:q,children:"Try inline audio"}):null,w("button",{type:"button",class:"fl-btn-link",disabled:_,onClick:D,children:"I\u2019m done"})]})]})]})]}):null]})}function wT({bridge:n}){let[e,t]=Ve(null);if(ni(()=>(n.onPayload(r=>t(r)),()=>n.destroy()),[n]),!e)return w("div",{class:"fl-shell",children:w("div",{class:"fl-brand-row",children:[w(Hn,{state:"thinking",size:32,live:!0}),w("div",{children:[w("div",{class:"fl-mono",children:"FLOWE LIVE"}),w("p",{class:"fl-body",children:"Preparing your session\u2026"})]})]})});let i=e.view??(e.auth?"auth":"live_session");return w("div",{class:"fl-shell",children:i==="auth"?w(_T,{payload:e,bridge:n,onReady:t}):i==="quota"?w("div",{class:"fl-stack",children:[w("div",{class:"fl-brand-row",children:[w(Hn,{state:"awake",size:34}),w("div",{children:[w("div",{class:"fl-mono",children:e.account?.team_paused?"FLOWE FOR TEAMS":"FLOWE PRO"}),w("h2",{class:"fl-title",children:e.account?.team_paused?"Your team plan is off":e.tier==="deep"?"Deep Resets come with Flowe Pro":"This week\u2019s Quick Resets are used"})]})]}),w("p",{class:"fl-body",children:e.message||"Micro-resets stay free. Flowe Pro gives unlimited live resets."}),e.upgrade_url?w("div",{class:"fl-row",children:w("button",{type:"button",class:"fl-btn-primary",onClick:()=>n.openLink(e.upgrade_url),children:"See Flowe Pro"})}):null]}):i==="complete"?w("div",{class:"fl-stack",children:[w("div",{class:"fl-header",children:[w("div",{class:"fl-brand-row",children:[w(Hn,{state:"glad",size:38,pro:!!e.account?.is_pro}),w("div",{children:[w("div",{class:"fl-mono",children:e.completed===!0?"SAVED TO YOUR JOURNEY":"SESSION ENDED"}),w("h2",{class:"fl-title",children:"Welcome back."})]})]}),w("div",{class:"fl-row",children:[typeof e.sessions_today=="number"?w("span",{class:"fl-badge fl-badge-ok",children:["Today \xB7 ",e.sessions_today]}):null,typeof e.streak_days=="number"&&e.streak_days>0?w("span",{class:"fl-badge",children:["Streak \xB7 ",e.streak_days,"d"]}):null]})]}),w("p",{class:"fl-body",children:e.completed===!0?`${e.session_type_name??"Your session"} is in your Flowe Journey.`:"Flowe could not save this session to your Journey."})]}):w(CT,{payload:e,bridge:n,onComplete:t})})}var ET=dm("flowe-live-session"),um=document.getElementById("app");um&&Xd(w(wT,{bridge:ET}),um);
48
+ `)}).join("")}flush(){var e;let t=this.buffered;return this.buffered="",(e=Mu(t))!==null&&e!==void 0?e:t}};function Mu(n){let e=n.trim();if(!(!e.startsWith("{")||!e.endsWith("}")))try{let t=JSON.parse(e);if(t!==null&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{}}function Ro(){return new CompressionStream("deflate-raw")}function Xf(){return new DecompressionStream("deflate-raw")}function Ou(n,e){return g(this,void 0,void 0,function*(){let t=new DecompressionStream("deflate-raw"),i=t.writable.getWriter();return i.write(n).catch(()=>{}),i.close().catch(()=>{}),Zf(t.readable,e)})}function Zf(n,e){return g(this,void 0,void 0,function*(){let t=n.getReader(),i=[],r=0;for(;;){let o=yield t.read(),c=o.done,d=o.value;if(c)break;if(i.push(d),r+=d.byteLength,typeof e=="number"&&r>e)throw yield t.cancel(),new fe("Decompressed payload exceeds the maximum payload size of ".concat(e," bytes"),de.PayloadTooLarge)}let s=new Uint8Array(r),a=0;for(let o of i)s.set(o,a),a+=o.byteLength;return s})}var Zt=15e3,qb=5e9,jb=500,Vb="lk.transcription",Ga=class extends Oe.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=e.maxPayloadByteLength,i=t===void 0?qb:t,r=e.maxOpenStreamsPerParticipant,s=r===void 0?jb:r;super(),this.log=W,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.isConnected=!1,this.bufferedPackets=[],this.maxPayloadByteLength=i,this.maxOpenStreamsPerParticipant=s}setConnected(e){this.isConnected=e,e&&this.flushBufferedPackets()}flushBufferedPackets(){let e=this.bufferedPackets;this.bufferedPackets=[];for(let t of e){let i=t.packet,r=t.encryptionType;this.handleDataStreamPacket(i,r)}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new fe('A text stream handler for topic "'.concat(e,'" has already been set.'),de.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new fe('A byte stream handler for topic "'.concat(e,'" has already been set.'),de.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){let e=new fe("Room disconnected in the middle of receiving data",de.AbnormalEnd);for(let t of this.byteStreamControllers.values())t.controller.error(e);for(let t of this.textStreamControllers.values())for(let i of t.controllers)i.error(e);this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.bufferedPackets=[]}validateParticipantHasNoActiveDataStreams(e){let t=Array.from(this.textStreamControllers.entries()).filter(a=>F(a,2)[1].sendingParticipantIdentity===e),i=Array.from(this.byteStreamControllers.entries()).filter(a=>a[1].sendingParticipantIdentity===e);if(t.length>0||i.length>0){let a=new fe("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),de.AbnormalEnd);for(let o of i){var r=F(o,2);let c=r[0];r[1].controller.error(a),this.byteStreamControllers.delete(c)}for(let o of t){var s=F(o,2);let c=s[0],d=s[1];for(let l of d.controllers)l.error(a);this.textStreamControllers.delete(c)}}}handleDataStreamPacket(e,t){if(!this.isConnected){this.bufferedPackets.push({packet:e,encryptionType:t});return}switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case"streamChunk":return this.handleStreamChunk(e.value.value,t);case"streamTrailer":return this.handleStreamTrailer(e.value.value,t);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}}hasTooManyOpenStreams(e){let t=0;for(let i of[this.byteStreamControllers,this.textStreamControllers])for(let r of i.values())r.sendingParticipantIdentity===e&&(t+=1);return t>=this.maxOpenStreamsPerParticipant}handleStreamHeader(e,t,i){var r;if(this.hasTooManyOpenStreams(t)){this.log.error("Participant ".concat(t," already has ").concat(this.maxOpenStreamsPerParticipant," data streams open, dropping stream ").concat(e.streamId));return}switch(e.contentHeader.case){case"byteHeader":{let s=this.byteStreamHandlers.get(e.topic);if(!s){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let a,o={id:e.streamId,name:(r=e.contentHeader.value.name)!==null&&r!==void 0?r:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:kn(e.timestamp),attributes:e.attributes,encryptionType:i},c;switch(e.compression){case Ae.DEFLATE_RAW:if(!On()){W.warn("Data stream ".concat(e.streamId," received with deflate-raw compression, but this browser does not support deflate-raw decompression. Dropping..."));return}c=!0;break;case Ae.NONE:c=!1;break;default:W.warn("Data stream ".concat(e.streamId," received with unknown compression type ").concat(e.compression,", dropping..."));return}let d=e.inlineContent;if(typeof d<"u"){s(new is(o,xu(e.streamId,c?Ou(d,this.maxPayloadByteLength):d),kn(e.totalLength)),{identity:t});return}let l=new ReadableStream({start:u=>{if(a=u,this.byteStreamControllers.has(e.streamId))throw new fe("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),de.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:o,controller:a,startTime:Date.now(),sendingParticipantIdentity:t})},cancel:()=>{var u;((u=this.byteStreamControllers.get(e.streamId))===null||u===void 0?void 0:u.controller)===a&&this.byteStreamControllers.delete(e.streamId)}});s(new is(o,c?Kb(l,e.streamId,this.maxPayloadByteLength):l.pipeThrough(ss(e.streamId)),kn(e.totalLength)),{identity:t});return}case"textHeader":{let s=[];e.topic===Vb&&this.listenerCount("transcriptionStreamArrived")>0&&s.push((u,h)=>{let f=h.identity;this.emit("transcriptionStreamArrived",{reader:u,participantIdentity:f})});let a=this.textStreamHandlers.get(e.topic);if(a&&s.push(a),s.length===0){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let o={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:i,attachedStreamIds:e.contentHeader.value.attachedStreamIds},c;switch(e.compression){case Ae.DEFLATE_RAW:if(!On()){W.warn("Data stream ".concat(e.streamId," received with deflate-raw compression, but this browser does not support deflate-raw decompression. Dropping..."));return}c=!0;break;case Ae.NONE:c=!1;break;default:W.warn("Data stream ".concat(e.streamId," received with unknown compression type ").concat(e.compression,", dropping..."));return}let d=e.inlineContent;if(typeof d<"u"){let u=c?Ou(d,this.maxPayloadByteLength):d;for(let h of s)h(new rs(o,xu(e.streamId,u),kn(e.totalLength)),{identity:t});return}if(this.textStreamControllers.has(e.streamId))throw new fe("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),de.AlreadyOpened);let l={info:o,sendingParticipantIdentity:t,controllers:[]};this.textStreamControllers.set(e.streamId,l);for(let u of s){let h,f=new ReadableStream({start:m=>{h=m,l.controllers.push(m)},cancel:()=>{let m=l.controllers.indexOf(h);m!==-1&&l.controllers.splice(m,1),l.controllers.length===0&&this.textStreamControllers.get(e.streamId)===l&&this.textStreamControllers.delete(e.streamId)}});u(new rs(o,c?zb(f,e.streamId,this.maxPayloadByteLength):f.pipeThrough(ss(e.streamId)),kn(e.totalLength)),{identity:t})}return}}}handleStreamChunk(e,t){let i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?(i.controller.error(new fe("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),de.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):i.controller.enqueue(e));let r=this.textStreamControllers.get(e.streamId);if(r)if(r.info.encryptionType!==t){let s=new fe("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(r.info.encryptionType),de.EncryptionTypeMismatch);for(let a of r.controllers)a.error(s);this.textStreamControllers.delete(e.streamId)}else for(let s of r.controllers)s.enqueue(e)}handleStreamTrailer(e,t){let i=this.textStreamControllers.get(e.streamId);if(i){if(i.info.encryptionType!==t){let s=new fe("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),de.EncryptionTypeMismatch);for(let a of i.controllers)a.error(s)}else if(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),e.reason){let s=new fe("Data stream ".concat(e.streamId," closed abnormally: ").concat(e.reason),de.AbnormalEnd);for(let a of i.controllers)a.error(s)}else for(let s of i.controllers)s.close();this.textStreamControllers.delete(e.streamId)}let r=this.byteStreamControllers.get(e.streamId);r&&(r.info.encryptionType!==t?r.controller.error(new fe("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(r.info.encryptionType),de.EncryptionTypeMismatch)):(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),e.attributes),e.reason?r.controller.error(new fe("Data stream ".concat(e.streamId," closed abnormally: ").concat(e.reason),de.AbnormalEnd)):r.controller.close()),this.byteStreamControllers.delete(e.streamId))}};function xu(n,e){return new ReadableStream({start:t=>g(this,void 0,void 0,function*(){let i=yield e;t.enqueue(new Pt({streamId:n,chunkIndex:BigInt(0),content:i})),t.close()})})}function ss(n){let e=-1;return new TransformStream({transform:(t,i)=>{let r=kn(t.chunkIndex);if(r<=e){W.warn("ignoring duplicate chunk ".concat(r," ").concat(t.version>0?"(version ".concat(t.version,")"):""," for data stream ").concat(n," (last processed: ").concat(e,")"));return}if(r>e+1)throw new fe("Missing chunk(s) ".concat(e+1,"..").concat(r-1," for data stream ").concat(n," - cannot reassemble payload"),de.Incomplete);e=r,t.content.length!==0&&i.enqueue(t)}})}function ep(){return new TransformStream({transform:(n,e)=>{e.enqueue(n.content)}})}function Wb(n){let e=0;return new TransformStream({transform:(t,i)=>{t.byteLength>0&&(i.enqueue(new Pt({streamId:n,chunkIndex:at(e),content:t})),e+=1)}})}function Hb(n){let e=new TextDecoder("utf-8"),t=new TextEncoder,i=0,r=s=>{try{return s?e.decode(s,{stream:!0}):e.decode()}catch(a){throw new fe("Cannot decode compressed data stream ".concat(n," as text: ").concat(a),de.DecodeFailed)}};return new TransformStream({transform:(s,a)=>{let o=r(s);o.length>0&&(a.enqueue(new Pt({streamId:n,chunkIndex:at(i),content:t.encode(o)})),i+=1)},flush:s=>{let a=r();a.length>0&&(s.enqueue(new Pt({streamId:n,chunkIndex:at(i),content:t.encode(a)})),i+=1)}})}function Kb(n,e,t){return n.pipeThrough(ss(e)).pipeThrough(ep()).pipeThrough(Xf()).pipeThrough(tp(e,t)).pipeThrough(Wb(e))}function zb(n,e,t){return n.pipeThrough(ss(e)).pipeThrough(ep()).pipeThrough(Xf()).pipeThrough(tp(e,t)).pipeThrough(Hb(e))}function tp(n,e){let t=0;return new TransformStream({transform:(i,r)=>{if(t+=i.byteLength,t>e)throw new fe("Data stream ".concat(n," exceeds the maximum payload size of ").concat(e," bytes"),de.PayloadTooLarge);r.enqueue(i)}})}var os=class{constructor(e,t,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return g(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)===null||e===void 0||e.call(this)})}},Ja=class extends os{},$a=class extends os{};function Io(n,e,t){var i;return new ys({streamId:n.id,mimeType:n.mimeType,topic:n.topic,timestamp:at(n.timestamp),totalLength:at(n.size),attributes:n.attributes,compression:(i=t?.compression)!==null&&i!==void 0?i:Ae.NONE,inlineContent:t?.inlineContent,contentHeader:{case:"textHeader",value:new sf({version:e?.version,attachedStreamIds:n.attachedStreamIds,replyToStreamId:e?.replyToStreamId,operationType:e?.type==="update"?Qo.UPDATE:Qo.CREATE})}})}function dr(n,e){var t;return new ys({streamId:n.id,mimeType:n.mimeType,topic:n.topic,timestamp:at(n.timestamp),totalLength:at(n.size),attributes:n.attributes,compression:(t=e?.compression)!==null&&t!==void 0?t:Ae.NONE,inlineContent:e?.inlineContent,contentHeader:{case:"byteHeader",value:new of({name:n.name})}})}function Yt(n,e){return new Fe({destinationIdentities:e,value:{case:"streamHeader",value:n}})}var Gb=new TextEncoder,Qa=class{constructor(e,t,i,r,s){this.engine=e,this.log=t,this.getRemoteParticipantClientProtocol=i,this.getRemoteParticipantCapabilities=r,this.getAllRemoteParticipantIdentities=s}setupEngine(e){this.engine=e}sendText(e,t){return g(this,void 0,void 0,function*(){var i,r,s,a,o;let c=pt(),d=Gb.encode(e),l=d.byteLength,u=(i=t?.compress)!==null&&i!==void 0?i:!0,h={id:c,mimeType:"text/plain",timestamp:Date.now(),topic:(r=t?.topic)!==null&&r!==void 0?r:"",size:l,attributes:t?.attributes,encryptionType:!((s=this.engine.e2eeManager)===null||s===void 0)&&s.isDataChannelEncryptionEnabled?X.GCM:X.NONE},m=u&&On()&&this.allRecipientsSupportV2(t?.destinationIdentities)&&this.allRecipientsSupportCompression(t?.destinationIdentities)?as.fromStream(_r(d).pipeThrough(Ro())):null;if((!t?.attachments||t.attachments.length===0)&&this.allRecipientsSupportV2(t?.destinationIdentities)){let b=d,k=Ae.NONE;if(m){let O=yield m.collect();O.byteLength<d.byteLength&&(b=O,k=Ae.DEFLATE_RAW)}let S=Io(h,void 0,{compression:k,inlineContent:b}),E=Yt(S,t?.destinationIdentities);if(E.toBinary().byteLength<=Zt)return yield this.engine.sendDataPacket(E,z.RELIABLE),(a=t?.onProgress)===null||a===void 0||a.call(t,1),h}let y=(o=t?.attachments)===null||o===void 0?void 0:o.map(()=>pt()),v=y?y.length+1:1,_=new Array(v).fill(0),P=(b,k)=>{var S;_[k]=b,(S=t?.onProgress)===null||S===void 0||S.call(t,_.reduce((E,O)=>E+O,0)/v)};if(m){h.attachedStreamIds=y;let b=Io(h,void 0,{compression:Ae.DEFLATE_RAW}),k=Yt(b,t?.destinationIdentities);yield this.sendChunkedByteStream(k,c,t?.destinationIdentities,m.stream().pipeThrough(Ao(d.length,S=>P(S,0)))),d.length===0&&P(1,0)}else{let b=yield this.streamText({streamId:c,totalSize:l,destinationIdentities:t?.destinationIdentities,topic:t?.topic,attachedStreamIds:y,attributes:t?.attributes});yield b.write(e),P(1,0),yield b.close(),h=b.info}return t?.attachments&&y&&(yield Promise.all(t.attachments.map((b,k)=>g(this,void 0,void 0,function*(){return this._sendFile(y[k],b,{topic:t.topic,mimeType:b.type,destinationIdentities:t.destinationIdentities,compress:t.compress,onProgress:S=>{P(S,k+1)}})})))),h})}sendBytes(e,t){return g(this,void 0,void 0,function*(){var i,r,s,a,o,c,d;let l=pt(),u=t?.destinationIdentities,h=(i=t?.compress)!==null&&i!==void 0?i:!0,f={id:l,name:(r=t?.name)!==null&&r!==void 0?r:"unknown",mimeType:(s=t?.mimeType)!==null&&s!==void 0?s:"application/octet-stream",timestamp:Date.now(),topic:(a=t?.topic)!==null&&a!==void 0?a:"",size:e.byteLength,attributes:t?.attributes,encryptionType:!((o=this.engine.e2eeManager)===null||o===void 0)&&o.isDataChannelEncryptionEnabled?X.GCM:X.NONE},m=Ao(e.length,t?.onProgress),y=h&&On()&&this.allRecipientsSupportV2(u)&&this.allRecipientsSupportCompression(u)?as.fromStream(_r(e).pipeThrough(m).pipeThrough(Ro())):null;if(this.allRecipientsSupportV2(u)){let b=e,k=Ae.NONE;if(y){let O=yield y.collect();O.byteLength<e.byteLength&&(b=O,k=Ae.DEFLATE_RAW)}let S=dr(f,{compression:k,inlineContent:b}),E=Yt(S,u);if(E.toBinary().byteLength<=Zt)return yield this.engine.sendDataPacket(E,z.RELIABLE),(c=t?.onProgress)===null||c===void 0||c.call(t,1),f}let v=dr(f,{compression:y?Ae.DEFLATE_RAW:Ae.NONE}),_=Yt(v,u),P=y?y.stream():_r(e).pipeThrough(m);return yield this.sendChunkedByteStream(_,l,u,P),e.length===0&&((d=t?.onProgress)===null||d===void 0||d.call(t,1)),f})}allRecipientsSupportV2(e){return(e&&e.length>0?e:this.getAllRemoteParticipantIdentities()).every(i=>this.getRemoteParticipantClientProtocol(i)>=Jv)}allRecipientsSupportCompression(e){return(e&&e.length>0?e:this.getAllRemoteParticipantIdentities()).every(i=>this.getRemoteParticipantCapabilities(i).includes(Pi.CAP_COMPRESSION_DEFLATE_RAW))}sendChunkedByteStream(e,t,i,r){return g(this,void 0,void 0,function*(){var s,a,o,c;let d=this.engine;yield Mo(d,e);let l=0;try{for(var u=!0,h=ze(By(r,Zt)),f;f=yield h.next(),s=f.done,!s;u=!0){c=f.value,u=!1;let m=c,p=new Fe({destinationIdentities:i,value:{case:"streamChunk",value:new Pt({content:m,streamId:t,chunkIndex:at(l)})}});yield d.sendDataPacket(p,z.RELIABLE),l+=1}}catch(m){a={error:m}}finally{try{!u&&!s&&(o=h.return)&&(yield o.call(h))}finally{if(a)throw a.error}}yield Oo(t,i,d)})}streamText(e){return g(this,void 0,void 0,function*(){var t,i,r;let s=(t=e?.streamId)!==null&&t!==void 0?t:pt(),a=e?.destinationIdentities,o={id:s,mimeType:"text/plain",timestamp:Date.now(),topic:(i=e?.topic)!==null&&i!==void 0?i:"",size:e?.totalSize,attributes:e?.attributes,encryptionType:!((r=this.engine.e2eeManager)===null||r===void 0)&&r.isDataChannelEncryptionEnabled?X.GCM:X.NONE,attachedStreamIds:e?.attachedStreamIds},c=Io(o,e),d=Yt(c,a);yield Mo(this.engine,d);let l=0,u=this.engine,h=new WritableStream({write(p){return g(this,void 0,void 0,function*(){for(let y of Uy(p,Zt)){let v=new Pt({content:y,streamId:s,chunkIndex:at(l)}),_=new Fe({destinationIdentities:a,value:{case:"streamChunk",value:v}});yield u.sendDataPacket(_,z.RELIABLE),l+=1}})},close(){return g(this,void 0,void 0,function*(){yield Oo(s,a,u)})},abort(p){console.log("Sink error:",p)}}),f=()=>g(this,void 0,void 0,function*(){yield m.close()});u.once(A.Closing,f);let m=new Ja(h,o,()=>this.engine.off(A.Closing,f));return m})}sendFile(e,t){return g(this,void 0,void 0,function*(){let i=pt();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return g(this,void 0,void 0,function*(){var r,s,a,o,c;let d=i?.destinationIdentities,l=((r=i?.compress)!==null&&r!==void 0?r:!0)&&On()&&this.allRecipientsSupportV2(d)&&this.allRecipientsSupportCompression(d),u={id:e,name:t.name,mimeType:(s=i?.mimeType)!==null&&s!==void 0?s:t.type,topic:(a=i?.topic)!==null&&a!==void 0?a:"",timestamp:Date.now(),size:t.size,encryptionType:!((o=this.engine.e2eeManager)===null||o===void 0)&&o.isDataChannelEncryptionEnabled?X.GCM:X.NONE},h=dr(u,{compression:l?Ae.DEFLATE_RAW:Ae.NONE}),f=Yt(h,d),m=t.stream().pipeThrough(Ao(t.size,i?.onProgress)),p=l?m.pipeThrough(Ro()):m;return yield this.sendChunkedByteStream(f,e,d,p),t.size===0&&((c=i?.onProgress)===null||c===void 0||c.call(i,1)),u})}streamBytes(e){return g(this,void 0,void 0,function*(){var t,i,r,s,a;let o=(t=e?.streamId)!==null&&t!==void 0?t:pt(),c=e?.destinationIdentities,d={id:o,mimeType:(i=e?.mimeType)!==null&&i!==void 0?i:"application/octet-stream",topic:(r=e?.topic)!==null&&r!==void 0?r:"",timestamp:Date.now(),attributes:e?.attributes,size:e?.totalSize,name:(s=e?.name)!==null&&s!==void 0?s:"unknown",encryptionType:!((a=this.engine.e2eeManager)===null||a===void 0)&&a.isDataChannelEncryptionEnabled?X.GCM:X.NONE},l=dr(d),u=Yt(l,c);yield Mo(this.engine,u);let h=0,f=new ye,m=this.engine,p=this.log,y=new WritableStream({write(_){return g(this,void 0,void 0,function*(){let P=yield f.lock(),b=0;try{for(;b<_.byteLength;){let k=_.slice(b,b+Zt),S=new Fe({destinationIdentities:c,value:{case:"streamChunk",value:new Pt({content:k,streamId:o,chunkIndex:at(h)})}});yield m.sendDataPacket(S,z.RELIABLE),h+=1,b+=k.byteLength}}finally{P()}})},close(){return g(this,void 0,void 0,function*(){yield Oo(o,c,m)})},abort(_){p.error("Sink error:",_)}});return new $a(y,d)})}},as=class n{constructor(e){this.state=e}static fromStream(e){return new n({type:"stream",stream:e})}collect(){return g(this,void 0,void 0,function*(){switch(this.state.type){case"stream":let e=yield Zf(this.state.stream);return this.state={type:"collected",bytes:e},e;case"collected":return this.state.bytes}})}stream(){switch(this.state.type){case"stream":return this.state.stream;case"collected":return _r(this.state.bytes)}}};function Ao(n,e){let t=0;return new TransformStream({transform(i,r){t+=i.byteLength,e&&typeof n=="number"&&n>0&&e(Math.min(t/n,1)),r.enqueue(i)}})}function Mo(n,e){return g(this,void 0,void 0,function*(){if(e.toBinary().byteLength>Zt)throw new fe("data stream header exceeds the ".concat(Zt,"-byte limit; reduce attribute size"),de.HeaderTooLarge);yield n.sendDataPacket(e,z.RELIABLE)})}function Oo(n,e,t){return g(this,void 0,void 0,function*(){let i=new Fe({destinationIdentities:e,value:{case:"streamTrailer",value:new Nc({streamId:n})}});yield t.sendDataPacket(i,z.RELIABLE)})}var cs=sd("dataStreams",[],(n,e,t)=>{let i=new Ga(t??n.options.dataStream),r=new Qa(n.engine,e.log,d=>{var l,u;return(u=(l=n.remoteParticipants.get(d))===null||l===void 0?void 0:l.clientProtocol)!==null&&u!==void 0?u:zc},d=>{var l,u;return(u=(l=n.remoteParticipants.get(d))===null||l===void 0?void 0:l.capabilities)!==null&&u!==void 0?u:[]},()=>Array.from(n.remoteParticipants.keys())),s=d=>{var l;let u=n.getParticipantByIdentity(d);for(let h of(l=u?.trackPublications.values())!==null&&l!==void 0?l:[])if(h.source===C.Source.Microphone)return h.trackSid},a=d=>{for(let l of n.remoteParticipants.values())if(l.attributes[Nn.PublishOnBehalf]===d)return l.identity},o=new Ka({onTranscription:d=>e.handleTranscription(d),getMicrophoneTrackSid:s,getDelegatingPublisherIdentity:a});i.on("transcriptionStreamArrived",d=>{let l=d.reader,u=d.participantIdentity;o.handleTextStream(l,u)});let c=(d,l,u)=>i.handleDataStreamPacket(l,u);return n.on(R.ConnectionStateChanged,d=>i.setConnected(d===G.Connected)).on(R.ParticipantDisconnected,d=>i.validateParticipantHasNoActiveDataStreams(d.identity)),{incoming:i,outgoing:r,byteStreamOpener:d=>r.streamBytes(d),dataPackets:{streamHeader:c,streamChunk:c,streamTrailer:c},onEngineCreated:d=>r.setupEngine(d),onDisconnect:()=>{o.reset(),i.clearControllers()},room:{registerTextStreamHandler:(d,l)=>i.registerTextStreamHandler(d,l),unregisterTextStreamHandler:d=>i.unregisterTextStreamHandler(d),registerByteStreamHandler:(d,l)=>i.registerByteStreamHandler(d,l),unregisterByteStreamHandler:d=>i.unregisterByteStreamHandler(d)},localParticipant:{sendText:(d,l)=>r.sendText(d,l),streamText:d=>r.streamText(d),sendFile:(d,l)=>r.sendFile(d,l),sendBytes:(d,l)=>r.sendBytes(d,l),streamBytes:d=>r.streamBytes(d)}}}),np={deviceId:{ideal:"default"},resolution:_i.h720.resolution},Jb={simulcast:!0,screenShareEncoding:Ec.h1080fps15.encoding,videoCodec:xr,backupCodec:!0},$b={defaults:np,createTrack:(n,e,t,i)=>new ts(n,e,t,i)};function ud(){ub($b)}function Qb(n){return g(this,void 0,void 0,function*(){return ud(),(yield Es({audio:!1,video:n??!0}))[0]})}function Yb(n,e){let t=n.localParticipant,i=n.options;return{prepareInitial(r,s,a){var o,c,d;if((o=s.videoCodec)!==null&&o!==void 0||(s.videoCodec=xr),s.backupCodec=Lu(s.backupCodec),!["vp8","h264"].includes(s.videoCodec)||s.scalabilityMode||typeof s.backupCodec=="object"&&s.backupCodec.codec!==s.videoCodec)return;a.width=r.width,a.height=r.height,r.frameRate&&s.videoEncoding&&(s.videoEncoding=Object.assign(Object.assign({},s.videoEncoding),{maxFramerate:(c=s.videoEncoding.maxFramerate)!==null&&c!==void 0?c:r.frameRate}));let l=Si(!1,r.width,r.height,s);if(r.frameRate)for(let u of l)u.maxFramerate=Math.min((d=u.maxFramerate)!==null&&d!==void 0?d:r.frameRate,r.frameRate);return a.layers=qa(r.width,r.height,l),a.simulcastCodecs=[new kr({codec:s.videoCodec,layers:a.layers})],{encodings:l,startBitrate:Eu(s.videoCodec,s,l)}},prepare(r,s,a){return g(this,void 0,void 0,function*(){var o,c,d,l;!wy()&&n.hasE2EESetup&&(e.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2"),s.simulcast=!1),r.source===C.Source.ScreenShare&&fn()&&(s.simulcast=!1),s.videoCodec==="av1"&&!ly()&&(s.videoCodec=void 0),s.videoCodec==="vp9"&&!uy()&&(s.videoCodec=void 0),s.videoCodec===void 0&&(s.videoCodec=xr),t.enabledPublishVideoCodecs.length>0&&(t.enabledPublishVideoCodecs.some(y=>s.videoCodec===mi(y.mime))||(s.videoCodec=mi(t.enabledPublishVideoCodecs[0].mime)));let u=s.videoCodec,h;try{h=yield r.waitForDimensions()}catch{let v=(c=(o=i.videoCaptureDefaults)===null||o===void 0?void 0:o.resolution)!==null&&c!==void 0?c:_i.h720.resolution;h={width:v.width,height:v.height},e.error("could not determine track dimensions, using defaults",Object.assign(Object.assign({},K(r)),{dims:h}))}a.width=h.width,a.height=h.height,It(u)&&r.source===C.Source.ScreenShare&&(s.scalabilityMode="L1T3","contentHint"in r.mediaStreamTrack&&(r.mediaStreamTrack.contentHint="motion",e.debug("forcing contentHint to motion for screenshare with SVC codecs",K(r)))),In(u,s)&&(Ef()||!py((d=n.engine)===null||d===void 0?void 0:d.serverVersion))&&(s.simulcast=!1,e.info("SVC simulcast is not supported, disabling simulcast.",K(r)));let f=In(u,s);It(u)&&!f&&(s.scalabilityMode=(l=s.scalabilityMode)!==null&&l!==void 0?l:"L3T3_KEY");let m=new kr({codec:u,cid:r.mediaStreamTrack.id});f&&(m.videoLayerMode=Mc.ONE_SPATIAL_LAYER_PER_STREAM),a.simulcastCodecs=[m],s.backupCodec=Lu(s.backupCodec),s.backupCodec&&u!==s.backupCodec.codec&&a.encryption===X.NONE&&(i.dynacast||(i.dynacast=!0),a.simulcastCodecs.push(new kr({codec:s.backupCodec.codec,cid:""})));let p=Si(r.source===C.Source.ScreenShare,a.width,a.height,s);return a.layers=qa(a.width,a.height,p,It(s.videoCodec)&&!In(s.videoCodec,s)),p})},senderCreated(r,s,a,o){var c,d;if((c=s.degradationPreference)!==null&&c!==void 0||(s.degradationPreference=Lb(r)),r.setDegradationPreference(s.degradationPreference),a&&r.codec&&Af(r.codec)){let l=Eu(r.codec,s,a);l>0&&((d=n.engine.pcManager)===null||d===void 0||d.publisher.setTrackCodecBitrate({cid:o.cid,codec:r.codec,maxbr:l/1e3,isScreenShare:r.source===C.Source.ScreenShare}))}},serverCodecChanged(r,s,a,o){let c;if(a.codecs.forEach(l=>{c===void 0&&(c=l.mimeType)}),!c)return;let d=mi(c);if(d!==s.videoCodec)return e.debug("falling back to server selected codec",Object.assign(Object.assign({},K(r)),{codec:d})),s.videoCodec=d,Si(r.source===C.Source.ScreenShare,o.width,o.height,s)},createScreenTracks:r=>ip(n,r)}}function ip(n,e){return g(this,void 0,void 0,function*(){let t=n.localParticipant;if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Ri("getDisplayMedia not supported");e.resolution===void 0&&!ky()&&(e.resolution=Ec.h1080fps30.resolution);let i=ty(e),r=yield navigator.mediaDevices.getDisplayMedia(i),s=r.getVideoTracks();if(s.length===0)throw new le("no video track found");let a=new ts(s[0],void 0,!1,t.trackLoggerOptions);a.source=C.Source.ScreenShare,e.contentHint&&(a.mediaStreamTrack.contentHint=e.contentHint);let o=[a];if(r.getAudioTracks().length>0){t.emit(L.AudioStreamAcquired);let c=new jn(r.getAudioTracks()[0],void 0,!1,t.audioContext,t.trackLoggerOptions);c.source=C.Source.ScreenShareAudio,o.push(c)}return o})}function Xb(n){return g(this,void 0,void 0,function*(){let e=n.localParticipant;if(!(e.pendingPublishing.has(C.Source.Camera)||e.pendingPublishing.has(C.Source.Microphone))){e.pendingPublishing.add(C.Source.Camera),e.pendingPublishing.add(C.Source.Microphone);try{let t=yield e.createTracks({audio:!0,video:!0});yield Promise.all(t.map(i=>e.publishTrack(i)))}finally{e.pendingPublishing.delete(C.Source.Camera),e.pendingPublishing.delete(C.Source.Microphone)}}})}function rp(n,e,t,i,r){return g(this,void 0,void 0,function*(){var s;let a=n.localParticipant;if(a.isE2EEEnabled)return;let o;if(a.trackPublications.forEach(S=>{S.track&&S.track===t&&(o=S)}),!o)throw new le("track is not published");if(!We(t))throw new le("track is not a video track");let c=Object.assign(Object.assign({},(s=n.options)===null||s===void 0?void 0:s.publishDefaults),r),d=zf(t,i,c);if(!d){e.info("backup codec has been disabled, ignoring request to add additional codec for track",K(t));return}let l=t.addSimulcastTrack(i,d);if(!l)return;let u=a.normalizeRequestedFrameMetadataOptions(t,c),h=t.mediaStreamTrack.getSettings(),f=h.width,m=h.height,p=f&&m?{width:f,height:m}:void 0;p||e.warn("could not determine track dimensions, publishing backup codec without layers",K(t));let y=p?qa(p.width,p.height,d):[],v=new dn({cid:l.mediaStreamTrack.id,type:C.kindToProto(t.kind),muted:t.isMuted,source:C.sourceToProto(t.source),sid:t.sid,width:p?.width,height:p?.height,packetTrailerFeatures:u,layers:y,simulcastCodecs:[{codec:c.videoCodec,cid:l.mediaStreamTrack.id,layers:y}]}),_=n.engine;if(!_||_.isClosed)throw new J("cannot publish track when not connected");let P=()=>g(this,void 0,void 0,function*(){yield _.createSimulcastSender(t,l,c,d),yield _.negotiate()}),k=(yield Promise.all([_.addTrack(v),P()]))[0];e.debug("published ".concat(i," for track ").concat(t.sid),{encodings:d,trackInfo:k})})}function Zb(n,e,t){return g(this,void 0,void 0,function*(){var i,r,s,a,o;if(!(!((o=n.options)===null||o===void 0)&&o.dynacast))return;let c=n.localParticipant.videoTrackPublications.get(t.trackSid);if(!c){e.warn("received subscribed quality update for unknown track",{trackSid:t.trackSid});return}if(!c.videoTrack)return;let d=yield c.videoTrack.setPublishingCodecs(t.subscribedCodecs);try{for(var l=!0,u=ze(d),h;h=yield u.next(),i=h.done,!i;l=!0){a=h.value,l=!1;let f=a;kh(f)&&(e.debug("publish ".concat(f," for ").concat(c.videoTrack.sid),K(c)),yield rp(n,e,c.videoTrack,f,c.options))}}catch(f){r={error:f}}finally{try{!l&&!i&&(s=u.return)&&(yield s.call(u))}finally{if(r)throw r.error}}})}function Lu(n){return n===!0?{codec:xr}:n}var sp={key:Symbol("lk.extension.video"),install(n,e){ud(),n.options.videoCaptureDefaults=Object.assign(Object.assign({},np),n.options.videoCaptureDefaults),n.options.publishDefaults=Object.assign(Object.assign({},Jb),n.options.publishDefaults);let t=n.localParticipant;return{videoPublisher:Yb(n,e.log),onEngineCreated:i=>{i.on(A.SubscribedQualityUpdate,r=>Zb(n,e.log,r))},localParticipant:{setCameraEnabled:(i,r,s)=>t.setTrackEnabled(C.Source.Camera,i,r,s),setScreenShareEnabled:(i,r,s)=>t.setTrackEnabled(C.Source.ScreenShare,i,r,s),enableCameraAndMicrophone:()=>Xb(n),createScreenTracks:i=>ip(n,i),publishAdditionalCodecForTrack:(i,r,s)=>rp(n,e.log,i,r,s)}}}},ek=n=>Ub(n,[cs,sp]),rt;(function(n){n[n.IDLE=0]="IDLE",n[n.RUNNING=1]="RUNNING",n[n.SKIPPED=2]="SKIPPED",n[n.SUCCESS=3]="SUCCESS",n[n.FAILED=4]="FAILED"})(rt||(rt={}));var kt=class extends Oe.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=rt.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=ek(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return g(this,void 0,void 0,function*(){if(this.status!==rt.IDLE)throw Error("check is running already");this.setStatus(rt.RUNNING);try{yield this.perform()}catch(t){t instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(t.message):this.appendError(t.message))}return yield this.disconnect(),yield new Promise(t=>setTimeout(t,500)),this.status!==rt.SKIPPED&&this.setStatus(this.isSuccess()?rt.SUCCESS:rt.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return g(this,void 0,void 0,function*(){return this.room.state===G.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return g(this,void 0,void 0,function*(){this.room&&this.room.state!==G.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(rt.SKIPPED)}switchProtocol(e){return g(this,void 0,void 0,function*(){let t=!1,i=!1;if(this.room.on(R.Reconnecting,()=>{t=!0}),this.room.once(R.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(s=>setTimeout(s,1e3)),!t)return;let r=Date.now()+1e4;for(;Date.now()<r;){if(i)return;yield Re(100)}throw new Error("Could not reconnect using ".concat(e," protocol after 10 seconds"))})}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return(e=this.room)===null||e===void 0?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}},Ya=class extends kt{get description(){return"Cloud regions"}perform(){return g(this,void 0,void 0,function*(){let e=new ct(this.url,this.token);if(!e.isCloud()){this.skip();return}let t=[],i=new Set;for(let s=0;s<3;s++){let a=yield e.getNextBestRegionUrl();if(!a)break;if(i.has(a))continue;i.add(a);let o=yield this.checkCloudRegion(a);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),t.push(o)}t.sort((s,a)=>(s.duration-a.duration)*.5+(s.rtt-a.rtt)*.5);let r=t[0];this.bestStats=r,this.appendMessage("best Cloud region: ".concat(r.region))})}getInfo(){let e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return g(this,void 0,void 0,function*(){var t,i;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));let r=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!r)throw new Error("Region not found");let s=yield this.room.localParticipant.streamText({topic:"test"}),a=1e3,c=1e6/a,d="A".repeat(a),l=Date.now();for(let m=0;m<c;m++)yield s.write(d);yield s.close();let u=Date.now(),h=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),f={region:r,rtt:1e4,duration:u-l};return h?.forEach(m=>{m.type==="candidate-pair"&&m.nominated&&(f.rtt=m.currentRoundTripTime*1e3)}),yield this.disconnect(),f})}},xo=1e4,Xa=class extends kt{get description(){return"Connection via UDP vs TCP"}perform(){return g(this,void 0,void 0,function*(){let e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):this.appendMessage("best connection quality via udp");let i=this.bestStats;this.appendMessage("upstream bitrate: ".concat((i.bitrateTotal/i.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((i.rttTotal/i.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((i.jitterTotal/i.count*1e3).toFixed(2)," ms")),i.packetsLost>0&&this.appendWarning("packets lost: ".concat((i.packetsLost/i.packetsSent*100).toFixed(2),"%")),i.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((i.qualityLimitationDurations.bandwidth/(xo/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(xo/1e3)*100).toFixed(2),"%"))})}getInfo(){let e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return g(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");let t=document.createElement("canvas");t.width=1280,t.height=720;let i=t.getContext("2d");if(!i)throw new Error("Could not get canvas context");let r=0,s=()=>{r=(r+1)%360,i.fillStyle="hsl(".concat(r,", 100%, 50%)"),i.fillRect(0,0,t.width,t.height),requestAnimationFrame(s)};s();let o=t.captureStream(30).getVideoTracks()[0],d=(yield this.room.localParticipant.publishTrack(o,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,l={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},u=setInterval(()=>g(this,void 0,void 0,function*(){let h=yield d.getRTCStatsReport();h?.forEach(f=>{f.type==="outbound-rtp"?(l.packetsSent=f.packetsSent,l.qualityLimitationDurations=f.qualityLimitationDurations,l.bitrateTotal+=f.targetBitrate,l.count++):f.type==="remote-inbound-rtp"&&(l.packetsLost=f.packetsLost,l.rttTotal+=f.roundTripTime,l.jitterTotal+=f.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,xo)),clearInterval(u),o.stop(),t.remove(),yield this.disconnect(),l})}},Za=class extends kt{get description(){return"Can publish audio"}perform(){return g(this,void 0,void 0,function*(){var e;let t=yield this.connect(),i=yield hb();if(yield Sf(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,3e3));let s=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let a=0;if(s.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="audio"||!o.kind&&o.mediaType==="audio")&&(a=o.packetsSent)}),a===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(a," audio packets"))})}},ec=class extends kt{get description(){return"Can publish video"}perform(){return g(this,void 0,void 0,function*(){var e;let t=yield this.connect(),i=yield Qb();yield this.checkForVideo(i.mediaStreamTrack),t.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,5e3));let r=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let s=0;if(r.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="video"||!a.kind&&a.mediaType==="video")&&(s+=a.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," video packets"))})}checkForVideo(e){return g(this,void 0,void 0,function*(){let t=new MediaStream;t.addTrack(e.clone());let i=document.createElement("video");i.srcObject=t,i.muted=!0,i.autoplay=!0,i.playsInline=!0,i.setAttribute("playsinline","true"),document.body.appendChild(i),yield new Promise(r=>{i.onplay=()=>{setTimeout(()=>{var s,a,o,c;let d=document.createElement("canvas"),l=e.getSettings(),u=(a=(s=l.width)!==null&&s!==void 0?s:i.videoWidth)!==null&&a!==void 0?a:1280,h=(c=(o=l.height)!==null&&o!==void 0?o:i.videoHeight)!==null&&c!==void 0?c:720;d.width=u,d.height=h;let f=d.getContext("2d");f.drawImage(i,0,0);let p=f.getImageData(0,0,d.width,d.height).data,y=!0;for(let v=0;v<p.length;v+=4)if(p[v]!==0||p[v+1]!==0||p[v+2]!==0){y=!1;break}y?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),r()},1e3)},i.play()}),t.getTracks().forEach(r=>r.stop()),i.remove()})}},tc=class extends kt{get description(){return"Resuming connection after interruption"}perform(){return g(this,void 0,void 0,function*(){var e;let t=yield this.connect(),i=!1,r=!1,s,a=new Promise(c=>{setTimeout(c,5e3),s=c}),o=()=>{i=!0};if(t.on(R.SignalReconnecting,o).on(R.Reconnecting,o).on(R.Reconnected,()=>{r=!0,s(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close(),t.engine.client.emit(N.Close,""),yield a,i){if(!r||t.state!==G.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}else throw new Error("Did not attempt to reconnect")})}},nc=class extends kt{get description(){return"Can connect via TURN"}perform(){return g(this,void 0,void 0,function*(){var e,t,i;qn(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(e=yield new ct(this.url,this.token).getNextBestRegionUrl())!==null&&e!==void 0?e:this.url);let r=new Oi,s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0),a=!1,o=!1,c=!1;for(let d of s.iceServers)for(let l of d.urls)l.startsWith("turn:")?(o=!0,c=!0):l.startsWith("turns:")&&(o=!0,c=!0,a=!0),l.startsWith("stun:")&&(c=!0);c?o&&!a&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield r.close(),!((i=(t=this.connectOptions)===null||t===void 0?void 0:t.rtcConfig)===null||i===void 0)&&i.iceServers||o?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(d=>setTimeout(d,0)))})}},ic=class extends kt{get description(){return"Establishing WebRTC connection"}perform(){return g(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(R.SignalConnected,()=>{var i;this.room.engine.client.on(N.Trickle,r=>{if(r.candidate){let s=new RTCIceCandidate(r),a="".concat(s.protocol," ").concat(s.address,":").concat(s.port," ").concat(s.type);s.address&&(tk(s.address)?a+=" (private)":s.protocol==="tcp"&&s.tcpType==="passive"?(e=!0,a+=" (passive)"):s.protocol==="udp"&&(t=!0)),this.appendMessage(a)}}),!((i=this.room.engine.pcManager)===null||i===void 0)&&i.subscriber&&(this.room.engine.pcManager.subscriber.onIceCandidateError=r=>{r instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(r.errorCode," ").concat(r.errorText," ").concat(r.url))})});try{yield this.connect(),W.info("now the room is connected")}catch(i){throw this.appendWarning("ports need to be open on firewall in order to connect."),i}e||this.appendWarning("Server is not configured for ICE/TCP"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}};function tk(n){let e=n.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){let t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}var rc=class extends kt{get description(){return"Connecting to signal connection via WebSocket"}perform(){return g(this,void 0,void 0,function*(){var e,t,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let r=new Oi,s;try{s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(a){if(qn(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(a.message,". Retrying with region fallback"));let c=yield new ct(this.url,this.token).getNextBestRegionUrl();c&&(s=yield r.join(c,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0),this.appendMessage("Fallback to region worked. To avoid initial connections failing, ensure you're calling room.prepareConnection() ahead of time"))}}s?(this.appendMessage("Connected to server, version ".concat(s.serverVersion,".")),((e=s.serverInfo)===null||e===void 0?void 0:e.edition)===ef.Cloud&&(!((t=s.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=s.serverInfo)===null||i===void 0?void 0:i.region))):this.appendError("Websocket connection could not be established"),yield r.close()})}},Du=class extends Oe.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=i}getNextCheckId(){let e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:rt.IDLE,name:"",description:""}),e}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==rt.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return g(this,void 0,void 0,function*(){let t=this.getNextCheckId(),i=new e(this.url,this.token,this.options),r=a=>{this.updateCheck(t,a)};i.on("update",r);let s=yield i.run();return i.off("update",r),s})}checkWebsocket(){return g(this,void 0,void 0,function*(){return this.createAndRunCheck(rc)})}checkWebRTC(){return g(this,void 0,void 0,function*(){return this.createAndRunCheck(ic)})}checkTURN(){return g(this,void 0,void 0,function*(){return this.createAndRunCheck(nc)})}checkReconnect(){return g(this,void 0,void 0,function*(){return this.createAndRunCheck(tc)})}checkPublishAudio(){return g(this,void 0,void 0,function*(){return this.createAndRunCheck(Za)})}checkPublishVideo(){return g(this,void 0,void 0,function*(){return this.createAndRunCheck(ec)})}checkConnectionProtocol(){return g(this,void 0,void 0,function*(){let e=yield this.createAndRunCheck(Xa);if(e.data&&"protocol"in e.data){let t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return g(this,void 0,void 0,function*(){return this.createAndRunCheck(Ya)})}},Vt;(function(n){n.SetKey="setKey",n.RatchetRequest="ratchetRequest",n.KeyRatcheted="keyRatcheted"})(Vt||(Vt={}));var Nu;(function(n){n.KeyRatcheted="keyRatcheted"})(Nu||(Nu={}));var vt;(function(n){n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError"})(vt||(vt={}));var Fu;(function(n){n.Error="cryptorError"})(Fu||(Fu={}));var Uu=class extends Oe.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.latestManuallySetKeyIndex=0,this.onKeyRatcheted=(t,i,r)=>{W.debug("key ratcheted event received",{participantId:i,keyIndex:r})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},Qy),e),this.on(Vt.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,i){let r={key:e,participantIdentity:t,keyIndex:i};if(!this.options.sharedKey&&!t)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(t??"shared","-").concat(i??0),r),i!==void 0&&(this.latestManuallySetKeyIndex=i),this.emit(Vt.SetKey,r,i!==void 0)}getKeys(){return Array.from(this.keyInfoMap.values())}getLatestManuallySetKeyIndex(){return this.latestManuallySetKeyIndex}getOptions(){return this.options}ratchetKey(e,t){this.emit(Vt.RatchetRequest,e,t)}};var ds;(function(n){n[n.InvalidKey=0]="InvalidKey",n[n.MissingKey=1]="MissingKey",n[n.InternalError=2]="InternalError"})(ds||(ds={}));var sc=class extends Ye{constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:ds.InternalError,i=arguments.length>2?arguments[2]:void 0;super(40,e),this.reason=t,this.participantIdentity=i}};new TextEncoder;var DT=new TextDecoder,NT=new TextDecoder("utf-8",{fatal:!0});var Ie=class extends Error{constructor(e,t){var i;super(e,t),j(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,(i=Error.captureStackTrace)===null||i===void 0||i.call(Error,this,this.constructor)}};j(Ie,"code","ERR_JOSE_GENERIC");var oc=class extends Ie{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:r,payload:t}}),j(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),j(this,"claim",void 0),j(this,"reason",void 0),j(this,"payload",void 0),this.claim=i,this.reason=r,this.payload=t}};j(oc,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");var ac=class extends Ie{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:r,payload:t}}),j(this,"code","ERR_JWT_EXPIRED"),j(this,"claim",void 0),j(this,"reason",void 0),j(this,"payload",void 0),this.claim=i,this.reason=r,this.payload=t}};j(ac,"code","ERR_JWT_EXPIRED");var cc=class extends Ie{constructor(){super(...arguments),j(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}};j(cc,"code","ERR_JOSE_ALG_NOT_ALLOWED");var dc=class extends Ie{constructor(){super(...arguments),j(this,"code","ERR_JOSE_NOT_SUPPORTED")}};j(dc,"code","ERR_JOSE_NOT_SUPPORTED");var lc=class extends Ie{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"decryption operation failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),j(this,"code","ERR_JWE_DECRYPTION_FAILED")}};j(lc,"code","ERR_JWE_DECRYPTION_FAILED");var uc=class extends Ie{constructor(){super(...arguments),j(this,"code","ERR_JWE_INVALID")}};j(uc,"code","ERR_JWE_INVALID");var hc=class extends Ie{constructor(){super(...arguments),j(this,"code","ERR_JWS_INVALID")}};j(hc,"code","ERR_JWS_INVALID");var fc=class extends Ie{constructor(){super(...arguments),j(this,"code","ERR_JWT_INVALID")}};j(fc,"code","ERR_JWT_INVALID");var pc=class extends Ie{constructor(){super(...arguments),j(this,"code","ERR_JWK_INVALID")}};j(pc,"code","ERR_JWK_INVALID");var mc=class extends Ie{constructor(){super(...arguments),j(this,"code","ERR_JWKS_INVALID")}};j(mc,"code","ERR_JWKS_INVALID");var gc=class extends Ie{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"no applicable key found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),j(this,"code","ERR_JWKS_NO_MATCHING_KEY")}};j(gc,"code","ERR_JWKS_NO_MATCHING_KEY");var vc=class extends Ie{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"multiple matching keys found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),j(this,Symbol.asyncIterator,pg(function*(){})),j(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};j(vc,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");var yc=class extends Ie{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"request timed out",t=arguments.length>1?arguments[1]:void 0;super(e,t),j(this,"code","ERR_JWKS_TIMEOUT")}};j(yc,"code","ERR_JWKS_TIMEOUT");var bc=class extends Ie{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"signature verification failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),j(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}};j(bc,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");var nk=1e3,FT=60*nk;var ls=class n extends Oe.EventEmitter{get logContext(){var e,t;return{room:(e=this.room)===null||e===void 0?void 0:e.name,participant:(t=this.room)===null||t===void 0?void 0:t.localParticipant.identity}}constructor(e,t){super(),this.keysPostedToWorker=new WeakSet,this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.log=we(he.E2EE,()=>this.logContext),this.onWorkerMessage=i=>{var r;let s=i.data,a=s.kind,o=s.data;switch(a){case"error":{let l=new Error(o.error.message);if(l.name=o.error.name,o.error.stack&&(l.stack=o.error.stack),o.uuid){let u=this.decryptDataRequests.get(o.uuid);if(u?.reject){u.reject(l);break}let h=this.encryptDataRequests.get(o.uuid);if(h?.reject){h.reject(l);break}}this.log.error(l.message),this.emit(vt.EncryptionError,l,o.participantIdentity);break}case"initAck":o.enabled&&this.keyProvider.getKeys().forEach(l=>{this.postKey(l,!1)});break;case"enable":if(o.local)this.encryptionEnabled!==o.enabled&&(this.emit(vt.ParticipantEncryptionStatusChanged,o.enabled,this.room.localParticipant),this.encryptionEnabled=o.enabled);else if(o.participantIdentity){let l=(r=this.room)===null||r===void 0?void 0:r.getParticipantByIdentity(o.participantIdentity);if(!l)throw TypeError("couldn't set encryption status, participant not found".concat(o.participantIdentity));this.emit(vt.ParticipantEncryptionStatusChanged,o.enabled,l)}break;case"ratchetKey":this.keyProvider.emit(Vt.KeyRatcheted,o.ratchetResult,o.participantIdentity,o.keyIndex);break;case"decryptDataResponse":let c=this.decryptDataRequests.get(o.uuid);c?.resolve&&c.resolve(o);break;case"encryptDataResponse":let d=this.encryptDataRequests.get(o.uuid);d?.resolve&&d.resolve(o);break;case"packetTrailerMetadata":this.handleFrameMetadata(o.trackId,o.rtpTimestamp,o.ssrc,o.metadata);break;case"log":Bn[o.level](o.msg,o.context);break}},this.onWorkerError=i=>{this.log.error("e2ee worker encountered an error:",{error:i.error}),this.emit(vt.EncryptionError,i.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!Yy())throw new Ri("tried to setup end-to-end encryption on an unsupported browser");if(this.log.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);let t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:Bn.getLevel()}};this.worker&&(this.log.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t),this.subscribeToLogLevelChanges())}}subscribeToLogLevelChanges(){var e;(e=this.unsubscribeLogLevel)===null||e===void 0||e.call(this);let t;if(n.disposeRegistry){let i=new WeakRef(this.worker);t=Fl(r=>{let s=i.deref();if(!s){t?.();return}s.postMessage({kind:"setLogLevel",data:{level:r}})}),n.disposeRegistry.register(this,t,this)}else{let i=this.worker;t=Fl(r=>{i.postMessage({kind:"setLogLevel",data:{level:r}})})}this.unsubscribeLogLevel=t}dispose(){var e,t,i;(e=this.unsubscribeLogLevel)===null||e===void 0||e.call(this),this.unsubscribeLogLevel=void 0,n.disposeRegistry&&n.disposeRegistry.unregister(this);let r=new sc("E2EEManager disposed",ds.InternalError);for(let s of[...this.encryptDataRequests.values()])(t=s.reject)===null||t===void 0||t.call(s,r);for(let s of[...this.decryptDataRequests.values()])(i=s.reject)===null||i===void 0||i.call(s,r);this.worker&&(this.worker.onmessage=null,this.worker.onerror=null),this.removeAllListeners()}setLocalParticipantCryptorEnabled(e){var t,i;this.log.debug("set e2ee to ".concat(e," for the local participant")),this.postEnable(e,(i=(t=this.room)===null||t===void 0?void 0:t.localParticipant.identity)!==null&&i!==void 0?i:"",!0)}setParticipantCryptorEnabled(e,t){this.setLocalParticipantCryptorEnabled(e)}setSifTrailer(e){!e||e.length===0?this.log.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}handleFrameMetadata(e,t,i,r){if(this.room){for(let s of[this.room.localParticipant,...this.room.remoteParticipants.values()])for(let a of s.trackPublications.values())if(a.track&&a.track.mediaStreamID===e&&a.track instanceof Li&&a.track.frameMetadataExtractor){a.track.frameMetadataExtractor.storeMetadata(t,i,r);return}}}setupEngine(e){e.on(A.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(R.TrackPublished,(i,r)=>this.setParticipantCryptorEnabledForPublication(i,r.identity)),e.on(R.ConnectionStateChanged,i=>{i===G.Connected&&e.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{this.setParticipantCryptorEnabledForPublication(s,r.identity)})})}).on(R.TrackUnsubscribed,(i,r,s)=>{var a;let o={kind:"removeTransform",data:{participantIdentity:s.identity,trackId:i.mediaStreamID}};(a=this.worker)===null||a===void 0||a.postMessage(o)}).on(R.TrackSubscribed,(i,r,s)=>{this.setupE2EEReceiver(i,s.identity,r.trackInfo)}).on(R.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");let i=t.getLatestManuallySetKeyIndex();t.getKeys().filter(r=>!this.keysPostedToWorker.has(r)).forEach(r=>{var s;this.postKey(r,i===((s=r.keyIndex)!==null&&s!==void 0?s:0))}),this.setLocalParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled)}),e.localParticipant.on(L.LocalSenderCreated,(i,r)=>g(this,void 0,void 0,function*(){this.setupE2EESender(r,i)})),e.localParticipant.on(L.LocalTrackPublished,i=>{if(!Mt(i.track)||!qe())return;let r={kind:"updateCodec",data:{trackId:i.track.mediaStreamID,codec:mi(i.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity,hasPacketTrailer:!1,operation:"encode"}};this.worker.postMessage(r)}),t.on(Vt.SetKey,(i,r)=>this.postKey(i,r??!0)).on(Vt.RatchetRequest,(i,r)=>this.postRatchetRequest(i,r))}encryptData(e){return g(this,void 0,void 0,function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");let t=pt(),i={kind:"encryptDataRequest",data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},r=new Ce;return r.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,r),this.worker.postMessage(i),r.promise})}handleEncryptedData(e,t,i,r){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");let s=pt(),a={kind:"decryptDataRequest",data:{uuid:s,payload:e,iv:t,participantIdentity:i,keyIndex:r}},o=new Ce;return o.onFinally=()=>{this.decryptDataRequests.delete(s)},this.decryptDataRequests.set(s,o),this.worker.postMessage(a),o.promise}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");let i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(i)}postKey(e,t){var i;if(!this.worker)throw Error("could not set key, worker is missing");let r=e.key,s=e.participantIdentity,a=e.keyIndex,o={kind:"setKey",data:{participantIdentity:s,isPublisher:s===((i=this.room)===null||i===void 0?void 0:i.localParticipant.identity),key:r,keyIndex:a,updateCurrentKeyIndex:t}};this.worker.postMessage(o),this.keysPostedToWorker.add(e)}postEnable(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;if(this.worker){let r={kind:"enable",data:{enabled:e,participantIdentity:t,local:i}};this.worker.postMessage(r)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((t=this.room)===null||t===void 0)&&t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");let i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");let t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setParticipantCryptorEnabledForPublication(e,t){if(!e.trackInfo){this.log.warn("skipping e2ee enabled update for publication without trackInfo",{trackSid:e.trackSid});return}this.postEnable(e.trackInfo.encryption!==X.NONE,t)}setupE2EEReceiver(e,t,i){if(!e.receiver)return;if(!i?.mimeType||i.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");let r=e.kind==="video"&&!!i.packetTrailerFeatures&&i.packetTrailerFeatures.length>0;this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?mi(i.mimeType):void 0,r,i.encryption!==X.NONE)}setupE2EESender(e,t){var i;if(!Mn(e)||!t){t||this.log.warn("early return because sender is not ready");return}let r=Mt(e),s=r?(i=e.publishOptions)===null||i===void 0?void 0:i.videoCodec:void 0;this.handleSender(t,e.mediaStreamID,s==="h264"||s==="h265"?s:void 0,r?Zc(e.publishOptions):void 0)}handleReceiver(e,t,i,r,s,a){return g(this,void 0,void 0,function*(){if(this.worker){if(ha()){let o={kind:"decode",participantIdentity:i,trackId:t,codec:r,hasPacketTrailer:s,encrypted:a};e.transform=new RTCRtpScriptTransform(this.worker,o)}else{if(sr in e&&or in e){let l={kind:"updateCodec",data:{trackId:t,previousTrackId:e[or],codec:r,participantIdentity:i,hasPacketTrailer:s,encrypted:a}};this.worker.postMessage(l),e[or]=t;return}let o=e.writableStream,c=e.readableStream;if(!o||!c){let l=e.createEncodedStreams();e.writableStream=l.writable,o=l.writable,e.readableStream=l.readable,c=l.readable}let d={kind:"decode",data:{readableStream:c,writableStream:o,trackId:t,codec:r,participantIdentity:i,hasPacketTrailer:s,encrypted:a}};this.worker.postMessage(d,[c,o])}e[sr]=!0,e[or]=t}})}handleSender(e,t,i,r){var s;if(!(sr in e||!this.worker)){if(!(!((s=this.room)===null||s===void 0)&&s.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(ha()){this.log.info("initialize script transform");let a={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i,hasPacketTrailer:Ar(r),packetTrailer:r};e.transform=new RTCRtpScriptTransform(this.worker,a)}else{this.log.info("initialize encoded streams");let a=e.createEncodedStreams(),o={kind:"encode",data:{readableStream:a.readable,writableStream:a.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity,hasPacketTrailer:Ar(r),packetTrailer:r}};this.worker.postMessage(o,[a.readable,a.writable])}e[sr]=!0}}};ls.disposeRegistry=typeof FinalizationRegistry<"u"&&typeof WeakRef<"u"&&new FinalizationRegistry(n=>{n()});var ik=sd("e2ee",[],(n,e,t)=>{let i=!n.options.e2ee,r=t??(n.options.encryption||n.options.e2ee),s,a=()=>{};if(r){if("e2eeManager"in r)s=r.e2eeManager,s.isDataChannelEncryptionEnabled=i;else{let l=new ls(r,i);s=l,a=()=>{l.dispose(),r.worker.terminate()}}let c=(l,u)=>{Fy(u)&&(n.isE2EEEnabled=l),n.emit(R.ParticipantEncryptionStatusChanged,l,u)},d=(l,u)=>{let h=u?n.getParticipantByIdentity(u):void 0;n.emit(R.EncryptionError,l,h)};if(s.on(vt.ParticipantEncryptionStatusChanged,c),s.on(vt.EncryptionError,d),"e2eeManager"in r){let l=s;a=()=>{l.off(vt.ParticipantEncryptionStatusChanged,c),l.off(vt.EncryptionError,d)}}s.setup(n),s.setupEngine(n.engine)}let o=new ye;return{manager:s,e2eeManager:s,room:{setE2EEEnabled:c=>g(void 0,void 0,void 0,function*(){let d=yield o.lock();try{if(s)n.isE2EEEnabled!==c&&(yield n.localParticipant.setE2EEEnabled(c),s.setLocalParticipantCryptorEnabled?s.setLocalParticipantCryptorEnabled(c):n.localParticipant.identity!==""&&s.setParticipantCryptorEnabled(c,n.localParticipant.identity));else throw Error("e2ee not configured, please set e2ee settings within the room options")}finally{d()}})},dispose:a}}),rk=sd("frameMetadata",[],(n,e,t)=>{var i;let r=(i=t??n.options.frameMetadata)!==null&&i!==void 0?i:n.options.packetTrailer,s=new Ha(r);return s.setup(n),{manager:s,frameMetadataOptions:r,dispose:()=>s.dispose()}}),sk={key:Symbol("lk.extension.chat"),install(n,e){let t=n.localParticipant;t.on(L.ChatMessage,r=>{n.emit(R.ChatMessage,r,t)});let i=r=>g(this,void 0,void 0,function*(){let s=new Fe({value:{case:"chatMessage",value:new xc(Object.assign(Object.assign({},r),{timestamp:ue.parse(r.timestamp),editTimestamp:r.editTimestamp!==void 0?ue.parse(r.editTimestamp):void 0}))}});return yield n.engine.sendDataPacket(s,z.RELIABLE),t.emit(L.ChatMessage,r),r});return{dataPackets:{chatMessage:(r,s,a,o)=>{n.emit(R.ChatMessage,Dy(r),o)}},localParticipant:{sendChatMessage:(r,s)=>i({id:pt(),message:r,timestamp:Date.now(),attachedFiles:s?.attachments}),editChatMessage:(r,s)=>i(Object.assign(Object.assign({},s),{message:r,editTimestamp:Date.now()}))}}}},Lo=we(he.DataTracks),en=class n extends Be{constructor(e,t,i,r){super(19,"Frame ".concat(i," dropped: ").concat(e),r),this.name="DataTrackDepacketizerDropError",this.reason=t,this.reasonName=tn[t],this.frameNumber=i}static interrupted(e,t){return new n("Interrupted by the start of a new frame ".concat(t),tn.Interrupted,e)}static unknownFrame(e){return new n("Initial packet was never received.",tn.UnknownFrame,e)}static bufferFull(e){return new n("Reorder buffer is full.",tn.BufferFull,e)}static incomplete(e,t,i){return new n("Not all packets received before final packet. Received ".concat(t," packets, expected ").concat(i," packets."),tn.Incomplete,e)}},tn;(function(n){n[n.Interrupted=0]="Interrupted",n[n.UnknownFrame=1]="UnknownFrame",n[n.BufferFull=2]="BufferFull",n[n.Incomplete=3]="Incomplete"})(tn||(tn={}));var us=class n{constructor(){this.partials=new Map}push(e,t){switch(e.header.marker){case ce.Single:return this.frameFromSingle(e,t);case ce.Start:return this.beginPartial(e,t);case ce.Inter:case ce.Final:return this.pushToPartial(e)}}reset(){this.partials.clear()}peekOldestPartialFrameNumber(){let e=this.partials.keys().next();return e.done?null:e.value}frameFromSingle(e,t){var i;if(e.header.marker!==ce.Single)throw new Error("Depacketizer.frameFromSingle: packet.header.marker was not FrameMarker.Single, found ".concat(e.header.marker,"."));let r=(i=t?.maxPartialFrames)!==null&&i!==void 0?i:1;if(this.partials.size>=r){let s=this.peekOldestPartialFrameNumber();if(typeof s!="number")throw new Error("Depacketizer.frameFromSingle: no oldest frame number found, but partials.size is ".concat(this.partials.size,"."));if(this.partials.delete(s),t?.throwOnInterruption)throw en.interrupted(s,e.header.frameNumber.value);Lo.warn("Data track frame ".concat(s," was interrupted by single-packet frame ").concat(e.header.frameNumber.value,", dropping."))}return{payload:e.payload,extensions:e.header.extensions}}beginPartial(e,t){var i;if(e.header.marker!==ce.Start)throw new Error("Depacketizer.beginPartial: packet.header.marker was not FrameMarker.Start, found ".concat(e.header.marker,"."));let r=e.header.sequence,s=e.header.frameNumber.value,a={startSequence:r,extensions:e.header.extensions,payloads:new Map([[r.value,e.payload]])},o=(i=t?.maxPartialFrames)!==null&&i!==void 0?i:1;for(;this.partials.size>=o;){let c=this.peekOldestPartialFrameNumber();if(typeof c!="number")break;if(this.partials.delete(c),t?.throwOnInterruption)throw en.interrupted(c,s);Lo.warn("Data track partials full (max ".concat(o,"), evicted oldest frame ").concat(c," to make room for new frame ").concat(s,"."))}return this.partials.set(s,a),null}pushToPartial(e){if(e.header.marker!==ce.Inter&&e.header.marker!==ce.Final)throw new Error("Depacketizer.pushToPartial: packet.header.marker was not FrameMarker.Inter or FrameMarker.Final, found ".concat(e.header.marker,"."));let t=e.header.frameNumber.value,i=this.partials.get(t);if(!i)throw this.partials.delete(t),en.unknownFrame(t);if(i.payloads.size>=n.MAX_BUFFER_PACKETS)throw this.partials.delete(t),en.bufferFull(t);return i.payloads.has(e.header.sequence.value)&&Lo.warn("Data track frame ".concat(t," received duplicate packet for sequence ").concat(e.header.sequence.value,", so replacing with newly received packet.")),i.payloads.set(e.header.sequence.value,e.payload),e.header.marker===ce.Final?this.finalize(t,i,e.header.sequence.value):null}finalize(e,t,i){let r=t.payloads.size,s=0;for(let d of t.payloads.values())s+=d.length;let a=new Uint8Array(s),o=t.startSequence.clone(),c=0;for(;;){let d=t.payloads.get(o.value);if(!d)break;t.payloads.delete(o.value);let l=a.length-c;if(d.length>l)throw new Error("Depacketizer.finalize: Expected at least ".concat(d.length," more bytes left in the payload buffer, only got ").concat(l," bytes."));if(a.set(d,c),c+=d.length,o.value!=i){o.increment();continue}return this.partials.delete(e),{payload:a,extensions:t.extensions}}throw this.partials.delete(e),en.incomplete(e,r,i-t.startSequence.value+1)}};us.MAX_BUFFER_PACKETS=128;var nn;(function(n){n[n.Unpublished=0]="Unpublished",n[n.Timeout=1]="Timeout",n[n.Disconnected=2]="Disconnected",n[n.Cancelled=4]="Cancelled"})(nn||(nn={}));var it=class n extends Be{constructor(e,t,i){super(22,e,i),this.name="DataTrackSubscribeError",this.reason=t,this.reasonName=nn[t]}static unpublished(){return new n("The track has been unpublished and is no longer available",nn.Unpublished)}static timeout(){return new n("Request to subscribe to data track timed-out",nn.Timeout)}static disconnected(){return new n("Cannot subscribe to data track when disconnected",nn.Disconnected)}static cancelled(){return new n("Subscription to data track cancelled by caller",nn.Cancelled)}},Do=we(he.DataTracks),kc=class{constructor(e){var t,i;let r=e.e2eeManager!==null;if(e.info.usesE2ee!==r)throw new Error("IncomingDataTrackPipeline: DataTrackInfo.usesE2ee must match presence of decryptionProvider");let s=new us;this.publisherIdentity=e.publisherIdentity,this.e2eeManager=(t=e.e2eeManager)!==null&&t!==void 0?t:null,this.depacketizer=s,this.options=(i=e.pipelineOptions)!==null&&i!==void 0?i:{}}updateE2eeManager(e){this.e2eeManager=e}setOptions(e){this.options=e}processPacket(e){return g(this,void 0,void 0,function*(){let t=this.depacketize(e);if(!t)return null;let i=yield this.decryptIfNeeded(t);return i||null})}depacketize(e){let t;try{t=this.depacketizer.push(e,{throwOnInterruption:!1,maxPartialFrames:this.options.maxPartialFrames})}catch(i){return Do.warn("Data frame depacketize error: ".concat(i)),null}return t}decryptIfNeeded(e){return g(this,void 0,void 0,function*(){var t,i;let r=this.e2eeManager;if(!r)return e;let s=(i=(t=e.extensions)===null||t===void 0?void 0:t.e2ee)!==null&&i!==void 0?i:null;if(!s)return Do.error("Missing E2EE meta"),null;let a;try{a=yield r.handleEncryptedData(e.payload,s.iv,this.publisherIdentity,s.keyIndex)}catch(o){return Do.error("Error decrypting packet: ".concat(o)),null}return e.payload=a.payload,e})}},ke=we(he.DataTracks),ok=1e4,ak=16,Tc=class extends Oe.EventEmitter{constructor(e){var t;super(),this.descriptors=new Map,this.subscriptionHandles=new Map,this.e2eeManager=(t=e?.e2eeManager)!==null&&t!==void 0?t:null}updateE2eeManager(e){this.e2eeManager=e;for(let t of this.descriptors.values())t.subscription.type==="active"&&t.subscription.pipeline.updateE2eeManager(e)}setPipelineOptions(e,t){let i=this.descriptors.get(e);if(!i){ke.warn("Unknown track ".concat(e,", cannot set pipeline options."));return}i.pipelineOptions=t,i.subscription.type==="active"&&i.subscription.pipeline.setOptions(t)}openSubscriptionStream(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ak,r=null,s=new Ce,a=this.descriptors.get(e),o=()=>{t?.removeEventListener("abort",d)},c=()=>{if(o(),!r){ke.warn("ReadableStream subscribed to ".concat(e," was not started."));return}if(!a||this.descriptors.get(a.info.sid)!==a){ke.warn("Unknown track ".concat(e,", skipping cancel..."));return}if(a.subscription.type!=="active"){ke.warn("Subscription for track ".concat(e," is not active, skipping cancel..."));return}a.subscription.streamControllers.delete(r),a.subscription.streamControllers.size===0&&this.unSubscribeRequest(a.info.sid)},d=()=>{var u;r&&(a?.subscription.type==="active"&&a.subscription.streamControllers.delete(r),r.error(it.cancelled()),(u=s.reject)===null||u===void 0||u.call(s,it.cancelled()),c())};return[new ReadableStream({start:u=>{r=u,this.subscribeRequest(e,t).then(()=>g(this,void 0,void 0,function*(){var h,f,m;if(!a||this.descriptors.get(a.info.sid)!==a){ke.error("Unknown track ".concat(e));let p=it.disconnected();u.error(p),(h=s.reject)===null||h===void 0||h.call(s,p);return}if(a.subscription.type!=="active"){ke.error("Subscription for track ".concat(e," is not active"));let p=it.disconnected();u.error(p),(f=s.reject)===null||f===void 0||f.call(s,p);return}if(t?.aborted){d();return}t?.addEventListener("abort",d),a.subscription.streamControllers.set(u,o),(m=s.resolve)===null||m===void 0||m.call(s)})).catch(h=>{var f;u.error(h),(f=s.reject)===null||f===void 0||f.call(s,h)})},cancel:()=>{c()}},new CountQueuingStrategy({highWaterMark:i})),s.promise]}subscribeRequest(e,t){return g(this,void 0,void 0,function*(){let i=this.descriptors.get(e);if(!i)throw new Error("Cannot subscribe to unknown track");let r=(s,a,o)=>g(this,void 0,void 0,function*(){if(s.subscription.type==="active")return;if(s.subscription.type!=="pending")throw new Error("Descriptor for track ".concat(e," is not pending, found ").concat(s.subscription.type));let c=Lf([a,o].filter(u=>typeof u<"u")),d=new Ce;s.subscription.completionFuture.promise.then(()=>{var u;return(u=d.resolve)===null||u===void 0?void 0:u.call(d)}).catch(u=>{var h;return(h=d.reject)===null||h===void 0?void 0:h.call(d,u)});let l=()=>{var u;if(s.subscription.type==="pending"){if(s.subscription.pendingRequestCount-=1,o?.aborted){s.subscription.cancel();return}if(s.subscription.pendingRequestCount<=0){s.subscription.cancel();return}(u=d.reject)===null||u===void 0||u.call(d,it.cancelled())}};c.aborted&&l(),c.addEventListener("abort",l),yield d.promise,c.removeEventListener("abort",l)});switch(i.subscription.type){case"none":{i.subscription={type:"pending",completionFuture:new Ce,pendingRequestCount:1,cancel:()=>{var a,o;let c=i.subscription;i.subscription={type:"none"},this.emit("sfuUpdateSubscription",{sid:i.info.sid,subscribe:!1}),c.type==="pending"&&((o=(a=c.completionFuture).reject)===null||o===void 0||o.call(a,s.aborted?it.timeout():it.cancelled()))}},this.emit("sfuUpdateSubscription",{sid:e,subscribe:!0});let s=td(ok);yield r(i,t,s);return}case"pending":{i.subscription.pendingRequestCount+=1,yield r(i,t);return}case"active":return}})}querySubscribed(){return g(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).filter(t=>t.subscription.type==="active").map(t=>[t.info,t.publisherIdentity])})}unSubscribeRequest(e){var t;let i=this.descriptors.get(e);if(!i)throw new Error("Cannot subscribe to unknown track");if(i.subscription.type!=="active"){ke.warn("Unexpected descriptor state in unSubscribeRequest, expected active, found ".concat((t=i.subscription)===null||t===void 0?void 0:t.type));return}this.closeStreamControllers(i.subscription.streamControllers,e);let r=i.subscription;i.subscription={type:"none"},this.subscriptionHandles.delete(r.subcriptionHandle),this.emit("sfuUpdateSubscription",{sid:e,subscribe:!1})}closeStreamControllers(e,t){for(let r of e){var i=F(r,2);let s=i[0],a=i[1];a();try{s.close()}catch(o){ke.warn("Failed to close readable stream for track ".concat(t,": ").concat(o))}}}receiveSfuPublicationUpdates(e){return g(this,void 0,void 0,function*(){if(e.size===0)return;let t=new Map;for(let s of e.entries()){var i=F(s,2);let a=i[0],o=i[1],c=new Set;for(let d of o)c.add(d.sid),!this.descriptors.has(d.sid)&&(this.handleSidReassigned(a,d)||(yield this.handleTrackPublished(a,d)));t.set(a,c)}for(let s of t.entries()){var r=F(s,2);let a=r[0],o=r[1],d=Array.from(this.descriptors.entries()).filter(l=>{let u=F(l,2);return u[0],u[1].publisherIdentity===a}).map(l=>F(l,1)[0]).filter(l=>!o.has(l));for(let l of d)this.handleTrackUnpublished(l)}})}queryPublications(){return g(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).map(e=>e.info)})}handleTrackPublished(e,t){return g(this,void 0,void 0,function*(){if(this.descriptors.has(t.sid)){ke.error("Existing descriptor for track ".concat(t.sid));return}let i={info:t,publisherIdentity:e,subscription:{type:"none"},pipelineOptions:{}};this.descriptors.set(i.info.sid,i);let r=new Zr(i.info,this,{publisherIdentity:e});this.emit("trackPublished",{track:r})})}handleSidReassigned(e,t){let i=Array.from(this.descriptors.entries()).find(u=>{let h=F(u,2);h[0];let f=h[1];return f.publisherIdentity===e&&f.info.pubHandle===t.pubHandle});if(!i)return!1;let r=F(i,2),s=r[0],a=r[1],o=a.info,c=o.name,d=o.usesE2ee;if(c!==t.name||d!==t.usesE2ee)return ke.warn("Info mismatch for ".concat(s,", treating as new publication")),!1;let l=t.sid;if(ke.debug("SID reassigned: ".concat(s," -> ").concat(l)),!this.descriptors.delete(s))return!1;switch(a.info.sid=l,a.subscription.type){case"none":break;case"pending":case"active":this.emit("sfuUpdateSubscription",{sid:l,subscribe:!0});break}return a.subscription.type==="active"&&this.subscriptionHandles.set(a.subscription.subcriptionHandle,l),this.descriptors.set(l,a),!0}handleTrackUnpublished(e){let t=this.descriptors.get(e);if(!t){ke.error("Unknown track ".concat(e));return}this.descriptors.delete(e),t.subscription.type==="active"&&(this.closeStreamControllers(t.subscription.streamControllers,e),this.subscriptionHandles.delete(t.subscription.subcriptionHandle)),this.emit("trackUnpublished",{sid:e,publisherIdentity:t.publisherIdentity})}receivedSfuSubscriberHandles(e){for(let i of e.entries()){var t=F(i,2);let r=t[0],s=t[1];this.registerSubscriberHandle(r,s)}}registerSubscriberHandle(e,t){var i,r;let s=this.descriptors.get(t);if(!s){ke.error("Unknown track ".concat(t));return}switch(s.subscription.type){case"none":{ke.warn("No subscription for ".concat(t));return}case"active":{this.subscriptionHandles.delete(s.subscription.subcriptionHandle),s.subscription.subcriptionHandle=e,this.subscriptionHandles.set(e,t);return}case"pending":{ke.debug("data track subscription activated",{sid:t,handle:e});let a=new kc({info:s.info,publisherIdentity:s.publisherIdentity,e2eeManager:this.e2eeManager,pipelineOptions:s.pipelineOptions}),o=s.subscription;s.subscription={type:"active",subcriptionHandle:e,pipeline:a,streamControllers:new Map},this.subscriptionHandles.set(e,t),(r=(i=o.completionFuture).resolve)===null||r===void 0||r.call(i)}}}packetReceived(e){return g(this,void 0,void 0,function*(){let t;try{var i=Jr.fromBinary(e),r=F(i,1);t=r[0]}catch(c){ke.error("Failed to deserialize packet: ".concat(c));return}let s=this.subscriptionHandles.get(t.header.trackHandle);if(!s){ke.warn("Unknown subscriber handle ".concat(t.header.trackHandle));return}let a=this.descriptors.get(s);if(!a){ke.error("Missing descriptor for track ".concat(s));return}if(a.subscription.type!=="active"){ke.warn("Received packet for track ".concat(s," without active subscription"));return}let o=yield a.subscription.pipeline.processPacket(t);if(o)for(let c of a.subscription.streamControllers.keys()){if(c.desiredSize!==null&&c.desiredSize<=0){ke.warn("Cannot send frame to subscribers: readable stream is full (desiredSize is ".concat(c.desiredSize,"). To increase this threshold, set a higher 'options.highWaterMark' when calling .subscribe()."));continue}let d=Wf.lossyIntoFrame(o);c.enqueue(d)}})}resendSubscriptionUpdates(){for(let t of this.descriptors){var e=F(t,2);let i=e[0];e[1].subscription.type!=="none"&&this.emit("sfuUpdateSubscription",{sid:i,subscribe:!0})}}handleRemoteParticipantDisconnected(e){var t,i;for(let r of this.descriptors.values())if(r.publisherIdentity===e)switch(r.subscription.type){case"none":break;case"pending":(i=(t=r.subscription.completionFuture).reject)===null||i===void 0||i.call(t,it.disconnected());break;case"active":this.unSubscribeRequest(r.info.sid);break}}reset(){var e,t;for(let i of this.descriptors.values())this.emit("trackUnpublished",{sid:i.info.sid,publisherIdentity:i.publisherIdentity}),i.subscription.type==="pending"&&((t=(e=i.subscription.completionFuture).reject)===null||t===void 0||t.call(e,it.disconnected())),i.subscription.type==="active"&&this.closeStreamControllers(i.subscription.streamControllers,i.info.sid);this.descriptors.clear(),this.subscriptionHandles.clear()}},hs=class n{constructor(e){this.e2eeManager=e.e2eeManager,this.packetizer=new Fa(e.info.pubHandle,n.TRANSPORT_MTU_BYTES)}updateE2eeManager(e){this.e2eeManager=e}processFrame(e){return yf(this,arguments,function*(){let i=yield Rt(this.encryptIfNeeded(e));try{yield Rt(yield*Vv(ze(this.packetizer.packetize(i))))}catch(r){throw r instanceof $r?Yr.packetizer(r):r}})}encryptIfNeeded(e){return g(this,void 0,void 0,function*(){if(!this.e2eeManager)return e;let t;try{t=yield this.e2eeManager.encryptData(e.payload)}catch(i){throw Yr.encryption(i)}return e.payload=t.payload,e.extensions.e2ee=new un(t.keyIndex,t.iv),e})}};hs.TRANSPORT_MTU_BYTES=16e3;var Je=we(he.DataTracks),Bu={pending(){return{type:"pending",completionFuture:new Ce}},active(n,e){return{type:"active",info:n,publishState:"published",pipeline:new hs({info:n,e2eeManager:e}),unpublishingFuture:new Ce}}},ck=1e4,Sc=class n extends Oe.EventEmitter{constructor(e){var t;super(),this.handleAllocator=new Na,this.descriptors=new Map,this.inFlightPacketCounter=new Map,this.e2eeManager=(t=e?.e2eeManager)!==null&&t!==void 0?t:null}static withDescriptors(e){let t=new n;return t.descriptors=e,t}updateE2eeManager(e){this.e2eeManager=e;for(let t of this.descriptors.values())t.type==="active"&&t.pipeline.updateE2eeManager(e)}getDescriptor(e){var t;return(t=this.descriptors.get(e))!==null&&t!==void 0?t:null}tryProcessAndSend(e,t){return g(this,void 0,void 0,function*(){var i,r,s,a,o;let c=this.getDescriptor(e);if(c?.type!=="active"||c.publishState==="unpublished")throw sn.trackUnpublished();if(c.publishState==="republishing")throw sn.dropped("Data track republishing");try{try{for(var d=!0,l=ze(c.pipeline.processFrame(t)),u;u=yield l.next(),i=u.done,!i;d=!0){a=u.value,d=!1;let h=a,f=(o=this.inFlightPacketCounter.get(e))!==null&&o!==void 0?o:0;this.inFlightPacketCounter.set(e,f+1),f===0&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!1}),this.emit("packetAvailable",{handle:e,bytes:h.toBinary()})}}catch(h){r={error:h}}finally{try{!d&&!i&&(s=l.return)&&(yield s.call(l))}finally{if(r)throw r.error}}}catch(h){throw sn.dropped(h)}})}handlePacketSendComplete(e){var t;let r=((t=this.inFlightPacketCounter.get(e))!==null&&t!==void 0?t:0)-1;r<0&&(Je.warn("OutgoingDataTrackManager.handlePacketSendComplete: inFlightPacketCounter was decremented below 0 (got ".concat(this.inFlightPacketCounter," - resetting to 0. Were more packets send than were emitted?")),r=0),this.inFlightPacketCounter.set(e,r),r===0&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!0})}publishRequest(e,t){return g(this,void 0,void 0,function*(){let i=this.handleAllocator.get();if(!i)throw Qe.limitReached();let r=td(ck),s=t?Lf([t,r]):r;if(this.descriptors.has(i))throw new Error("Descriptor for handle already exists");let a=Bu.pending();this.descriptors.set(i,a);let o=()=>{var c,d;let l=this.descriptors.get(i);if(!l){Je.warn("No descriptor for ".concat(i));return}this.descriptors.delete(i),this.emit("sfuUnpublishRequest",{handle:i}),l.type==="pending"&&((d=(c=l.completionFuture).reject)===null||d===void 0||d.call(c,r.aborted?Qe.timeout():Qe.cancelled()))};return s.aborted?(o(),a.completionFuture.promise.then(()=>i)):(s.addEventListener("abort",o),this.emit("sfuPublishRequest",{handle:i,name:e.name,usesE2ee:this.e2eeManager!==null}),yield a.completionFuture.promise,s.removeEventListener("abort",o),this.emit("trackPublished",{track:Xr.withExplicitHandle(e,this,i)}),i)})}queryPublished(){return Array.from(this.descriptors.values()).filter(t=>t.type==="active").map(t=>t.info)}unpublishRequest(e){return g(this,void 0,void 0,function*(){let t=this.descriptors.get(e);if(!t){Je.warn("No descriptor for ".concat(e));return}if(t.type!=="active"){Je.warn("Track ".concat(e," not active"));return}this.emit("sfuUnpublishRequest",{handle:e}),yield t.unpublishingFuture.promise,this.inFlightPacketCounter.delete(e),this.emit("trackUnpublished",{sid:t.info.sid})})}receivedSfuPublishResponse(e,t){var i,r,s,a;let o=this.descriptors.get(e);if(!o){Je.warn("No descriptor for ".concat(e));return}switch(this.descriptors.delete(e),o.type){case"pending":{if(t.type==="ok"){let c=t.data;Je.debug("SFU accepted publish request for handle ".concat(e),{sid:c.sid});let d=c.usesE2ee?this.e2eeManager:null;this.descriptors.set(c.pubHandle,Bu.active(c,d)),(r=(i=o.completionFuture).resolve)===null||r===void 0||r.call(i)}else Je.debug("SFU rejected publish request for handle ".concat(e),{error:t.error}),(a=(s=o.completionFuture).reject)===null||a===void 0||a.call(s,t.error);return}case"active":{if(o.publishState!=="republishing"){Je.warn("Track ".concat(e," already active"));return}if(t.type==="error"){Je.warn("Republish failed for track ".concat(e,": ").concat(t.error)),o.publishState="unpublished";return}Je.debug("Track ".concat(e," republished")),o.info.sid=t.data.sid,o.publishState="published",this.descriptors.set(o.info.pubHandle,o)}}}receivedSfuUnpublishResponse(e){var t,i;let r=this.descriptors.get(e);if(!r){Je.warn("No descriptor for ".concat(e));return}if(this.descriptors.delete(e),r.type!=="active"){Je.warn("Track ".concat(e," not active"));return}r.publishState="unpublished",(i=(t=r.unpublishingFuture).resolve)===null||i===void 0||i.call(t)}sfuWillRepublishTracks(){var e,t;for(let r of this.descriptors.entries()){var i=F(r,2);let s=i[0],a=i[1];switch(a.type){case"pending":this.descriptors.delete(s),(t=(e=a.completionFuture).reject)===null||t===void 0||t.call(e,Qe.disconnected());break;case"active":a.publishState="republishing",this.emit("sfuPublishRequest",{handle:a.info.pubHandle,name:a.info.name,usesE2ee:a.info.usesE2ee})}}}reset(){return g(this,void 0,void 0,function*(){var e,t,i,r;this.handleAllocator.reset();for(let s of this.descriptors.values())switch(s.type){case"pending":(t=(e=s.completionFuture).reject)===null||t===void 0||t.call(e,Qe.disconnected());break;case"active":(r=(i=s.unpublishingFuture).resolve)===null||r===void 0||r.call(i),yield this.unpublishRequest(s.info.pubHandle);break}this.descriptors.clear(),this.inFlightPacketCounter.clear(),this.emit("reset")})}},qu=n=>n.map(e=>Ua.from(e)),dk={key:Symbol("lk.extension.dataTracks"),install(n,e){let t=new Tc,i=new Sc;t.on("sfuUpdateSubscription",d=>{n.engine.client.sendUpdateDataSubscription(d.sid,d.subscribe)}).on("trackPublished",d=>{var l;d.track.publisherIdentity!==n.localParticipant.identity&&(n.emit(R.DataTrackPublished,d.track),(l=n.remoteParticipants.get(d.track.publisherIdentity))===null||l===void 0||l.addRemoteDataTrack(d.track))}).on("trackUnpublished",d=>{var l;d.publisherIdentity!==n.localParticipant.identity&&(n.emit(R.DataTrackUnpublished,d.sid),(l=n.remoteParticipants.get(d.publisherIdentity))===null||l===void 0||l.removeRemoteDataTrack(d.sid))}),i.on("sfuPublishRequest",d=>{n.engine.client.sendPublishDataTrackRequest(d.handle,d.name,d.usesE2ee)}).on("sfuUnpublishRequest",d=>{n.engine.client.sendUnPublishDataTrackRequest(d.handle)}).on("trackPublished",d=>{n.emit(R.LocalDataTrackPublished,d.track)}).on("trackUnpublished",d=>{n.emit(R.LocalDataTrackUnpublished,d.sid)}).on("packetAvailable",d=>{let l=d.handle,u=d.bytes;n.engine.sendDataTrackFrame(u).finally(()=>i.handlePacketSendComplete(l))});let r=d=>{var l;let u=(l=e.slot("e2eeManager"))!==null&&l!==void 0?l:null;t.updateE2eeManager(u),i.updateE2eeManager(u),d.on(A.PublishDataTrackResponse,h=>{if(!h.info){e.log.warn("received PublishDataTrackResponse, but event.info was ".concat(h.info,", so skipping."));return}i.receivedSfuPublishResponse(h.info.pubHandle,{type:"ok",data:{sid:h.info.sid,pubHandle:h.info.pubHandle,name:h.info.name,usesE2ee:h.info.encryption!==X.NONE}})}).on(A.UnPublishDataTrackResponse,h=>{if(!h.info){e.log.warn("received UnPublishDataTrackResponse, but event.info was ".concat(h.info,", so skipping."));return}i.receivedSfuUnpublishResponse(h.info.pubHandle)}).on(A.DataTrackSubscriberHandles,h=>{let f=new Map(Object.entries(h.subHandles).map(m=>{let p=F(m,2),y=p[0],v=p[1];return[parseInt(y,10),v.trackSid]}));t.receivedSfuSubscriberHandles(f)}).on(A.DataTrackPacketReceived,h=>{try{t.packetReceived(h)}catch(f){throw f}}).on(A.Joined,h=>{t.receiveSfuPublicationUpdates(new Map(h.otherParticipants.map(f=>[f.identity,qu(f.dataTracks)])))}).on(A.Restarted,()=>{i.sfuWillRepublishTracks(),t.resendSubscriptionUpdates()}).on(A.SignalRequestResponse,h=>{if(h.request.case!=="publishDataTrack")return;let f;switch(h.reason){case rn.NOT_ALLOWED:f=Qe.notAllowed(h.message);break;case rn.DUPLICATE_NAME:f=Qe.duplicateName(h.message);break;case rn.INVALID_NAME:f=Qe.invalidName(h.message);break;case rn.LIMIT_EXCEEDED:f=Qe.limitReached(h.message);break;default:f=Qe.unknown(h.reason,h.message);break}i.receivedSfuPublishResponse(h.request.value.pubHandle,{type:"error",error:f})})},s=()=>{t.reset(),i.reset()},a=(d,l)=>{for(let u of l.dataTracks)d.addRemoteDataTrack(new Zr(Ua.from(u),t,{publisherIdentity:l.identity}))},o=d=>{t.receiveSfuPublicationUpdates(new Map(d.filter(l=>l.identity!==n.localParticipant.identity).map(l=>[l.identity,qu(l.dataTracks)])))},c=()=>i.queryPublished().map(d=>new Uc({info:Ua.toProtobuf(d)}));return n.on(R.ParticipantDisconnected,d=>t.handleRemoteParticipantDisconnected(d.identity)),{incoming:t,outgoing:i,onEngineCreated:r,onDisconnect:s,onParticipantCreated:a,onParticipantUpdates:o,syncState:c,localParticipant:{publishDataTrack:d=>g(this,void 0,void 0,function*(){let l=new Xr(d,i);return yield l.publish(),l})}}}},_c={key:Symbol("lk.extension.rpc"),requires:[cs],install(n,e){let t=e.get(cs),i=t.incoming,r=t.outgoing,s=l=>{var u,h;return(h=(u=n.remoteParticipants.get(l))===null||u===void 0?void 0:u.clientProtocol)!==null&&h!==void 0?h:zc},a=new ja(e.log,r,s,()=>{var l;return(l=n.engine)===null||l===void 0?void 0:l.serverVersion});a.on("sendDataPacket",l=>{let u=l.packet;var h;(h=n.engine)===null||h===void 0||h.sendDataPacket(u,z.RELIABLE)});let o=new Va(e.log,r,s);return o.on("sendDataPacket",l=>{let u=l.packet;var h;(h=n.engine)===null||h===void 0||h.sendDataPacket(u,z.RELIABLE)}),i.registerTextStreamHandler($f,(l,u)=>g(this,[l,u],void 0,function(h,f){let m=f.identity;return(function*(){var p;yield o.handleIncomingDataStream(h,m,(p=h.info.attributes)!==null&&p!==void 0?p:{})})()})),i.registerTextStreamHandler(Qf,(l,u)=>g(this,[l,u],void 0,function(h,f){let m=f.identity;return(function*(){var p;yield a.handleIncomingDataStream(h,m,(p=h.info.attributes)!==null&&p!==void 0?p:{})})()})),n.on(R.ParticipantDisconnected,l=>a.handleParticipantDisconnected(l.identity)),{dataPackets:{rpcRequest:(l,u)=>{o.handleIncomingRpcRequest(u.participantIdentity,l)},rpcResponse:l=>{switch(l.value.case){case"payload":a.handleIncomingRpcResponseSuccess(l.requestId,l.value.value);break;case"error":a.handleIncomingRpcResponseFailure(l.requestId,ae.fromProto(l.value.value));break;default:e.log.warn("Unknown rpcResponse.value.case: ".concat(l.value.case));break}},rpcAck:l=>a.handleIncomingRpcAck(l.requestId)},onDisconnect:()=>a.handleRoomDisconnected(),room:{registerRpcMethod:(l,u)=>o.registerRpcMethod(l,u),unregisterRpcMethod:l=>o.unregisterRpcMethod(l)},localParticipant:{performRpc:l=>a.performRpc(l).then(u=>{let h=F(u,2);return h[0],h[1]})}}}},lk={key:Symbol("lk.extension.rpcLegacy"),requires:[_c],install(n,e){let t=e.get(_c).room,i=t.registerRpcMethod,r=t.unregisterRpcMethod;return{localParticipant:{registerRpcMethod:i,unregisterRpcMethod:r}}}},uk={key:Symbol("lk.extension.simulatedParticipants"),install(n,e){return{room:{simulateParticipants:t=>hk(n,e,t)}}}};function hk(n,e,t){return g(this,void 0,void 0,function*(){var i,r,s,a;let o=Object.assign({audio:!0,video:!0,useRealTracks:!1},t.publish),c=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},t.participants),d=n.localParticipant,l=d.trackLoggerOptions;if(e.simulateConnected(new ms({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:ue.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),new cn({identity:"simulated-local",name:"local-name"})),o.video){let u=new xi(C.Kind.Video,new Sn({source:Te.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:ot.AUDIO,name:"video-dummy"}),qr().createTrack(o.useRealTracks&&(!((i=window.navigator.mediaDevices)===null||i===void 0)&&i.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Kl(160*((r=c.aspectRatios[0])!==null&&r!==void 0?r:1),160,!0,!0),void 0,!1,l),l);d.addTrackPublication(u),d.emit(L.LocalTrackPublished,u)}if(o.audio){let u=new xi(C.Kind.Audio,new Sn({source:Te.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:ot.AUDIO}),new jn(o.useRealTracks&&(!((s=navigator.mediaDevices)===null||s===void 0)&&s.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:e.acquireEmptyAudioStreamTrack(),void 0,!1,d.audioContext,l),l);d.addTrackPublication(u),d.emit(L.LocalTrackPublished,u)}for(let u=0;u<c.count-1;u+=1){let h=new cn({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(u),state:wn.ACTIVE,tracks:[],joinedAt:ue.parse(Date.now())}),f=e.getOrCreateParticipant(h.identity,h);if(c.video){let m=Kl(160*((a=c.aspectRatios[u%c.aspectRatios.length])!==null&&a!==void 0?a:1),160,!1,!0),p=new Sn({source:Te.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:ot.AUDIO});f.addSubscribedMediaTrack(m,p.sid,new MediaStream([m]),new RTCRtpReceiver),h.tracks=[...h.tracks,p]}if(c.audio){let m=e.acquireEmptyAudioStreamTrack(),p=new Sn({source:Te.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:ot.AUDIO});f.addSubscribedMediaTrack(m,p.sid,new MediaStream([m]),new RTCRtpReceiver),h.tracks=[...h.tracks,p]}f.updateInfo(h)}})}var fk=[cs,_c,lk,dk,rk,ik,sp,uk,sk],fs=class extends Di{constructor(e){super(e),qf(this,fk)}};ud();var pk=Symbol.for("pv"),mk=0;function w(n,e,t,i,r,s){e||(e={});var a,o,c=e;if("ref"in c&&typeof n!="function")for(o in c={},e)o=="ref"?a=e[o]:c[o]=e[o];var d={type:n,props:c,key:t,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:pk,__v:--mk,__i:-1,__u:0};return(r||s)&&(d.__source=r,d.__self=s),ne.vnode&&ne.vnode(d),d}var lt={body:"var(--fl-peek-body, #8b7ba4)",grey:"var(--fl-peek-grey, #6b645c)",muzzle:"var(--fl-peek-muzzle, #f1eaf6)",ink:"var(--fl-peek-ink, #2b2338)",blush:"var(--fl-peek-blush, #e9a99a)",moon:"var(--fl-peek-moon, #dccfe9)"},gk="M38.5 117 C36 104 37 90 40 78 C45 55 61 40 80 40 C99 40 115 55 120 78 C123 90 124 104 121.5 117 Z",vk="M52 58 Q60 47 72 44",yk="M74 89 Q80 86 86 89 Q83.5 95 80 95 Q76.5 95 74 89 Z",bk="M80 95 v3 M74.2 100 q2.9 2.8 5.8 0 q2.9 2.8 5.8 0",kk=[[64,95],[62.5,101],[68.5,102.5],[96,95],[97.5,101],[91.5,102.5]],Tk="M 18 116 A 62 15 0 0 1 142 116",Sk="M 142 116 A 62 15 0 0 1 30.2 124.8",_k="M 146 131 A 76 18 0 0 1 40 142",Ck="M 44 116 A 60 60 0 1 1 116 116 Z",hd=[[61,72],[99,72]],wk={resting:7e3,listening:3600,awake:2400,thinking:3e3},fd={transformBox:"fill-box",transformOrigin:"center"},dt=n=>Math.round(n*100)/100;function Ek({state:n,small:e}){if(n==="awake"||n==="listening"||n==="thinking"){let[r,s]=n==="listening"?[5.4,7.2]:[5,6.6];e&&([r,s]=[r*1.35,s*1.25]);let[a,o]=n==="thinking"?[3.8,-4.8]:[0,0];return w(Ze,{children:hd.map(([c,d])=>w("g",{children:[w("ellipse",{cx:dt(c+a),cy:dt(d+o),rx:dt(r),ry:dt(s),style:{fill:lt.ink}}),e?null:w("circle",{cx:dt(c+a+r*.34),cy:dt(d+o-s*.4),r:1.8,fill:"#ffffff"})]},c))})}if(n==="glad")return w(Ze,{children:hd.map(([r,s])=>w("path",{d:`M${dt(r-6.3)} ${dt(s+2.4)} q6.3 -8.6 12.6 0`,fill:"none",strokeWidth:e?6.2:4.4,strokeLinecap:"round",style:{stroke:lt.ink}},r))});let[t,i]=e?[7.2,6.6]:[6.8,4.6];return w(Ze,{children:hd.map(([r,s])=>w("path",{d:`M${dt(r-t)} ${dt(s-1.4)} q${t} 6.8 ${dt(2*t)} 0`,fill:"none",strokeWidth:i,strokeLinecap:"round",style:{stroke:lt.ink}},r))})}function Hn({state:n="resting",size:e=32,live:t,pro:i=!1,label:r}){let s=e<=32,a=n==="grey"?lt.grey:lt.body,o=t??(n==="listening"||n==="thinking")?wk[n]:void 0,c=o?{animationDuration:`${o}ms`}:void 0;return w("svg",{viewBox:"0 0 160 160",width:e,height:e,role:r?"img":void 0,"aria-label":r,"aria-hidden":r?void 0:!0,style:{display:"block",flexShrink:0,overflow:"visible"},children:[i?w("path",{d:Ck,style:{fill:lt.moon}}):null,n==="listening"?w("ellipse",{cx:80,cy:116,rx:74,ry:18,fill:"none",strokeWidth:3.5,opacity:.32,style:{stroke:a}}):null,o&&n!=="thinking"?[0,o/2].map(d=>w("ellipse",{cx:80,cy:116,rx:62,ry:15,fill:"none",strokeWidth:s?6:3.5,opacity:0,class:"peek-anim-ripple",style:{...fd,...c,animationDelay:`${d}ms`,stroke:a}},d)):null,w("path",{d:Tk,fill:"none",strokeWidth:s?7:5,strokeLinecap:"round",opacity:.5,style:{stroke:a}}),w("g",{class:o?"peek-anim-bob":void 0,style:c,children:[w("path",{d:gk,style:{fill:a}}),s?null:w("path",{d:vk,fill:"none",stroke:"#ffffff",strokeWidth:4,strokeLinecap:"round",opacity:.3}),w("ellipse",{cx:80,cy:96,rx:25,ry:15,style:{fill:lt.muzzle}}),w("path",{d:yk,style:{fill:lt.ink}}),s?null:w(Ze,{children:[w("path",{d:bk,fill:"none",strokeWidth:2.1,strokeLinecap:"round",style:{stroke:lt.ink}}),kk.map(([d,l])=>w("circle",{cx:d,cy:l,r:1.6,opacity:.4,style:{fill:lt.ink}},`${d}-${l}`))]}),w("g",{style:fd,children:[w("g",{class:!o||n==="resting"?void 0:n==="thinking"?"peek-anim-look":"peek-anim-blink",style:fd,children:w(Ek,{state:n,small:s})}),n==="glad"?[54.5,105.5].map(d=>w("ellipse",{cx:d,cy:82.5,rx:6.2,ry:3.6,opacity:.85,style:{fill:lt.blush}},d)):null]},n)]}),w("path",{d:Sk,fill:"none",strokeWidth:s?8:6,strokeLinecap:"round",opacity:.8,style:{stroke:a}}),s?null:w("path",{d:_k,fill:"none",strokeWidth:3,strokeLinecap:"round",opacity:.3,style:{stroke:a}})]})}function op({size:n=132,stroke:e=3.5,fraction:t,breathScale:i,label:r,children:s}){let a=50-e/2,o=2*Math.PI*a,c=Math.min(1,Math.max(0,t));return w("div",{class:"fl-ring-wrap",style:{width:`${n}px`,height:`${n}px`},role:r?"timer":void 0,"aria-label":r,children:[typeof i=="number"?w("div",{class:"fl-breath-halo",style:{transform:`scale(${i.toFixed(3)})`},"aria-hidden":"true"}):null,w("svg",{viewBox:"0 0 100 100",width:n,height:n,"aria-hidden":"true",children:[w("circle",{cx:"50",cy:"50",r:a,fill:"none","stroke-width":e,style:{stroke:"var(--fl-track-strong)"}}),w("circle",{cx:"50",cy:"50",r:a,fill:"none","stroke-width":e,"stroke-linecap":"round","stroke-dasharray":o,"stroke-dashoffset":o*(1-c),transform:"rotate(-90 50 50)",style:{stroke:"var(--fl-accent)",transition:"stroke-dashoffset 220ms linear"}})]}),s?w("div",{class:"fl-ring-center",children:s}):null]})}var am=bm(om(),1);function Fd({value:n,size:e=96}){let t="",i=21;try{let r=am.default.create(n,{errorCorrectionLevel:"M"});i=r.modules.size;let s=r.modules.data,a=[];for(let o=0;o<i;o++)for(let c=0;c<i;c++)s[o*i+c]&&a.push(`M${c},${o}h1v1h-1z`);t=a.join("")}catch{t=""}return w("div",{class:"fl-qr-tile","aria-label":`QR code for ${n}`,children:w("svg",{viewBox:`0 0 ${i} ${i}`,width:e,height:e,shapeRendering:"crispEdges",role:"img","aria-label":"Scan to open in Flowe",children:[w("rect",{width:i,height:i,fill:"#ffffff"}),w("path",{d:t,fill:"#1a1611"})]})})}var kT="2026-01-26";function Us(n){let e=n==="dark"||!n&&window.matchMedia?.("(prefers-color-scheme: dark)").matches;document.documentElement.dataset.theme=e?"dark":"light"}function cm(n){if(n.structuredContent&&typeof n.structuredContent=="object")return n.structuredContent;let e=n.content?.find(t=>t.type==="text"&&typeof t.text=="string");if(e?.text)try{let t=JSON.parse(e.text);if(t&&typeof t=="object")return t}catch{return{message:e.text}}return null}function dm(n,e){Us(void 0);let t=window.matchMedia?.("(prefers-color-scheme: dark)"),i,r=()=>{i||Us(void 0)};t?.addEventListener?.("change",r);let s=null,a=e??null,o=1,c=new Map,d=k=>{a=k,s?.(k)},l=typeof window<"u"&&window.parent&&window.parent!==window;function u(k){l&&window.parent.postMessage(k,"*")}function h(k,S,E=15e3){if(!l)return Promise.reject(new Error("MCP host not connected"));let O=o++;return new Promise((q,x)=>{let D=window.setTimeout(()=>{c.delete(O),x(new Error(`MCP host timeout (${k})`))},E);c.set(O,{resolve:B=>{clearTimeout(D),q(B)},reject:B=>{clearTimeout(D),x(B)}}),u({jsonrpc:"2.0",id:O,method:k,params:S})})}function f(k,S={}){u({jsonrpc:"2.0",method:k,params:S})}let m=k=>{let S=k.data;if(!(!S||typeof S!="object"||S.jsonrpc!=="2.0")){if(typeof S.id=="number"&&!S.method&&c.has(S.id)){let E=c.get(S.id);c.delete(S.id),S.error?E.reject(new Error(S.error.message||"MCP host error")):E.resolve(S.result??{});return}if(S.method==="ui/resource-teardown"&&S.id!==void 0){u({jsonrpc:"2.0",id:S.id,result:{}});return}if(S.method==="ui/notifications/host-context-changed"){let E=S.params?.theme;E&&(i=E,Us(E));return}if(S.method==="ui/notifications/tool-result"&&S.params){let E=cm(S.params);E&&d(E)}}};window.addEventListener("message",m);let p=null,y=0,v=0;function _(){let k=document.documentElement,S=Math.ceil(k.scrollWidth),E=Math.ceil(document.body.scrollHeight||k.scrollHeight);E>0&&(S!==y||E!==v)&&(y=S,v=E,f("ui/notifications/size-changed",{width:S,height:E}))}typeof ResizeObserver<"u"&&(p=new ResizeObserver(()=>_()),p.observe(document.body));let P=!1,b=l?h("ui/initialize",{protocolVersion:kT,appInfo:{name:n,version:"0.3.2"},appCapabilities:{}},4e3).then(k=>{P=!0;let S=k.hostContext;S?.theme&&(i=S.theme,Us(S.theme)),f("ui/notifications/initialized",{}),_()}).catch(()=>{}):Promise.resolve();return{callTool:async(k,S={})=>{if(await b,!P)throw new Error("MCP host not connected");let E=await h("tools/call",{name:k,arguments:S}),O=cm(E);if(E.isError){let q=O?.message||(E.content?.[0]?.text??"Tool call failed");throw new Error(q)}return O??{}},openLink:async k=>{if(await b,P)try{await h("ui/open-link",{url:k},4e3);return}catch{}window.open(k,"_blank","noopener,noreferrer")},updateContext:async k=>{if(await b,!!P)try{await h("ui/update-model-context",{content:[{type:"text",text:k}]},4e3)}catch{}},onPayload:k=>{s=k,a&&k(a)},destroy:()=>{window.removeEventListener("message",m),t?.removeEventListener?.("change",r),p?.disconnect()}}}var TT={welcome:"Settling in",body_scan:"Body scan",yoga_nidra:"Deep rest",awakening:"Awakening",acute:"Reset",intake:"Check-in",identify:"Identify",investigate:"Explore",interrupt:"Shift",install:"Integrate"};function ST(n){return n?TT[n]??n.replace(/_/g," "):"Guided session"}function lm(n){let e=Math.max(0,Math.floor(n)),t=Math.floor(e/60),i=e%60;return`${t}:${String(i).padStart(2,"0")}`}function _T({payload:n,bridge:e,onReady:t}){let i=n.auth,[r,s]=Ve("pending"),[a,o]=Ve(!1),[c,d]=Ve(null);ni(()=>{if(!i||r!=="pending")return;let u=Math.max(2e3,(i.interval||3)*1e3),h=!1,f=window.setInterval(async()=>{if(!h)try{let m=await e.callTool("flowe_auth_poll",{device_code:i.device_code});if(m.status==="authorized"){h=!0,clearInterval(f),s("launching");let p=n.pending_tier??"quick",y=n.pending_session_type??(p==="deep"?"ht_stress":"quick_reset"),v=p==="deep"?"flowe_deep_reset":"flowe_quick_reset";try{let _=await e.callTool(v,{session_type:y,voice:n.voice,ambient:n.ambient});t({..._,account:m.account??_.account})}catch(_){d(_.message)}}else m.status==="expired"&&(h=!0,clearInterval(f),s("expired"))}catch{}},u);return()=>{h=!0,clearInterval(f)}},[i?.device_code,r]);let l=n.pending_tier==="deep"?"Deep Reset":"Quick Reset";return w("div",{class:"fl-stack",children:[w("div",{class:"fl-header",children:w("div",{class:"fl-brand-row",children:[w(Hn,{state:r==="launching"?"glad":"awake",size:34,live:r==="launching"}),w("div",{children:[w("div",{class:"fl-mono",children:"FLOWE ACCOUNT REQUIRED"}),w("h2",{class:"fl-title",children:r==="launching"?`Signed in \u2014 starting your ${l}\u2026`:`Sign in to start your ${l}`})]})]})}),w("p",{class:"fl-body",children:"Real Flowe Quick and Deep Resets use your account for live AI voice guidance and sync directly to your Journey."}),i&&r!=="launching"?w("div",{class:"fl-runner-stage",style:{alignItems:"center"},children:[w(Fd,{value:i.verification_uri_complete,size:96}),w("div",{class:"fl-stack",style:{gap:"10px",flex:1},children:[w("div",{class:"fl-row",children:[w("span",{class:"fl-code-box",children:i.user_code}),w("button",{type:"button",class:"fl-btn-link",onClick:()=>{navigator.clipboard?.writeText(i.user_code),o(!0),setTimeout(()=>o(!1),1800)},children:a?"Copied":"Copy code"})]}),w("div",{class:"fl-row",children:[w("button",{type:"button",class:"fl-btn-primary",onClick:()=>e.openLink(i.verification_uri_complete),children:"Continue in browser"}),w("span",{class:"fl-mono",children:r==="expired"?"EXPIRED \u2014 RETRY":"WAITING FOR APPROVAL\u2026"})]})]})]}):null,c?w("p",{class:"fl-error",children:c}):null]})}function CT({payload:n,bridge:e,onComplete:t}){let i=n.tier==="deep",r=Math.max(60,(n.estimated_duration??(i?20:10))*60),s=n.phases&&n.phases.length>0?n.phases:[n.current_phase??"yoga_nidra"],[a,o]=Ve(n.livekit_url&&n.livekit_token?"ready":"handoff"),[c,d]=Ve(i?"Ready to join two-way voice session.":"Ready when you are. Listen-only."),[l,u]=Ve(n.current_phase??s[0]),[h,f]=Ve(!i),[m,p]=Ve(!1),[y,v]=Ve(0),[_,P]=Ve(!1),[b,k]=Ve(null),S=nr(null),E=nr(null),O=nr(null);ni(()=>{if(a!=="connected")return;O.current||(O.current=Date.now());let V=window.setInterval(()=>{document.hidden||!O.current||v(Math.floor((Date.now()-O.current)/1e3))},1e3);return()=>clearInterval(V)},[a]),ni(()=>()=>{let V=S.current;S.current=null,V&&V.disconnect()},[]);async function q(){if(!n.livekit_url||!n.livekit_token){o("handoff");return}o("connecting"),d("Connecting to your Flowe guide\u2026"),k(null);try{let V=new fs({adaptiveStream:!0,dynacast:!0});if(S.current=V,V.on(R.TrackSubscribed,se=>{if(se.kind===C.Kind.Audio&&E.current){let Q=se.attach();Q.autoplay=!0,E.current.appendChild(Q),d("Flowe is guiding you.")}}),V.on(R.TrackUnsubscribed,se=>{se.detach().forEach(Q=>Q.remove())}),V.on(R.ActiveSpeakersChanged,se=>{let Q=se.some(De=>!De.isLocal);p(Q)}),V.on(R.DataReceived,se=>{try{let Q=JSON.parse(new TextDecoder().decode(se)),De=Q.phase??Q.current_phase;typeof De=="string"&&De.length>0&&u(De),Q.type==="session_complete"&&D()}catch{}}),V.on(R.Disconnected,()=>{p(!1)}),await V.connect(n.livekit_url,n.livekit_token),i)try{await V.localParticipant.setMicrophoneEnabled(!0),f(!1)}catch{k("Microphone access was blocked by this host \u2014 continue in Flowe Desktop or your browser."),await V.disconnect(),S.current=null,o("handoff");return}O.current=Date.now(),o("connected"),d(i?"Connected \u2014 speak naturally when prompted.":"Flowe is guiding you.")}catch{S.current=null,k("This host sandbox restricts inline audio streaming \u2014 open in Flowe or scan to continue seamlessly."),o("handoff")}}async function x(){let V=S.current;if(!V)return;let se=!h;try{await V.localParticipant.setMicrophoneEnabled(!se),f(se)}catch{}}async function D(){if(_)return;P(!0);let V=S.current;S.current=null,V&&await V.disconnect().catch(()=>{});let se=Math.max(1,Math.round(y/60)),Q={};if(n.session_id)try{Q=await e.callTool("flowe_session_complete",{session_id:n.session_id,duration_minutes:se})}catch{}await e.updateContext(`User finished their ${i?"Deep Reset":"Quick Reset"} (${n.session_type_name??"Flowe session"}).`),t({...n,...Q,view:"complete"})}let B=Math.max(0,r-y),H=Math.min(1,y/r),$=Math.max(0,s.indexOf(l));return w("div",{class:"fl-stack",children:[w("div",{ref:E,style:{display:"none"}}),w("div",{class:"fl-header",children:[w("div",{class:"fl-brand-row",children:[w(Hn,{state:a==="connecting"?"thinking":a==="connected"?i&&!h&&!m?"listening":m?"awake":"resting":"awake",size:36,live:a==="connected"||a==="connecting",pro:!!n.account?.is_pro,label:n.session_type_name??"Flowe session"}),w("div",{children:[w("div",{class:"fl-mono",children:[i?"DEEP RESET \xB7 INTERACTIVE VOICE":"QUICK RESET \xB7 LISTEN ONLY",n.ambient&&n.ambient!=="none"?` \xB7 ${n.ambient.replace(/_/g," ").toUpperCase()}`:""]}),w("h2",{class:"fl-title",children:n.session_type_name||"Flowe Session"})]})]}),w("span",{class:"fl-badge",children:[n.estimated_duration??(i?20:10)," min"]})]}),a==="ready"?w("div",{class:"fl-stack",children:[w("p",{class:"fl-body",children:i?"Your interactive Flowe voice room is ready. Uses your microphone for guided dialogue, or open on Flowe Desktop / mobile.":`Your live ${(n.voice??"ada").replace(/^\w/,V=>V.toUpperCase())} voice room is ready. Sit back and listen \u2014 no microphone needed.`}),w("div",{class:"fl-row",children:[w("button",{type:"button",class:"fl-btn-primary",onClick:q,children:i?"Join live voice session":"Begin Quick Reset"}),n.web_url?w("button",{type:"button",class:"fl-btn-secondary",onClick:()=>e.openLink(n.web_url),children:"Open in browser"}):null,w("button",{type:"button",class:"fl-btn-link",onClick:()=>o("handoff"),children:"Show phone QR"})]})]}):null,a==="connecting"||a==="connected"?w("div",{class:"fl-runner-stage",children:[w(op,{size:128,stroke:3.5,fraction:H,breathScale:m?1.1:.96,label:`${lm(B)} remaining`,children:[w("span",{class:"fl-ring-time",children:lm(B)}),w("span",{class:"fl-mono",children:ST(l)})]}),w("div",{class:"fl-stack",style:{gap:"10px",flex:1},children:[w("p",{class:"fl-body","aria-live":"polite",children:c}),s.length>1?w("div",{class:"fl-pips","aria-label":`Phase ${$+1} of ${s.length}`,children:s.map((V,se)=>w("span",{class:"fl-pip","data-state":se<$?"done":se===$?"active":"todo"},V))}):null,w("div",{class:"fl-row",children:[i&&a==="connected"?w("button",{type:"button",class:"fl-btn-secondary",onClick:x,children:h?"Unmute mic":"Mute mic"}):null,w("button",{type:"button",class:"fl-btn-secondary",disabled:_,onClick:D,children:_?"Finishing\u2026":"End session"}),w("button",{type:"button",class:"fl-btn-link",onClick:()=>o("handoff"),children:"Move to phone"})]})]})]}):null,a==="handoff"?w("div",{class:"fl-stack",children:[b?w("p",{class:"fl-body",children:b}):null,w("div",{class:"fl-runner-stage",style:{alignItems:"center"},children:[n.join_url?w(Fd,{value:n.join_url,size:96}):null,w("div",{class:"fl-stack",style:{gap:"10px",flex:1},children:[w("p",{class:"fl-body",children:"Scan with your phone to join in the Flowe app, or launch on desktop. Your session is already queued."}),w("div",{class:"fl-row",children:[n.web_url?w("button",{type:"button",class:"fl-btn-primary",onClick:()=>e.openLink(n.web_url),children:"Open in Flowe"}):null,n.livekit_url&&n.livekit_token?w("button",{type:"button",class:"fl-btn-secondary",onClick:q,children:"Try inline audio"}):null,w("button",{type:"button",class:"fl-btn-link",disabled:_,onClick:D,children:"I\u2019m done"})]})]})]})]}):null]})}function wT({bridge:n}){let[e,t]=Ve(null);if(ni(()=>(n.onPayload(r=>t(r)),()=>n.destroy()),[n]),!e)return w("div",{class:"fl-shell",children:w("div",{class:"fl-brand-row",children:[w(Hn,{state:"thinking",size:32,live:!0}),w("div",{children:[w("div",{class:"fl-mono",children:"FLOWE LIVE"}),w("p",{class:"fl-body",children:"Preparing your session\u2026"})]})]})});let i=e.view??(e.auth?"auth":"live_session");return w("div",{class:"fl-shell",children:i==="auth"?w(_T,{payload:e,bridge:n,onReady:t}):i==="quota"?w("div",{class:"fl-stack",children:[w("div",{class:"fl-brand-row",children:[w(Hn,{state:"awake",size:34}),w("div",{children:[w("div",{class:"fl-mono",children:e.account?.team_paused?"FLOWE FOR TEAMS":"FLOWE PRO"}),w("h2",{class:"fl-title",children:e.account?.team_paused?"Your team plan is off":e.tier==="deep"?"Deep Resets come with Flowe Pro":"This week\u2019s Quick Resets are used"})]})]}),w("p",{class:"fl-body",children:e.message||"Micro-resets stay free. Flowe Pro gives unlimited live resets."}),e.upgrade_url?w("div",{class:"fl-row",children:w("button",{type:"button",class:"fl-btn-primary",onClick:()=>n.openLink(e.upgrade_url),children:"See Flowe Pro"})}):null]}):i==="complete"?w("div",{class:"fl-stack",children:[w("div",{class:"fl-header",children:[w("div",{class:"fl-brand-row",children:[w(Hn,{state:"glad",size:38,pro:!!e.account?.is_pro}),w("div",{children:[w("div",{class:"fl-mono",children:e.completed===!0?"SAVED TO YOUR JOURNEY":"SESSION ENDED"}),w("h2",{class:"fl-title",children:"Welcome back."})]})]}),w("div",{class:"fl-row",children:[typeof e.sessions_today=="number"?w("span",{class:"fl-badge fl-badge-ok",children:["Today \xB7 ",e.sessions_today]}):null,typeof e.streak_days=="number"&&e.streak_days>0?w("span",{class:"fl-badge",children:["Streak \xB7 ",e.streak_days,"d"]}):null]})]}),w("p",{class:"fl-body",children:e.completed===!0?`${e.session_type_name??"Your session"} is in your Flowe Journey.`:"Flowe could not save this session to your Journey."})]}):w(CT,{payload:e,bridge:n,onComplete:t})})}var ET=dm("flowe-live-session"),um=document.getElementById("app");um&&Xd(w(wT,{bridge:ET}),um);
49
49
  </script></body></html>