obi-sdk 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,761 @@
1
+ (function(ge,W){typeof exports=="object"&&typeof module<"u"?W(exports,require("lit")):typeof define=="function"&&define.amd?define(["exports","lit"],W):(ge=typeof globalThis<"u"?globalThis:ge||self,W(ge.ObiSDK={},ge.lit))})(this,function(ge,W){"use strict";var ae;(function(i){i.assertEqual=r=>r;function e(r){}i.assertIs=e;function t(r){throw new Error}i.assertNever=t,i.arrayToEnum=r=>{const s={};for(const a of r)s[a]=a;return s},i.getValidEnumValues=r=>{const s=i.objectKeys(r).filter(o=>typeof r[r[o]]!="number"),a={};for(const o of s)a[o]=r[o];return i.objectValues(a)},i.objectValues=r=>i.objectKeys(r).map(function(s){return r[s]}),i.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{const s=[];for(const a in r)Object.prototype.hasOwnProperty.call(r,a)&&s.push(a);return s},i.find=(r,s)=>{for(const a of r)if(s(a))return a},i.isInteger=typeof Number.isInteger=="function"?r=>Number.isInteger(r):r=>typeof r=="number"&&isFinite(r)&&Math.floor(r)===r;function n(r,s=" | "){return r.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}i.joinValues=n,i.jsonStringifyReplacer=(r,s)=>typeof s=="bigint"?s.toString():s})(ae||(ae={}));var ms;(function(i){i.mergeShapes=(e,t)=>({...e,...t})})(ms||(ms={}));const B=ae.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Mt=i=>{switch(typeof i){case"undefined":return B.undefined;case"string":return B.string;case"number":return isNaN(i)?B.nan:B.number;case"boolean":return B.boolean;case"function":return B.function;case"bigint":return B.bigint;case"symbol":return B.symbol;case"object":return Array.isArray(i)?B.array:i===null?B.null:i.then&&typeof i.then=="function"&&i.catch&&typeof i.catch=="function"?B.promise:typeof Map<"u"&&i instanceof Map?B.map:typeof Set<"u"&&i instanceof Set?B.set:typeof Date<"u"&&i instanceof Date?B.date:B.object;default:return B.unknown}},I=ae.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Tl=i=>JSON.stringify(i,null,2).replace(/"([^"]+)":/g,"$1:");class nt extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(s){return s.message},n={_errors:[]},r=s=>{for(const a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(r);else if(a.code==="invalid_return_type")r(a.returnTypeError);else if(a.code==="invalid_arguments")r(a.argumentsError);else if(a.path.length===0)n._errors.push(t(a));else{let o=n,c=0;for(;c<a.path.length;){const d=a.path[c];c===a.path.length-1?(o[d]=o[d]||{_errors:[]},o[d]._errors.push(t(a))):o[d]=o[d]||{_errors:[]},o=o[d],c++}}};return r(this),n}static assert(e){if(!(e instanceof nt))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ae.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},n=[];for(const r of this.issues)r.path.length>0?(t[r.path[0]]=t[r.path[0]]||[],t[r.path[0]].push(e(r))):n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}nt.create=i=>new nt(i);const Nn=(i,e)=>{let t;switch(i.code){case I.invalid_type:i.received===B.undefined?t="Required":t=`Expected ${i.expected}, received ${i.received}`;break;case I.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(i.expected,ae.jsonStringifyReplacer)}`;break;case I.unrecognized_keys:t=`Unrecognized key(s) in object: ${ae.joinValues(i.keys,", ")}`;break;case I.invalid_union:t="Invalid input";break;case I.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${ae.joinValues(i.options)}`;break;case I.invalid_enum_value:t=`Invalid enum value. Expected ${ae.joinValues(i.options)}, received '${i.received}'`;break;case I.invalid_arguments:t="Invalid function arguments";break;case I.invalid_return_type:t="Invalid function return type";break;case I.invalid_date:t="Invalid date";break;case I.invalid_string:typeof i.validation=="object"?"includes"in i.validation?(t=`Invalid input: must include "${i.validation.includes}"`,typeof i.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${i.validation.position}`)):"startsWith"in i.validation?t=`Invalid input: must start with "${i.validation.startsWith}"`:"endsWith"in i.validation?t=`Invalid input: must end with "${i.validation.endsWith}"`:ae.assertNever(i.validation):i.validation!=="regex"?t=`Invalid ${i.validation}`:t="Invalid";break;case I.too_small:i.type==="array"?t=`Array must contain ${i.exact?"exactly":i.inclusive?"at least":"more than"} ${i.minimum} element(s)`:i.type==="string"?t=`String must contain ${i.exact?"exactly":i.inclusive?"at least":"over"} ${i.minimum} character(s)`:i.type==="number"?t=`Number must be ${i.exact?"exactly equal to ":i.inclusive?"greater than or equal to ":"greater than "}${i.minimum}`:i.type==="date"?t=`Date must be ${i.exact?"exactly equal to ":i.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(i.minimum))}`:t="Invalid input";break;case I.too_big:i.type==="array"?t=`Array must contain ${i.exact?"exactly":i.inclusive?"at most":"less than"} ${i.maximum} element(s)`:i.type==="string"?t=`String must contain ${i.exact?"exactly":i.inclusive?"at most":"under"} ${i.maximum} character(s)`:i.type==="number"?t=`Number must be ${i.exact?"exactly":i.inclusive?"less than or equal to":"less than"} ${i.maximum}`:i.type==="bigint"?t=`BigInt must be ${i.exact?"exactly":i.inclusive?"less than or equal to":"less than"} ${i.maximum}`:i.type==="date"?t=`Date must be ${i.exact?"exactly":i.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(i.maximum))}`:t="Invalid input";break;case I.custom:t="Invalid input";break;case I.invalid_intersection_types:t="Intersection results could not be merged";break;case I.not_multiple_of:t=`Number must be a multiple of ${i.multipleOf}`;break;case I.not_finite:t="Number must be finite";break;default:t=e.defaultError,ae.assertNever(i)}return{message:t}};let lo=Nn;function Cl(i){lo=i}function rr(){return lo}const sr=i=>{const{data:e,path:t,errorMaps:n,issueData:r}=i,s=[...t,...r.path||[]],a={...r,path:s};if(r.message!==void 0)return{...r,path:s,message:r.message};let o="";const c=n.filter(d=>!!d).slice().reverse();for(const d of c)o=d(a,{data:e,defaultError:o}).message;return{...r,path:s,message:o}},_l=[];function j(i,e){const t=rr(),n=sr({issueData:e,data:i.data,path:i.path,errorMaps:[i.common.contextualErrorMap,i.schemaErrorMap,t,t===Nn?void 0:Nn].filter(r=>!!r)});i.common.issues.push(n)}class We{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const n=[];for(const r of t){if(r.status==="aborted")return Z;r.status==="dirty"&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const r of t){const s=await r.key,a=await r.value;n.push({key:s,value:a})}return We.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const r of t){const{key:s,value:a}=r;if(s.status==="aborted"||a.status==="aborted")return Z;s.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||r.alwaysSet)&&(n[s.value]=a.value)}return{status:e.value,value:n}}}const Z=Object.freeze({status:"aborted"}),Ln=i=>({status:"dirty",value:i}),Ge=i=>({status:"valid",value:i}),gs=i=>i.status==="aborted",vs=i=>i.status==="dirty",yn=i=>i.status==="valid",ui=i=>typeof Promise<"u"&&i instanceof Promise;function ar(i,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?i!==e||!n:!e.has(i))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(i):n?n.value:e.get(i)}function ho(i,e,t,n,r){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?i!==e||!r:!e.has(i))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?r.call(i,t):r?r.value=t:e.set(i,t),t}typeof SuppressedError=="function"&&SuppressedError;var z;(function(i){i.errToObj=e=>typeof e=="string"?{message:e}:e||{},i.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(z||(z={}));var li,hi;class Tt{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const fo=(i,e)=>{if(yn(e))return{success:!0,data:e.value};if(!i.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new nt(i.common.issues);return this._error=t,this._error}}};function X(i){if(!i)return{};const{errorMap:e,invalid_type_error:t,required_error:n,description:r}=i;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:r}:{errorMap:(a,o)=>{var c,d;const{message:u}=i;return a.code==="invalid_enum_value"?{message:u??o.defaultError}:typeof o.data>"u"?{message:(c=u??n)!==null&&c!==void 0?c:o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:(d=u??t)!==null&&d!==void 0?d:o.defaultError}},description:r}}class ee{get description(){return this._def.description}_getType(e){return Mt(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Mt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new We,ctx:{common:e.parent.common,data:e.data,parsedType:Mt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(ui(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){var n;const r={common:{issues:[],async:(n=t==null?void 0:t.async)!==null&&n!==void 0?n:!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Mt(e)},s=this._parseSync({data:e,path:r.path,parent:r});return fo(r,s)}"~validate"(e){var t,n;const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Mt(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:r});return yn(s)?{value:s.value}:{issues:r.common.issues}}catch(s){!((n=(t=s==null?void 0:s.message)===null||t===void 0?void 0:t.toLowerCase())===null||n===void 0)&&n.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(s=>yn(s)?{value:s.value}:{issues:r.common.issues})}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={common:{issues:[],contextualErrorMap:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Mt(e)},r=this._parse({data:e,path:n.path,parent:n}),s=await(ui(r)?r:Promise.resolve(r));return fo(n,s)}refine(e,t){const n=r=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(r):t;return this._refinement((r,s)=>{const a=e(r),o=()=>s.addIssue({code:I.custom,...n(r)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t=="function"?t(n,r):t),!1))}_refinement(e){return new ut({schema:this,typeName:K.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return _t.create(this,this._def)}nullable(){return Ht.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return dt.create(this)}promise(){return $n.create(this,this._def)}or(e){return gi.create([this,e],this._def)}and(e){return vi.create(this,e,this._def)}transform(e){return new ut({...X(this._def),schema:this,typeName:K.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new Ti({...X(this._def),innerType:this,defaultValue:t,typeName:K.ZodDefault})}brand(){return new ks({typeName:K.ZodBranded,type:this,...X(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Ci({...X(this._def),innerType:this,catchValue:t,typeName:K.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return _i.create(this,e)}readonly(){return Ei.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const El=/^c[^\s-]{8,}$/i,wl=/^[0-9a-z]+$/,Pl=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Rl=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,xl=/^[a-z0-9_-]{21}$/i,Il=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ol=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Al=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Dl="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let ys;const Ml=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Nl=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Ll=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Ul=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,jl=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Fl=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,po="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",$l=new RegExp(`^${po}$`);function mo(i){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return i.precision?e=`${e}\\.\\d{${i.precision}}`:i.precision==null&&(e=`${e}(\\.\\d+)?`),e}function Bl(i){return new RegExp(`^${mo(i)}$`)}function go(i){let e=`${po}T${mo(i)}`;const t=[];return t.push(i.local?"Z?":"Z"),i.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Vl(i,e){return!!((e==="v4"||!e)&&Ml.test(i)||(e==="v6"||!e)&&Ll.test(i))}function ql(i,e){if(!Il.test(i))return!1;try{const[t]=i.split("."),n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),r=JSON.parse(atob(n));return!(typeof r!="object"||r===null||!r.typ||!r.alg||e&&r.alg!==e)}catch{return!1}}function zl(i,e){return!!((e==="v4"||!e)&&Nl.test(i)||(e==="v6"||!e)&&Ul.test(i))}class ct extends ee{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==B.string){const s=this._getOrReturnCtx(e);return j(s,{code:I.invalid_type,expected:B.string,received:s.parsedType}),Z}const n=new We;let r;for(const s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(r=this._getOrReturnCtx(e,r),j(r,{code:I.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(r=this._getOrReturnCtx(e,r),j(r,{code:I.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){const a=e.data.length>s.value,o=e.data.length<s.value;(a||o)&&(r=this._getOrReturnCtx(e,r),a?j(r,{code:I.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):o&&j(r,{code:I.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")Al.test(e.data)||(r=this._getOrReturnCtx(e,r),j(r,{validation:"email",code:I.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")ys||(ys=new RegExp(Dl,"u")),ys.test(e.data)||(r=this._getOrReturnCtx(e,r),j(r,{validation:"emoji",code:I.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")Rl.test(e.data)||(r=this._getOrReturnCtx(e,r),j(r,{validation:"uuid",code:I.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")xl.test(e.data)||(r=this._getOrReturnCtx(e,r),j(r,{validation:"nanoid",code:I.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")El.test(e.data)||(r=this._getOrReturnCtx(e,r),j(r,{validation:"cuid",code:I.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")wl.test(e.data)||(r=this._getOrReturnCtx(e,r),j(r,{validation:"cuid2",code:I.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")Pl.test(e.data)||(r=this._getOrReturnCtx(e,r),j(r,{validation:"ulid",code:I.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),j(r,{validation:"url",code:I.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),j(r,{validation:"regex",code:I.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(r=this._getOrReturnCtx(e,r),j(r,{code:I.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(r=this._getOrReturnCtx(e,r),j(r,{code:I.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(r=this._getOrReturnCtx(e,r),j(r,{code:I.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?go(s).test(e.data)||(r=this._getOrReturnCtx(e,r),j(r,{code:I.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?$l.test(e.data)||(r=this._getOrReturnCtx(e,r),j(r,{code:I.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?Bl(s).test(e.data)||(r=this._getOrReturnCtx(e,r),j(r,{code:I.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?Ol.test(e.data)||(r=this._getOrReturnCtx(e,r),j(r,{validation:"duration",code:I.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?Vl(e.data,s.version)||(r=this._getOrReturnCtx(e,r),j(r,{validation:"ip",code:I.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?ql(e.data,s.alg)||(r=this._getOrReturnCtx(e,r),j(r,{validation:"jwt",code:I.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?zl(e.data,s.version)||(r=this._getOrReturnCtx(e,r),j(r,{validation:"cidr",code:I.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?jl.test(e.data)||(r=this._getOrReturnCtx(e,r),j(r,{validation:"base64",code:I.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?Fl.test(e.data)||(r=this._getOrReturnCtx(e,r),j(r,{validation:"base64url",code:I.invalid_string,message:s.message}),n.dirty()):ae.assertNever(s);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(r=>e.test(r),{validation:t,code:I.invalid_string,...z.errToObj(n)})}_addCheck(e){return new ct({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...z.errToObj(e)})}url(e){return this._addCheck({kind:"url",...z.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...z.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...z.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...z.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...z.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...z.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...z.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...z.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...z.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...z.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...z.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...z.errToObj(e)})}datetime(e){var t,n;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(t=e==null?void 0:e.offset)!==null&&t!==void 0?t:!1,local:(n=e==null?void 0:e.local)!==null&&n!==void 0?n:!1,...z.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...z.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...z.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...z.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...z.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...z.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...z.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...z.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...z.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...z.errToObj(t)})}nonempty(e){return this.min(1,z.errToObj(e))}trim(){return new ct({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ct({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ct({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}ct.create=i=>{var e;return new ct({checks:[],typeName:K.ZodString,coerce:(e=i==null?void 0:i.coerce)!==null&&e!==void 0?e:!1,...X(i)})};function Wl(i,e){const t=(i.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,r=t>n?t:n,s=parseInt(i.toFixed(r).replace(".","")),a=parseInt(e.toFixed(r).replace(".",""));return s%a/Math.pow(10,r)}class Wt extends ee{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==B.number){const s=this._getOrReturnCtx(e);return j(s,{code:I.invalid_type,expected:B.number,received:s.parsedType}),Z}let n;const r=new We;for(const s of this._def.checks)s.kind==="int"?ae.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),j(n,{code:I.invalid_type,expected:"integer",received:"float",message:s.message}),r.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),j(n,{code:I.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),j(n,{code:I.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty()):s.kind==="multipleOf"?Wl(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),j(n,{code:I.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),j(n,{code:I.not_finite,message:s.message}),r.dirty()):ae.assertNever(s);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,z.toString(t))}gt(e,t){return this.setLimit("min",e,!1,z.toString(t))}lte(e,t){return this.setLimit("max",e,!0,z.toString(t))}lt(e,t){return this.setLimit("max",e,!1,z.toString(t))}setLimit(e,t,n,r){return new Wt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:z.toString(r)}]})}_addCheck(e){return new Wt({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:z.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:z.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:z.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:z.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:z.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:z.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ae.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}}Wt.create=i=>new Wt({checks:[],typeName:K.ZodNumber,coerce:(i==null?void 0:i.coerce)||!1,...X(i)});class Gt extends ee{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==B.bigint)return this._getInvalidInput(e);let n;const r=new We;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),j(n,{code:I.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),j(n,{code:I.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),j(n,{code:I.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):ae.assertNever(s);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return j(t,{code:I.invalid_type,expected:B.bigint,received:t.parsedType}),Z}gte(e,t){return this.setLimit("min",e,!0,z.toString(t))}gt(e,t){return this.setLimit("min",e,!1,z.toString(t))}lte(e,t){return this.setLimit("max",e,!0,z.toString(t))}lt(e,t){return this.setLimit("max",e,!1,z.toString(t))}setLimit(e,t,n,r){return new Gt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:z.toString(r)}]})}_addCheck(e){return new Gt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:z.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:z.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}Gt.create=i=>{var e;return new Gt({checks:[],typeName:K.ZodBigInt,coerce:(e=i==null?void 0:i.coerce)!==null&&e!==void 0?e:!1,...X(i)})};class fi extends ee{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==B.boolean){const n=this._getOrReturnCtx(e);return j(n,{code:I.invalid_type,expected:B.boolean,received:n.parsedType}),Z}return Ge(e.data)}}fi.create=i=>new fi({typeName:K.ZodBoolean,coerce:(i==null?void 0:i.coerce)||!1,...X(i)});class bn extends ee{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==B.date){const s=this._getOrReturnCtx(e);return j(s,{code:I.invalid_type,expected:B.date,received:s.parsedType}),Z}if(isNaN(e.data.getTime())){const s=this._getOrReturnCtx(e);return j(s,{code:I.invalid_date}),Z}const n=new We;let r;for(const s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(r=this._getOrReturnCtx(e,r),j(r,{code:I.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(r=this._getOrReturnCtx(e,r),j(r,{code:I.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ae.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new bn({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:z.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:z.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}bn.create=i=>new bn({checks:[],coerce:(i==null?void 0:i.coerce)||!1,typeName:K.ZodDate,...X(i)});class or extends ee{_parse(e){if(this._getType(e)!==B.symbol){const n=this._getOrReturnCtx(e);return j(n,{code:I.invalid_type,expected:B.symbol,received:n.parsedType}),Z}return Ge(e.data)}}or.create=i=>new or({typeName:K.ZodSymbol,...X(i)});class pi extends ee{_parse(e){if(this._getType(e)!==B.undefined){const n=this._getOrReturnCtx(e);return j(n,{code:I.invalid_type,expected:B.undefined,received:n.parsedType}),Z}return Ge(e.data)}}pi.create=i=>new pi({typeName:K.ZodUndefined,...X(i)});class mi extends ee{_parse(e){if(this._getType(e)!==B.null){const n=this._getOrReturnCtx(e);return j(n,{code:I.invalid_type,expected:B.null,received:n.parsedType}),Z}return Ge(e.data)}}mi.create=i=>new mi({typeName:K.ZodNull,...X(i)});class Un extends ee{constructor(){super(...arguments),this._any=!0}_parse(e){return Ge(e.data)}}Un.create=i=>new Un({typeName:K.ZodAny,...X(i)});class kn extends ee{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ge(e.data)}}kn.create=i=>new kn({typeName:K.ZodUnknown,...X(i)});class Nt extends ee{_parse(e){const t=this._getOrReturnCtx(e);return j(t,{code:I.invalid_type,expected:B.never,received:t.parsedType}),Z}}Nt.create=i=>new Nt({typeName:K.ZodNever,...X(i)});class cr extends ee{_parse(e){if(this._getType(e)!==B.undefined){const n=this._getOrReturnCtx(e);return j(n,{code:I.invalid_type,expected:B.void,received:n.parsedType}),Z}return Ge(e.data)}}cr.create=i=>new cr({typeName:K.ZodVoid,...X(i)});class dt extends ee{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==B.array)return j(t,{code:I.invalid_type,expected:B.array,received:t.parsedType}),Z;if(r.exactLength!==null){const a=t.data.length>r.exactLength.value,o=t.data.length<r.exactLength.value;(a||o)&&(j(t,{code:a?I.too_big:I.too_small,minimum:o?r.exactLength.value:void 0,maximum:a?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(j(t,{code:I.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(j(t,{code:I.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((a,o)=>r.type._parseAsync(new Tt(t,a,t.path,o)))).then(a=>We.mergeArray(n,a));const s=[...t.data].map((a,o)=>r.type._parseSync(new Tt(t,a,t.path,o)));return We.mergeArray(n,s)}get element(){return this._def.type}min(e,t){return new dt({...this._def,minLength:{value:e,message:z.toString(t)}})}max(e,t){return new dt({...this._def,maxLength:{value:e,message:z.toString(t)}})}length(e,t){return new dt({...this._def,exactLength:{value:e,message:z.toString(t)}})}nonempty(e){return this.min(1,e)}}dt.create=(i,e)=>new dt({type:i,minLength:null,maxLength:null,exactLength:null,typeName:K.ZodArray,...X(e)});function jn(i){if(i instanceof Pe){const e={};for(const t in i.shape){const n=i.shape[t];e[t]=_t.create(jn(n))}return new Pe({...i._def,shape:()=>e})}else return i instanceof dt?new dt({...i._def,type:jn(i.element)}):i instanceof _t?_t.create(jn(i.unwrap())):i instanceof Ht?Ht.create(jn(i.unwrap())):i instanceof Ct?Ct.create(i.items.map(e=>jn(e))):i}class Pe extends ee{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=ae.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==B.object){const d=this._getOrReturnCtx(e);return j(d,{code:I.invalid_type,expected:B.object,received:d.parsedType}),Z}const{status:n,ctx:r}=this._processInputParams(e),{shape:s,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof Nt&&this._def.unknownKeys==="strip"))for(const d in r.data)a.includes(d)||o.push(d);const c=[];for(const d of a){const u=s[d],h=r.data[d];c.push({key:{status:"valid",value:d},value:u._parse(new Tt(r,h,r.path,d)),alwaysSet:d in r.data})}if(this._def.catchall instanceof Nt){const d=this._def.unknownKeys;if(d==="passthrough")for(const u of o)c.push({key:{status:"valid",value:u},value:{status:"valid",value:r.data[u]}});else if(d==="strict")o.length>0&&(j(r,{code:I.unrecognized_keys,keys:o}),n.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const u of o){const h=r.data[u];c.push({key:{status:"valid",value:u},value:d._parse(new Tt(r,h,r.path,u)),alwaysSet:u in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const d=[];for(const u of c){const h=await u.key,f=await u.value;d.push({key:h,value:f,alwaysSet:u.alwaysSet})}return d}).then(d=>We.mergeObjectSync(n,d)):We.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return z.errToObj,new Pe({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{var r,s,a,o;const c=(a=(s=(r=this._def).errorMap)===null||s===void 0?void 0:s.call(r,t,n).message)!==null&&a!==void 0?a:n.defaultError;return t.code==="unrecognized_keys"?{message:(o=z.errToObj(e).message)!==null&&o!==void 0?o:c}:{message:c}}}:{}})}strip(){return new Pe({...this._def,unknownKeys:"strip"})}passthrough(){return new Pe({...this._def,unknownKeys:"passthrough"})}extend(e){return new Pe({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Pe({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:K.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Pe({...this._def,catchall:e})}pick(e){const t={};return ae.objectKeys(e).forEach(n=>{e[n]&&this.shape[n]&&(t[n]=this.shape[n])}),new Pe({...this._def,shape:()=>t})}omit(e){const t={};return ae.objectKeys(this.shape).forEach(n=>{e[n]||(t[n]=this.shape[n])}),new Pe({...this._def,shape:()=>t})}deepPartial(){return jn(this)}partial(e){const t={};return ae.objectKeys(this.shape).forEach(n=>{const r=this.shape[n];e&&!e[n]?t[n]=r:t[n]=r.optional()}),new Pe({...this._def,shape:()=>t})}required(e){const t={};return ae.objectKeys(this.shape).forEach(n=>{if(e&&!e[n])t[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof _t;)s=s._def.innerType;t[n]=s}}),new Pe({...this._def,shape:()=>t})}keyof(){return vo(ae.objectKeys(this.shape))}}Pe.create=(i,e)=>new Pe({shape:()=>i,unknownKeys:"strip",catchall:Nt.create(),typeName:K.ZodObject,...X(e)}),Pe.strictCreate=(i,e)=>new Pe({shape:()=>i,unknownKeys:"strict",catchall:Nt.create(),typeName:K.ZodObject,...X(e)}),Pe.lazycreate=(i,e)=>new Pe({shape:i,unknownKeys:"strip",catchall:Nt.create(),typeName:K.ZodObject,...X(e)});class gi extends ee{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;function r(s){for(const o of s)if(o.result.status==="valid")return o.result;for(const o of s)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;const a=s.map(o=>new nt(o.ctx.common.issues));return j(t,{code:I.invalid_union,unionErrors:a}),Z}if(t.common.async)return Promise.all(n.map(async s=>{const a={...t,common:{...t.common,issues:[]},parent:null};return{result:await s._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(r);{let s;const a=[];for(const c of n){const d={...t,common:{...t.common,issues:[]},parent:null},u=c._parseSync({data:t.data,path:t.path,parent:d});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(s)return t.common.issues.push(...s.ctx.common.issues),s.result;const o=a.map(c=>new nt(c));return j(t,{code:I.invalid_union,unionErrors:o}),Z}}get options(){return this._def.options}}gi.create=(i,e)=>new gi({options:i,typeName:K.ZodUnion,...X(e)});const Lt=i=>i instanceof bi?Lt(i.schema):i instanceof ut?Lt(i.innerType()):i instanceof ki?[i.value]:i instanceof Kt?i.options:i instanceof Si?ae.objectValues(i.enum):i instanceof Ti?Lt(i._def.innerType):i instanceof pi?[void 0]:i instanceof mi?[null]:i instanceof _t?[void 0,...Lt(i.unwrap())]:i instanceof Ht?[null,...Lt(i.unwrap())]:i instanceof ks||i instanceof Ei?Lt(i.unwrap()):i instanceof Ci?Lt(i._def.innerType):[];class dr extends ee{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==B.object)return j(t,{code:I.invalid_type,expected:B.object,received:t.parsedType}),Z;const n=this.discriminator,r=t.data[n],s=this.optionsMap.get(r);return s?t.common.async?s._parseAsync({data:t.data,path:t.path,parent:t}):s._parseSync({data:t.data,path:t.path,parent:t}):(j(t,{code:I.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),Z)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){const r=new Map;for(const s of t){const a=Lt(s.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const o of a){if(r.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);r.set(o,s)}}return new dr({typeName:K.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:r,...X(n)})}}function bs(i,e){const t=Mt(i),n=Mt(e);if(i===e)return{valid:!0,data:i};if(t===B.object&&n===B.object){const r=ae.objectKeys(e),s=ae.objectKeys(i).filter(o=>r.indexOf(o)!==-1),a={...i,...e};for(const o of s){const c=bs(i[o],e[o]);if(!c.valid)return{valid:!1};a[o]=c.data}return{valid:!0,data:a}}else if(t===B.array&&n===B.array){if(i.length!==e.length)return{valid:!1};const r=[];for(let s=0;s<i.length;s++){const a=i[s],o=e[s],c=bs(a,o);if(!c.valid)return{valid:!1};r.push(c.data)}return{valid:!0,data:r}}else return t===B.date&&n===B.date&&+i==+e?{valid:!0,data:i}:{valid:!1}}class vi extends ee{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),r=(s,a)=>{if(gs(s)||gs(a))return Z;const o=bs(s.value,a.value);return o.valid?((vs(s)||vs(a))&&t.dirty(),{status:t.value,value:o.data}):(j(n,{code:I.invalid_intersection_types}),Z)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,a])=>r(s,a)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}vi.create=(i,e,t)=>new vi({left:i,right:e,typeName:K.ZodIntersection,...X(t)});class Ct extends ee{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==B.array)return j(n,{code:I.invalid_type,expected:B.array,received:n.parsedType}),Z;if(n.data.length<this._def.items.length)return j(n,{code:I.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Z;!this._def.rest&&n.data.length>this._def.items.length&&(j(n,{code:I.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const s=[...n.data].map((a,o)=>{const c=this._def.items[o]||this._def.rest;return c?c._parse(new Tt(n,a,n.path,o)):null}).filter(a=>!!a);return n.common.async?Promise.all(s).then(a=>We.mergeArray(t,a)):We.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new Ct({...this._def,rest:e})}}Ct.create=(i,e)=>{if(!Array.isArray(i))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ct({items:i,typeName:K.ZodTuple,rest:null,...X(e)})};class yi extends ee{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==B.object)return j(n,{code:I.invalid_type,expected:B.object,received:n.parsedType}),Z;const r=[],s=this._def.keyType,a=this._def.valueType;for(const o in n.data)r.push({key:s._parse(new Tt(n,o,n.path,o)),value:a._parse(new Tt(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?We.mergeObjectAsync(t,r):We.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof ee?new yi({keyType:e,valueType:t,typeName:K.ZodRecord,...X(n)}):new yi({keyType:ct.create(),valueType:e,typeName:K.ZodRecord,...X(t)})}}class ur extends ee{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==B.map)return j(n,{code:I.invalid_type,expected:B.map,received:n.parsedType}),Z;const r=this._def.keyType,s=this._def.valueType,a=[...n.data.entries()].map(([o,c],d)=>({key:r._parse(new Tt(n,o,n.path,[d,"key"])),value:s._parse(new Tt(n,c,n.path,[d,"value"]))}));if(n.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const c of a){const d=await c.key,u=await c.value;if(d.status==="aborted"||u.status==="aborted")return Z;(d.status==="dirty"||u.status==="dirty")&&t.dirty(),o.set(d.value,u.value)}return{status:t.value,value:o}})}else{const o=new Map;for(const c of a){const d=c.key,u=c.value;if(d.status==="aborted"||u.status==="aborted")return Z;(d.status==="dirty"||u.status==="dirty")&&t.dirty(),o.set(d.value,u.value)}return{status:t.value,value:o}}}}ur.create=(i,e,t)=>new ur({valueType:e,keyType:i,typeName:K.ZodMap,...X(t)});class Sn extends ee{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==B.set)return j(n,{code:I.invalid_type,expected:B.set,received:n.parsedType}),Z;const r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(j(n,{code:I.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(j(n,{code:I.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());const s=this._def.valueType;function a(c){const d=new Set;for(const u of c){if(u.status==="aborted")return Z;u.status==="dirty"&&t.dirty(),d.add(u.value)}return{status:t.value,value:d}}const o=[...n.data.values()].map((c,d)=>s._parse(new Tt(n,c,n.path,d)));return n.common.async?Promise.all(o).then(c=>a(c)):a(o)}min(e,t){return new Sn({...this._def,minSize:{value:e,message:z.toString(t)}})}max(e,t){return new Sn({...this._def,maxSize:{value:e,message:z.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Sn.create=(i,e)=>new Sn({valueType:i,minSize:null,maxSize:null,typeName:K.ZodSet,...X(e)});class Fn extends ee{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==B.function)return j(t,{code:I.invalid_type,expected:B.function,received:t.parsedType}),Z;function n(o,c){return sr({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,rr(),Nn].filter(d=>!!d),issueData:{code:I.invalid_arguments,argumentsError:c}})}function r(o,c){return sr({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,rr(),Nn].filter(d=>!!d),issueData:{code:I.invalid_return_type,returnTypeError:c}})}const s={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof $n){const o=this;return Ge(async function(...c){const d=new nt([]),u=await o._def.args.parseAsync(c,s).catch(g=>{throw d.addIssue(n(c,g)),d}),h=await Reflect.apply(a,this,u);return await o._def.returns._def.type.parseAsync(h,s).catch(g=>{throw d.addIssue(r(h,g)),d})})}else{const o=this;return Ge(function(...c){const d=o._def.args.safeParse(c,s);if(!d.success)throw new nt([n(c,d.error)]);const u=Reflect.apply(a,this,d.data),h=o._def.returns.safeParse(u,s);if(!h.success)throw new nt([r(u,h.error)]);return h.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Fn({...this._def,args:Ct.create(e).rest(kn.create())})}returns(e){return new Fn({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new Fn({args:e||Ct.create([]).rest(kn.create()),returns:t||kn.create(),typeName:K.ZodFunction,...X(n)})}}class bi extends ee{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}bi.create=(i,e)=>new bi({getter:i,typeName:K.ZodLazy,...X(e)});class ki extends ee{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return j(t,{received:t.data,code:I.invalid_literal,expected:this._def.value}),Z}return{status:"valid",value:e.data}}get value(){return this._def.value}}ki.create=(i,e)=>new ki({value:i,typeName:K.ZodLiteral,...X(e)});function vo(i,e){return new Kt({values:i,typeName:K.ZodEnum,...X(e)})}class Kt extends ee{constructor(){super(...arguments),li.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),n=this._def.values;return j(t,{expected:ae.joinValues(n),received:t.parsedType,code:I.invalid_type}),Z}if(ar(this,li,"f")||ho(this,li,new Set(this._def.values),"f"),!ar(this,li,"f").has(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return j(t,{received:t.data,code:I.invalid_enum_value,options:n}),Z}return Ge(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Kt.create(e,{...this._def,...t})}exclude(e,t=this._def){return Kt.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}}li=new WeakMap,Kt.create=vo;class Si extends ee{constructor(){super(...arguments),hi.set(this,void 0)}_parse(e){const t=ae.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==B.string&&n.parsedType!==B.number){const r=ae.objectValues(t);return j(n,{expected:ae.joinValues(r),received:n.parsedType,code:I.invalid_type}),Z}if(ar(this,hi,"f")||ho(this,hi,new Set(ae.getValidEnumValues(this._def.values)),"f"),!ar(this,hi,"f").has(e.data)){const r=ae.objectValues(t);return j(n,{received:n.data,code:I.invalid_enum_value,options:r}),Z}return Ge(e.data)}get enum(){return this._def.values}}hi=new WeakMap,Si.create=(i,e)=>new Si({values:i,typeName:K.ZodNativeEnum,...X(e)});class $n extends ee{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==B.promise&&t.common.async===!1)return j(t,{code:I.invalid_type,expected:B.promise,received:t.parsedType}),Z;const n=t.parsedType===B.promise?t.data:Promise.resolve(t.data);return Ge(n.then(r=>this._def.type.parseAsync(r,{path:t.path,errorMap:t.common.contextualErrorMap})))}}$n.create=(i,e)=>new $n({type:i,typeName:K.ZodPromise,...X(e)});class ut extends ee{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===K.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,s={addIssue:a=>{j(n,a),a.fatal?t.abort():t.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),r.type==="preprocess"){const a=r.transform(n.data,s);if(n.common.async)return Promise.resolve(a).then(async o=>{if(t.value==="aborted")return Z;const c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?Z:c.status==="dirty"||t.value==="dirty"?Ln(c.value):c});{if(t.value==="aborted")return Z;const o=this._def.schema._parseSync({data:a,path:n.path,parent:n});return o.status==="aborted"?Z:o.status==="dirty"||t.value==="dirty"?Ln(o.value):o}}if(r.type==="refinement"){const a=o=>{const c=r.refinement(o,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?Z:(o.status==="dirty"&&t.dirty(),a(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?Z:(o.status==="dirty"&&t.dirty(),a(o.value).then(()=>({status:t.value,value:o.value}))))}if(r.type==="transform")if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!yn(a))return a;const o=r.transform(a.value,s);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>yn(a)?Promise.resolve(r.transform(a.value,s)).then(o=>({status:t.value,value:o})):a);ae.assertNever(r)}}ut.create=(i,e,t)=>new ut({schema:i,typeName:K.ZodEffects,effect:e,...X(t)}),ut.createWithPreprocess=(i,e,t)=>new ut({schema:e,effect:{type:"preprocess",transform:i},typeName:K.ZodEffects,...X(t)});class _t extends ee{_parse(e){return this._getType(e)===B.undefined?Ge(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}_t.create=(i,e)=>new _t({innerType:i,typeName:K.ZodOptional,...X(e)});class Ht extends ee{_parse(e){return this._getType(e)===B.null?Ge(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ht.create=(i,e)=>new Ht({innerType:i,typeName:K.ZodNullable,...X(e)});class Ti extends ee{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===B.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Ti.create=(i,e)=>new Ti({innerType:i,typeName:K.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...X(e)});class Ci extends ee{_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return ui(r)?r.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new nt(n.common.issues)},input:n.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new nt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}Ci.create=(i,e)=>new Ci({innerType:i,typeName:K.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...X(e)});class lr extends ee{_parse(e){if(this._getType(e)!==B.nan){const n=this._getOrReturnCtx(e);return j(n,{code:I.invalid_type,expected:B.nan,received:n.parsedType}),Z}return{status:"valid",value:e.data}}}lr.create=i=>new lr({typeName:K.ZodNaN,...X(i)});const Gl=Symbol("zod_brand");class ks extends ee{_parse(e){const{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class _i extends ee{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?Z:s.status==="dirty"?(t.dirty(),Ln(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{const r=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return r.status==="aborted"?Z:r.status==="dirty"?(t.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:n.path,parent:n})}}static create(e,t){return new _i({in:e,out:t,typeName:K.ZodPipeline})}}class Ei extends ee{_parse(e){const t=this._def.innerType._parse(e),n=r=>(yn(r)&&(r.value=Object.freeze(r.value)),r);return ui(t)?t.then(r=>n(r)):n(t)}unwrap(){return this._def.innerType}}Ei.create=(i,e)=>new Ei({innerType:i,typeName:K.ZodReadonly,...X(e)});function yo(i,e){const t=typeof i=="function"?i(e):typeof i=="string"?{message:i}:i;return typeof t=="string"?{message:t}:t}function bo(i,e={},t){return i?Un.create().superRefine((n,r)=>{var s,a;const o=i(n);if(o instanceof Promise)return o.then(c=>{var d,u;if(!c){const h=yo(e,n),f=(u=(d=h.fatal)!==null&&d!==void 0?d:t)!==null&&u!==void 0?u:!0;r.addIssue({code:"custom",...h,fatal:f})}});if(!o){const c=yo(e,n),d=(a=(s=c.fatal)!==null&&s!==void 0?s:t)!==null&&a!==void 0?a:!0;r.addIssue({code:"custom",...c,fatal:d})}}):Un.create()}const Kl={object:Pe.lazycreate};var K;(function(i){i.ZodString="ZodString",i.ZodNumber="ZodNumber",i.ZodNaN="ZodNaN",i.ZodBigInt="ZodBigInt",i.ZodBoolean="ZodBoolean",i.ZodDate="ZodDate",i.ZodSymbol="ZodSymbol",i.ZodUndefined="ZodUndefined",i.ZodNull="ZodNull",i.ZodAny="ZodAny",i.ZodUnknown="ZodUnknown",i.ZodNever="ZodNever",i.ZodVoid="ZodVoid",i.ZodArray="ZodArray",i.ZodObject="ZodObject",i.ZodUnion="ZodUnion",i.ZodDiscriminatedUnion="ZodDiscriminatedUnion",i.ZodIntersection="ZodIntersection",i.ZodTuple="ZodTuple",i.ZodRecord="ZodRecord",i.ZodMap="ZodMap",i.ZodSet="ZodSet",i.ZodFunction="ZodFunction",i.ZodLazy="ZodLazy",i.ZodLiteral="ZodLiteral",i.ZodEnum="ZodEnum",i.ZodEffects="ZodEffects",i.ZodNativeEnum="ZodNativeEnum",i.ZodOptional="ZodOptional",i.ZodNullable="ZodNullable",i.ZodDefault="ZodDefault",i.ZodCatch="ZodCatch",i.ZodPromise="ZodPromise",i.ZodBranded="ZodBranded",i.ZodPipeline="ZodPipeline",i.ZodReadonly="ZodReadonly"})(K||(K={}));const Hl=(i,e={message:`Input not instance of ${i.name}`})=>bo(t=>t instanceof i,e),ko=ct.create,So=Wt.create,Zl=lr.create,Jl=Gt.create,To=fi.create,Yl=bn.create,Ql=or.create,Xl=pi.create,eh=mi.create,th=Un.create,nh=kn.create,ih=Nt.create,rh=cr.create,sh=dt.create,ah=Pe.create,oh=Pe.strictCreate,ch=gi.create,dh=dr.create,uh=vi.create,lh=Ct.create,hh=yi.create,fh=ur.create,ph=Sn.create,mh=Fn.create,gh=bi.create,vh=ki.create,yh=Kt.create,bh=Si.create,kh=$n.create,Co=ut.create,Sh=_t.create,Th=Ht.create,Ch=ut.createWithPreprocess,_h=_i.create;var Bn=Object.freeze({__proto__:null,defaultErrorMap:Nn,setErrorMap:Cl,getErrorMap:rr,makeIssue:sr,EMPTY_PATH:_l,addIssueToContext:j,ParseStatus:We,INVALID:Z,DIRTY:Ln,OK:Ge,isAborted:gs,isDirty:vs,isValid:yn,isAsync:ui,get util(){return ae},get objectUtil(){return ms},ZodParsedType:B,getParsedType:Mt,ZodType:ee,datetimeRegex:go,ZodString:ct,ZodNumber:Wt,ZodBigInt:Gt,ZodBoolean:fi,ZodDate:bn,ZodSymbol:or,ZodUndefined:pi,ZodNull:mi,ZodAny:Un,ZodUnknown:kn,ZodNever:Nt,ZodVoid:cr,ZodArray:dt,ZodObject:Pe,ZodUnion:gi,ZodDiscriminatedUnion:dr,ZodIntersection:vi,ZodTuple:Ct,ZodRecord:yi,ZodMap:ur,ZodSet:Sn,ZodFunction:Fn,ZodLazy:bi,ZodLiteral:ki,ZodEnum:Kt,ZodNativeEnum:Si,ZodPromise:$n,ZodEffects:ut,ZodTransformer:ut,ZodOptional:_t,ZodNullable:Ht,ZodDefault:Ti,ZodCatch:Ci,ZodNaN:lr,BRAND:Gl,ZodBranded:ks,ZodPipeline:_i,ZodReadonly:Ei,custom:bo,Schema:ee,ZodSchema:ee,late:Kl,get ZodFirstPartyTypeKind(){return K},coerce:{string:i=>ct.create({...i,coerce:!0}),number:i=>Wt.create({...i,coerce:!0}),boolean:i=>fi.create({...i,coerce:!0}),bigint:i=>Gt.create({...i,coerce:!0}),date:i=>bn.create({...i,coerce:!0})},any:th,array:sh,bigint:Jl,boolean:To,date:Yl,discriminatedUnion:dh,effect:Co,enum:yh,function:mh,instanceof:Hl,intersection:uh,lazy:gh,literal:vh,map:fh,nan:Zl,nativeEnum:bh,never:ih,null:eh,nullable:Th,number:So,object:ah,oboolean:()=>To().optional(),onumber:()=>So().optional(),optional:Sh,ostring:()=>ko().optional(),pipeline:_h,preprocess:Ch,promise:kh,record:hh,set:ph,strictObject:oh,string:ko,symbol:Ql,transformer:Co,tuple:lh,undefined:Xl,union:ch,unknown:nh,void:rh,NEVER:Z,ZodIssueCode:I,quotelessJson:Tl,ZodError:nt});const _o=Bn.object({apiKey:Bn.string().optional(),baseUrl:Bn.string().default("https://iamobi.ai/api"),enableVoice:Bn.boolean().default(!0),enableScreenCapture:Bn.boolean().default(!0),debug:Bn.boolean().default(!1)});var lt=(i=>(i.READY="ready",i.ERROR="error",i.VOICE_START="voice:start",i.VOICE_STOP="voice:stop",i.SCREEN_CAPTURE_START="screen:start",i.SCREEN_CAPTURE_STOP="screen:stop",i.STATE_CHANGE="state:change",i))(lt||{}),G=(i=>(i.READY="ready",i.ERROR="error",i.PAUSED="paused",i.LOADING="loading",i.THINKING="thinking",i.RESEARCHING="researching",i.AGENT_SPEAKING="agent_speaking",i.USER_SPEAKING="user_speaking",i.AWAITING_USER_INPUT="awaiting_user_input",i))(G||{});function Eo(i){return{all:i=i||new Map,on:function(e,t){var n=i.get(e);n?n.push(t):i.set(e,[t])},off:function(e,t){var n=i.get(e);n&&(t?n.splice(n.indexOf(t)>>>0,1):i.set(e,[]))},emit:function(e,t){var n=i.get(e);n&&n.slice().map(function(r){r(t)}),(n=i.get("*"))&&n.slice().map(function(r){r(e,t)})}}}class wo{constructor(e={}){this.state=G.READY,this.emitter=Eo(),this.voiceEnabled=!1,this.screenCaptureEnabled=!1,this.config=_o.parse(e),this.config.debug&&console.log("ObiSDK initialized with config:",this.config)}async init(){try{this.config.enableVoice&&await this.initVoice(),this.config.enableScreenCapture&&await this.initScreenCapture(),this.setState(G.READY),this.emitter.emit(lt.READY),this.config.debug&&console.log("ObiSDK ready")}catch(e){const t={code:"init_failed",message:"Failed to initialize SDK",details:e};this.handleError(t)}}async initVoice(){if(!window.navigator.mediaDevices||!window.navigator.mediaDevices.getUserMedia)throw new Error("Voice recording not supported in this browser");try{await window.navigator.mediaDevices.getUserMedia({audio:!0}),this.voiceEnabled=!0,this.config.debug&&console.log("Voice capabilities initialized")}catch(e){throw new Error(`Microphone access denied: ${e}`)}}async initScreenCapture(){if(!window.navigator.mediaDevices||!window.navigator.mediaDevices.getDisplayMedia)throw new Error("Screen capture not supported in this browser");this.screenCaptureEnabled=!0,this.config.debug&&console.log("Screen capture capabilities initialized")}setState(e){this.state=e,this.emitter.emit(lt.STATE_CHANGE,e)}handleError(e){this.setState(G.ERROR),this.emitter.emit(lt.ERROR,e),this.config.debug&&console.error("ObiSDK error:",e)}async startVoiceRecording(){if(!this.voiceEnabled){this.handleError({code:"voice_disabled",message:"Voice recording is not enabled or available"});return}try{this.setState(G.AGENT_SPEAKING),this.emitter.emit(lt.VOICE_START),this.config.debug&&console.log("Voice recording started")}catch(e){this.handleError({code:"voice_start_failed",message:"Failed to start voice recording",details:e})}}async stopVoiceRecording(){if(this.state===G.READY)return{transcript:void 0};try{const e={transcript:"Sample transcript"};return this.setState(G.READY),this.emitter.emit(lt.VOICE_STOP,e),this.config.debug&&console.log("Voice recording stopped:",e),e}catch(e){return this.handleError({code:"voice_stop_failed",message:"Failed to stop voice recording",details:e}),{transcript:void 0}}}async startScreenCapture(){if(!this.screenCaptureEnabled){this.handleError({code:"screen_capture_disabled",message:"Screen capture is not enabled or available"});return}try{this.setState(G.AGENT_SPEAKING),this.emitter.emit(lt.SCREEN_CAPTURE_START),this.config.debug&&console.log("Screen capture started")}catch(e){this.handleError({code:"screen_capture_start_failed",message:"Failed to start screen capture",details:e})}}async stopScreenCapture(){if(this.state===G.READY)return{screenshot:void 0};try{const e={screenshot:"data:image/png;base64,..."};return this.setState(G.READY),this.emitter.emit(lt.SCREEN_CAPTURE_STOP,e),this.config.debug&&console.log("Screen capture stopped"),e}catch(e){return this.handleError({code:"screen_capture_stop_failed",message:"Failed to stop screen capture",details:e}),{screenshot:void 0}}}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}getState(){return this.state}dispose(){this.emitter.all.clear(),this.config.debug&&console.log("ObiSDK disposed")}}function Eh(i,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if(n!=="default"&&!(n in i)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(i,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(i)}var wh=Object.defineProperty,Ph=(i,e,t)=>e in i?wh(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Po=(i,e,t)=>Ph(i,typeof e!="symbol"?e+"":e,t);let Ze=class{constructor(){Po(this,"_locking"),Po(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e;const t=new Promise(r=>e=()=>{this._locks-=1,r()}),n=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),n}};function Oe(i,e){if(!i)throw new Error(e)}const Rh=34028234663852886e22,xh=-34028234663852886e22,Ih=4294967295,Oh=2147483647,Ah=-2147483648;function hr(i){if(typeof i!="number")throw new Error("invalid int 32: "+typeof i);if(!Number.isInteger(i)||i>Oh||i<Ah)throw new Error("invalid int 32: "+i)}function Ss(i){if(typeof i!="number")throw new Error("invalid uint 32: "+typeof i);if(!Number.isInteger(i)||i>Ih||i<0)throw new Error("invalid uint 32: "+i)}function Ro(i){if(typeof i!="number")throw new Error("invalid float 32: "+typeof i);if(Number.isFinite(i)&&(i>Rh||i<xh))throw new Error("invalid float 32: "+i)}const xo=Symbol("@bufbuild/protobuf/enum-type");function Dh(i){const e=i[xo];return Oe(e,"missing enum type on enum object"),e}function Io(i,e,t,n){i[xo]=Oo(e,t.map(r=>({no:r.no,name:r.name,localName:i[r.no]})))}function Oo(i,e,t){const n=Object.create(null),r=Object.create(null),s=[];for(const a of e){const o=Ao(a);s.push(o),n[a.name]=o,r[a.no]=o}return{typeName:i,values:s,findName(a){return n[a]},findNumber(a){return r[a]}}}function Mh(i,e,t){const n={};for(const r of e){const s=Ao(r);n[s.localName]=s.no,n[s.no]=s.localName}return Io(n,i,e),n}function Ao(i){return"localName"in i?i:Object.assign(Object.assign({},i),{localName:i.name})}class Ts{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const n=this.getType(),r=n.runtime.bin,s=r.makeReadOptions(t);return r.readMessage(this,s.readerFactory(e),e.byteLength,s),this}fromJson(e,t){const n=this.getType(),r=n.runtime.json,s=r.makeReadOptions(t);return r.readMessage(n,e,s,this),this}fromJsonString(e,t){let n;try{n=JSON.parse(e)}catch(r){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(r instanceof Error?r.message:String(r)))}return this.fromJson(n,t)}toBinary(e){const t=this.getType(),n=t.runtime.bin,r=n.makeWriteOptions(e),s=r.writerFactory();return n.writeMessage(this,s,r),s.finish()}toJson(e){const t=this.getType(),n=t.runtime.json,r=n.makeWriteOptions(e);return n.writeMessage(this,r)}toJsonString(e){var t;const n=this.toJson(e);return JSON.stringify(n,null,(t=e==null?void 0:e.prettySpaces)!==null&&t!==void 0?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function Nh(i,e,t,n){var r;const s=(r=n==null?void 0:n.localName)!==null&&r!==void 0?r:e.substring(e.lastIndexOf(".")+1),a={[s]:function(o){i.util.initFields(this),i.util.initPartial(o,this)}}[s];return Object.setPrototypeOf(a.prototype,new Ts),Object.assign(a,{runtime:i,typeName:e,fields:i.util.newFieldList(t),fromBinary(o,c){return new a().fromBinary(o,c)},fromJson(o,c){return new a().fromJson(o,c)},fromJsonString(o,c){return new a().fromJsonString(o,c)},equals(o,c){return i.util.equals(a,o,c)}}),a}function Lh(){let i=0,e=0;for(let n=0;n<28;n+=7){let r=this.buf[this.pos++];if(i|=(r&127)<<n,!(r&128))return this.assertBounds(),[i,e]}let t=this.buf[this.pos++];if(i|=(t&15)<<28,e=(t&112)>>4,!(t&128))return this.assertBounds(),[i,e];for(let n=3;n<=31;n+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<n,!(r&128))return this.assertBounds(),[i,e]}throw new Error("invalid varint")}function Cs(i,e,t){for(let s=0;s<28;s=s+7){const a=i>>>s,o=!(!(a>>>7)&&e==0),c=(o?a|128:a)&255;if(t.push(c),!o)return}const n=i>>>28&15|(e&7)<<4,r=!!(e>>3);if(t.push((r?n|128:n)&255),!!r){for(let s=3;s<31;s=s+7){const a=e>>>s,o=!!(a>>>7),c=(o?a|128:a)&255;if(t.push(c),!o)return}t.push(e>>>31&1)}}const fr=4294967296;function Do(i){const e=i[0]==="-";e&&(i=i.slice(1));const t=1e6;let n=0,r=0;function s(a,o){const c=Number(i.slice(a,o));r*=t,n=n*t+c,n>=fr&&(r=r+(n/fr|0),n=n%fr)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),e?No(n,r):_s(n,r)}function Uh(i,e){let t=_s(i,e);const n=t.hi&2147483648;n&&(t=No(t.lo,t.hi));const r=Mo(t.lo,t.hi);return n?"-"+r:r}function Mo(i,e){if({lo:i,hi:e}=jh(i,e),e<=2097151)return String(fr*e+i);const t=i&16777215,n=(i>>>24|e<<8)&16777215,r=e>>16&65535;let s=t+n*6777216+r*6710656,a=n+r*8147497,o=r*2;const c=1e7;return s>=c&&(a+=Math.floor(s/c),s%=c),a>=c&&(o+=Math.floor(a/c),a%=c),o.toString()+Lo(a)+Lo(s)}function jh(i,e){return{lo:i>>>0,hi:e>>>0}}function _s(i,e){return{lo:i|0,hi:e|0}}function No(i,e){return e=~e,i?i=~i+1:e+=1,_s(i,e)}const Lo=i=>{const e=String(i);return"0000000".slice(e.length)+e};function Uo(i,e){if(i>=0){for(;i>127;)e.push(i&127|128),i=i>>>7;e.push(i)}else{for(let t=0;t<9;t++)e.push(i&127|128),i=i>>7;e.push(1)}}function Fh(){let i=this.buf[this.pos++],e=i&127;if(!(i&128))return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<7,!(i&128))return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<14,!(i&128))return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<21,!(i&128))return this.assertBounds(),e;i=this.buf[this.pos++],e|=(i&15)<<28;for(let t=5;i&128&&t<10;t++)i=this.buf[this.pos++];if(i&128)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function $h(){const i=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof i.getBigInt64=="function"&&typeof i.getBigUint64=="function"&&typeof i.setBigInt64=="function"&&typeof i.setBigUint64=="function"&&(typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){const r=BigInt("-9223372036854775808"),s=BigInt("9223372036854775807"),a=BigInt("0"),o=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(c){const d=typeof c=="bigint"?c:BigInt(c);if(d>s||d<r)throw new Error("int64 invalid: ".concat(c));return d},uParse(c){const d=typeof c=="bigint"?c:BigInt(c);if(d>o||d<a)throw new Error("uint64 invalid: ".concat(c));return d},enc(c){return i.setBigInt64(0,this.parse(c),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},uEnc(c){return i.setBigInt64(0,this.uParse(c),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},dec(c,d){return i.setInt32(0,c,!0),i.setInt32(4,d,!0),i.getBigInt64(0,!0)},uDec(c,d){return i.setInt32(0,c,!0),i.setInt32(4,d,!0),i.getBigUint64(0,!0)}}}const t=r=>Oe(/^-?[0-9]+$/.test(r),"int64 invalid: ".concat(r)),n=r=>Oe(/^[0-9]+$/.test(r),"uint64 invalid: ".concat(r));return{zero:"0",supported:!1,parse(r){return typeof r!="string"&&(r=r.toString()),t(r),r},uParse(r){return typeof r!="string"&&(r=r.toString()),n(r),r},enc(r){return typeof r!="string"&&(r=r.toString()),t(r),Do(r)},uEnc(r){return typeof r!="string"&&(r=r.toString()),n(r),Do(r)},dec(r,s){return Uh(r,s)},uDec(r,s){return Mo(r,s)}}}const _e=$h();var P;(function(i){i[i.DOUBLE=1]="DOUBLE",i[i.FLOAT=2]="FLOAT",i[i.INT64=3]="INT64",i[i.UINT64=4]="UINT64",i[i.INT32=5]="INT32",i[i.FIXED64=6]="FIXED64",i[i.FIXED32=7]="FIXED32",i[i.BOOL=8]="BOOL",i[i.STRING=9]="STRING",i[i.BYTES=12]="BYTES",i[i.UINT32=13]="UINT32",i[i.SFIXED32=15]="SFIXED32",i[i.SFIXED64=16]="SFIXED64",i[i.SINT32=17]="SINT32",i[i.SINT64=18]="SINT64"})(P||(P={}));var Zt;(function(i){i[i.BIGINT=0]="BIGINT",i[i.STRING=1]="STRING"})(Zt||(Zt={}));function Jt(i,e,t){if(e===t)return!0;if(i==P.BYTES){if(!(e instanceof Uint8Array)||!(t instanceof Uint8Array)||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}switch(i){case P.UINT64:case P.FIXED64:case P.INT64:case P.SFIXED64:case P.SINT64:return e==t}return!1}function Vn(i,e){switch(i){case P.BOOL:return!1;case P.UINT64:case P.FIXED64:case P.INT64:case P.SFIXED64:case P.SINT64:return e==0?_e.zero:"0";case P.DOUBLE:case P.FLOAT:return 0;case P.BYTES:return new Uint8Array(0);case P.STRING:return"";default:return 0}}function jo(i,e){switch(i){case P.BOOL:return e===!1;case P.STRING:return e==="";case P.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}var Ne;(function(i){i[i.Varint=0]="Varint",i[i.Bit64=1]="Bit64",i[i.LengthDelimited=2]="LengthDelimited",i[i.StartGroup=3]="StartGroup",i[i.EndGroup=4]="EndGroup",i[i.Bit32=5]="Bit32"})(Ne||(Ne={}));class Bh{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let r=0;r<this.chunks.length;r++)e+=this.chunks[r].length;let t=new Uint8Array(e),n=0;for(let r=0;r<this.chunks.length;r++)t.set(this.chunks[r],n),n+=this.chunks[r].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(Ss(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return hr(e),Uo(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){Ro(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){Ss(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){hr(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return hr(e),e=(e<<1^e>>31)>>>0,Uo(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=_e.enc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=_e.uEnc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=_e.enc(e);return Cs(t.lo,t.hi,this.buf),this}sint64(e){let t=_e.enc(e),n=t.hi>>31,r=t.lo<<1^n,s=(t.hi<<1|t.lo>>>31)^n;return Cs(r,s,this.buf),this}uint64(e){let t=_e.uEnc(e);return Cs(t.lo,t.hi,this.buf),this}}class Vh{constructor(e,t){this.varint64=Lh,this.uint32=Fh,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,n=e&7;if(t<=0||n<0||n>5)throw new Error("illegal tag: field no "+t+" wire type "+n);return[t,n]}skip(e,t){let n=this.pos;switch(e){case Ne.Varint:for(;this.buf[this.pos++]&128;);break;case Ne.Bit64:this.pos+=4;case Ne.Bit32:this.pos+=4;break;case Ne.LengthDelimited:let r=this.uint32();this.pos+=r;break;case Ne.StartGroup:for(;;){const[s,a]=this.tag();if(a===Ne.EndGroup){if(t!==void 0&&s!==t)throw new Error("invalid end group tag");break}this.skip(a,s)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return _e.dec(...this.varint64())}uint64(){return _e.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(e&1);return e=(e>>>1|(t&1)<<31)^n,t=t>>>1^n,_e.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return _e.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return _e.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}}function qh(i,e,t,n){let r;return{typeName:e,extendee:t,get field(){if(!r){const s=typeof n=="function"?n():n;s.name=e.split(".").pop(),s.jsonName="[".concat(e,"]"),r=i.util.newFieldList([s]).list()[0]}return r},runtime:i}}function Fo(i){const e=i.field.localName,t=Object.create(null);return t[e]=zh(i),[t,()=>t[e]]}function zh(i){const e=i.field;if(e.repeated)return[];if(e.default!==void 0)return e.default;switch(e.kind){case"enum":return e.T.values[0].no;case"scalar":return Vn(e.T,e.L);case"message":const t=e.T,n=new t;return t.fieldWrapper?t.fieldWrapper.unwrapField(n):n;case"map":throw"map fields are not allowed to be extensions"}}function Wh(i,e){if(!e.repeated&&(e.kind=="enum"||e.kind=="scalar")){for(let t=i.length-1;t>=0;--t)if(i[t].no==e.no)return[i[t]];return[]}return i.filter(t=>t.no===e.no)}let Ut="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),pr=[];for(let i=0;i<Ut.length;i++)pr[Ut[i].charCodeAt(0)]=i;pr["-".charCodeAt(0)]=Ut.indexOf("+"),pr["_".charCodeAt(0)]=Ut.indexOf("/");const $o={dec(i){let e=i.length*3/4;i[i.length-2]=="="?e-=2:i[i.length-1]=="="&&(e-=1);let t=new Uint8Array(e),n=0,r=0,s,a=0;for(let o=0;o<i.length;o++){if(s=pr[i.charCodeAt(o)],s===void 0)switch(i[o]){case"=":r=0;case`
2
+ `:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:a=s,r=1;break;case 1:t[n++]=a<<2|(s&48)>>4,a=s,r=2;break;case 2:t[n++]=(a&15)<<4|(s&60)>>2,a=s,r=3;break;case 3:t[n++]=(a&3)<<6|s,r=0;break}}if(r==1)throw Error("invalid base64 string.");return t.subarray(0,n)},enc(i){let e="",t=0,n,r=0;for(let s=0;s<i.length;s++)switch(n=i[s],t){case 0:e+=Ut[n>>2],r=(n&3)<<4,t=1;break;case 1:e+=Ut[r|n>>4],r=(n&15)<<2,t=2;break;case 2:e+=Ut[r|n>>6],e+=Ut[n&63],t=0;break}return t&&(e+=Ut[r],e+="=",t==1&&(e+="=")),e}};function Gh(i,e,t){Vo(e,i);const n=e.runtime.bin.makeReadOptions(t),r=Wh(i.getType().runtime.bin.listUnknownFields(i),e.field),[s,a]=Fo(e);for(const o of r)e.runtime.bin.readField(s,n.readerFactory(o.data),e.field,o.wireType,n);return a()}function Kh(i,e,t,n){Vo(e,i);const r=e.runtime.bin.makeReadOptions(n),s=e.runtime.bin.makeWriteOptions(n);if(Bo(i,e)){const d=i.getType().runtime.bin.listUnknownFields(i).filter(u=>u.no!=e.field.no);i.getType().runtime.bin.discardUnknownFields(i);for(const u of d)i.getType().runtime.bin.onUnknownField(i,u.no,u.wireType,u.data)}const a=s.writerFactory();let o=e.field;!o.opt&&!o.repeated&&(o.kind=="enum"||o.kind=="scalar")&&(o=Object.assign(Object.assign({},e.field),{opt:!0})),e.runtime.bin.writeField(o,t,a,s);const c=r.readerFactory(a.finish());for(;c.pos<c.len;){const[d,u]=c.tag(),h=c.skip(u,d);i.getType().runtime.bin.onUnknownField(i,d,u,h)}}function Bo(i,e){const t=i.getType();return e.extendee.typeName===t.typeName&&!!t.runtime.bin.listUnknownFields(i).find(n=>n.no==e.field.no)}function Vo(i,e){Oe(i.extendee.typeName==e.getType().typeName,"extension ".concat(i.typeName," can only be applied to message ").concat(i.extendee.typeName))}function qo(i,e){const t=i.localName;if(i.repeated)return e[t].length>0;if(i.oneof)return e[i.oneof.localName].case===t;switch(i.kind){case"enum":case"scalar":return i.opt||i.req?e[t]!==void 0:i.kind=="enum"?e[t]!==i.T.values[0].no:!jo(i.T,e[t]);case"message":return e[t]!==void 0;case"map":return Object.keys(e[t]).length>0}}function zo(i,e){const t=i.localName,n=!i.opt&&!i.req;if(i.repeated)e[t]=[];else if(i.oneof)e[i.oneof.localName]={case:void 0};else switch(i.kind){case"map":e[t]={};break;case"enum":e[t]=n?i.T.values[0].no:void 0;break;case"scalar":e[t]=n?Vn(i.T,i.L):void 0;break;case"message":e[t]=void 0;break}}function Tn(i,e){if(i===null||typeof i!="object"||!Object.getOwnPropertyNames(Ts.prototype).every(n=>n in i&&typeof i[n]=="function"))return!1;const t=i.getType();return t===null||typeof t!="function"||!("typeName"in t)||typeof t.typeName!="string"?!1:e===void 0?!0:t.typeName==e.typeName}function Wo(i,e){return Tn(e)||!i.fieldWrapper?e:i.fieldWrapper.wrapField(e)}P.DOUBLE,P.FLOAT,P.INT64,P.UINT64,P.INT32,P.UINT32,P.BOOL,P.STRING,P.BYTES;const Go={ignoreUnknownFields:!1},Ko={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function Hh(i){return i?Object.assign(Object.assign({},Go),i):Go}function Zh(i){return i?Object.assign(Object.assign({},Ko),i):Ko}const mr=Symbol(),gr=Symbol();function Jh(){return{makeReadOptions:Hh,makeWriteOptions:Zh,readMessage(i,e,t,n){if(e==null||Array.isArray(e)||typeof e!="object")throw new Error("cannot decode message ".concat(i.typeName," from JSON: ").concat(Et(e)));n=n??new i;const r=new Map,s=t.typeRegistry;for(const[a,o]of Object.entries(e)){const c=i.fields.findJsonName(a);if(c){if(c.oneof){if(o===null&&c.kind=="scalar")continue;const d=r.get(c.oneof);if(d!==void 0)throw new Error("cannot decode message ".concat(i.typeName,' from JSON: multiple keys for oneof "').concat(c.oneof.name,'" present: "').concat(d,'", "').concat(a,'"'));r.set(c.oneof,a)}Ho(n,o,c,t,i)}else{let d=!1;if(s!=null&&s.findExtension&&a.startsWith("[")&&a.endsWith("]")){const u=s.findExtension(a.substring(1,a.length-1));if(u&&u.extendee.typeName==i.typeName){d=!0;const[h,f]=Fo(u);Ho(h,o,u.field,t,u),Kh(n,u,f(),t)}}if(!d&&!t.ignoreUnknownFields)throw new Error("cannot decode message ".concat(i.typeName,' from JSON: key "').concat(a,'" is unknown'))}}return n},writeMessage(i,e){const t=i.getType(),n={};let r;try{for(r of t.fields.byNumber()){if(!qo(r,i)){if(r.req)throw"required field not set";if(!e.emitDefaultValues||!Qh(r))continue}const a=r.oneof?i[r.oneof.localName].value:i[r.localName],o=Zo(r,a,e);o!==void 0&&(n[e.useProtoFieldName?r.name:r.jsonName]=o)}const s=e.typeRegistry;if(s!=null&&s.findExtensionFor)for(const a of t.runtime.bin.listUnknownFields(i)){const o=s.findExtensionFor(t.typeName,a.no);if(o&&Bo(i,o)){const c=Gh(i,o,e),d=Zo(o.field,c,e);d!==void 0&&(n[o.field.jsonName]=d)}}}catch(s){const a=r?"cannot encode field ".concat(t.typeName,".").concat(r.name," to JSON"):"cannot encode message ".concat(t.typeName," to JSON"),o=s instanceof Error?s.message:String(s);throw new Error(a+(o.length>0?": ".concat(o):""))}return n},readScalar(i,e,t){return wi(i,e,t??Zt.BIGINT,!0)},writeScalar(i,e,t){if(e!==void 0&&(t||jo(i,e)))return vr(i,e)},debug:Et}}function Et(i){if(i===null)return"null";switch(typeof i){case"object":return Array.isArray(i)?"array":"object";case"string":return i.length>100?"string":'"'.concat(i.split('"').join('\\"'),'"');default:return String(i)}}function Ho(i,e,t,n,r){let s=t.localName;if(t.repeated){if(Oe(t.kind!="map"),e===null)return;if(!Array.isArray(e))throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Et(e)));const a=i[s];for(const o of e){if(o===null)throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Et(o)));switch(t.kind){case"message":a.push(t.T.fromJson(o,n));break;case"enum":const c=Es(t.T,o,n.ignoreUnknownFields,!0);c!==gr&&a.push(c);break;case"scalar":try{a.push(wi(t.T,o,t.L,!0))}catch(d){let u="cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Et(o));throw d instanceof Error&&d.message.length>0&&(u+=": ".concat(d.message)),new Error(u)}break}}}else if(t.kind=="map"){if(e===null)return;if(typeof e!="object"||Array.isArray(e))throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Et(e)));const a=i[s];for(const[o,c]of Object.entries(e)){if(c===null)throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: map value null"));let d;try{d=Yh(t.K,o)}catch(u){let h="cannot decode map key for field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Et(e));throw u instanceof Error&&u.message.length>0&&(h+=": ".concat(u.message)),new Error(h)}switch(t.V.kind){case"message":a[d]=t.V.T.fromJson(c,n);break;case"enum":const u=Es(t.V.T,c,n.ignoreUnknownFields,!0);u!==gr&&(a[d]=u);break;case"scalar":try{a[d]=wi(t.V.T,c,Zt.BIGINT,!0)}catch(h){let f="cannot decode map value for field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Et(e));throw h instanceof Error&&h.message.length>0&&(f+=": ".concat(h.message)),new Error(f)}break}}}else switch(t.oneof&&(i=i[t.oneof.localName]={case:s},s="value"),t.kind){case"message":const a=t.T;if(e===null&&a.typeName!="google.protobuf.Value")return;let o=i[s];Tn(o)?o.fromJson(e,n):(i[s]=o=a.fromJson(e,n),a.fieldWrapper&&!t.oneof&&(i[s]=a.fieldWrapper.unwrapField(o)));break;case"enum":const c=Es(t.T,e,n.ignoreUnknownFields,!1);switch(c){case mr:zo(t,i);break;case gr:break;default:i[s]=c;break}break;case"scalar":try{const d=wi(t.T,e,t.L,!1);switch(d){case mr:zo(t,i);break;default:i[s]=d;break}}catch(d){let u="cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Et(e));throw d instanceof Error&&d.message.length>0&&(u+=": ".concat(d.message)),new Error(u)}break}}function Yh(i,e){if(i===P.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return wi(i,e,Zt.BIGINT,!0).toString()}function wi(i,e,t,n){if(e===null)return n?Vn(i,t):mr;switch(i){case P.DOUBLE:case P.FLOAT:if(e==="NaN")return Number.NaN;if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e===""||typeof e=="string"&&e.trim().length!==e.length||typeof e!="string"&&typeof e!="number")break;const r=Number(e);if(Number.isNaN(r)||!Number.isFinite(r))break;return i==P.FLOAT&&Ro(r),r;case P.INT32:case P.FIXED32:case P.SFIXED32:case P.SINT32:case P.UINT32:let s;if(typeof e=="number"?s=e:typeof e=="string"&&e.length>0&&e.trim().length===e.length&&(s=Number(e)),s===void 0)break;return i==P.UINT32||i==P.FIXED32?Ss(s):hr(s),s;case P.INT64:case P.SFIXED64:case P.SINT64:if(typeof e!="number"&&typeof e!="string")break;const a=_e.parse(e);return t?a.toString():a;case P.FIXED64:case P.UINT64:if(typeof e!="number"&&typeof e!="string")break;const o=_e.uParse(e);return t?o.toString():o;case P.BOOL:if(typeof e!="boolean")break;return e;case P.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case P.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return $o.dec(e)}throw new Error}function Es(i,e,t,n){if(e===null)return i.typeName=="google.protobuf.NullValue"?0:n?i.values[0].no:mr;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":const r=i.findName(e);if(r!==void 0)return r.no;if(t)return gr;break}throw new Error("cannot decode enum ".concat(i.typeName," from JSON: ").concat(Et(e)))}function Qh(i){return i.repeated||i.kind=="map"?!0:!(i.oneof||i.kind=="message"||i.opt||i.req)}function Zo(i,e,t){if(i.kind=="map"){Oe(typeof e=="object"&&e!=null);const n={},r=Object.entries(e);switch(i.V.kind){case"scalar":for(const[a,o]of r)n[a.toString()]=vr(i.V.T,o);break;case"message":for(const[a,o]of r)n[a.toString()]=o.toJson(t);break;case"enum":const s=i.V.T;for(const[a,o]of r)n[a.toString()]=ws(s,o,t.enumAsInteger);break}return t.emitDefaultValues||r.length>0?n:void 0}if(i.repeated){Oe(Array.isArray(e));const n=[];switch(i.kind){case"scalar":for(let r=0;r<e.length;r++)n.push(vr(i.T,e[r]));break;case"enum":for(let r=0;r<e.length;r++)n.push(ws(i.T,e[r],t.enumAsInteger));break;case"message":for(let r=0;r<e.length;r++)n.push(e[r].toJson(t));break}return t.emitDefaultValues||n.length>0?n:void 0}switch(i.kind){case"scalar":return vr(i.T,e);case"enum":return ws(i.T,e,t.enumAsInteger);case"message":return Wo(i.T,e).toJson(t)}}function ws(i,e,t){var n;if(Oe(typeof e=="number"),i.typeName=="google.protobuf.NullValue")return null;if(t)return e;const r=i.findNumber(e);return(n=r==null?void 0:r.name)!==null&&n!==void 0?n:e}function vr(i,e){switch(i){case P.INT32:case P.SFIXED32:case P.SINT32:case P.FIXED32:case P.UINT32:return Oe(typeof e=="number"),e;case P.FLOAT:case P.DOUBLE:return Oe(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case P.STRING:return Oe(typeof e=="string"),e;case P.BOOL:return Oe(typeof e=="boolean"),e;case P.UINT64:case P.FIXED64:case P.INT64:case P.SFIXED64:case P.SINT64:return Oe(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case P.BYTES:return Oe(e instanceof Uint8Array),$o.enc(e)}}const qn=Symbol("@bufbuild/protobuf/unknown-fields"),Jo={readUnknownFields:!0,readerFactory:i=>new Vh(i)},Yo={writeUnknownFields:!0,writerFactory:()=>new Bh};function Xh(i){return i?Object.assign(Object.assign({},Jo),i):Jo}function ef(i){return i?Object.assign(Object.assign({},Yo),i):Yo}function tf(){return{makeReadOptions:Xh,makeWriteOptions:ef,listUnknownFields(i){var e;return(e=i[qn])!==null&&e!==void 0?e:[]},discardUnknownFields(i){delete i[qn]},writeUnknownFields(i,e){const n=i[qn];if(n)for(const r of n)e.tag(r.no,r.wireType).raw(r.data)},onUnknownField(i,e,t,n){const r=i;Array.isArray(r[qn])||(r[qn]=[]),r[qn].push({no:e,wireType:t,data:n})},readMessage(i,e,t,n,r){const s=i.getType(),a=r?e.len:e.pos+t;let o,c;for(;e.pos<a&&([o,c]=e.tag(),!(r===!0&&c==Ne.EndGroup));){const d=s.fields.find(o);if(!d){const u=e.skip(c,o);n.readUnknownFields&&this.onUnknownField(i,o,c,u);continue}Qo(i,e,d,c,n)}if(r&&(c!=Ne.EndGroup||o!==t))throw new Error("invalid end group tag")},readField:Qo,writeMessage(i,e,t){const n=i.getType();for(const r of n.fields.byNumber()){if(!qo(r,i)){if(r.req)throw new Error("cannot encode field ".concat(n.typeName,".").concat(r.name," to binary: required field not set"));continue}const s=r.oneof?i[r.oneof.localName].value:i[r.localName];Xo(r,s,e,t)}return t.writeUnknownFields&&this.writeUnknownFields(i,e),e},writeField(i,e,t,n){e!==void 0&&Xo(i,e,t,n)}}}function Qo(i,e,t,n,r){let{repeated:s,localName:a}=t;switch(t.oneof&&(i=i[t.oneof.localName],i.case!=a&&delete i.value,i.case=a,a="value"),t.kind){case"scalar":case"enum":const o=t.kind=="enum"?P.INT32:t.T;let c=br;if(t.kind=="scalar"&&t.L>0&&(c=rf),s){let f=i[a];if(n==Ne.LengthDelimited&&o!=P.STRING&&o!=P.BYTES){let y=e.uint32()+e.pos;for(;e.pos<y;)f.push(c(e,o))}else f.push(c(e,o))}else i[a]=c(e,o);break;case"message":const d=t.T;s?i[a].push(yr(e,new d,r,t)):Tn(i[a])?yr(e,i[a],r,t):(i[a]=yr(e,new d,r,t),d.fieldWrapper&&!t.oneof&&!t.repeated&&(i[a]=d.fieldWrapper.unwrapField(i[a])));break;case"map":let[u,h]=nf(t,e,r);i[a][u]=h;break}}function yr(i,e,t,n){const r=e.getType().runtime.bin,s=n==null?void 0:n.delimited;return r.readMessage(e,i,s?n.no:i.uint32(),t,s),e}function nf(i,e,t){const n=e.uint32(),r=e.pos+n;let s,a;for(;e.pos<r;){const[o]=e.tag();switch(o){case 1:s=br(e,i.K);break;case 2:switch(i.V.kind){case"scalar":a=br(e,i.V.T);break;case"enum":a=e.int32();break;case"message":a=yr(e,new i.V.T,t,void 0);break}break}}if(s===void 0&&(s=Vn(i.K,Zt.BIGINT)),typeof s!="string"&&typeof s!="number"&&(s=s.toString()),a===void 0)switch(i.V.kind){case"scalar":a=Vn(i.V.T,Zt.BIGINT);break;case"enum":a=i.V.T.values[0].no;break;case"message":a=new i.V.T;break}return[s,a]}function rf(i,e){const t=br(i,e);return typeof t=="bigint"?t.toString():t}function br(i,e){switch(e){case P.STRING:return i.string();case P.BOOL:return i.bool();case P.DOUBLE:return i.double();case P.FLOAT:return i.float();case P.INT32:return i.int32();case P.INT64:return i.int64();case P.UINT64:return i.uint64();case P.FIXED64:return i.fixed64();case P.BYTES:return i.bytes();case P.FIXED32:return i.fixed32();case P.SFIXED32:return i.sfixed32();case P.SFIXED64:return i.sfixed64();case P.SINT64:return i.sint64();case P.UINT32:return i.uint32();case P.SINT32:return i.sint32()}}function Xo(i,e,t,n){Oe(e!==void 0);const r=i.repeated;switch(i.kind){case"scalar":case"enum":let s=i.kind=="enum"?P.INT32:i.T;if(r)if(Oe(Array.isArray(e)),i.packed)af(t,s,i.no,e);else for(const a of e)Pi(t,s,i.no,a);else Pi(t,s,i.no,e);break;case"message":if(r){Oe(Array.isArray(e));for(const a of e)ec(t,n,i,a)}else ec(t,n,i,e);break;case"map":Oe(typeof e=="object"&&e!=null);for(const[a,o]of Object.entries(e))sf(t,n,i,a,o);break}}function sf(i,e,t,n,r){i.tag(t.no,Ne.LengthDelimited),i.fork();let s=n;switch(t.K){case P.INT32:case P.FIXED32:case P.UINT32:case P.SFIXED32:case P.SINT32:s=Number.parseInt(n);break;case P.BOOL:Oe(n=="true"||n=="false"),s=n=="true";break}switch(Pi(i,t.K,1,s),t.V.kind){case"scalar":Pi(i,t.V.T,2,r);break;case"enum":Pi(i,P.INT32,2,r);break;case"message":Oe(r!==void 0),i.tag(2,Ne.LengthDelimited).bytes(r.toBinary(e));break}i.join()}function ec(i,e,t,n){const r=Wo(t.T,n);t.delimited?i.tag(t.no,Ne.StartGroup).raw(r.toBinary(e)).tag(t.no,Ne.EndGroup):i.tag(t.no,Ne.LengthDelimited).bytes(r.toBinary(e))}function Pi(i,e,t,n){Oe(n!==void 0);let[r,s]=tc(e);i.tag(t,r)[s](n)}function af(i,e,t,n){if(!n.length)return;i.tag(t,Ne.LengthDelimited).fork();let[,r]=tc(e);for(let s=0;s<n.length;s++)i[r](n[s]);i.join()}function tc(i){let e=Ne.Varint;switch(i){case P.BYTES:case P.STRING:e=Ne.LengthDelimited;break;case P.DOUBLE:case P.FIXED64:case P.SFIXED64:e=Ne.Bit64;break;case P.FIXED32:case P.SFIXED32:case P.FLOAT:e=Ne.Bit32;break}const t=P[i].toLowerCase();return[e,t]}function of(){return{setEnumType:Io,initPartial(i,e){if(i===void 0)return;const t=e.getType();for(const n of t.fields.byMember()){const r=n.localName,s=e,a=i;if(a[r]!=null)switch(n.kind){case"oneof":const o=a[r].case;if(o===void 0)continue;const c=n.findField(o);let d=a[r].value;c&&c.kind=="message"&&!Tn(d,c.T)?d=new c.T(d):c&&c.kind==="scalar"&&c.T===P.BYTES&&(d=Ri(d)),s[r]={case:o,value:d};break;case"scalar":case"enum":let u=a[r];n.T===P.BYTES&&(u=n.repeated?u.map(Ri):Ri(u)),s[r]=u;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===P.BYTES)for(const[g,y]of Object.entries(a[r]))s[r][g]=Ri(y);else Object.assign(s[r],a[r]);break;case"message":const f=n.V.T;for(const g of Object.keys(a[r])){let y=a[r][g];f.fieldWrapper||(y=new f(y)),s[r][g]=y}break}break;case"message":const h=n.T;if(n.repeated)s[r]=a[r].map(f=>Tn(f,h)?f:new h(f));else{const f=a[r];h.fieldWrapper?h.typeName==="google.protobuf.BytesValue"?s[r]=Ri(f):s[r]=f:s[r]=Tn(f,h)?f:new h(f)}break}}},equals(i,e,t){return e===t?!0:!e||!t?!1:i.fields.byMember().every(n=>{const r=e[n.localName],s=t[n.localName];if(n.repeated){if(r.length!==s.length)return!1;switch(n.kind){case"message":return r.every((a,o)=>n.T.equals(a,s[o]));case"scalar":return r.every((a,o)=>Jt(n.T,a,s[o]));case"enum":return r.every((a,o)=>Jt(P.INT32,a,s[o]))}throw new Error("repeated cannot contain ".concat(n.kind))}switch(n.kind){case"message":return n.T.equals(r,s);case"enum":return Jt(P.INT32,r,s);case"scalar":return Jt(n.T,r,s);case"oneof":if(r.case!==s.case)return!1;const a=n.findField(r.case);if(a===void 0)return!0;switch(a.kind){case"message":return a.T.equals(r.value,s.value);case"enum":return Jt(P.INT32,r.value,s.value);case"scalar":return Jt(a.T,r.value,s.value)}throw new Error("oneof cannot contain ".concat(a.kind));case"map":const o=Object.keys(r).concat(Object.keys(s));switch(n.V.kind){case"message":const c=n.V.T;return o.every(u=>c.equals(r[u],s[u]));case"enum":return o.every(u=>Jt(P.INT32,r[u],s[u]));case"scalar":const d=n.V.T;return o.every(u=>Jt(d,r[u],s[u]))}break}})},clone(i){const e=i.getType(),t=new e,n=t;for(const r of e.fields.byMember()){const s=i[r.localName];let a;if(r.repeated)a=s.map(kr);else if(r.kind=="map"){a=n[r.localName];for(const[o,c]of Object.entries(s))a[o]=kr(c)}else r.kind=="oneof"?a=r.findField(s.case)?{case:s.case,value:kr(s.value)}:{case:void 0}:a=kr(s);n[r.localName]=a}for(const r of e.runtime.bin.listUnknownFields(i))e.runtime.bin.onUnknownField(n,r.no,r.wireType,r.data);return t}}}function kr(i){if(i===void 0)return i;if(Tn(i))return i.clone();if(i instanceof Uint8Array){const e=new Uint8Array(i.byteLength);return e.set(i),e}return i}function Ri(i){return i instanceof Uint8Array?i:new Uint8Array(i)}function cf(i,e,t){return{syntax:i,json:Jh(),bin:tf(),util:Object.assign(Object.assign({},of()),{newFieldList:e,initFields:t}),makeMessageType(n,r,s){return Nh(this,n,r,s)},makeEnum:Mh,makeEnumType:Oo,getEnumType:Dh,makeExtension(n,r,s){return qh(this,n,r,s)}}}class df{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const t={};for(const n of this.list())t[n.jsonName]=t[n.name]=n;this.jsonNames=t}return this.jsonNames[e]}find(e){if(!this.numbers){const t={};for(const n of this.list())t[n.no]=n;this.numbers=t}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((e,t)=>e.no-t.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const n of this.list())n.oneof?n.oneof!==t&&(t=n.oneof,e.push(t)):e.push(n)}return this.members}}function nc(i,e){const t=ic(i);return e?t:mf(pf(t))}function uf(i){return nc(i,!1)}const lf=ic;function ic(i){let e=!1;const t=[];for(let n=0;n<i.length;n++){let r=i.charAt(n);switch(r){case"_":e=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":t.push(r),e=!1;break;default:e&&(e=!1,r=r.toUpperCase()),t.push(r);break}}return t.join("")}const hf=new Set(["constructor","toString","toJSON","valueOf"]),ff=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),rc=i=>"".concat(i,"$"),pf=i=>ff.has(i)?rc(i):i,mf=i=>hf.has(i)?rc(i):i;class gf{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=uf(e)}addField(e){Oe(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let t=0;t<this.fields.length;t++)this._lookup[this.fields[t].localName]=this.fields[t]}return this._lookup[e]}}function vf(i,e){var t,n,r,s,a,o;const c=[];let d;for(const u of typeof i=="function"?i():i){const h=u;if(h.localName=nc(u.name,u.oneof!==void 0),h.jsonName=(t=u.jsonName)!==null&&t!==void 0?t:lf(u.name),h.repeated=(n=u.repeated)!==null&&n!==void 0?n:!1,u.kind=="scalar"&&(h.L=(r=u.L)!==null&&r!==void 0?r:Zt.BIGINT),h.delimited=(s=u.delimited)!==null&&s!==void 0?s:!1,h.req=(a=u.req)!==null&&a!==void 0?a:!1,h.opt=(o=u.opt)!==null&&o!==void 0?o:!1,u.packed===void 0&&(h.packed=u.kind=="enum"||u.kind=="scalar"&&u.T!=P.BYTES&&u.T!=P.STRING),u.oneof!==void 0){const f=typeof u.oneof=="string"?u.oneof:u.oneof.name;(!d||d.name!=f)&&(d=new gf(f)),h.oneof=d,d.addField(h)}c.push(h)}return c}const C=cf("proto3",i=>new df(i,e=>vf(e)),i=>{for(const e of i.getType().fields.byMember()){if(e.opt)continue;const t=e.localName,n=i;if(e.repeated){n[t]=[];continue}switch(e.kind){case"oneof":n[t]={case:void 0};break;case"enum":n[t]=0;break;case"map":n[t]={};break;case"scalar":n[t]=Vn(e.T,e.L);break}}});class Je extends Ts{constructor(e){super(),this.seconds=_e.zero,this.nanos=0,C.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(C.json.debug(e)));const n=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const r=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[8]:"Z"));if(Number.isNaN(r))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(r<Date.parse("0001-01-01T00:00:00Z")||r>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=_e.parse(r/1e3),this.nanos=0,n[7]&&(this.nanos=parseInt("1"+n[7]+"0".repeat(9-n[7].length))-1e9),this}toJson(e){const t=Number(this.seconds)*1e3;if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let n="Z";if(this.nanos>0){const r=(this.nanos+1e9).toString().substring(1);r.substring(3)==="000000"?n="."+r.substring(0,3)+"Z":r.substring(6)==="000"?n="."+r.substring(0,6)+"Z":n="."+r+"Z"}return new Date(t).toISOString().replace(".000Z",n)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return Je.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new Je({seconds:_e.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new Je().fromBinary(e,t)}static fromJson(e,t){return new Je().fromJson(e,t)}static fromJsonString(e,t){return new Je().fromJsonString(e,t)}static equals(e,t){return C.util.equals(Je,e,t)}}Je.runtime=C,Je.typeName="google.protobuf.Timestamp",Je.fields=C.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const yf=C.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Je},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:bf,repeated:!0},{no:5,name:"events",kind:"message",T:Sf,repeated:!0}]),bf=C.makeMessageType("livekit.TimeSeriesMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"samples",kind:"message",T:kf,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),kf=C.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Je},{no:3,name:"value",kind:"scalar",T:2}]),Sf=C.makeMessageType("livekit.EventMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"start_timestamp_ms",kind:"scalar",T:3},{no:5,name:"end_timestamp_ms",kind:"scalar",T:3,opt:!0},{no:6,name:"normalized_start_timestamp",kind:"message",T:Je},{no:7,name:"normalized_end_timestamp",kind:"message",T:Je,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),sc=C.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),ht=C.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),Le=C.makeEnum("livekit.TrackSource",[{no:0,name:"UNKNOWN"},{no:1,name:"CAMERA"},{no:2,name:"MICROPHONE"},{no:3,name:"SCREEN_SHARE"},{no:4,name:"SCREEN_SHARE_AUDIO"}]),zn=C.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),xi=C.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Ii=C.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),ft=C.makeEnum("livekit.DisconnectReason",[{no:0,name:"UNKNOWN_REASON"},{no:1,name:"CLIENT_INITIATED"},{no:2,name:"DUPLICATE_IDENTITY"},{no:3,name:"SERVER_SHUTDOWN"},{no:4,name:"PARTICIPANT_REMOVED"},{no:5,name:"ROOM_DELETED"},{no:6,name:"STATE_MISMATCH"},{no:7,name:"JOIN_FAILURE"},{no:8,name:"MIGRATION"},{no:9,name:"SIGNAL_CLOSE"},{no:10,name:"ROOM_CLOSED"},{no:11,name:"USER_UNAVAILABLE"},{no:12,name:"USER_REJECTED"},{no:13,name:"SIP_TRUNK_FAILURE"}]),Wn=C.makeEnum("livekit.ReconnectReason",[{no:0,name:"RR_UNKNOWN"},{no:1,name:"RR_SIGNAL_DISCONNECTED"},{no:2,name:"RR_PUBLISHER_FAILED"},{no:3,name:"RR_SUBSCRIBER_FAILED"},{no:4,name:"RR_SWITCH_CANDIDATE"}]),Tf=C.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),wt=C.makeEnum("livekit.AudioTrackFeature",[{no:0,name:"TF_STEREO"},{no:1,name:"TF_NO_DTX"},{no:2,name:"TF_AUTO_GAIN_CONTROL"},{no:3,name:"TF_ECHO_CANCELLATION"},{no:4,name:"TF_NOISE_SUPPRESSION"},{no:5,name:"TF_ENHANCED_NOISE_CANCELLATION"}]),Ps=C.makeMessageType("livekit.Room",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"empty_timeout",kind:"scalar",T:13},{no:14,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:5,name:"creation_time",kind:"scalar",T:3},{no:15,name:"creation_time_ms",kind:"scalar",T:3},{no:6,name:"turn_password",kind:"scalar",T:9},{no:7,name:"enabled_codecs",kind:"message",T:Sr,repeated:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"num_participants",kind:"scalar",T:13},{no:11,name:"num_publishers",kind:"scalar",T:13},{no:10,name:"active_recording",kind:"scalar",T:8},{no:13,name:"version",kind:"message",T:yc}]),Sr=C.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),Cf=C.makeMessageType("livekit.ParticipantPermission",()=>[{no:1,name:"can_subscribe",kind:"scalar",T:8},{no:2,name:"can_publish",kind:"scalar",T:8},{no:3,name:"can_publish_data",kind:"scalar",T:8},{no:9,name:"can_publish_sources",kind:"enum",T:C.getEnumType(Le),repeated:!0},{no:7,name:"hidden",kind:"scalar",T:8},{no:8,name:"recorder",kind:"scalar",T:8},{no:10,name:"can_update_metadata",kind:"scalar",T:8},{no:11,name:"agent",kind:"scalar",T:8},{no:12,name:"can_subscribe_metrics",kind:"scalar",T:8}]),Oi=C.makeMessageType("livekit.ParticipantInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:C.getEnumType(Rs)},{no:4,name:"tracks",kind:"message",T:Gn,repeated:!0},{no:5,name:"metadata",kind:"scalar",T:9},{no:6,name:"joined_at",kind:"scalar",T:3},{no:17,name:"joined_at_ms",kind:"scalar",T:3},{no:9,name:"name",kind:"scalar",T:9},{no:10,name:"version",kind:"scalar",T:13},{no:11,name:"permission",kind:"message",T:Cf},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:C.getEnumType(Tr)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:C.getEnumType(ft)},{no:18,name:"kind_details",kind:"enum",T:C.getEnumType(_f),repeated:!0}]),Rs=C.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),Tr=C.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]),_f=C.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),it=C.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),Ef=C.makeMessageType("livekit.SimulcastCodecInfo",()=>[{no:1,name:"mime_type",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:Cn,repeated:!0}]),Gn=C.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:C.getEnumType(ht)},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"muted",kind:"scalar",T:8},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"simulcast",kind:"scalar",T:8},{no:8,name:"disable_dtx",kind:"scalar",T:8},{no:9,name:"source",kind:"enum",T:C.getEnumType(Le)},{no:10,name:"layers",kind:"message",T:Cn,repeated:!0},{no:11,name:"mime_type",kind:"scalar",T:9},{no:12,name:"mid",kind:"scalar",T:9},{no:13,name:"codecs",kind:"message",T:Ef,repeated:!0},{no:14,name:"stereo",kind:"scalar",T:8},{no:15,name:"disable_red",kind:"scalar",T:8},{no:16,name:"encryption",kind:"enum",T:C.getEnumType(it)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:yc},{no:19,name:"audio_features",kind:"enum",T:C.getEnumType(wt),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:C.getEnumType(sc)}]),Cn=C.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:C.getEnumType(zn)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13}]),Ye=C.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:C.getEnumType(le)},{no:4,name:"participant_identity",kind:"scalar",T:9},{no:5,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:2,name:"user",kind:"message",T:oc,oneof:"value"},{no:3,name:"speaker",kind:"message",T:wf,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:cc,oneof:"value"},{no:7,name:"transcription",kind:"message",T:Pf,oneof:"value"},{no:8,name:"metrics",kind:"message",T:yf,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:xs,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:dc,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:uc,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:lc,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:Os,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:As,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:Ds,oneof:"value"}]),le=C.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),wf=C.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:ac,repeated:!0}]),ac=C.makeMessageType("livekit.SpeakerInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"level",kind:"scalar",T:2},{no:3,name:"active",kind:"scalar",T:8}]),oc=C.makeMessageType("livekit.UserPacket",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:5,name:"participant_identity",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"destination_sids",kind:"scalar",T:9,repeated:!0},{no:6,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:4,name:"topic",kind:"scalar",T:9,opt:!0},{no:8,name:"id",kind:"scalar",T:9,opt:!0},{no:9,name:"start_time",kind:"scalar",T:4,opt:!0},{no:10,name:"end_time",kind:"scalar",T:4,opt:!0},{no:11,name:"nonce",kind:"scalar",T:12}]),cc=C.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),Pf=C.makeMessageType("livekit.Transcription",()=>[{no:2,name:"transcribed_participant_identity",kind:"scalar",T:9},{no:3,name:"track_id",kind:"scalar",T:9},{no:4,name:"segments",kind:"message",T:Rf,repeated:!0}]),Rf=C.makeMessageType("livekit.TranscriptionSegment",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}]),xs=C.makeMessageType("livekit.ChatMessage",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"edit_timestamp",kind:"scalar",T:3,opt:!0},{no:4,name:"message",kind:"scalar",T:9},{no:5,name:"deleted",kind:"scalar",T:8},{no:6,name:"generated",kind:"scalar",T:8}]),dc=C.makeMessageType("livekit.RpcRequest",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"method",kind:"scalar",T:9},{no:3,name:"payload",kind:"scalar",T:9},{no:4,name:"response_timeout_ms",kind:"scalar",T:13},{no:5,name:"version",kind:"scalar",T:13}]),uc=C.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),lc=C.makeMessageType("livekit.RpcResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:9,oneof:"value"},{no:3,name:"error",kind:"message",T:hc,oneof:"value"}]),hc=C.makeMessageType("livekit.RpcError",()=>[{no:1,name:"code",kind:"scalar",T:13},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"data",kind:"scalar",T:9}]),fc=C.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),xf=C.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:C.getEnumType(pc)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"region",kind:"scalar",T:9},{no:5,name:"node_id",kind:"scalar",T:9},{no:6,name:"debug_info",kind:"scalar",T:9},{no:7,name:"agent_protocol",kind:"scalar",T:5}]),pc=C.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),If=C.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:C.getEnumType(mc)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"os",kind:"scalar",T:9},{no:5,name:"os_version",kind:"scalar",T:9},{no:6,name:"device_model",kind:"scalar",T:9},{no:7,name:"browser",kind:"scalar",T:9},{no:8,name:"browser_version",kind:"scalar",T:9},{no:9,name:"address",kind:"scalar",T:9},{no:10,name:"network",kind:"scalar",T:9},{no:11,name:"other_sdks",kind:"scalar",T:9}]),mc=C.makeEnum("livekit.ClientInfo.SDK",[{no:0,name:"UNKNOWN"},{no:1,name:"JS"},{no:2,name:"SWIFT"},{no:3,name:"ANDROID"},{no:4,name:"FLUTTER"},{no:5,name:"GO"},{no:6,name:"UNITY"},{no:7,name:"REACT_NATIVE"},{no:8,name:"RUST"},{no:9,name:"PYTHON"},{no:10,name:"CPP"},{no:11,name:"UNITY_WEB"},{no:12,name:"NODE"}]),gc=C.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:vc},{no:2,name:"screen",kind:"message",T:vc},{no:3,name:"resume_connection",kind:"enum",T:C.getEnumType(Ii)},{no:4,name:"disabled_codecs",kind:"message",T:Of},{no:5,name:"force_relay",kind:"enum",T:C.getEnumType(Ii)}]),vc=C.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:C.getEnumType(Ii)}]),Of=C.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:Sr,repeated:!0},{no:2,name:"publish",kind:"message",T:Sr,repeated:!0}]),yc=C.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),Is=C.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),bc=C.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:C.getEnumType(Is)},{no:2,name:"version",kind:"scalar",T:5},{no:3,name:"reply_to_stream_id",kind:"scalar",T:9},{no:4,name:"attached_stream_ids",kind:"scalar",T:9,repeated:!0},{no:5,name:"generated",kind:"scalar",T:8}],{localName:"DataStream_TextHeader"}),kc=C.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),Os=C.makeMessageType("livekit.DataStream.Header",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"topic",kind:"scalar",T:9},{no:4,name:"mime_type",kind:"scalar",T:9},{no:5,name:"total_length",kind:"scalar",T:4,opt:!0},{no:7,name:"encryption_type",kind:"enum",T:C.getEnumType(it)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:bc,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:kc,oneof:"content_header"}],{localName:"DataStream_Header"}),As=C.makeMessageType("livekit.DataStream.Chunk",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"chunk_index",kind:"scalar",T:4},{no:3,name:"content",kind:"scalar",T:12},{no:4,name:"version",kind:"scalar",T:5},{no:5,name:"iv",kind:"scalar",T:12,opt:!0}],{localName:"DataStream_Chunk"}),Ds=C.makeMessageType("livekit.DataStream.Trailer",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"reason",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}],{localName:"DataStream_Trailer"}),pt=C.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),Ms=C.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),Af=C.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),Df=C.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:_n,oneof:"message"},{no:2,name:"answer",kind:"message",T:_n,oneof:"message"},{no:3,name:"trickle",kind:"message",T:Us,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Ls,oneof:"message"},{no:5,name:"mute",kind:"message",T:js,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Cr,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Tc,oneof:"message"},{no:8,name:"leave",kind:"message",T:_r,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:_c,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Rc,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:xc,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Pt,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:Ec,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Oc,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:Cc,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:jf,oneof:"message"}]),Sc=C.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:Mf,oneof:"message"},{no:2,name:"answer",kind:"message",T:_n,oneof:"message"},{no:3,name:"offer",kind:"message",T:_n,oneof:"message"},{no:4,name:"trickle",kind:"message",T:Us,oneof:"message"},{no:5,name:"update",kind:"message",T:Uf,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Fs,oneof:"message"},{no:8,name:"leave",kind:"message",T:_r,oneof:"message"},{no:9,name:"mute",kind:"message",T:js,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Ff,oneof:"message"},{no:11,name:"room_update",kind:"message",T:$f,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:Vf,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:zf,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:Gf,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Kf,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Lf,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:Nf,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Hf,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:Yf,oneof:"message"},{no:22,name:"request_response",kind:"message",T:Qf,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Xf,oneof:"message"}]),Ns=C.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}]),Ls=C.makeMessageType("livekit.AddTrackRequest",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"type",kind:"enum",T:C.getEnumType(ht)},{no:4,name:"width",kind:"scalar",T:13},{no:5,name:"height",kind:"scalar",T:13},{no:6,name:"muted",kind:"scalar",T:8},{no:7,name:"disable_dtx",kind:"scalar",T:8},{no:8,name:"source",kind:"enum",T:C.getEnumType(Le)},{no:9,name:"layers",kind:"message",T:Cn,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:Ns,repeated:!0},{no:11,name:"sid",kind:"scalar",T:9},{no:12,name:"stereo",kind:"scalar",T:8},{no:13,name:"disable_red",kind:"scalar",T:8},{no:14,name:"encryption",kind:"enum",T:C.getEnumType(it)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:C.getEnumType(sc)}]),Us=C.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:C.getEnumType(pt)},{no:3,name:"final",kind:"scalar",T:8}]),js=C.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),Mf=C.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:Ps},{no:2,name:"participant",kind:"message",T:Oi},{no:3,name:"other_participants",kind:"message",T:Oi,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:wc,repeated:!0},{no:6,name:"subscriber_primary",kind:"scalar",T:8},{no:7,name:"alternative_url",kind:"scalar",T:9},{no:8,name:"client_configuration",kind:"message",T:gc},{no:9,name:"server_region",kind:"scalar",T:9},{no:10,name:"ping_timeout",kind:"scalar",T:5},{no:11,name:"ping_interval",kind:"scalar",T:5},{no:12,name:"server_info",kind:"message",T:xf},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:Sr,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),Nf=C.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:wc,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:gc}]),Fs=C.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Gn}]),Lf=C.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),_n=C.makeMessageType("livekit.SessionDescription",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9}]),Uf=C.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:Oi,repeated:!0}]),Cr=C.makeMessageType("livekit.UpdateSubscription",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"participant_tracks",kind:"message",T:fc,repeated:!0}]),Tc=C.makeMessageType("livekit.UpdateTrackSettings",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:3,name:"disabled",kind:"scalar",T:8},{no:4,name:"quality",kind:"enum",T:C.getEnumType(zn)},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"fps",kind:"scalar",T:13},{no:8,name:"priority",kind:"scalar",T:13}]),Cc=C.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:C.getEnumType(wt),repeated:!0}]),jf=C.makeMessageType("livekit.UpdateLocalVideoTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13}]),_r=C.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:C.getEnumType(ft)},{no:3,name:"action",kind:"enum",T:C.getEnumType(Kn)},{no:4,name:"regions",kind:"message",T:Zf}]),Kn=C.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),_c=C.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:Cn,repeated:!0}]),Ec=C.makeMessageType("livekit.UpdateParticipantMetadata",()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:4,name:"request_id",kind:"scalar",T:13}]),wc=C.makeMessageType("livekit.ICEServer",()=>[{no:1,name:"urls",kind:"scalar",T:9,repeated:!0},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"credential",kind:"scalar",T:9}]),Ff=C.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:ac,repeated:!0}]),$f=C.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:Ps}]),Bf=C.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:C.getEnumType(xi)},{no:3,name:"score",kind:"scalar",T:2}]),Vf=C.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:Bf,repeated:!0}]),qf=C.makeMessageType("livekit.StreamStateInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:C.getEnumType(Ms)}]),zf=C.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:qf,repeated:!0}]),$s=C.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:C.getEnumType(zn)},{no:2,name:"enabled",kind:"scalar",T:8}]),Wf=C.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:$s,repeated:!0}]),Gf=C.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:$s,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:Wf,repeated:!0}]),Pc=C.makeMessageType("livekit.TrackPermission",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"all_tracks",kind:"scalar",T:8},{no:3,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:4,name:"participant_identity",kind:"scalar",T:9}]),Rc=C.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Pc,repeated:!0}]),Kf=C.makeMessageType("livekit.SubscriptionPermissionUpdate",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"allowed",kind:"scalar",T:8}]),xc=C.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:_n},{no:2,name:"subscription",kind:"message",T:Cr},{no:3,name:"publish_tracks",kind:"message",T:Fs,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Ic,repeated:!0},{no:5,name:"offer",kind:"message",T:_n},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0}]),Ic=C.makeMessageType("livekit.DataChannelInfo",()=>[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:13},{no:3,name:"target",kind:"enum",T:C.getEnumType(pt)}]),Pt=C.makeMessageType("livekit.SimulateScenario",()=>[{no:1,name:"speaker_update",kind:"scalar",T:5,oneof:"scenario"},{no:2,name:"node_failure",kind:"scalar",T:8,oneof:"scenario"},{no:3,name:"migration",kind:"scalar",T:8,oneof:"scenario"},{no:4,name:"server_leave",kind:"scalar",T:8,oneof:"scenario"},{no:5,name:"switch_candidate_protocol",kind:"enum",T:C.getEnumType(Af),oneof:"scenario"},{no:6,name:"subscriber_bandwidth",kind:"scalar",T:3,oneof:"scenario"},{no:7,name:"disconnect_signal_on_resume",kind:"scalar",T:8,oneof:"scenario"},{no:8,name:"disconnect_signal_on_resume_no_messages",kind:"scalar",T:8,oneof:"scenario"},{no:9,name:"leave_request_full_reconnect",kind:"scalar",T:8,oneof:"scenario"}]),Oc=C.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),Hf=C.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),Zf=C.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:Jf,repeated:!0}]),Jf=C.makeMessageType("livekit.RegionInfo",()=>[{no:1,name:"region",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9},{no:3,name:"distance",kind:"scalar",T:3}]),Yf=C.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:C.getEnumType(Tf)}]),Qf=C.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:C.getEnumType(Bs)},{no:3,name:"message",kind:"scalar",T:9}]),Bs=C.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"}]),Xf=C.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]);function ep(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Er={exports:{}},tp=Er.exports,Ac;function np(){return Ac||(Ac=1,function(i){(function(e,t){i.exports?i.exports=t():e.log=t()})(tp,function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"],s={},a=null;function o(v,_){var w=v[_];if(typeof w.bind=="function")return w.bind(v);try{return Function.prototype.bind.call(w,v)}catch{return function(){return Function.prototype.apply.apply(w,[v,arguments])}}}function c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function d(v){return v==="debug"&&(v="log"),typeof console===t?!1:v==="trace"&&n?c:console[v]!==void 0?o(console,v):console.log!==void 0?o(console,"log"):e}function u(){for(var v=this.getLevel(),_=0;_<r.length;_++){var w=r[_];this[w]=_<v?e:this.methodFactory(w,v,this.name)}if(this.log=this.debug,typeof console===t&&v<this.levels.SILENT)return"No console available for logging"}function h(v){return function(){typeof console!==t&&(u.call(this),this[v].apply(this,arguments))}}function f(v,_,w){return d(v)||h.apply(this,arguments)}function g(v,_){var w=this,N,U,b,k="loglevel";typeof v=="string"?k+=":"+v:typeof v=="symbol"&&(k=void 0);function x(ne){var be=(r[ne]||"silent").toUpperCase();if(!(typeof window===t||!k)){try{window.localStorage[k]=be;return}catch{}try{window.document.cookie=encodeURIComponent(k)+"="+be+";"}catch{}}}function F(){var ne;if(!(typeof window===t||!k)){try{ne=window.localStorage[k]}catch{}if(typeof ne===t)try{var be=window.document.cookie,st=encodeURIComponent(k),St=be.indexOf(st+"=");St!==-1&&(ne=/^([^;]+)/.exec(be.slice(St+st.length+1))[1])}catch{}return w.levels[ne]===void 0&&(ne=void 0),ne}}function q(){if(!(typeof window===t||!k)){try{window.localStorage.removeItem(k)}catch{}try{window.document.cookie=encodeURIComponent(k)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function te(ne){var be=ne;if(typeof be=="string"&&w.levels[be.toUpperCase()]!==void 0&&(be=w.levels[be.toUpperCase()]),typeof be=="number"&&be>=0&&be<=w.levels.SILENT)return be;throw new TypeError("log.setLevel() called with invalid level: "+ne)}w.name=v,w.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},w.methodFactory=_||f,w.getLevel=function(){return b??U??N},w.setLevel=function(ne,be){return b=te(ne),be!==!1&&x(b),u.call(w)},w.setDefaultLevel=function(ne){U=te(ne),F()||w.setLevel(ne,!1)},w.resetLevel=function(){b=null,q(),u.call(w)},w.enableAll=function(ne){w.setLevel(w.levels.TRACE,ne)},w.disableAll=function(ne){w.setLevel(w.levels.SILENT,ne)},w.rebuild=function(){if(a!==w&&(N=te(a.getLevel())),u.call(w),a===w)for(var ne in s)s[ne].rebuild()},N=te(a?a.getLevel():"WARN");var Y=F();Y!=null&&(b=te(Y)),u.call(w)}a=new g,a.getLogger=function(_){if(typeof _!="symbol"&&typeof _!="string"||_==="")throw new TypeError("You must supply a name when creating a logger.");var w=s[_];return w||(w=s[_]=new g(_,a.methodFactory)),w};var y=typeof window!==t?window.log:void 0;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=y),a},a.getLoggers=function(){return s},a.default=a,a})}(Er)),Er.exports}var wr=np(),Vs;(function(i){i[i.trace=0]="trace",i[i.debug=1]="debug",i[i.info=2]="info",i[i.warn=3]="warn",i[i.error=4]="error",i[i.silent=5]="silent"})(Vs||(Vs={}));var mt;(function(i){i.Default="livekit",i.Room="livekit-room",i.Participant="livekit-participant",i.Track="livekit-track",i.Publication="livekit-track-publication",i.Engine="livekit-engine",i.Signal="livekit-signal",i.PCManager="livekit-pc-manager",i.PCTransport="livekit-pc-transport",i.E2EE="lk-e2ee"})(mt||(mt={}));let re=wr.getLogger("livekit");Object.values(mt).map(i=>wr.getLogger(i)),re.setDefaultLevel(Vs.info);function jt(i){const e=wr.getLogger(i);return e.setDefaultLevel(re.getLevel()),e}const ip=wr.getLogger("lk-e2ee"),Ai=7e3,rp=[0,300,2*2*300,3*3*300,4*4*300,Ai,Ai,Ai,Ai,Ai];class sp{constructor(e){this._retryDelays=e!==void 0?[...e]:rp}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+Math.random()*1e3}}function ap(i,e){var t={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&e.indexOf(n)<0&&(t[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,n=Object.getOwnPropertySymbols(i);r<n.length;r++)e.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(i,n[r])&&(t[n[r]]=i[n[r]]);return t}function m(i,e,t,n){function r(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function o(u){try{d(n.next(u))}catch(h){a(h)}}function c(u){try{d(n.throw(u))}catch(h){a(h)}}function d(u){u.done?s(u.value):r(u.value).then(o,c)}d((n=n.apply(i,e||[])).next())})}function Dc(i){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&i[e],n=0;if(t)return t.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&n>=i.length&&(i=void 0),{value:i&&i[n++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Yt(i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=i[Symbol.asyncIterator],t;return e?e.call(i):(i=typeof Dc=="function"?Dc(i):i[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(s){t[s]=i[s]&&function(a){return new Promise(function(o,c){a=i[s](a),r(o,c,a.done,a.value)})}}function r(s,a,o,c){Promise.resolve(c).then(function(d){s({value:d,done:o})},a)}}typeof SuppressedError=="function"&&SuppressedError;var Pr={exports:{}},Mc;function op(){if(Mc)return Pr.exports;Mc=1;var i=typeof Reflect=="object"?Reflect:null,e=i&&typeof i.apply=="function"?i.apply:function(k,x,F){return Function.prototype.apply.call(k,x,F)},t;i&&typeof i.ownKeys=="function"?t=i.ownKeys:Object.getOwnPropertySymbols?t=function(k){return Object.getOwnPropertyNames(k).concat(Object.getOwnPropertySymbols(k))}:t=function(k){return Object.getOwnPropertyNames(k)};function n(b){console&&console.warn&&console.warn(b)}var r=Number.isNaN||function(k){return k!==k};function s(){s.init.call(this)}Pr.exports=s,Pr.exports.once=w,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var a=10;function o(b){if(typeof b!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof b)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(b){if(typeof b!="number"||b<0||r(b))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+b+".");a=b}}),s.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(k){if(typeof k!="number"||k<0||r(k))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+k+".");return this._maxListeners=k,this};function c(b){return b._maxListeners===void 0?s.defaultMaxListeners:b._maxListeners}s.prototype.getMaxListeners=function(){return c(this)},s.prototype.emit=function(k){for(var x=[],F=1;F<arguments.length;F++)x.push(arguments[F]);var q=k==="error",te=this._events;if(te!==void 0)q=q&&te.error===void 0;else if(!q)return!1;if(q){var Y;if(x.length>0&&(Y=x[0]),Y instanceof Error)throw Y;var ne=new Error("Unhandled error."+(Y?" ("+Y.message+")":""));throw ne.context=Y,ne}var be=te[k];if(be===void 0)return!1;if(typeof be=="function")e(be,this,x);else for(var st=be.length,St=y(be,st),F=0;F<st;++F)e(St[F],this,x);return!0};function d(b,k,x,F){var q,te,Y;if(o(x),te=b._events,te===void 0?(te=b._events=Object.create(null),b._eventsCount=0):(te.newListener!==void 0&&(b.emit("newListener",k,x.listener?x.listener:x),te=b._events),Y=te[k]),Y===void 0)Y=te[k]=x,++b._eventsCount;else if(typeof Y=="function"?Y=te[k]=F?[x,Y]:[Y,x]:F?Y.unshift(x):Y.push(x),q=c(b),q>0&&Y.length>q&&!Y.warned){Y.warned=!0;var ne=new Error("Possible EventEmitter memory leak detected. "+Y.length+" "+String(k)+" listeners added. Use emitter.setMaxListeners() to increase limit");ne.name="MaxListenersExceededWarning",ne.emitter=b,ne.type=k,ne.count=Y.length,n(ne)}return b}s.prototype.addListener=function(k,x){return d(this,k,x,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(k,x){return d(this,k,x,!0)};function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function h(b,k,x){var F={fired:!1,wrapFn:void 0,target:b,type:k,listener:x},q=u.bind(F);return q.listener=x,F.wrapFn=q,q}s.prototype.once=function(k,x){return o(x),this.on(k,h(this,k,x)),this},s.prototype.prependOnceListener=function(k,x){return o(x),this.prependListener(k,h(this,k,x)),this},s.prototype.removeListener=function(k,x){var F,q,te,Y,ne;if(o(x),q=this._events,q===void 0)return this;if(F=q[k],F===void 0)return this;if(F===x||F.listener===x)--this._eventsCount===0?this._events=Object.create(null):(delete q[k],q.removeListener&&this.emit("removeListener",k,F.listener||x));else if(typeof F!="function"){for(te=-1,Y=F.length-1;Y>=0;Y--)if(F[Y]===x||F[Y].listener===x){ne=F[Y].listener,te=Y;break}if(te<0)return this;te===0?F.shift():v(F,te),F.length===1&&(q[k]=F[0]),q.removeListener!==void 0&&this.emit("removeListener",k,ne||x)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(k){var x,F,q;if(F=this._events,F===void 0)return this;if(F.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):F[k]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete F[k]),this;if(arguments.length===0){var te=Object.keys(F),Y;for(q=0;q<te.length;++q)Y=te[q],Y!=="removeListener"&&this.removeAllListeners(Y);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(x=F[k],typeof x=="function")this.removeListener(k,x);else if(x!==void 0)for(q=x.length-1;q>=0;q--)this.removeListener(k,x[q]);return this};function f(b,k,x){var F=b._events;if(F===void 0)return[];var q=F[k];return q===void 0?[]:typeof q=="function"?x?[q.listener||q]:[q]:x?_(q):y(q,q.length)}s.prototype.listeners=function(k){return f(this,k,!0)},s.prototype.rawListeners=function(k){return f(this,k,!1)},s.listenerCount=function(b,k){return typeof b.listenerCount=="function"?b.listenerCount(k):g.call(b,k)},s.prototype.listenerCount=g;function g(b){var k=this._events;if(k!==void 0){var x=k[b];if(typeof x=="function")return 1;if(x!==void 0)return x.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function y(b,k){for(var x=new Array(k),F=0;F<k;++F)x[F]=b[F];return x}function v(b,k){for(;k+1<b.length;k++)b[k]=b[k+1];b.pop()}function _(b){for(var k=new Array(b.length),x=0;x<k.length;++x)k[x]=b[x].listener||b[x];return k}function w(b,k){return new Promise(function(x,F){function q(Y){b.removeListener(k,te),F(Y)}function te(){typeof b.removeListener=="function"&&b.removeListener("error",q),x([].slice.call(arguments))}U(b,k,te,{once:!0}),k!=="error"&&N(b,q,{once:!0})})}function N(b,k,x){typeof b.on=="function"&&U(b,"error",k,x)}function U(b,k,x,F){if(typeof b.on=="function")F.once?b.once(k,x):b.on(k,x);else if(typeof b.addEventListener=="function")b.addEventListener(k,function q(te){F.once&&b.removeEventListener(k,q),x(te)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof b)}return Pr.exports}var Rt=op();let Nc=!0,Lc=!0;function Rr(i,e,t){const n=i.match(e);return n&&n.length>=t&&parseInt(n[t],10)}function En(i,e,t){if(!i.RTCPeerConnection)return;const n=i.RTCPeerConnection.prototype,r=n.addEventListener;n.addEventListener=function(a,o){if(a!==e)return r.apply(this,arguments);const c=d=>{const u=t(d);u&&(o.handleEvent?o.handleEvent(u):o(u))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(o,c),r.apply(this,[a,c])};const s=n.removeEventListener;n.removeEventListener=function(a,o){if(a!==e||!this._eventMap||!this._eventMap[e])return s.apply(this,arguments);if(!this._eventMap[e].has(o))return s.apply(this,arguments);const c=this._eventMap[e].get(o);return this._eventMap[e].delete(o),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,s.apply(this,[a,c])},Object.defineProperty(n,"on"+e,{get(){return this["_on"+e]},set(a){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),a&&this.addEventListener(e,this["_on"+e]=a)},enumerable:!0,configurable:!0})}function cp(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(Nc=i,i?"adapter.js logging disabled":"adapter.js logging enabled")}function dp(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(Lc=!i,"adapter.js deprecation warnings "+(i?"disabled":"enabled"))}function Uc(){if(typeof window=="object"){if(Nc)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function qs(i,e){Lc&&console.warn(i+" is deprecated, please use "+e+" instead.")}function up(i){const e={browser:null,version:null};if(typeof i>"u"||!i.navigator||!i.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:t}=i;if(t.userAgentData&&t.userAgentData.brands){const n=t.userAgentData.brands.find(r=>r.brand==="Chromium");if(n)return{browser:"chrome",version:parseInt(n.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=Rr(t.userAgent,/Firefox\/(\d+)\./,1);else if(t.webkitGetUserMedia||i.isSecureContext===!1&&i.webkitRTCPeerConnection)e.browser="chrome",e.version=Rr(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(i.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=Rr(t.userAgent,/AppleWebKit\/(\d+)\./,1),e.supportsUnifiedPlan=i.RTCRtpTransceiver&&"currentDirection"in i.RTCRtpTransceiver.prototype;else return e.browser="Not a supported browser.",e;return e}function jc(i){return Object.prototype.toString.call(i)==="[object Object]"}function Fc(i){return jc(i)?Object.keys(i).reduce(function(e,t){const n=jc(i[t]),r=n?Fc(i[t]):i[t],s=n&&!Object.keys(r).length;return r===void 0||s?e:Object.assign(e,{[t]:r})},{}):i}function zs(i,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?zs(i,i.get(e[n]),t):n.endsWith("Ids")&&e[n].forEach(r=>{zs(i,i.get(r),t)})}))}function $c(i,e,t){const n=t?"outbound-rtp":"inbound-rtp",r=new Map;if(e===null)return r;const s=[];return i.forEach(a=>{a.type==="track"&&a.trackIdentifier===e.id&&s.push(a)}),s.forEach(a=>{i.forEach(o=>{o.type===n&&o.trackId===a.id&&zs(i,o,r)})}),r}const Bc=Uc;function Vc(i,e){const t=i&&i.navigator;if(!t.mediaDevices)return;const n=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;const c={};return Object.keys(o).forEach(d=>{if(d==="require"||d==="advanced"||d==="mediaSource")return;const u=typeof o[d]=="object"?o[d]:{ideal:o[d]};u.exact!==void 0&&typeof u.exact=="number"&&(u.min=u.max=u.exact);const h=function(f,g){return f?f+g.charAt(0).toUpperCase()+g.slice(1):g==="deviceId"?"sourceId":g};if(u.ideal!==void 0){c.optional=c.optional||[];let f={};typeof u.ideal=="number"?(f[h("min",d)]=u.ideal,c.optional.push(f),f={},f[h("max",d)]=u.ideal,c.optional.push(f)):(f[h("",d)]=u.ideal,c.optional.push(f))}u.exact!==void 0&&typeof u.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[h("",d)]=u.exact):["min","max"].forEach(f=>{u[f]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[h(f,d)]=u[f])})}),o.advanced&&(c.optional=(c.optional||[]).concat(o.advanced)),c},r=function(o,c){if(e.version>=61)return c(o);if(o=JSON.parse(JSON.stringify(o)),o&&typeof o.audio=="object"){const d=function(u,h,f){h in u&&!(f in u)&&(u[f]=u[h],delete u[h])};o=JSON.parse(JSON.stringify(o)),d(o.audio,"autoGainControl","googAutoGainControl"),d(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=n(o.audio)}if(o&&typeof o.video=="object"){let d=o.video.facingMode;d=d&&(typeof d=="object"?d:{ideal:d});const u=e.version<66;if(d&&(d.exact==="user"||d.exact==="environment"||d.ideal==="user"||d.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!u)){delete o.video.facingMode;let h;if(d.exact==="environment"||d.ideal==="environment"?h=["back","rear"]:(d.exact==="user"||d.ideal==="user")&&(h=["front"]),h)return t.mediaDevices.enumerateDevices().then(f=>{f=f.filter(y=>y.kind==="videoinput");let g=f.find(y=>h.some(v=>y.label.toLowerCase().includes(v)));return!g&&f.length&&h.includes("back")&&(g=f[f.length-1]),g&&(o.video.deviceId=d.exact?{exact:g.deviceId}:{ideal:g.deviceId}),o.video=n(o.video),Bc("chrome: "+JSON.stringify(o)),c(o)})}o.video=n(o.video)}return Bc("chrome: "+JSON.stringify(o)),c(o)},s=function(o){return e.version>=64?o:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[o.name]||o.name,message:o.message,constraint:o.constraint||o.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},a=function(o,c,d){r(o,u=>{t.webkitGetUserMedia(u,c,h=>{d&&d(s(h))})})};if(t.getUserMedia=a.bind(t),t.mediaDevices.getUserMedia){const o=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(c){return r(c,d=>o(d).then(u=>{if(d.audio&&!u.getAudioTracks().length||d.video&&!u.getVideoTracks().length)throw u.getTracks().forEach(h=>{h.stop()}),new DOMException("","NotFoundError");return u},u=>Promise.reject(s(u))))}}}function qc(i){i.MediaStream=i.MediaStream||i.webkitMediaStream}function zc(i){if(typeof i=="object"&&i.RTCPeerConnection&&!("ontrack"in i.RTCPeerConnection.prototype)){Object.defineProperty(i.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(t){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=t)},enumerable:!0,configurable:!0});const e=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=n=>{n.stream.addEventListener("addtrack",r=>{let s;i.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(o=>o.track&&o.track.id===r.track.id):s={track:r.track};const a=new Event("track");a.track=r.track,a.receiver=s,a.transceiver={receiver:s},a.streams=[n.stream],this.dispatchEvent(a)}),n.stream.getTracks().forEach(r=>{let s;i.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(o=>o.track&&o.track.id===r.id):s={track:r};const a=new Event("track");a.track=r,a.receiver=s,a.transceiver={receiver:s},a.streams=[n.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else En(i,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function Wc(i){if(typeof i=="object"&&i.RTCPeerConnection&&!("getSenders"in i.RTCPeerConnection.prototype)&&"createDTMFSender"in i.RTCPeerConnection.prototype){const e=function(r,s){return{track:s,get dtmf(){return this._dtmf===void 0&&(s.kind==="audio"?this._dtmf=r.createDTMFSender(s):this._dtmf=null),this._dtmf},_pc:r}};if(!i.RTCPeerConnection.prototype.getSenders){i.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(o,c){let d=r.apply(this,arguments);return d||(d=e(this,o),this._senders.push(d)),d};const s=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(o){s.apply(this,arguments);const c=this._senders.indexOf(o);c!==-1&&this._senders.splice(c,1)}}const t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(s){this._senders=this._senders||[],t.apply(this,[s]),s.getTracks().forEach(a=>{this._senders.push(e(this,a))})};const n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(s){this._senders=this._senders||[],n.apply(this,[s]),s.getTracks().forEach(a=>{const o=this._senders.find(c=>c.track===a);o&&this._senders.splice(this._senders.indexOf(o),1)})}}else if(typeof i=="object"&&i.RTCPeerConnection&&"getSenders"in i.RTCPeerConnection.prototype&&"createDTMFSender"in i.RTCPeerConnection.prototype&&i.RTCRtpSender&&!("dtmf"in i.RTCRtpSender.prototype)){const e=i.RTCPeerConnection.prototype.getSenders;i.RTCPeerConnection.prototype.getSenders=function(){const n=e.apply(this,[]);return n.forEach(r=>r._pc=this),n},Object.defineProperty(i.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function Gc(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender&&i.RTCRtpReceiver))return;if(!("getStats"in i.RTCRtpSender.prototype)){const t=i.RTCPeerConnection.prototype.getSenders;t&&(i.RTCPeerConnection.prototype.getSenders=function(){const s=t.apply(this,[]);return s.forEach(a=>a._pc=this),s});const n=i.RTCPeerConnection.prototype.addTrack;n&&(i.RTCPeerConnection.prototype.addTrack=function(){const s=n.apply(this,arguments);return s._pc=this,s}),i.RTCRtpSender.prototype.getStats=function(){const s=this;return this._pc.getStats().then(a=>$c(a,s.track,!0))}}if(!("getStats"in i.RTCRtpReceiver.prototype)){const t=i.RTCPeerConnection.prototype.getReceivers;t&&(i.RTCPeerConnection.prototype.getReceivers=function(){const r=t.apply(this,[]);return r.forEach(s=>s._pc=this),r}),En(i,"track",n=>(n.receiver._pc=n.srcElement,n)),i.RTCRtpReceiver.prototype.getStats=function(){const r=this;return this._pc.getStats().then(s=>$c(s,r.track,!1))}}if(!("getStats"in i.RTCRtpSender.prototype&&"getStats"in i.RTCRtpReceiver.prototype))return;const e=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof i.MediaStreamTrack){const n=arguments[0];let r,s,a;return this.getSenders().forEach(o=>{o.track===n&&(r?a=!0:r=o)}),this.getReceivers().forEach(o=>(o.track===n&&(s?a=!0:s=o),o.track===n)),a||r&&s?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):r?r.getStats():s?s.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function Kc(i){i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(a=>this._shimmedLocalStreams[a][0])};const e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(a,o){if(!o)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const c=e.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(c)===-1&&this._shimmedLocalStreams[o.id].push(c):this._shimmedLocalStreams[o.id]=[o,c],c};const t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(a){this._shimmedLocalStreams=this._shimmedLocalStreams||{},a.getTracks().forEach(d=>{if(this.getSenders().find(h=>h.track===d))throw new DOMException("Track already exists.","InvalidAccessError")});const o=this.getSenders();t.apply(this,arguments);const c=this.getSenders().filter(d=>o.indexOf(d)===-1);this._shimmedLocalStreams[a.id]=[a].concat(c)};const n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[a.id],n.apply(this,arguments)};const r=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},a&&Object.keys(this._shimmedLocalStreams).forEach(o=>{const c=this._shimmedLocalStreams[o].indexOf(a);c!==-1&&this._shimmedLocalStreams[o].splice(c,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),r.apply(this,arguments)}}function Hc(i,e){if(!i.RTCPeerConnection)return;if(i.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Kc(i);const t=i.RTCPeerConnection.prototype.getLocalStreams;i.RTCPeerConnection.prototype.getLocalStreams=function(){const u=t.apply(this);return this._reverseStreams=this._reverseStreams||{},u.map(h=>this._reverseStreams[h.id])};const n=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(u){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},u.getTracks().forEach(h=>{if(this.getSenders().find(g=>g.track===h))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[u.id]){const h=new i.MediaStream(u.getTracks());this._streams[u.id]=h,this._reverseStreams[h.id]=u,u=h}n.apply(this,[u])};const r=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(u){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[u.id]||u]),delete this._reverseStreams[this._streams[u.id]?this._streams[u.id].id:u.id],delete this._streams[u.id]},i.RTCPeerConnection.prototype.addTrack=function(u,h){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const f=[].slice.call(arguments,1);if(f.length!==1||!f[0].getTracks().find(v=>v===u))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(v=>v.track===u))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const y=this._streams[h.id];if(y)y.addTrack(u),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const v=new i.MediaStream([u]);this._streams[h.id]=v,this._reverseStreams[v.id]=h,this.addStream(v)}return this.getSenders().find(v=>v.track===u)};function s(d,u){let h=u.sdp;return Object.keys(d._reverseStreams||[]).forEach(f=>{const g=d._reverseStreams[f],y=d._streams[g.id];h=h.replace(new RegExp(y.id,"g"),g.id)}),new RTCSessionDescription({type:u.type,sdp:h})}function a(d,u){let h=u.sdp;return Object.keys(d._reverseStreams||[]).forEach(f=>{const g=d._reverseStreams[f],y=d._streams[g.id];h=h.replace(new RegExp(g.id,"g"),y.id)}),new RTCSessionDescription({type:u.type,sdp:h})}["createOffer","createAnswer"].forEach(function(d){const u=i.RTCPeerConnection.prototype[d],h={[d](){const f=arguments;return arguments.length&&typeof arguments[0]=="function"?u.apply(this,[y=>{const v=s(this,y);f[0].apply(null,[v])},y=>{f[1]&&f[1].apply(null,y)},arguments[2]]):u.apply(this,arguments).then(y=>s(this,y))}};i.RTCPeerConnection.prototype[d]=h[d]});const o=i.RTCPeerConnection.prototype.setLocalDescription;i.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?o.apply(this,arguments):(arguments[0]=a(this,arguments[0]),o.apply(this,arguments))};const c=Object.getOwnPropertyDescriptor(i.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(i.RTCPeerConnection.prototype,"localDescription",{get(){const d=c.get.apply(this);return d.type===""?d:s(this,d)}}),i.RTCPeerConnection.prototype.removeTrack=function(u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!u._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(u._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let f;Object.keys(this._streams).forEach(g=>{this._streams[g].getTracks().find(v=>u.track===v)&&(f=this._streams[g])}),f&&(f.getTracks().length===1?this.removeStream(this._reverseStreams[f.id]):f.removeTrack(u.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Ws(i,e){!i.RTCPeerConnection&&i.webkitRTCPeerConnection&&(i.RTCPeerConnection=i.webkitRTCPeerConnection),i.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const n=i.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};i.RTCPeerConnection.prototype[t]=r[t]})}function Zc(i,e){En(i,"negotiationneeded",t=>{const n=t.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return t})}var Jc=Object.freeze({__proto__:null,fixNegotiationNeeded:Zc,shimAddTrackRemoveTrack:Hc,shimAddTrackRemoveTrackWithNative:Kc,shimGetSendersWithDtmf:Wc,shimGetUserMedia:Vc,shimMediaStream:qc,shimOnTrack:zc,shimPeerConnection:Ws,shimSenderReceiverGetStats:Gc});function Yc(i,e){const t=i&&i.navigator,n=i&&i.MediaStreamTrack;if(t.getUserMedia=function(r,s,a){qs("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(r).then(s,a)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const r=function(a,o,c){o in a&&!(c in a)&&(a[c]=a[o],delete a[o])},s=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(a){return typeof a=="object"&&typeof a.audio=="object"&&(a=JSON.parse(JSON.stringify(a)),r(a.audio,"autoGainControl","mozAutoGainControl"),r(a.audio,"noiseSuppression","mozNoiseSuppression")),s(a)},n&&n.prototype.getSettings){const a=n.prototype.getSettings;n.prototype.getSettings=function(){const o=a.apply(this,arguments);return r(o,"mozAutoGainControl","autoGainControl"),r(o,"mozNoiseSuppression","noiseSuppression"),o}}if(n&&n.prototype.applyConstraints){const a=n.prototype.applyConstraints;n.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),r(o,"autoGainControl","mozAutoGainControl"),r(o,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[o])}}}}function lp(i,e){i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices||i.navigator.mediaDevices&&(i.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){const r=new DOMException("getDisplayMedia without video constraints is undefined");return r.name="NotFoundError",r.code=8,Promise.reject(r)}return n.video===!0?n.video={mediaSource:e}:n.video.mediaSource=e,i.navigator.mediaDevices.getUserMedia(n)})}function Qc(i){typeof i=="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Gs(i,e){if(typeof i!="object"||!(i.RTCPeerConnection||i.mozRTCPeerConnection))return;!i.RTCPeerConnection&&i.mozRTCPeerConnection&&(i.RTCPeerConnection=i.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(r){const s=i.RTCPeerConnection.prototype[r],a={[r](){return arguments[0]=new(r==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),s.apply(this,arguments)}};i.RTCPeerConnection.prototype[r]=a[r]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){const[s,a,o]=arguments;return n.apply(this,[s||null]).then(c=>{if(e.version<53&&!a)try{c.forEach(d=>{d.type=t[d.type]||d.type})}catch(d){if(d.name!=="TypeError")throw d;c.forEach((u,h)=>{c.set(h,Object.assign({},u,{type:t[u.type]||u.type}))})}return c}).then(a,o)}}function Xc(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpSender.prototype)return;const e=i.RTCPeerConnection.prototype.getSenders;e&&(i.RTCPeerConnection.prototype.getSenders=function(){const r=e.apply(this,[]);return r.forEach(s=>s._pc=this),r});const t=i.RTCPeerConnection.prototype.addTrack;t&&(i.RTCPeerConnection.prototype.addTrack=function(){const r=t.apply(this,arguments);return r._pc=this,r}),i.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function ed(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpReceiver.prototype)return;const e=i.RTCPeerConnection.prototype.getReceivers;e&&(i.RTCPeerConnection.prototype.getReceivers=function(){const n=e.apply(this,[]);return n.forEach(r=>r._pc=this),n}),En(i,"track",t=>(t.receiver._pc=t.srcElement,t)),i.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function td(i){!i.RTCPeerConnection||"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(t){qs("removeStream","removeTrack"),this.getSenders().forEach(n=>{n.track&&t.getTracks().includes(n.track)&&this.removeTrack(n)})})}function nd(i){i.DataChannel&&!i.RTCDataChannel&&(i.RTCDataChannel=i.DataChannel)}function id(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.addTransceiver;e&&(i.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let n=arguments[1]&&arguments[1].sendEncodings;n===void 0&&(n=[]),n=[...n];const r=n.length>0;r&&n.forEach(a=>{if("rid"in a&&!/^[a-z0-9]{0,16}$/i.test(a.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in a&&!(parseFloat(a.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in a&&!(parseFloat(a.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const s=e.apply(this,arguments);if(r){const{sender:a}=s,o=a.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=n,a.sendEncodings=n,this.setParametersPromises.push(a.setParameters(o).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return s})}function rd(i){if(!(typeof i=="object"&&i.RTCRtpSender))return;const e=i.RTCRtpSender.prototype.getParameters;e&&(i.RTCRtpSender.prototype.getParameters=function(){const n=e.apply(this,arguments);return"encodings"in n||(n.encodings=[].concat(this.sendEncodings||[{}])),n})}function sd(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function ad(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.createAnswer;i.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}var od=Object.freeze({__proto__:null,shimAddTransceiver:id,shimCreateAnswer:ad,shimCreateOffer:sd,shimGetDisplayMedia:lp,shimGetParameters:rd,shimGetUserMedia:Yc,shimOnTrack:Qc,shimPeerConnection:Gs,shimRTCDataChannel:nd,shimReceiverGetStats:ed,shimRemoveStream:td,shimSenderGetStats:Xc});function cd(i){if(!(typeof i!="object"||!i.RTCPeerConnection)){if("getLocalStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in i.RTCPeerConnection.prototype)){const e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addStream=function(n){this._localStreams||(this._localStreams=[]),this._localStreams.includes(n)||this._localStreams.push(n),n.getAudioTracks().forEach(r=>e.call(this,r,n)),n.getVideoTracks().forEach(r=>e.call(this,r,n))},i.RTCPeerConnection.prototype.addTrack=function(n){for(var r=arguments.length,s=new Array(r>1?r-1:0),a=1;a<r;a++)s[a-1]=arguments[a];return s&&s.forEach(o=>{this._localStreams?this._localStreams.includes(o)||this._localStreams.push(o):this._localStreams=[o]}),e.apply(this,arguments)}}"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const n=this._localStreams.indexOf(t);if(n===-1)return;this._localStreams.splice(n,1);const r=t.getTracks();this.getSenders().forEach(s=>{r.includes(s.track)&&this.removeTrack(s)})})}}function dd(i){if(!(typeof i!="object"||!i.RTCPeerConnection)&&("getRemoteStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in i.RTCPeerConnection.prototype))){Object.defineProperty(i.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=n=>{n.streams.forEach(r=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(r))return;this._remoteStreams.push(r);const s=new Event("addstream");s.stream=r,this.dispatchEvent(s)})})}});const e=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){const n=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(r){r.streams.forEach(s=>{if(n._remoteStreams||(n._remoteStreams=[]),n._remoteStreams.indexOf(s)>=0)return;n._remoteStreams.push(s);const a=new Event("addstream");a.stream=s,n.dispatchEvent(a)})}),e.apply(n,arguments)}}}function ud(i){if(typeof i!="object"||!i.RTCPeerConnection)return;const e=i.RTCPeerConnection.prototype,t=e.createOffer,n=e.createAnswer,r=e.setLocalDescription,s=e.setRemoteDescription,a=e.addIceCandidate;e.createOffer=function(d,u){const h=arguments.length>=2?arguments[2]:arguments[0],f=t.apply(this,[h]);return u?(f.then(d,u),Promise.resolve()):f},e.createAnswer=function(d,u){const h=arguments.length>=2?arguments[2]:arguments[0],f=n.apply(this,[h]);return u?(f.then(d,u),Promise.resolve()):f};let o=function(c,d,u){const h=r.apply(this,[c]);return u?(h.then(d,u),Promise.resolve()):h};e.setLocalDescription=o,o=function(c,d,u){const h=s.apply(this,[c]);return u?(h.then(d,u),Promise.resolve()):h},e.setRemoteDescription=o,o=function(c,d,u){const h=a.apply(this,[c]);return u?(h.then(d,u),Promise.resolve()):h},e.addIceCandidate=o}function ld(i){const e=i&&i.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,n=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=r=>n(hd(r))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(n,r,s){e.mediaDevices.getUserMedia(n).then(r,s)}).bind(e))}function hd(i){return i&&i.video!==void 0?Object.assign({},i,{video:Fc(i.video)}):i}function fd(i){if(!i.RTCPeerConnection)return;const e=i.RTCPeerConnection;i.RTCPeerConnection=function(n,r){if(n&&n.iceServers){const s=[];for(let a=0;a<n.iceServers.length;a++){let o=n.iceServers[a];o.urls===void 0&&o.url?(qs("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,s.push(o)):s.push(n.iceServers[a])}n.iceServers=s}return new e(n,r)},i.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(i.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function pd(i){typeof i=="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function md(i){const e=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(n){if(n){typeof n.offerToReceiveAudio<"u"&&(n.offerToReceiveAudio=!!n.offerToReceiveAudio);const r=this.getTransceivers().find(a=>a.receiver.track.kind==="audio");n.offerToReceiveAudio===!1&&r?r.direction==="sendrecv"?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":r.direction==="recvonly"&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):n.offerToReceiveAudio===!0&&!r&&this.addTransceiver("audio",{direction:"recvonly"}),typeof n.offerToReceiveVideo<"u"&&(n.offerToReceiveVideo=!!n.offerToReceiveVideo);const s=this.getTransceivers().find(a=>a.receiver.track.kind==="video");n.offerToReceiveVideo===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):n.offerToReceiveVideo===!0&&!s&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function gd(i){typeof i!="object"||i.AudioContext||(i.AudioContext=i.webkitAudioContext)}var vd=Object.freeze({__proto__:null,shimAudioContext:gd,shimCallbacksAPI:ud,shimConstraints:hd,shimCreateOfferLegacy:md,shimGetUserMedia:ld,shimLocalStreamsAPI:cd,shimRTCIceServerUrls:fd,shimRemoteStreamsAPI:dd,shimTrackEventTransceiver:pd}),Ks={exports:{}},yd;function hp(){return yd||(yd=1,function(i){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(`
3
+ `).map(n=>n.trim())},e.splitSections=function(t){return t.split(`
4
+ m=`).map((r,s)=>(s>0?"m="+r:r).trim()+`\r
5
+ `)},e.getDescription=function(t){const n=e.splitSections(t);return n&&n[0]},e.getMediaSections=function(t){const n=e.splitSections(t);return n.shift(),n},e.matchPrefix=function(t,n){return e.splitLines(t).filter(r=>r.indexOf(n)===0)},e.parseCandidate=function(t){let n;t.indexOf("a=candidate:")===0?n=t.substring(12).split(" "):n=t.substring(10).split(" ");const r={foundation:n[0],component:{1:"rtp",2:"rtcp"}[n[1]]||n[1],protocol:n[2].toLowerCase(),priority:parseInt(n[3],10),ip:n[4],address:n[4],port:parseInt(n[5],10),type:n[7]};for(let s=8;s<n.length;s+=2)switch(n[s]){case"raddr":r.relatedAddress=n[s+1];break;case"rport":r.relatedPort=parseInt(n[s+1],10);break;case"tcptype":r.tcpType=n[s+1];break;case"ufrag":r.ufrag=n[s+1],r.usernameFragment=n[s+1];break;default:r[n[s]]===void 0&&(r[n[s]]=n[s+1]);break}return r},e.writeCandidate=function(t){const n=[];n.push(t.foundation);const r=t.component;r==="rtp"?n.push(1):r==="rtcp"?n.push(2):n.push(r),n.push(t.protocol.toUpperCase()),n.push(t.priority),n.push(t.address||t.ip),n.push(t.port);const s=t.type;return n.push("typ"),n.push(s),s!=="host"&&t.relatedAddress&&t.relatedPort&&(n.push("raddr"),n.push(t.relatedAddress),n.push("rport"),n.push(t.relatedPort)),t.tcpType&&t.protocol.toLowerCase()==="tcp"&&(n.push("tcptype"),n.push(t.tcpType)),(t.usernameFragment||t.ufrag)&&(n.push("ufrag"),n.push(t.usernameFragment||t.ufrag)),"candidate:"+n.join(" ")},e.parseIceOptions=function(t){return t.substring(14).split(" ")},e.parseRtpMap=function(t){let n=t.substring(9).split(" ");const r={payloadType:parseInt(n.shift(),10)};return n=n[0].split("/"),r.name=n[0],r.clockRate=parseInt(n[1],10),r.channels=n.length===3?parseInt(n[2],10):1,r.numChannels=r.channels,r},e.writeRtpMap=function(t){let n=t.payloadType;t.preferredPayloadType!==void 0&&(n=t.preferredPayloadType);const r=t.channels||t.numChannels||1;return"a=rtpmap:"+n+" "+t.name+"/"+t.clockRate+(r!==1?"/"+r:"")+`\r
6
+ `},e.parseExtmap=function(t){const n=t.substring(9).split(" ");return{id:parseInt(n[0],10),direction:n[0].indexOf("/")>0?n[0].split("/")[1]:"sendrecv",uri:n[1],attributes:n.slice(2).join(" ")}},e.writeExtmap=function(t){return"a=extmap:"+(t.id||t.preferredId)+(t.direction&&t.direction!=="sendrecv"?"/"+t.direction:"")+" "+t.uri+(t.attributes?" "+t.attributes:"")+`\r
7
+ `},e.parseFmtp=function(t){const n={};let r;const s=t.substring(t.indexOf(" ")+1).split(";");for(let a=0;a<s.length;a++)r=s[a].trim().split("="),n[r[0].trim()]=r[1];return n},e.writeFmtp=function(t){let n="",r=t.payloadType;if(t.preferredPayloadType!==void 0&&(r=t.preferredPayloadType),t.parameters&&Object.keys(t.parameters).length){const s=[];Object.keys(t.parameters).forEach(a=>{t.parameters[a]!==void 0?s.push(a+"="+t.parameters[a]):s.push(a)}),n+="a=fmtp:"+r+" "+s.join(";")+`\r
8
+ `}return n},e.parseRtcpFb=function(t){const n=t.substring(t.indexOf(" ")+1).split(" ");return{type:n.shift(),parameter:n.join(" ")}},e.writeRtcpFb=function(t){let n="",r=t.payloadType;return t.preferredPayloadType!==void 0&&(r=t.preferredPayloadType),t.rtcpFeedback&&t.rtcpFeedback.length&&t.rtcpFeedback.forEach(s=>{n+="a=rtcp-fb:"+r+" "+s.type+(s.parameter&&s.parameter.length?" "+s.parameter:"")+`\r
9
+ `}),n},e.parseSsrcMedia=function(t){const n=t.indexOf(" "),r={ssrc:parseInt(t.substring(7,n),10)},s=t.indexOf(":",n);return s>-1?(r.attribute=t.substring(n+1,s),r.value=t.substring(s+1)):r.attribute=t.substring(n+1),r},e.parseSsrcGroup=function(t){const n=t.substring(13).split(" ");return{semantics:n.shift(),ssrcs:n.map(r=>parseInt(r,10))}},e.getMid=function(t){const n=e.matchPrefix(t,"a=mid:")[0];if(n)return n.substring(6)},e.parseFingerprint=function(t){const n=t.substring(14).split(" ");return{algorithm:n[0].toLowerCase(),value:n[1].toUpperCase()}},e.getDtlsParameters=function(t,n){return{role:"auto",fingerprints:e.matchPrefix(t+n,"a=fingerprint:").map(e.parseFingerprint)}},e.writeDtlsParameters=function(t,n){let r="a=setup:"+n+`\r
10
+ `;return t.fingerprints.forEach(s=>{r+="a=fingerprint:"+s.algorithm+" "+s.value+`\r
11
+ `}),r},e.parseCryptoLine=function(t){const n=t.substring(9).split(" ");return{tag:parseInt(n[0],10),cryptoSuite:n[1],keyParams:n[2],sessionParams:n.slice(3)}},e.writeCryptoLine=function(t){return"a=crypto:"+t.tag+" "+t.cryptoSuite+" "+(typeof t.keyParams=="object"?e.writeCryptoKeyParams(t.keyParams):t.keyParams)+(t.sessionParams?" "+t.sessionParams.join(" "):"")+`\r
12
+ `},e.parseCryptoKeyParams=function(t){if(t.indexOf("inline:")!==0)return null;const n=t.substring(7).split("|");return{keyMethod:"inline",keySalt:n[0],lifeTime:n[1],mkiValue:n[2]?n[2].split(":")[0]:void 0,mkiLength:n[2]?n[2].split(":")[1]:void 0}},e.writeCryptoKeyParams=function(t){return t.keyMethod+":"+t.keySalt+(t.lifeTime?"|"+t.lifeTime:"")+(t.mkiValue&&t.mkiLength?"|"+t.mkiValue+":"+t.mkiLength:"")},e.getCryptoParameters=function(t,n){return e.matchPrefix(t+n,"a=crypto:").map(e.parseCryptoLine)},e.getIceParameters=function(t,n){const r=e.matchPrefix(t+n,"a=ice-ufrag:")[0],s=e.matchPrefix(t+n,"a=ice-pwd:")[0];return r&&s?{usernameFragment:r.substring(12),password:s.substring(10)}:null},e.writeIceParameters=function(t){let n="a=ice-ufrag:"+t.usernameFragment+`\r
13
+ a=ice-pwd:`+t.password+`\r
14
+ `;return t.iceLite&&(n+=`a=ice-lite\r
15
+ `),n},e.parseRtpParameters=function(t){const n={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},s=e.splitLines(t)[0].split(" ");n.profile=s[2];for(let o=3;o<s.length;o++){const c=s[o],d=e.matchPrefix(t,"a=rtpmap:"+c+" ")[0];if(d){const u=e.parseRtpMap(d),h=e.matchPrefix(t,"a=fmtp:"+c+" ");switch(u.parameters=h.length?e.parseFmtp(h[0]):{},u.rtcpFeedback=e.matchPrefix(t,"a=rtcp-fb:"+c+" ").map(e.parseRtcpFb),n.codecs.push(u),u.name.toUpperCase()){case"RED":case"ULPFEC":n.fecMechanisms.push(u.name.toUpperCase());break}}}e.matchPrefix(t,"a=extmap:").forEach(o=>{n.headerExtensions.push(e.parseExtmap(o))});const a=e.matchPrefix(t,"a=rtcp-fb:* ").map(e.parseRtcpFb);return n.codecs.forEach(o=>{a.forEach(c=>{o.rtcpFeedback.find(u=>u.type===c.type&&u.parameter===c.parameter)||o.rtcpFeedback.push(c)})}),n},e.writeRtpDescription=function(t,n){let r="";r+="m="+t+" ",r+=n.codecs.length>0?"9":"0",r+=" "+(n.profile||"UDP/TLS/RTP/SAVPF")+" ",r+=n.codecs.map(a=>a.preferredPayloadType!==void 0?a.preferredPayloadType:a.payloadType).join(" ")+`\r
16
+ `,r+=`c=IN IP4 0.0.0.0\r
17
+ `,r+=`a=rtcp:9 IN IP4 0.0.0.0\r
18
+ `,n.codecs.forEach(a=>{r+=e.writeRtpMap(a),r+=e.writeFmtp(a),r+=e.writeRtcpFb(a)});let s=0;return n.codecs.forEach(a=>{a.maxptime>s&&(s=a.maxptime)}),s>0&&(r+="a=maxptime:"+s+`\r
19
+ `),n.headerExtensions&&n.headerExtensions.forEach(a=>{r+=e.writeExtmap(a)}),r},e.parseRtpEncodingParameters=function(t){const n=[],r=e.parseRtpParameters(t),s=r.fecMechanisms.indexOf("RED")!==-1,a=r.fecMechanisms.indexOf("ULPFEC")!==-1,o=e.matchPrefix(t,"a=ssrc:").map(f=>e.parseSsrcMedia(f)).filter(f=>f.attribute==="cname"),c=o.length>0&&o[0].ssrc;let d;const u=e.matchPrefix(t,"a=ssrc-group:FID").map(f=>f.substring(17).split(" ").map(y=>parseInt(y,10)));u.length>0&&u[0].length>1&&u[0][0]===c&&(d=u[0][1]),r.codecs.forEach(f=>{if(f.name.toUpperCase()==="RTX"&&f.parameters.apt){let g={ssrc:c,codecPayloadType:parseInt(f.parameters.apt,10)};c&&d&&(g.rtx={ssrc:d}),n.push(g),s&&(g=JSON.parse(JSON.stringify(g)),g.fec={ssrc:c,mechanism:a?"red+ulpfec":"red"},n.push(g))}}),n.length===0&&c&&n.push({ssrc:c});let h=e.matchPrefix(t,"b=");return h.length&&(h[0].indexOf("b=TIAS:")===0?h=parseInt(h[0].substring(7),10):h[0].indexOf("b=AS:")===0?h=parseInt(h[0].substring(5),10)*1e3*.95-50*40*8:h=void 0,n.forEach(f=>{f.maxBitrate=h})),n},e.parseRtcpParameters=function(t){const n={},r=e.matchPrefix(t,"a=ssrc:").map(o=>e.parseSsrcMedia(o)).filter(o=>o.attribute==="cname")[0];r&&(n.cname=r.value,n.ssrc=r.ssrc);const s=e.matchPrefix(t,"a=rtcp-rsize");n.reducedSize=s.length>0,n.compound=s.length===0;const a=e.matchPrefix(t,"a=rtcp-mux");return n.mux=a.length>0,n},e.writeRtcpParameters=function(t){let n="";return t.reducedSize&&(n+=`a=rtcp-rsize\r
20
+ `),t.mux&&(n+=`a=rtcp-mux\r
21
+ `),t.ssrc!==void 0&&t.cname&&(n+="a=ssrc:"+t.ssrc+" cname:"+t.cname+`\r
22
+ `),n},e.parseMsid=function(t){let n;const r=e.matchPrefix(t,"a=msid:");if(r.length===1)return n=r[0].substring(7).split(" "),{stream:n[0],track:n[1]};const s=e.matchPrefix(t,"a=ssrc:").map(a=>e.parseSsrcMedia(a)).filter(a=>a.attribute==="msid");if(s.length>0)return n=s[0].value.split(" "),{stream:n[0],track:n[1]}},e.parseSctpDescription=function(t){const n=e.parseMLine(t),r=e.matchPrefix(t,"a=max-message-size:");let s;r.length>0&&(s=parseInt(r[0].substring(19),10)),isNaN(s)&&(s=65536);const a=e.matchPrefix(t,"a=sctp-port:");if(a.length>0)return{port:parseInt(a[0].substring(12),10),protocol:n.fmt,maxMessageSize:s};const o=e.matchPrefix(t,"a=sctpmap:");if(o.length>0){const c=o[0].substring(10).split(" ");return{port:parseInt(c[0],10),protocol:c[1],maxMessageSize:s}}},e.writeSctpDescription=function(t,n){let r=[];return t.protocol!=="DTLS/SCTP"?r=["m="+t.kind+" 9 "+t.protocol+" "+n.protocol+`\r
23
+ `,`c=IN IP4 0.0.0.0\r
24
+ `,"a=sctp-port:"+n.port+`\r
25
+ `]:r=["m="+t.kind+" 9 "+t.protocol+" "+n.port+`\r
26
+ `,`c=IN IP4 0.0.0.0\r
27
+ `,"a=sctpmap:"+n.port+" "+n.protocol+` 65535\r
28
+ `],n.maxMessageSize!==void 0&&r.push("a=max-message-size:"+n.maxMessageSize+`\r
29
+ `),r.join("")},e.generateSessionId=function(){return Math.random().toString().substr(2,22)},e.writeSessionBoilerplate=function(t,n,r){let s;const a=n!==void 0?n:2;return t?s=t:s=e.generateSessionId(),`v=0\r
30
+ o=`+(r||"thisisadapterortc")+" "+s+" "+a+` IN IP4 127.0.0.1\r
31
+ s=-\r
32
+ t=0 0\r
33
+ `},e.getDirection=function(t,n){const r=e.splitLines(t);for(let s=0;s<r.length;s++)switch(r[s]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[s].substring(2)}return n?e.getDirection(n):"sendrecv"},e.getKind=function(t){return e.splitLines(t)[0].split(" ")[0].substring(2)},e.isRejected=function(t){return t.split(" ",2)[1]==="0"},e.parseMLine=function(t){const r=e.splitLines(t)[0].substring(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},e.parseOLine=function(t){const r=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},e.isValidSDP=function(t){if(typeof t!="string"||t.length===0)return!1;const n=e.splitLines(t);for(let r=0;r<n.length;r++)if(n[r].length<2||n[r].charAt(1)!=="=")return!1;return!0},i.exports=e}(Ks)),Ks.exports}var bd=hp(),Hn=ep(bd),fp=Eh({__proto__:null,default:Hn},[bd]);function xr(i){if(!i.RTCIceCandidate||i.RTCIceCandidate&&"foundation"in i.RTCIceCandidate.prototype)return;const e=i.RTCIceCandidate;i.RTCIceCandidate=function(n){if(typeof n=="object"&&n.candidate&&n.candidate.indexOf("a=")===0&&(n=JSON.parse(JSON.stringify(n)),n.candidate=n.candidate.substring(2)),n.candidate&&n.candidate.length){const r=new e(n),s=Hn.parseCandidate(n.candidate);for(const a in s)a in r||Object.defineProperty(r,a,{value:s[a]});return r.toJSON=function(){return{candidate:r.candidate,sdpMid:r.sdpMid,sdpMLineIndex:r.sdpMLineIndex,usernameFragment:r.usernameFragment}},r}return new e(n)},i.RTCIceCandidate.prototype=e.prototype,En(i,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new i.RTCIceCandidate(t.candidate),writable:"false"}),t))}function Hs(i){!i.RTCIceCandidate||i.RTCIceCandidate&&"relayProtocol"in i.RTCIceCandidate.prototype||En(i,"icecandidate",e=>{if(e.candidate){const t=Hn.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function Ir(i,e){if(!i.RTCPeerConnection)return;"sctp"in i.RTCPeerConnection.prototype||Object.defineProperty(i.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const t=function(o){if(!o||!o.sdp)return!1;const c=Hn.splitSections(o.sdp);return c.shift(),c.some(d=>{const u=Hn.parseMLine(d);return u&&u.kind==="application"&&u.protocol.indexOf("SCTP")!==-1})},n=function(o){const c=o.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(c===null||c.length<2)return-1;const d=parseInt(c[1],10);return d!==d?-1:d},r=function(o){let c=65536;return e.browser==="firefox"&&(e.version<57?o===-1?c=16384:c=2147483637:e.version<60?c=e.version===57?65535:65536:c=2147483637),c},s=function(o,c){let d=65536;e.browser==="firefox"&&e.version===57&&(d=65535);const u=Hn.matchPrefix(o.sdp,"a=max-message-size:");return u.length>0?d=parseInt(u[0].substring(19),10):e.browser==="firefox"&&c!==-1&&(d=2147483637),d},a=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76){const{sdpSemantics:c}=this.getConfiguration();c==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(t(arguments[0])){const c=n(arguments[0]),d=r(c),u=s(arguments[0],c);let h;d===0&&u===0?h=Number.POSITIVE_INFINITY:d===0||u===0?h=Math.max(d,u):h=Math.min(d,u);const f={};Object.defineProperty(f,"maxMessageSize",{get(){return h}}),this._sctp=f}return a.apply(this,arguments)}}function Or(i){if(!(i.RTCPeerConnection&&"createDataChannel"in i.RTCPeerConnection.prototype))return;function e(n,r){const s=n.send;n.send=function(){const o=arguments[0],c=o.length||o.size||o.byteLength;if(n.readyState==="open"&&r.sctp&&c>r.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+r.sctp.maxMessageSize+" bytes)");return s.apply(n,arguments)}}const t=i.RTCPeerConnection.prototype.createDataChannel;i.RTCPeerConnection.prototype.createDataChannel=function(){const r=t.apply(this,arguments);return e(r,this),r},En(i,"datachannel",n=>(e(n.channel,n.target),n))}function Zs(i){if(!i.RTCPeerConnection||"connectionState"in i.RTCPeerConnection.prototype)return;const e=i.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(t){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),t&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=t)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(t=>{const n=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=r=>{const s=r.target;if(s._lastConnectionState!==s.connectionState){s._lastConnectionState=s.connectionState;const a=new Event("connectionstatechange",r);s.dispatchEvent(a)}return r},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}})}function Js(i,e){if(!i.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e.version>=605)return;const t=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(r){if(r&&r.sdp&&r.sdp.indexOf(`
34
+ a=extmap-allow-mixed`)!==-1){const s=r.sdp.split(`
35
+ `).filter(a=>a.trim()!=="a=extmap-allow-mixed").join(`
36
+ `);i.RTCSessionDescription&&r instanceof i.RTCSessionDescription?arguments[0]=new i.RTCSessionDescription({type:r.type,sdp:s}):r.sdp=s}return t.apply(this,arguments)}}function Ar(i,e){if(!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype))return;const t=i.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(i.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Dr(i,e){if(!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype))return;const t=i.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(i.RTCPeerConnection.prototype.setLocalDescription=function(){let r=arguments[0]||{};if(typeof r!="object"||r.type&&r.sdp)return t.apply(this,arguments);if(r={type:r.type,sdp:r.sdp},!r.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":r.type="offer";break;default:r.type="answer";break}return r.sdp||r.type!=="offer"&&r.type!=="answer"?t.apply(this,[r]):(r.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(a=>t.apply(this,[a]))})}var pp=Object.freeze({__proto__:null,removeExtmapAllowMixed:Js,shimAddIceCandidateNullOrEmpty:Ar,shimConnectionState:Zs,shimMaxMessageSize:Ir,shimParameterlessSetLocalDescription:Dr,shimRTCIceCandidate:xr,shimRTCIceCandidateRelayProtocol:Hs,shimSendThrowTypeError:Or});function mp(){let{window:i}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const t=Uc,n=up(i),r={browserDetails:n,commonShim:pp,extractVersion:Rr,disableLog:cp,disableWarnings:dp,sdp:fp};switch(n.browser){case"chrome":if(!Jc||!Ws||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),r;if(n.version===null)return t("Chrome shim can not determine version, not shimming."),r;t("adapter.js shimming chrome."),r.browserShim=Jc,Ar(i,n),Dr(i),Vc(i,n),qc(i),Ws(i,n),zc(i),Hc(i,n),Wc(i),Gc(i),Zc(i,n),xr(i),Hs(i),Zs(i),Ir(i,n),Or(i),Js(i,n);break;case"firefox":if(!od||!Gs||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),r;t("adapter.js shimming firefox."),r.browserShim=od,Ar(i,n),Dr(i),Yc(i,n),Gs(i,n),Qc(i),td(i),Xc(i),ed(i),nd(i),id(i),rd(i),sd(i),ad(i),xr(i),Zs(i),Ir(i,n),Or(i);break;case"safari":if(!vd||!e.shimSafari)return t("Safari shim is not included in this adapter release."),r;t("adapter.js shimming safari."),r.browserShim=vd,Ar(i,n),Dr(i),fd(i),md(i),ud(i),cd(i),dd(i),pd(i),ld(i),gd(i),xr(i),Hs(i),Ir(i,n),Or(i),Js(i,n);break;default:t("Unsupported browser!");break}return r}mp({window:typeof window>"u"?void 0:window});const gp=10,Mr="lk_e2ee",vp={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:gp,keyringSize:16};var Qt;(function(i){i.SetKey="setKey",i.RatchetRequest="ratchetRequest",i.KeyRatcheted="keyRatcheted"})(Qt||(Qt={}));var kd;(function(i){i.KeyRatcheted="keyRatcheted"})(kd||(kd={}));var Xt;(function(i){i.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",i.EncryptionError="encryptionError"})(Xt||(Xt={}));var Sd;(function(i){i.Error="cryptorError"})(Sd||(Sd={}));function yp(){return bp()||Ys()}function Ys(){return typeof window.RTCRtpScriptTransform<"u"}function bp(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class Xy extends Rt.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,n)=>{re.debug("key ratcheted event received",{material:t,keyIndex:n})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},vp),e),this.on(Qt.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,n){const r={key:e,participantIdentity:t,keyIndex:n};if(!this.options.sharedKey&&!t)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(t??"shared","-").concat(n??0),r),this.emit(Qt.SetKey,r)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(Qt.RatchetRequest,e,t)}}class en extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var oe;(function(i){i[i.NotAllowed=0]="NotAllowed",i[i.ServerUnreachable=1]="ServerUnreachable",i[i.InternalError=2]="InternalError",i[i.Cancelled=3]="Cancelled",i[i.LeaveRequest=4]="LeaveRequest"})(oe||(oe={}));class ye extends en{constructor(e,t,n,r){super(1,e),this.name="ConnectionError",this.status=n,this.reason=t,this.context=r,this.reasonName=oe[t]}}class Qs extends en{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class Ft extends en{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class kp extends en{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class Fe extends en{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Xs extends en{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class ea extends en{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class Td extends en{constructor(e,t){super(15,e),this.reason=t,this.reasonName=typeof t=="string"?t:Bs[t]}}var Nr;(function(i){i.PermissionDenied="PermissionDenied",i.NotFound="NotFound",i.DeviceInUse="DeviceInUse",i.Other="Other"})(Nr||(Nr={})),function(i){function e(t){if(t&&"name"in t)return t.name==="NotFoundError"||t.name==="DevicesNotFoundError"?i.NotFound:t.name==="NotAllowedError"||t.name==="PermissionDeniedError"?i.PermissionDenied:t.name==="NotReadableError"||t.name==="TrackStartError"?i.DeviceInUse:i.Other}i.getFailure=e}(Nr||(Nr={}));var Cd;(function(i){i[i.InvalidKey=0]="InvalidKey",i[i.MissingKey=1]="MissingKey",i[i.InternalError=2]="InternalError"})(Cd||(Cd={}));var O;(function(i){i.Connected="connected",i.Reconnecting="reconnecting",i.SignalReconnecting="signalReconnecting",i.Reconnected="reconnected",i.Disconnected="disconnected",i.ConnectionStateChanged="connectionStateChanged",i.MediaDevicesChanged="mediaDevicesChanged",i.ParticipantConnected="participantConnected",i.ParticipantDisconnected="participantDisconnected",i.TrackPublished="trackPublished",i.TrackSubscribed="trackSubscribed",i.TrackSubscriptionFailed="trackSubscriptionFailed",i.TrackUnpublished="trackUnpublished",i.TrackUnsubscribed="trackUnsubscribed",i.TrackMuted="trackMuted",i.TrackUnmuted="trackUnmuted",i.LocalTrackPublished="localTrackPublished",i.LocalTrackUnpublished="localTrackUnpublished",i.LocalAudioSilenceDetected="localAudioSilenceDetected",i.ActiveSpeakersChanged="activeSpeakersChanged",i.ParticipantMetadataChanged="participantMetadataChanged",i.ParticipantNameChanged="participantNameChanged",i.ParticipantAttributesChanged="participantAttributesChanged",i.RoomMetadataChanged="roomMetadataChanged",i.DataReceived="dataReceived",i.SipDTMFReceived="sipDTMFReceived",i.TranscriptionReceived="transcriptionReceived",i.ConnectionQualityChanged="connectionQualityChanged",i.TrackStreamStateChanged="trackStreamStateChanged",i.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",i.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",i.AudioPlaybackStatusChanged="audioPlaybackChanged",i.VideoPlaybackStatusChanged="videoPlaybackChanged",i.MediaDevicesError="mediaDevicesError",i.ParticipantPermissionsChanged="participantPermissionsChanged",i.SignalConnected="signalConnected",i.RecordingStatusChanged="recordingStatusChanged",i.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",i.EncryptionError="encryptionError",i.DCBufferStatusChanged="dcBufferStatusChanged",i.ActiveDeviceChanged="activeDeviceChanged",i.ChatMessage="chatMessage",i.LocalTrackSubscribed="localTrackSubscribed",i.MetricsReceived="metricsReceived"})(O||(O={}));var $;(function(i){i.TrackPublished="trackPublished",i.TrackSubscribed="trackSubscribed",i.TrackSubscriptionFailed="trackSubscriptionFailed",i.TrackUnpublished="trackUnpublished",i.TrackUnsubscribed="trackUnsubscribed",i.TrackMuted="trackMuted",i.TrackUnmuted="trackUnmuted",i.LocalTrackPublished="localTrackPublished",i.LocalTrackUnpublished="localTrackUnpublished",i.ParticipantMetadataChanged="participantMetadataChanged",i.ParticipantNameChanged="participantNameChanged",i.DataReceived="dataReceived",i.SipDTMFReceived="sipDTMFReceived",i.TranscriptionReceived="transcriptionReceived",i.IsSpeakingChanged="isSpeakingChanged",i.ConnectionQualityChanged="connectionQualityChanged",i.TrackStreamStateChanged="trackStreamStateChanged",i.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",i.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",i.MediaDevicesError="mediaDevicesError",i.AudioStreamAcquired="audioStreamAcquired",i.ParticipantPermissionsChanged="participantPermissionsChanged",i.PCTrackAdded="pcTrackAdded",i.AttributesChanged="attributesChanged",i.LocalTrackSubscribed="localTrackSubscribed",i.ChatMessage="chatMessage"})($||($={}));var L;(function(i){i.TransportsCreated="transportsCreated",i.Connected="connected",i.Disconnected="disconnected",i.Resuming="resuming",i.Resumed="resumed",i.Restarting="restarting",i.Restarted="restarted",i.SignalResumed="signalResumed",i.SignalRestarted="signalRestarted",i.Closing="closing",i.MediaTrackAdded="mediaTrackAdded",i.ActiveSpeakersUpdate="activeSpeakersUpdate",i.DataPacketReceived="dataPacketReceived",i.RTPVideoMapUpdate="rtpVideoMapUpdate",i.DCBufferStatusChanged="dcBufferStatusChanged",i.ParticipantUpdate="participantUpdate",i.RoomUpdate="roomUpdate",i.SpeakersChanged="speakersChanged",i.StreamStateChanged="streamStateChanged",i.ConnectionQualityUpdate="connectionQualityUpdate",i.SubscriptionError="subscriptionError",i.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",i.RemoteMute="remoteMute",i.SubscribedQualityUpdate="subscribedQualityUpdate",i.LocalTrackUnpublished="localTrackUnpublished",i.LocalTrackSubscribed="localTrackSubscribed",i.Offline="offline",i.SignalRequestResponse="signalRequestResponse",i.SignalConnected="signalConnected"})(L||(L={}));var M;(function(i){i.Message="message",i.Muted="muted",i.Unmuted="unmuted",i.Restarted="restarted",i.Ended="ended",i.Subscribed="subscribed",i.Unsubscribed="unsubscribed",i.UpdateSettings="updateSettings",i.UpdateSubscription="updateSubscription",i.AudioPlaybackStarted="audioPlaybackStarted",i.AudioPlaybackFailed="audioPlaybackFailed",i.AudioSilenceDetected="audioSilenceDetected",i.VisibilityChanged="visibilityChanged",i.VideoDimensionsChanged="videoDimensionsChanged",i.VideoPlaybackStarted="videoPlaybackStarted",i.VideoPlaybackFailed="videoPlaybackFailed",i.ElementAttached="elementAttached",i.ElementDetached="elementDetached",i.UpstreamPaused="upstreamPaused",i.UpstreamResumed="upstreamResumed",i.SubscriptionPermissionChanged="subscriptionPermissionChanged",i.SubscriptionStatusChanged="subscriptionStatusChanged",i.SubscriptionFailed="subscriptionFailed",i.TrackProcessorUpdate="trackProcessorUpdate",i.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",i.TranscriptionReceived="transcriptionReceived",i.TimeSyncUpdate="timeSyncUpdate"})(M||(M={}));function Sp(i){return typeof i>"u"?i:typeof structuredClone=="function"?structuredClone(i):JSON.parse(JSON.stringify(i))}const Tp=/version\/(\d+(\.?_?\d+)+)/i;let ta;function gt(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof i>"u"&&typeof navigator>"u")return;const t=(i??navigator.userAgent).toLowerCase();if(ta===void 0||e){const n=Cp.find(r=>{let{test:s}=r;return s.test(t)});ta=n==null?void 0:n.describe(t)}return ta}const Cp=[{test:/firefox|iceweasel|fxios/i,describe(i){return{name:"Firefox",version:Lr(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:na(i)}}},{test:/chrom|crios|crmo/i,describe(i){return{name:"Chrome",version:Lr(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("crios")?"iOS":void 0,osVersion:na(i)}}},{test:/safari|applewebkit/i,describe(i){return{name:"Safari",version:Lr(Tp,i),os:i.includes("mobile/")?"iOS":"macOS",osVersion:na(i)}}}];function Lr(i,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const n=e.match(i);return n&&n.length>=t&&n[t]||""}function na(i){return i.includes("mac os")?Lr(/\(.+?(\d+_\d+(:?_\d+)?)/,i,1).replace(/_/g,"."):void 0}var _p="2.11.4";const Ep=_p,wp=15;class Be{}Be.setTimeout=function(){return setTimeout(...arguments)},Be.setInterval=function(){return setInterval(...arguments)},Be.clearTimeout=function(){return clearTimeout(...arguments)},Be.clearInterval=function(){return clearInterval(...arguments)};const Pp=5e3,Di=[];var ot;(function(i){i[i.LOW=0]="LOW",i[i.MEDIUM=1]="MEDIUM",i[i.HIGH=2]="HIGH"})(ot||(ot={}));class R extends Rt.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var r;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=R.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=re,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),Pp):this.handleAppVisibilityChanged()},this.log=jt((r=n.loggerName)!==null&&r!==void 0?r:mt.Track),this.loggerContextCb=n.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=R.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),pe(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===R.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===R.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(Di.forEach(s=>{s.parentElement===null&&!e&&(e=s)}),e&&Di.splice(Di.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),Zn(this.mediaStreamTrack,e);const n=e.srcObject.getTracks(),r=n.some(s=>s.kind==="audio");return e.play().then(()=>{this.emit(r?M.AudioPlaybackStarted:M.VideoPlaybackStarted)}).catch(s=>{s.name==="NotAllowedError"?this.emit(r?M.AudioPlaybackFailed:M.VideoPlaybackFailed,s):s.name==="AbortError"?re.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):re.warn("could not playback ".concat(r?"audio":"video"),s),r&&e&&n.some(a=>a.kind==="video")&&s.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(M.ElementAttached,e),e}detach(e){try{if(e){Jn(this.mediaStreamTrack,e);const n=this.attachedElements.indexOf(e);return n>=0&&(this.attachedElements.splice(n,1),this.recycleElement(e),this.emit(M.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(n=>{Jn(this.mediaStreamTrack,n),t.push(n),this.recycleElement(n),this.emit(M.ElementDetached,n)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=jt(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Di.forEach(n=>{n.parentElement||(t=!1)}),t&&Di.push(e)}}handleAppVisibilityChanged(){return m(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===R.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){Xe()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Xe()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Zn(i,e){let t;e.srcObject instanceof MediaStream?t=e.srcObject:t=new MediaStream;let n;i.kind==="audio"?n=t.getAudioTracks():n=t.getVideoTracks(),n.includes(i)||(n.forEach(r=>{t.removeTrack(r)}),t.addTrack(i)),(!tn()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(tn()||Yn())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function Jn(i,e){if(e.srcObject instanceof MediaStream){const t=e.srcObject;t.removeTrack(i),t.getTracks().length>0?e.srcObject=t:e.srcObject=null}}(function(i){let e;(function(d){d.Audio="audio",d.Video="video",d.Unknown="unknown"})(e=i.Kind||(i.Kind={}));let t;(function(d){d.Camera="camera",d.Microphone="microphone",d.ScreenShare="screen_share",d.ScreenShareAudio="screen_share_audio",d.Unknown="unknown"})(t=i.Source||(i.Source={}));let n;(function(d){d.Active="active",d.Paused="paused",d.Unknown="unknown"})(n=i.StreamState||(i.StreamState={}));function r(d){switch(d){case e.Audio:return ht.AUDIO;case e.Video:return ht.VIDEO;default:return ht.DATA}}i.kindToProto=r;function s(d){switch(d){case ht.AUDIO:return e.Audio;case ht.VIDEO:return e.Video;default:return e.Unknown}}i.kindFromProto=s;function a(d){switch(d){case t.Camera:return Le.CAMERA;case t.Microphone:return Le.MICROPHONE;case t.ScreenShare:return Le.SCREEN_SHARE;case t.ScreenShareAudio:return Le.SCREEN_SHARE_AUDIO;default:return Le.UNKNOWN}}i.sourceToProto=a;function o(d){switch(d){case Le.CAMERA:return t.Camera;case Le.MICROPHONE:return t.Microphone;case Le.SCREEN_SHARE:return t.ScreenShare;case Le.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}i.sourceFromProto=o;function c(d){switch(d){case Ms.ACTIVE:return n.Active;case Ms.PAUSED:return n.Paused;default:return n.Unknown}}i.streamStateFromProto=c})(R||(R={}));class ve{constructor(e,t,n,r,s){if(typeof e=="object")this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(t!==void 0&&n!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:n,maxFramerate:r,priority:s};else throw new TypeError("Unsupported options: provide at least width, height and maxBitrate")}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const Rp=["vp8","h264"],xp=["vp8","h264","vp9","av1"];function Ip(i){return!!Rp.find(e=>e===i)}var _d;(function(i){i[i.PREFER_REGRESSION=0]="PREFER_REGRESSION",i[i.SIMULCAST=1]="SIMULCAST",i[i.REGRESSION=2]="REGRESSION"})(_d||(_d={}));var ia;(function(i){i.telephone={maxBitrate:12e3},i.speech={maxBitrate:24e3},i.music={maxBitrate:48e3},i.musicStereo={maxBitrate:64e3},i.musicHighQuality={maxBitrate:96e3},i.musicHighQualityStereo={maxBitrate:128e3}})(ia||(ia={}));const Mi={h90:new ve(160,90,9e4,20),h180:new ve(320,180,16e4,20),h216:new ve(384,216,18e4,20),h360:new ve(640,360,45e4,20),h540:new ve(960,540,8e5,25),h720:new ve(1280,720,17e5,30),h1080:new ve(1920,1080,3e6,30),h1440:new ve(2560,1440,5e6,30),h2160:new ve(3840,2160,8e6,30)},ra={h120:new ve(160,120,7e4,20),h180:new ve(240,180,125e3,20),h240:new ve(320,240,14e4,20),h360:new ve(480,360,33e4,20),h480:new ve(640,480,5e5,20),h540:new ve(720,540,6e5,25),h720:new ve(960,720,13e5,30),h1080:new ve(1440,1080,23e5,30),h1440:new ve(1920,1440,38e5,30)},sa={h360fps3:new ve(640,360,2e5,3,"medium"),h360fps15:new ve(640,360,4e5,15,"medium"),h720fps5:new ve(1280,720,8e5,5,"medium"),h720fps15:new ve(1280,720,15e5,15,"medium"),h720fps30:new ve(1280,720,2e6,30,"medium"),h1080fps15:new ve(1920,1080,25e5,15,"medium"),h1080fps30:new ve(1920,1080,5e6,30,"medium"),original:new ve(0,0,7e6,30,"medium")},Op="|",Ed="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Ap(i){const e=i.split(Op);return e.length>1?[e[0],i.substr(e[0].length+1)]:[i,""]}function Qe(i){return m(this,void 0,void 0,function*(){return new Promise(e=>Be.setTimeout(e,i))})}function aa(){return"addTransceiver"in RTCPeerConnection.prototype}function oa(){return"addTrack"in RTCPeerConnection.prototype}function Dp(){if(!("getCapabilities"in RTCRtpSender)||tn())return!1;const i=RTCRtpSender.getCapabilities("video");let e=!1;if(i){for(const t of i.codecs)if(t.mimeType==="video/AV1"){e=!0;break}}return e}function Mp(){if(!("getCapabilities"in RTCRtpSender)||Yn())return!1;if(tn()){const t=gt();if(t!=null&&t.version&&wn(t.version,"16")<0)return!1}const i=RTCRtpSender.getCapabilities("video");let e=!1;if(i){for(const t of i.codecs)if(t.mimeType==="video/VP9"){e=!0;break}}return e}function Ni(i){return i==="av1"||i==="vp9"}function ca(i){return document?(i||(i=document.createElement("audio")),"setSinkId"in i):!1}function Np(){return typeof RTCPeerConnection>"u"?!1:aa()||oa()}function Yn(){var i;return((i=gt())===null||i===void 0?void 0:i.name)==="Firefox"}function tn(){var i;return((i=gt())===null||i===void 0?void 0:i.name)==="Safari"}function Lp(){const i=gt();return(i==null?void 0:i.name)==="Safari"&&i.version.startsWith("17.")}function wd(){var i,e;return Xe()?(e=(i=navigator.userAgentData)===null||i===void 0?void 0:i.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function Up(){const i=gt(),e="17.2";if(i)return i.name!=="Safari"&&i.os!=="iOS"||i.os==="iOS"&&i.osVersion&&wn(e,i.osVersion)>=0?!0:i.name==="Safari"&&wn(e,i.version)>=0}function Xe(){return typeof document<"u"}function xt(){return navigator.product=="ReactNative"}function da(i){return i.hostname.endsWith(".livekit.cloud")||i.hostname.endsWith(".livekit.run")}function Pd(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Rd(){if(!xt())return;let i=Pd();if(i)return i.platform}function xd(){if(Xe())return window.devicePixelRatio;if(xt()){let i=Pd();if(i)return i.devicePixelRatio}return 1}function wn(i,e){const t=i.split("."),n=e.split("."),r=Math.min(t.length,n.length);for(let s=0;s<r;++s){const a=parseInt(t[s],10),o=parseInt(n[s],10);if(a>o)return 1;if(a<o)return-1;if(s===r-1&&a===o)return 0}return i===""&&e!==""?-1:e===""?1:t.length==n.length?0:t.length<n.length?-1:1}function jp(i){for(const e of i)e.target.handleResize(e)}function Fp(i){for(const e of i)e.target.handleVisibilityChanged(e)}let ua=null;const Id=()=>(ua||(ua=new ResizeObserver(jp)),ua);let la=null;const Od=()=>(la||(la=new IntersectionObserver(Fp,{root:null,rootMargin:"0px"})),la);function $p(){var i;const e=new If({sdk:mc.JS,protocol:wp,version:Ep});return xt()&&(e.os=(i=Rd())!==null&&i!==void 0?i:""),e}function Ad(){let i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const r=document.createElement("canvas");r.width=i,r.height=e;const s=r.getContext("2d");s==null||s.fillRect(0,0,r.width,r.height),n&&s&&(s.beginPath(),s.arc(i/2,e/2,50,0,Math.PI*2,!0),s.closePath(),s.fillStyle="grey",s.fill());const a=r.captureStream(),[o]=a.getTracks();if(!o)throw Error("Could not get empty media stream video track");return o.enabled=t,o}let Li;function ha(){if(!Li){const i=new AudioContext,e=i.createOscillator(),t=i.createGain();t.gain.setValueAtTime(0,0);const n=i.createMediaStreamDestination();if(e.connect(t),t.connect(n),e.start(),[Li]=n.stream.getAudioTracks(),!Li)throw Error("Could not get empty media stream audio track");Li.enabled=!1}return Li.clone()}class Dd{constructor(e,t){this.onFinally=t,this.promise=new Promise((n,r)=>m(this,void 0,void 0,function*(){this.resolve=n,this.reject=r,e&&(yield e(n,r))})).finally(()=>{var n;return(n=this.onFinally)===null||n===void 0?void 0:n.call(this)})}}function Bp(i){return xp.includes(i)}function nn(i){if(typeof i=="string"||typeof i=="number")return i;if(Array.isArray(i))return i[0];if(i.exact)return Array.isArray(i.exact)?i.exact[0]:i.exact;if(i.ideal)return Array.isArray(i.ideal)?i.ideal[0]:i.ideal;throw Error("could not unwrap constraint")}function Vp(i){return i.startsWith("http")?i.replace(/^(http)/,"ws"):i}function fa(i){return i.startsWith("ws")?i.replace(/^(ws)/,"http"):i}function qp(i,e){return i.segments.map(t=>{let{id:n,text:r,language:s,startTime:a,endTime:o,final:c}=t;var d;const u=(d=e.get(n))!==null&&d!==void 0?d:Date.now(),h=Date.now();return c?e.delete(n):e.set(n,u),{id:n,text:r,startTime:Number.parseInt(a.toString()),endTime:Number.parseInt(o.toString()),final:c,language:s,firstReceivedTime:u,lastReceivedTime:h}})}function zp(i){const{id:e,timestamp:t,message:n,editTimestamp:r}=i;return{id:e,timestamp:Number.parseInt(t.toString()),editTimestamp:r?Number.parseInt(r.toString()):void 0,message:n}}function Md(i){switch(i.reason){case oe.LeaveRequest:return i.context;case oe.Cancelled:return ft.CLIENT_INITIATED;case oe.NotAllowed:return ft.USER_REJECTED;case oe.ServerUnreachable:return ft.JOIN_FAILURE;default:return ft.UNKNOWN_REASON}}function Ur(i){return i!==void 0?Number(i):void 0}function Pn(i){return i!==void 0?BigInt(i):void 0}function Qn(i){return!!i&&!(i instanceof MediaStreamTrack)&&i.isLocal}function $t(i){return!!i&&i.kind==R.Kind.Audio}function Xn(i){return!!i&&i.kind==R.Kind.Video}function rn(i){return Qn(i)&&Xn(i)}function Rn(i){return Qn(i)&&$t(i)}function pa(i){return!!i&&!i.isLocal}function Wp(i){return!!i&&!i.isLocal}function ma(i){return pa(i)&&Xn(i)}function Gp(i){return i.isLocal}function Kp(i,e){const t=[];let n=new TextEncoder().encode(i);for(;n.length>e;){let r=e;for(;r>0;){const s=n[r];if(s!==void 0&&(s&192)!==128)break;r--}t.push(n.slice(0,r)),n=n.slice(r)}return n.length>0&&t.push(n),t}function Nd(i,e,t){var n,r,s,a;const{optionsWithoutProcessor:o,audioProcessor:c,videoProcessor:d}=Fd(i??{}),u=e==null?void 0:e.processor,h=t==null?void 0:t.processor,f=o??{};return f.audio===!0&&(f.audio={}),f.video===!0&&(f.video={}),f.audio&&(ga(f.audio,e),(n=(s=f.audio).deviceId)!==null&&n!==void 0||(s.deviceId={ideal:"default"}),(c||u)&&(f.audio.processor=c??u)),f.video&&(ga(f.video,t),(r=(a=f.video).deviceId)!==null&&r!==void 0||(a.deviceId={ideal:"default"}),(d||h)&&(f.video.processor=d??h)),f}function ga(i,e){return Object.keys(e).forEach(t=>{i[t]===void 0&&(i[t]=e[t])}),i}function va(i){var e,t,n,r;const s={};if(i.video)if(typeof i.video=="object"){const a={},o=a,c=i.video;Object.keys(c).forEach(d=>{switch(d){case"resolution":ga(o,c.resolution);break;default:o[d]=c[d]}}),s.video=a,(e=(n=s.video).deviceId)!==null&&e!==void 0||(n.deviceId={ideal:"default"})}else s.video=i.video?{deviceId:{ideal:"default"}}:!1;else s.video=!1;return i.audio?typeof i.audio=="object"?(s.audio=i.audio,(t=(r=s.audio).deviceId)!==null&&t!==void 0||(r.deviceId={ideal:"default"})):s.audio={deviceId:{ideal:"default"}}:s.audio=!1,s}function Ld(i){return m(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){const n=Ud();if(n){const r=n.createAnalyser();r.fftSize=2048;const s=r.frequencyBinCount,a=new Uint8Array(s);n.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(r),yield Qe(t),r.getByteTimeDomainData(a);const c=a.some(d=>d!==128&&d!==0);return n.close(),!c}return!1}()})}function Ud(){var i;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const t=new e({latencyHint:"interactive"});if(t.state==="suspended"&&typeof window<"u"&&(!((i=window.document)===null||i===void 0)&&i.body)){const n=()=>m(this,void 0,void 0,function*(){var r;try{t.state==="suspended"&&(yield t.resume())}catch(s){console.warn("Error trying to auto-resume audio context",s)}(r=window.document.body)===null||r===void 0||r.removeEventListener("click",n)});window.document.body.addEventListener("click",n)}return t}}function Hp(i){return i==="audioinput"?R.Source.Microphone:i==="videoinput"?R.Source.Camera:R.Source.Unknown}function jd(i){return i===R.Source.Microphone?"audioinput":i===R.Source.Camera?"videoinput":void 0}function Zp(i){var e,t;let n=(e=i.video)!==null&&e!==void 0?e:!0;return i.resolution&&i.resolution.width>0&&i.resolution.height>0&&(n=typeof n=="boolean"?{}:n,tn()?n=Object.assign(Object.assign({},n),{width:{max:i.resolution.width},height:{max:i.resolution.height},frameRate:i.resolution.frameRate}):n=Object.assign(Object.assign({},n),{width:{ideal:i.resolution.width},height:{ideal:i.resolution.height},frameRate:i.resolution.frameRate})),{audio:(t=i.audio)!==null&&t!==void 0?t:!1,video:n,controller:i.controller,selfBrowserSurface:i.selfBrowserSurface,surfaceSwitching:i.surfaceSwitching,systemAudio:i.systemAudio,preferCurrentTab:i.preferCurrentTab}}function jr(i){return i.split("/")[1].toLowerCase()}function Jp(i){const e=[];return i.forEach(t=>{t.track!==void 0&&e.push(new Fs({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function pe(i){return"mediaStreamTrack"in i?{trackID:i.sid,source:i.source,muted:i.isMuted,enabled:i.mediaStreamTrack.enabled,kind:i.kind,streamID:i.mediaStreamID,streamTrackID:i.mediaStreamTrack.id}:{trackID:i.trackSid,enabled:i.isEnabled,muted:i.isMuted,trackInfo:Object.assign({mimeType:i.mimeType,name:i.trackName,encrypted:i.isEncrypted,kind:i.kind,source:i.source},i.track?pe(i.track):{})}}function Yp(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function Qp(i,e){var t;i===void 0&&(i={}),e===void 0&&(e={});const n=[...Object.keys(e),...Object.keys(i)],r={};for(const s of n)i[s]!==e[s]&&(r[s]=(t=e[s])!==null&&t!==void 0?t:"");return r}function Fd(i){const e=Object.assign({},i);let t,n;return typeof e.audio=="object"&&e.audio.processor&&(t=e.audio.processor,e.audio=Object.assign(Object.assign({},e.audio),{processor:void 0})),typeof e.video=="object"&&e.video.processor&&(n=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:t,videoProcessor:n,optionsWithoutProcessor:Sp(e)}}function Xp(i){switch(i){case Le.CAMERA:return R.Source.Camera;case Le.MICROPHONE:return R.Source.Microphone;case Le.SCREEN_SHARE:return R.Source.ScreenShare;case Le.SCREEN_SHARE_AUDIO:return R.Source.ScreenShareAudio;default:return R.Source.Unknown}}class em extends Rt.EventEmitter{constructor(e){super(),this.onWorkerMessage=t=>{var n,r;const{kind:s,data:a}=t.data;switch(s){case"error":re.error(a.error.message),this.emit(Xt.EncryptionError,a.error);break;case"initAck":a.enabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)});break;case"enable":if(a.enabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)}),this.encryptionEnabled!==a.enabled&&a.participantIdentity===((n=this.room)===null||n===void 0?void 0:n.localParticipant.identity))this.emit(Xt.ParticipantEncryptionStatusChanged,a.enabled,this.room.localParticipant),this.encryptionEnabled=a.enabled;else if(a.participantIdentity){const o=(r=this.room)===null||r===void 0?void 0:r.getParticipantByIdentity(a.participantIdentity);if(!o)throw TypeError("couldn't set encryption status, participant not found".concat(a.participantIdentity));this.emit(Xt.ParticipantEncryptionStatusChanged,a.enabled,o)}break;case"ratchetKey":this.keyProvider.emit(Qt.KeyRatcheted,a.material,a.keyIndex);break}},this.onWorkerError=t=>{re.error("e2ee worker encountered an error:",{error:t.error}),this.emit(Xt.EncryptionError,t.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!yp())throw new Qs("tried to setup end-to-end encryption on an unsupported browser");if(re.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:ip.getLevel()}};this.worker&&(re.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){re.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?re.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(L.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(O.TrackPublished,(n,r)=>this.setParticipantCryptorEnabled(n.trackInfo.encryption!==it.NONE,r.identity)),e.on(O.ConnectionStateChanged,n=>{n===fe.Connected&&e.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{this.setParticipantCryptorEnabled(s.trackInfo.encryption!==it.NONE,r.identity)})})}).on(O.TrackUnsubscribed,(n,r,s)=>{var a;const o={kind:"removeTransform",data:{participantIdentity:s.identity,trackId:n.mediaStreamID}};(a=this.worker)===null||a===void 0||a.postMessage(o)}).on(O.TrackSubscribed,(n,r,s)=>{this.setupE2EEReceiver(n,s.identity,r.trackInfo)}).on(O.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach(n=>{this.postKey(n)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on($.LocalTrackPublished,n=>m(this,void 0,void 0,function*(){this.setupE2EESender(n.track,n.track.sender)})),t.on(Qt.SetKey,n=>this.postKey(n)).on(Qt.RatchetRequest,(n,r)=>this.postRatchetRequest(n,r))}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const n={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(n)}postKey(e){let{key:t,participantIdentity:n,keyIndex:r}=e;var s;if(!this.worker)throw Error("could not set key, worker is missing");const a={kind:"setKey",data:{participantIdentity:n,isPublisher:n===((s=this.room)===null||s===void 0?void 0:s.localParticipant.identity),key:t,keyIndex:r}};this.worker.postMessage(a)}postEnable(e,t){if(this.worker){const n={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(n)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((t=this.room)===null||t===void 0)&&t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const n={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(n)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,n){if(e.receiver){if(!(n!=null&&n.mimeType)||n.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?jr(n.mimeType):void 0)}}setupE2EESender(e,t){if(!Qn(e)||!t){t||re.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,n,r){return m(this,void 0,void 0,function*(){if(this.worker){if(Ys()){const s={kind:"decode",participantIdentity:n,trackId:t,codec:r};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(Mr in e&&r){const c={kind:"updateCodec",data:{trackId:t,codec:r,participantIdentity:n}};this.worker.postMessage(c);return}let s=e.writableStream,a=e.readableStream;if(!s||!a){const c=e.createEncodedStreams();e.writableStream=c.writable,s=c.writable,e.readableStream=c.readable,a=c.readable}const o={kind:"decode",data:{readableStream:a,writableStream:s,trackId:t,codec:r,participantIdentity:n}};this.worker.postMessage(o,[a,s])}e[Mr]=!0}})}handleSender(e,t,n){var r;if(!(Mr in e||!this.worker)){if(!(!((r=this.room)===null||r===void 0)&&r.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(Ys()){re.info("initialize script transform");const s={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{re.info("initialize encoded streams");const s=e.createEncodedStreams(),a={kind:"encode",data:{readableStream:s.readable,writableStream:s.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(a,[s.readable,s.writable])}e[Mr]=!0}}}const ya="default";class $e{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new $e),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return m(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var s;if(((s=$e.userMediaPromiseMap)===null||s===void 0?void 0:s.size)>0){re.debug("awaiting getUserMedia promise");try{t?yield $e.userMediaPromiseMap.get(t):yield Promise.all($e.userMediaPromiseMap.values())}catch{re.warn("error waiting for media permissons")}}let a=yield navigator.mediaDevices.enumerateDevices();if(r&&!(tn()&&n.hasDeviceInUse(t))&&(a.filter(c=>c.kind===t).length===0||a.some(c=>{const d=c.label==="",u=t?c.kind===t:!0;return d&&u}))){const c={video:t!=="audioinput"&&t!=="audiooutput",audio:t!=="videoinput"&&{deviceId:{ideal:"default"}}},d=yield navigator.mediaDevices.getUserMedia(c);a=yield navigator.mediaDevices.enumerateDevices(),d.getTracks().forEach(u=>{u.stop()})}return n._previousDevices=a,t&&(a=a.filter(o=>o.kind===t)),a}()})}normalizeDeviceId(e,t,n){return m(this,void 0,void 0,function*(){if(t!==ya)return t;const r=yield this.getDevices(e),s=r.find(o=>o.deviceId===ya);if(!s){re.warn("could not reliably determine default device");return}const a=r.find(o=>o.deviceId!==ya&&o.groupId===(n??s.groupId));if(!a){re.warn("could not reliably determine default device");return}return a==null?void 0:a.deviceId})}hasDeviceInUse(e){return e?$e.userMediaPromiseMap.has(e):$e.userMediaPromiseMap.size>0}}$e.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],$e.userMediaPromiseMap=new Map;var Ui;(function(i){i[i.WAITING=0]="WAITING",i[i.RUNNING=1]="RUNNING",i[i.COMPLETED=2]="COMPLETED"})(Ui||(Ui={}));class tm{constructor(){this.pendingTasks=new Map,this.taskMutex=new Ze,this.nextTaskIndex=0}run(e){return m(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Ui.WAITING};this.pendingTasks.set(t.id,t);const n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Ui.RUNNING,yield e()}finally{t.status=Ui.COMPLETED,this.pendingTasks.delete(t.id),n()}})}flush(){return m(this,void 0,void 0,function*(){return this.run(()=>m(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}function nm(i,e){const t=new URL(Vp(i));return e.forEach((n,r)=>{t.searchParams.set(r,n)}),$d(t,"rtc")}function im(i){const e=new URL(fa(i));return $d(e,"validate")}function rm(i){return i.endsWith("/")?i:"".concat(i,"/")}function $d(i,e){return i.pathname="".concat(rm(i.pathname)).concat(e),i.toString()}const sm=["syncState","trickle","offer","answer","simulate","leave"];function am(i){const e=sm.indexOf(i.case)>=0;return re.trace("request allowed to bypass queue:",{canPass:e,req:i}),e}var Se;(function(i){i[i.CONNECTING=0]="CONNECTING",i[i.CONNECTED=1]="CONNECTED",i[i.RECONNECTING=2]="RECONNECTING",i[i.DISCONNECTING=3]="DISCONNECTING",i[i.DISCONNECTED=4]="DISCONNECTED"})(Se||(Se={}));class ba{get currentState(){return this.state}get isDisconnected(){return this.state===Se.DISCONNECTING||this.state===Se.DISCONNECTED}get isEstablishingConnection(){return this.state===Se.CONNECTING||this.state===Se.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var n;this.rtt=0,this.state=Se.DISCONNECTED,this.log=re,this._requestId=0,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0},this.log=jt((n=t.loggerName)!==null&&n!==void 0?n:mt.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new tm,this.queuedRequests=[],this.closingLock=new Ze,this.connectionLock=new Ze,this.state=Se.DISCONNECTED}get logContext(){var e,t;return(t=(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this))!==null&&t!==void 0?t:{}}join(e,t,n,r){return m(this,void 0,void 0,function*(){return this.state=Se.CONNECTING,this.options=n,yield this.connect(e,t,n,r)})}reconnect(e,t,n,r){return m(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);return}return this.state=Se.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:r}))})}connect(e,t,n,r){this.connectOptions=n;const s=$p(),a=om(t,s,n),o=nm(e,a),c=im(o);return new Promise((d,u)=>m(this,void 0,void 0,function*(){const h=yield this.connectionLock.lock();try{const f=()=>m(this,void 0,void 0,function*(){this.close(),clearTimeout(g),u(new ye("room connection has been cancelled (signal)",oe.Cancelled))}),g=setTimeout(()=>{this.close(),u(new ye("room connection has timed out (signal)",oe.ServerUnreachable))},n.websocketTimeout);r!=null&&r.aborted&&f(),r==null||r.addEventListener("abort",f);const y=new URL(o);y.searchParams.has("access_token")&&y.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(y),Object.assign({reconnect:n.reconnect,reconnectReason:n.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(o),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(g)},this.ws.onerror=v=>m(this,void 0,void 0,function*(){if(this.state!==Se.CONNECTED){this.state=Se.DISCONNECTED,clearTimeout(g);try{const _=yield fetch(c);if(_.status.toFixed(0).startsWith("4")){const w=yield _.text();u(new ye(w,oe.NotAllowed,_.status))}else u(new ye("Encountered unknown websocket error during connection: ".concat(v.toString()),oe.InternalError,_.status))}catch(_){u(new ye(_ instanceof Error?_.message:"server was not reachable",oe.ServerUnreachable))}return}this.handleWSError(v)}),this.ws.onmessage=v=>m(this,void 0,void 0,function*(){var _,w,N;let U;if(typeof v.data=="string"){const b=JSON.parse(v.data);U=Sc.fromJson(b,{ignoreUnknownFields:!0})}else if(v.data instanceof ArrayBuffer)U=Sc.fromBinary(new Uint8Array(v.data));else{this.log.error("could not decode websocket message: ".concat(typeof v.data),this.logContext);return}if(this.state!==Se.CONNECTED){let b=!1;if(((_=U.message)===null||_===void 0?void 0:_.case)==="join"?(this.state=Se.CONNECTED,r==null||r.removeEventListener("abort",f),this.pingTimeoutDuration=U.message.value.pingTimeout,this.pingIntervalDuration=U.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.startPingInterval()),d(U.message.value)):this.state===Se.RECONNECTING&&U.message.case!=="leave"?(this.state=Se.CONNECTED,r==null||r.removeEventListener("abort",f),this.startPingInterval(),((w=U.message)===null||w===void 0?void 0:w.case)==="reconnect"?d(U.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),d(void 0),b=!0)):this.isEstablishingConnection&&U.message.case==="leave"?u(new ye("Received leave request while trying to (re)connect",oe.LeaveRequest,void 0,U.message.value.reason)):n.reconnect||u(new ye("did not receive join response, got ".concat((N=U.message)===null||N===void 0?void 0:N.case," instead"),oe.InternalError)),!b)return}this.signalLatency&&(yield Qe(this.signalLatency)),this.handleSignalResponse(U)}),this.ws.onclose=v=>{this.isEstablishingConnection&&u(new ye("Websocket got closed during a (re)connection attempt",oe.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:v.reason,code:v.code,wasClean:v.wasClean,state:this.state})),this.handleOnClose(v.reason)}}finally{h()}}))}close(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){const n=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=Se.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;const r=new Promise(s=>{e.ws?e.ws.onclose=()=>{s()}:s()});e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([r,Qe(250)])),e.ws=void 0}}finally{t&&(e.state=Se.DISCONNECTED),n()}}()})}sendOffer(e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Fr(e)})}sendAnswer(e){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:Fr(e)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new Us({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new js({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return m(this,arguments,void 0,function(n,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return function*(){const o=s.getNextRequestId();return yield s.sendRequest({case:"updateMetadata",value:new Ec({requestId:o,metadata:n,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 _c({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Rc({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:_e.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Oc({timestamp:_e.parse(Date.now()),rtt:_e.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new Cc({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new _r({reason:ft.CLIENT_INITIATED,action:Kn.DISCONNECT})})}sendRequest(e){return m(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return function*(){if(!r&&!am(t)&&n.state===Se.RECONNECTING){n.queuedRequests.push(()=>m(n,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(r||(yield n.requestQueue.flush()),n.signalLatency&&(yield Qe(n.signalLatency)),!n.ws||n.ws.readyState!==n.ws.OPEN){n.log.error("cannot send signal request before connected, type: ".concat(t==null?void 0:t.case),n.logContext);return}const a=new Df({message:t});try{n.useJSON?n.ws.send(a.toJsonString()):n.ws.send(a.toBinary())}catch(o){n.log.error("error sending signal message",Object.assign(Object.assign({},n.logContext),{error:o}))}}()})}handleSignalResponse(e){var t,n;const r=e.message;if(r==null){this.log.debug("received unsupported message",this.logContext);return}let s=!1;if(r.case==="answer"){const a=Bd(r.value);this.onAnswer&&this.onAnswer(a)}else if(r.case==="offer"){const a=Bd(r.value);this.onOffer&&this.onOffer(a)}else if(r.case==="trickle"){const a=JSON.parse(r.value.candidateInit);this.onTrickle&&this.onTrickle(a,r.value.target)}else r.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((t=r.value.participants)!==null&&t!==void 0?t:[]):r.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(r.value):r.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((n=r.value.speakers)!==null&&n!==void 0?n:[]):r.case==="leave"?this.onLeave&&this.onLeave(r.value):r.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(r.value.sid,r.value.muted):r.case==="roomUpdate"?this.onRoomUpdate&&r.value.room&&this.onRoomUpdate(r.value.room):r.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(r.value):r.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(r.value):r.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(r.value):r.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(r.value):r.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(r.value):r.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(r.value):r.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(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.onRequestResponse&&this.onRequestResponse(r.value):r.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(r.value.trackSid):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:r.case})));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return m(this,void 0,void 0,function*(){if(this.state===Se.DISCONNECTED)return;const t=this.onClose;yield this.close(),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)})}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set",this.logContext);return}this.pingTimeout=Be.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&Be.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn("ping interval duration not set",this.logContext);return}this.log.debug("start ping interval",this.logContext),this.pingInterval=Be.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&Be.clearInterval(this.pingInterval)}}function Bd(i){const e={type:"offer",sdp:i.sdp};switch(i.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=i.type;break}return e}function Fr(i){return new _n({sdp:i.sdp,type:i.type})}function om(i,e,t){var n;const r=new URLSearchParams;return r.set("access_token",i),t.reconnect&&(r.set("reconnect","1"),t.sid&&r.set("sid",t.sid)),r.set("auto_subscribe",t.autoSubscribe?"1":"0"),r.set("sdk",xt()?"reactnative":"js"),r.set("version",e.version),r.set("protocol",e.protocol.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.reconnectReason&&r.set("reconnect_reason",t.reconnectReason.toString()),!((n=navigator.connection)===null||n===void 0)&&n.type&&r.set("network",navigator.connection.type),r}var vt={},ka={},Sa={exports:{}},Vd;function Ta(){if(Vd)return Sa.exports;Vd=1;var i=Sa.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return e.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return e.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return e.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=e.raddr!=null?" raddr %s rport %d":"%v%v",t+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(t+=" generation %d"),t+=e["network-id"]!=null?" network-id %d":"%v",t+=e["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return e.attribute!=null&&(t+=" %s",e.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return e.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(e.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=e.id!=null?"id=%s %s":"%v%s",t+=e.mediaClockValue!=null?"=%s":"",t+=e.rateNumerator!=null?" rate=%s":"",t+=e.rateDenominator!=null?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(i).forEach(function(e){var t=i[e];t.forEach(function(n){n.reg||(n.reg=/(.*)/),n.format||(n.format="%s")})}),Sa.exports}var qd;function cm(){return qd||(qd=1,function(i){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,c,d,u){if(u&&!d)c[u]=e(o[1]);else for(var h=0;h<d.length;h+=1)o[h+1]!=null&&(c[d[h]]=e(o[h+1]))},n=function(o,c,d){var u=o.name&&o.names;o.push&&!c[o.push]?c[o.push]=[]:u&&!c[o.name]&&(c[o.name]={});var h=o.push?{}:u?c[o.name]:c;t(d.match(o.reg),h,o.names,o.name),o.push&&c[o.push].push(h)},r=Ta(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);i.parse=function(o){var c={},d=[],u=c;return o.split(/(\r\n|\r|\n)/).filter(s).forEach(function(h){var f=h[0],g=h.slice(2);f==="m"&&(d.push({rtp:[],fmtp:[]}),u=d[d.length-1]);for(var y=0;y<(r[f]||[]).length;y+=1){var v=r[f][y];if(v.reg.test(g))return n(v,u,g)}}),c.media=d,c};var a=function(o,c){var d=c.split(/=(.+)/,2);return d.length===2?o[d[0]]=e(d[1]):d.length===1&&c.length>1&&(o[d[0]]=void 0),o};i.parseParams=function(o){return o.split(/;\s?/).reduce(a,{})},i.parseFmtpConfig=i.parseParams,i.parsePayloads=function(o){return o.toString().split(" ").map(Number)},i.parseRemoteCandidates=function(o){for(var c=[],d=o.split(" ").map(e),u=0;u<d.length;u+=3)c.push({component:d[u],ip:d[u+1],port:d[u+2]});return c},i.parseImageAttributes=function(o){return o.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(a,{})})},i.parseSimulcastStreamList=function(o){return o.split(";").map(function(c){return c.split(",").map(function(d){var u,h=!1;return d[0]!=="~"?u=e(d):(u=e(d.substring(1,d.length)),h=!0),{scid:u,paused:h}})})}}(ka)),ka}var Ca,zd;function dm(){if(zd)return Ca;zd=1;var i=Ta(),e=/%[sdv%]/g,t=function(a){var o=1,c=arguments,d=c.length;return a.replace(e,function(u){if(o>=d)return u;var h=c[o];switch(o+=1,u){case"%%":return"%";case"%s":return String(h);case"%d":return Number(h);case"%v":return""}})},n=function(a,o,c){var d=o.format instanceof Function?o.format(o.push?c:c[o.name]):o.format,u=[a+"="+d];if(o.names)for(var h=0;h<o.names.length;h+=1){var f=o.names[h];o.name?u.push(c[o.name][f]):u.push(c[o.names[h]])}else u.push(c[o.name]);return t.apply(null,u)},r=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["i","c","b","a"];return Ca=function(a,o){o=o||{},a.version==null&&(a.version=0),a.name==null&&(a.name=" "),a.media.forEach(function(h){h.payloads==null&&(h.payloads="")});var c=o.outerOrder||r,d=o.innerOrder||s,u=[];return c.forEach(function(h){i[h].forEach(function(f){f.name in a&&a[f.name]!=null?u.push(n(h,f,a)):f.push in a&&a[f.push]!=null&&a[f.push].forEach(function(g){u.push(n(h,f,g))})})}),a.media.forEach(function(h){u.push(n("m",i.m[0],h)),d.forEach(function(f){i[f].forEach(function(g){g.name in h&&h[g.name]!=null?u.push(n(f,g,h)):g.push in h&&h[g.push]!=null&&h[g.push].forEach(function(y){u.push(n(f,g,y))})})})}),u.join(`\r
37
+ `)+`\r
38
+ `},Ca}var Wd;function um(){if(Wd)return vt;Wd=1;var i=cm(),e=dm(),t=Ta();return vt.grammar=t,vt.write=e,vt.parse=i.parse,vt.parseParams=i.parseParams,vt.parseFmtpConfig=i.parseFmtpConfig,vt.parsePayloads=i.parsePayloads,vt.parseRemoteCandidates=i.parseRemoteCandidates,vt.parseImageAttributes=i.parseImageAttributes,vt.parseSimulcastStreamList=i.parseSimulcastStreamList,vt}var sn=um();function _a(i,e,t){var n,r,s;e===void 0&&(e=50),t===void 0&&(t={});var a=(n=t.isImmediate)!=null&&n,o=(r=t.callback)!=null&&r,c=t.maxWait,d=Date.now(),u=[];function h(){if(c!==void 0){var g=Date.now()-d;if(g+e>=c)return c-g}return e}var f=function(){var g=[].slice.call(arguments),y=this;return new Promise(function(v,_){var w=a&&s===void 0;if(s!==void 0&&clearTimeout(s),s=setTimeout(function(){if(s=void 0,d=Date.now(),!a){var U=i.apply(y,g);o&&o(U),u.forEach(function(b){return(0,b.resolve)(U)}),u=[]}},h()),w){var N=i.apply(y,g);return o&&o(N),v(N)}u.push({resolve:v,reject:_})})};return f.cancel=function(g){s!==void 0&&clearTimeout(s),u.forEach(function(y){return(0,y.reject)(g)}),u=[]},f}const lm=.7,hm=20,ei={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class Gd extends Rt.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var n;super(),this.log=re,this.ddExtID=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=_a(r=>m(this,void 0,void 0,function*(){this.emit(ei.NegotiationStarted);try{yield this.createAndSendOffer()}catch(s){if(r)r(s);else throw s}}),hm),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=jt((n=t.loggerName)!==null&&n!==void 0?n:mt.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC()}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var n;t.candidate&&((n=this.onIceCandidate)===null||n===void 0||n.call(this,t.candidate))},e.onicecandidateerror=t=>{var n;(n=this.onIceCandidateError)===null||n===void 0||n.call(this,t)},e.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,e.connectionState)},e.ondatachannel=t=>{var n;(n=this.onDataChannel)===null||n===void 0||n.call(this,t)},e.ontrack=t=>{var n;(n=this.onTrack)===null||n===void 0||n.call(this,t)},e}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return m(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e){return m(this,void 0,void 0,function*(){var t;let n;if(e.type==="offer"){let{stereoMids:r,nackMids:s}=fm(e);this.remoteStereoMids=r,this.remoteNackMids=s}else if(e.type==="answer"){const r=sn.parse((t=e.sdp)!==null&&t!==void 0?t:"");r.media.forEach(s=>{s.type==="audio"&&this.trackBitrates.some(a=>{if(!a.transceiver||s.mid!=a.transceiver.mid)return!1;let o=0;if(s.rtp.some(d=>d.codec.toUpperCase()===a.codec.toUpperCase()?(o=d.payload,!0):!1),o===0)return!0;let c=!1;for(const d of s.fmtp)if(d.payload===o){d.config=d.config.split(";").filter(u=>!u.includes("maxaveragebitrate")).join(";"),a.maxbr>0&&(d.config+=";maxaveragebitrate=".concat(a.maxbr*1e3)),c=!0;break}return c||a.maxbr>0&&s.fmtp.push({payload:o,config:"maxaveragebitrate=".concat(a.maxbr*1e3)}),!0})}),n=sn.write(r)}yield this.setMungedSDP(e,n,!0),this.pendingCandidates.forEach(r=>{this.pc.addIceCandidate(r)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(ei.NegotiationComplete),e.sdp&&sn.parse(e.sdp).media.forEach(s=>{s.type==="video"&&this.emit(ei.RTPVideoPayloadTypes,s.rtp)}))})}createAndSendOffer(e){return m(this,void 0,void 0,function*(){var t;if(this.onOffer===void 0)return;if(e!=null&&e.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const s=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&s)yield this._pc.setRemoteDescription(s);else{this.renegotiate=!0;return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const n=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:n.sdp},this.logContext));const r=sn.parse((t=n.sdp)!==null&&t!==void 0?t:"");r.media.forEach(s=>{Hd(s),s.type==="audio"?Kd(s,[],[]):s.type==="video"&&this.trackBitrates.some(a=>{if(!s.msid||!a.cid||!s.msid.includes(a.cid))return!1;let o=0;if(s.rtp.some(d=>d.codec.toUpperCase()===a.codec.toUpperCase()?(o=d.payload,!0):!1),o===0||(Ni(a.codec)&&this.ensureVideoDDExtensionForSVC(s,r),a.codec!=="av1"))return!0;const c=Math.round(a.maxbr*lm);for(const d of s.fmtp)if(d.payload===o){d.config.includes("x-google-start-bitrate")||(d.config+=";x-google-start-bitrate=".concat(c));break}return!0})}),yield this.setMungedSDP(n,sn.write(r)),this.onOffer(n)})}createAndSetAnswer(){return m(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),n=sn.parse((e=t.sdp)!==null&&e!==void 0?e:"");return n.media.forEach(r=>{Hd(r),r.type==="audio"&&Kd(r,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,sn.write(n)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new Fe("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new Fe("PC closed, cannot configure");return(t=this._pc)===null||t===void 0?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var t;return(t=this._pc)===null||t===void 0?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&t!==void 0?t:"closed"}getICEConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&t!==void 0?t:"closed"}getSignallingState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&t!==void 0?t:"closed"}getTransceivers(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[]}getSenders(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&t!==void 0?t:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return m(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const n=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),n.set(o.id,o);break;case"remote-candidate":r.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const a=(e=n.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(a!==void 0)return r.get(a)})}setMungedSDP(e,t,n){return m(this,void 0,void 0,function*(){if(t){const r=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(n?"remote":"local"," description"),this.logContext),n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(s){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:s,sdp:t})),e.sdp=r}}try{n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(r){let s="unknown error";r instanceof Error?s=r.message:typeof r=="string"&&(s=r);const a={error:s,sdp:e.sdp};throw!n&&this.pc.remoteDescription&&(a.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:a})),new Xs(s)}})}ensureVideoDDExtensionForSVC(e,t){var n,r;if(!((n=e.ext)===null||n===void 0?void 0:n.some(a=>a.uri===Ed))){if(this.ddExtID===0){let a=0;t.media.forEach(o=>{var c;o.type==="video"&&((c=o.ext)===null||c===void 0||c.forEach(d=>{d.value>a&&(a=d.value)}))}),this.ddExtID=a+1}(r=e.ext)===null||r===void 0||r.push({value:this.ddExtID,uri:Ed})}}}function Kd(i,e,t){let n=0;i.rtp.some(r=>r.codec==="opus"?(n=r.payload,!0):!1),n>0&&(i.rtcpFb||(i.rtcpFb=[]),t.includes(i.mid)&&!i.rtcpFb.some(r=>r.payload===n&&r.type==="nack")&&i.rtcpFb.push({payload:n,type:"nack"}),e.includes(i.mid)&&i.fmtp.some(r=>r.payload===n?(r.config.includes("stereo=1")||(r.config+=";stereo=1"),!0):!1))}function fm(i){var e;const t=[],n=[],r=sn.parse((e=i.sdp)!==null&&e!==void 0?e:"");let s=0;return r.media.forEach(a=>{var o;a.type==="audio"&&(a.rtp.some(c=>c.codec==="opus"?(s=c.payload,!0):!1),!((o=a.rtcpFb)===null||o===void 0)&&o.some(c=>c.payload===s&&c.type==="nack")&&n.push(a.mid),a.fmtp.some(c=>c.payload===s?(c.config.includes("sprop-stereo=1")&&t.push(a.mid),!0):!1))}),{stereoMids:t,nackMids:n}}function Hd(i){if(i.connection){const e=i.connection.ip.indexOf(":")>=0;(i.connection.version===4&&e||i.connection.version===6&&!e)&&(i.connection.ip="0.0.0.0",i.connection.version=4)}}const Ea="vp8",pm={audioPreset:ia.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:sa.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Ea,backupCodec:!0},Zd={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Jd={deviceId:{ideal:"default"},resolution:Mi.h720.resolution},mm={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new sp,disconnectOnPageLeave:!0,webAudioMix:!1},wa={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Ae;(function(i){i[i.NEW=0]="NEW",i[i.CONNECTING=1]="CONNECTING",i[i.CONNECTED=2]="CONNECTED",i[i.FAILED=3]="FAILED",i[i.CLOSING=4]="CLOSING",i[i.CLOSED=5]="CLOSED"})(Ae||(Ae={}));class gm{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,n){var r;this.peerConnectionTimeout=wa.peerConnectionTimeout,this.log=re,this.updateState=()=>{var s;const a=this.state,o=this.requiredTransports.map(c=>c.getConnectionState());o.every(c=>c==="connected")?this.state=Ae.CONNECTED:o.some(c=>c==="failed")?this.state=Ae.FAILED:o.some(c=>c==="connecting")?this.state=Ae.CONNECTING:o.every(c=>c==="closed")?this.state=Ae.CLOSED:o.some(c=>c==="closed")?this.state=Ae.CLOSING:o.every(c=>c==="new")&&(this.state=Ae.NEW),a!==this.state&&(this.log.debug("pc state change: from ".concat(Ae[a]," to ").concat(Ae[this.state]),this.logContext),(s=this.onStateChange)===null||s===void 0||s.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=jt((r=n.loggerName)!==null&&r!==void 0?r:mt.PCManager),this.loggerOptions=n,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new Gd(e,n),this.subscriber=new Gd(e,n),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=s=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,s,pt.PUBLISHER)},this.subscriber.onIceCandidate=s=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,s,pt.SUBSCRIBER)},this.subscriber.onDataChannel=s=>{var a;(a=this.onDataChannel)===null||a===void 0||a.call(this,s)},this.subscriber.onTrack=s=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,s)},this.publisher.onOffer=s=>{var a;(a=this.onPublisherOffer)===null||a===void 0||a.call(this,s)},this.state=Ae.NEW,this.connectionLock=new Ze,this.remoteOfferLock=new Ze}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}requireSubscriber(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e){return this.publisher.setRemoteDescription(e)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return m(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const e=this.publisher;for(const t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(n){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:n}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return m(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return m(this,void 0,void 0,function*(){t===pt.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e){return m(this,void 0,void 0,function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber.getSignallingState().toString()}));const t=yield this.remoteOfferLock.lock();try{return yield this.subscriber.setRemoteDescription(e),yield this.subscriber.createAndSetAnswer()}finally{t()}})}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return m(this,void 0,void 0,function*(){var n;const r=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((n=this.requiredTransports)===null||n===void 0?void 0:n.map(s=>this.ensureTransportConnected(s,e,t)))}finally{r()}})}negotiate(e){return m(this,void 0,void 0,function*(){return new Promise((t,n)=>m(this,void 0,void 0,function*(){const r=setTimeout(()=>{n("negotiation timed out")},this.peerConnectionTimeout),s=()=>{clearTimeout(r),n("negotiation aborted")};e.signal.addEventListener("abort",s),this.publisher.once(ei.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(ei.NegotiationComplete,()=>{clearTimeout(r),t()})}),yield this.publisher.negotiate(a=>{clearTimeout(r),n(a)})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===pt.PUBLISHER?this.publisher.getConnectedAddress():e===pt.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return m(this,arguments,void 0,function(n,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(n.getConnectionState()!=="connected")return new Promise((c,d)=>m(s,void 0,void 0,function*(){const u=()=>{this.log.warn("abort transport connection",this.logContext),Be.clearTimeout(h),d(new ye("room connection has been cancelled",oe.Cancelled))};r!=null&&r.signal.aborted&&u(),r==null||r.signal.addEventListener("abort",u);const h=Be.setTimeout(()=>{r==null||r.signal.removeEventListener("abort",u),d(new ye("could not establish pc connection",oe.InternalError))},a);for(;this.state!==Ae.CONNECTED;)if(yield Qe(50),r!=null&&r.signal.aborted){d(new ye("room connection has been cancelled",oe.Cancelled));return}Be.clearTimeout(h),r==null||r.signal.removeEventListener("abort",u),c()}))}()})}}class De extends Error{constructor(e,t,n){super(t),this.code=e,this.message=Qd(t,De.MAX_MESSAGE_BYTES),this.data=n?Qd(n,De.MAX_DATA_BYTES):void 0}static fromProto(e){return new De(e.code,e.message,e.data)}toProto(){return new hc({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new De(De.ErrorCode[e],De.ErrorMessage[e],t)}}De.MAX_MESSAGE_BYTES=256,De.MAX_DATA_BYTES=15360,De.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404},De.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};const Yd=15360;function Pa(i){return new TextEncoder().encode(i).length}function Qd(i,e){if(Pa(i)<=e)return i;let t=0,n=i.length;const r=new TextEncoder;for(;t<n;){const s=Math.floor((t+n+1)/2);r.encode(i.slice(0,s)).length<=e?t=s:n=s-1}return i.slice(0,t)}const Ra=2e3;function $r(i,e){if(!e)return 0;let t,n;return"bytesReceived"in i?(t=i.bytesReceived,n=e.bytesReceived):"bytesSent"in i&&(t=i.bytesSent,n=e.bytesSent),t===void 0||n===void 0||i.timestamp===void 0||e.timestamp===void 0?0:(t-n)*8*1e3/(i.timestamp-e.timestamp)}const vm=1e3;class Xd extends R{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}constructor(e,t,n){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._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=_a(()=>m(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>m(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 Ze,this.pauseUpstreamLock=new Ze,this.processorLock=new Ze,this.restartLock=new Ze,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==R.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return(t=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&t!==void 0?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return m(this,void 0,void 0,function*(){var n;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(s=>{Jn(this._mediaStreamTrack,s)}),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 r;if(this.processor&&e){const s=yield this.processorLock.lock();try{if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Zn(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),r=this.processor.processedTrack}finally{s()}}this.sender&&((n=this.sender.transport)===null||n===void 0?void 0:n.state)!=="closed"&&(yield this.sender.replaceTrack(r??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(s=>{Zn(r??e,s)}))})}waitForDimensions(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:vm;return function*(){var n;if(e.kind===R.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((n=gt())===null||n===void 0?void 0:n.os)==="iOS"&&(yield Qe(10));const r=Date.now();for(;Date.now()-r<t;){const s=e.dimensions;if(s)return s;yield Qe(50)}throw new Ft("unable to get track dimensions after timeout")}()})}setDeviceId(e){return m(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===nn(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),nn(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return m(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===R.Source.ScreenShare)return;const{deviceId:n,groupId:r}=e._mediaStreamTrack.getSettings(),s=e.kind===R.Kind.Audio?"audioinput":"videoinput";return t?$e.getInstance().normalizeDeviceId(s,n,r):n}()})}mute(){return m(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return m(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return m(this,void 0,void 0,function*(){if(!this.sender)throw new Ft("unable to replace an unpublished track");let n,r;return typeof t=="boolean"?n=t:t!==void 0&&(n=t.userProvidedTrack,r=t.stopProcessor),this.providedByUser=n??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),r&&this.processor&&(yield this.stopProcessor()),this})}restart(e){return m(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.restartLock.lock();try{e||(e=this._constraints);const{deviceId:n,facingMode:r}=e,s=ap(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const a={audio:!1,video:!1};this.kind===R.Kind.Video?a.video=n||r?{deviceId:n,facingMode:r}:!0:a.audio=n?{deviceId:n}:!0,this.attachedElements.forEach(d=>{Jn(this.mediaStreamTrack,d)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return yield c.applyConstraints(s),c.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(c),this._constraints=e,this.emit(M.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?M.Muted:M.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return m(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),wd()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(e=this.processor)===null||e===void 0||e.destroy(),this.processor=void 0}pauseUpstream(){return m(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(M.UpstreamPaused,this);const n=gt();if((n==null?void 0:n.name)==="Safari"&&wn(n.version,"12.0")<0)throw new Qs("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 m(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(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 m(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 m(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var s;const a=yield n.processorLock.lock();try{n.log.debug("setting up processor",n.logContext);const o=document.createElement(n.kind),c={kind:n.kind,track:n._mediaStreamTrack,element:o,audioContext:n.audioContext};if(yield t.init(c),n.log.debug("processor initialized",n.logContext),n.processor&&(yield n.stopProcessor()),n.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(Zn(n._mediaStreamTrack,o),o.muted=!0,o.play().catch(d=>n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{error:d}))),n.processor=t,n.processorElement=o,n.processor.processedTrack){for(const d of n.attachedElements)d!==n.processorElement&&r&&(Jn(n._mediaStreamTrack,d),Zn(n.processor.processedTrack,d));yield(s=n.sender)===null||s===void 0?void 0:s.replaceTrack(n.processor.processedTrack)}n.emit(M.TrackProcessorUpdate,n.processor)}finally{a()}}()})}getProcessor(){return this.processor}stopProcessor(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var n,r;e.processor&&(e.log.debug("stopping processor",e.logContext),(n=e.processor.processedTrack)===null||n===void 0||n.stop(),yield e.processor.destroy(),e.processor=void 0,t||((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))}()})}}class Br extends Xd{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let n=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,R.Kind.Audio,t,n,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>m(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=$r(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,wt.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(M.AudioTrackFeatureUpdate,this,wt.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return m(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===R.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return m(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const n=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==nn(this._constraints.deviceId);return this.source===R.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||n)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return m(this,void 0,void 0,function*(){let t;if(e){const n=va({audio:e});typeof n.audio!="boolean"&&(t=n.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return m(this,void 0,void 0,function*(){const n=yield t.restart.call(this,e);return this.checkForSilence(),n})}startMonitor(){Xe()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},Ra)))}setProcessor(e){return m(this,void 0,void 0,function*(){var t;const n=yield this.processorLock.lock();try{if(!xt()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());const r={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(r),this.processor=e,this.processor.processedTrack&&(yield(t=this.sender)===null||t===void 0?void 0:t.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(M.TrackProcessorUpdate,this.processor)}finally{n()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return m(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let n;return t.forEach(r=>{r.type==="outbound-rtp"&&(n={type:"audio",streamId:r.id,packetsSent:r.packetsSent,packetsLost:r.packetsLost,bytesSent:r.bytesSent,timestamp:r.timestamp,roundTripTime:r.roundTripTime,jitter:r.jitter})}),n})}checkForSilence(){return m(this,void 0,void 0,function*(){const e=yield Ld(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(M.AudioSilenceDetected)),e})}}function ym(i,e,t){switch(i.kind){case"audio":return new Br(i,e,!1,void 0,t);case"video":return new qr(i,e,!1,t);default:throw new Ft("unsupported track type: ".concat(i.kind))}}const bm=Object.values(Mi),km=Object.values(ra),Sm=Object.values(sa),Tm=[Mi.h180,Mi.h360],Cm=[ra.h180,ra.h360],_m=i=>[{scaleResolutionDownBy:2,fps:i.encoding.maxFramerate}].map(t=>{var n,r;return new ve(Math.floor(i.width/t.scaleResolutionDownBy),Math.floor(i.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(i.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((n=i.encoding.maxFramerate)!==null&&n!==void 0?n:30)/((r=t.fps)!==null&&r!==void 0?r:30))))),t.fps,i.encoding.priority)}),xa=["q","h","f"];function Ia(i,e,t,n){var r,s;let a=n==null?void 0:n.videoEncoding;i&&(a=n==null?void 0:n.screenShareEncoding);const o=n==null?void 0:n.simulcast,c=n==null?void 0:n.scalabilityMode,d=n==null?void 0:n.videoCodec;if(!a&&!o&&!c||!e||!t)return[{}];a||(a=wm(i,e,t,d),re.debug("using video encoding",a));const u=a.maxFramerate,h=new ve(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(c&&Ni(d)){const y=new Vr(c),v=[];if(y.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const _=gt();if(tn()||xt()||(_==null?void 0:_.name)==="Chrome"&&wn(_==null?void 0:_.version,"113")<0){const w=y.suffix=="h"?2:3;for(let N=0;N<y.spatial;N+=1)v.push({rid:xa[2-N],maxBitrate:a.maxBitrate/Math.pow(w,N),maxFramerate:h.encoding.maxFramerate});v[0].scalabilityMode=c}else v.push({maxBitrate:a.maxBitrate,maxFramerate:h.encoding.maxFramerate,scalabilityMode:c});return h.encoding.priority&&(v[0].priority=h.encoding.priority,v[0].networkPriority=h.encoding.priority),re.debug("using svc encoding",{encodings:v}),v}if(!o)return[a];let f=[];i?f=(r=tu(n==null?void 0:n.screenShareSimulcastLayers))!==null&&r!==void 0?r:eu(i,h):f=(s=tu(n==null?void 0:n.videoSimulcastLayers))!==null&&s!==void 0?s:eu(i,h);let g;if(f.length>0){const y=f[0];f.length>1&&([,g]=f);const v=Math.max(e,t);if(v>=960&&g)return Oa(e,t,[y,g,h],u);if(v>=480)return Oa(e,t,[y,h],u)}return Oa(e,t,[h])}function Em(i,e,t){var n,r,s,a;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&re.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const o=i.mediaStreamTrack.getSettings(),c=(n=o.width)!==null&&n!==void 0?n:(r=i.dimensions)===null||r===void 0?void 0:r.width,d=(s=o.height)!==null&&s!==void 0?s:(a=i.dimensions)===null||a===void 0?void 0:a.height;return i.source===R.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),Ia(i.source===R.Source.ScreenShare,c,d,t)}function wm(i,e,t,n){const r=Pm(i,e,t);let{encoding:s}=r[0];const a=Math.max(e,t);for(let o=0;o<r.length;o+=1){const c=r[o];if(s=c.encoding,c.width>=a)break}if(n)switch(n){case"av1":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 Pm(i,e,t){if(i)return Sm;const n=e>t?e/t:t/e;return Math.abs(n-16/9)<Math.abs(n-4/3)?bm:km}function eu(i,e){if(i)return _m(e);const{width:t,height:n}=e,r=t>n?t/n:n/t;return Math.abs(r-16/9)<Math.abs(r-4/3)?Tm:Cm}function Oa(i,e,t,n){const r=[];if(t.forEach((s,a)=>{if(a>=xa.length)return;const o=Math.min(i,e),d={rid:xa[a],scaleResolutionDownBy:Math.max(1,o/Math.min(s.width,s.height)),maxBitrate:s.encoding.maxBitrate},u=n&&s.encoding.maxFramerate?Math.min(n,s.encoding.maxFramerate):s.encoding.maxFramerate;u&&(d.maxFramerate=u);const h=Yn()||a===0;s.encoding.priority&&h&&(d.priority=s.encoding.priority,d.networkPriority=s.encoding.priority),r.push(d)}),xt()&&Rd()==="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,re.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),re.info('Setting framerate of encoding "'.concat((c=o.rid)!==null&&c!==void 0?c:"",'" to ').concat(s)),o.maxFramerate=s)})}return r}function tu(i){if(i)return i.sort((e,t)=>{const{encoding:n}=e,{encoding:r}=t;return n.maxBitrate>r.maxBitrate?1:n.maxBitrate<r.maxBitrate?-1:n.maxBitrate===r.maxBitrate&&n.maxFramerate&&r.maxFramerate?n.maxFramerate>r.maxFramerate?1:-1:0})}class Vr{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function Rm(i){return i.source===R.Source.ScreenShare||i.constraints.height&&nn(i.constraints.height)>=1080?"maintain-resolution":"balanced"}const xm=5e3;class qr extends Xd{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(e,R.Kind.Video,t,n,r),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>m(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let s;try{s=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}const a=new Map(s.map(o=>[o.rid,o]));if(this.prevStats){let o=0;a.forEach((c,d)=>{var u;const h=(u=this.prevStats)===null||u===void 0?void 0:u.get(d);o+=$r(c,h)}),this._currentBitrate=o}this.prevStats=a}),this.senderLock=new Ze}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!Xe())return;const n=(t=this.sender)===null||t===void 0?void 0:t.getParameters();n&&(this.encodings=n.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},Ra))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return m(this,void 0,void 0,function*(){var t,n,r,s,a;yield e.pauseUpstream.call(this);try{for(var o=!0,c=Yt(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(u){n={error:u}}finally{try{!o&&!t&&(r=c.return)&&(yield r.call(c))}finally{if(n)throw n.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return m(this,void 0,void 0,function*(){var t,n,r,s,a;yield e.resumeUpstream.call(this);try{for(var o=!0,c=Yt(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;o=!0){s=d.value,o=!1;const u=s;yield(a=u.sender)===null||a===void 0?void 0:a.replaceTrack(u.mediaStreamTrack)}}catch(u){n={error:u}}finally{try{!o&&!t&&(r=c.return)&&(yield r.call(c))}finally{if(n)throw n.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return m(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===R.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return m(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===R.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return m(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],n=yield this.sender.getStats();return n.forEach(r=>{var s;if(r.type==="outbound-rtp"){const 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=n.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})}setPublishingQuality(e){const t=[];for(let n=ot.LOW;n<=ot.HIGH;n+=1)t.push(new $s({quality:n,enabled:n<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(t)}restartTrack(e){return m(this,void 0,void 0,function*(){var t,n,r,s,a;let o;if(e){const h=va({video:e});typeof h.video!="boolean"&&(o=h.video)}yield this.restart(o);try{for(var c=!0,d=Yt(this.simulcastCodecs.values()),u;u=yield d.next(),t=u.done,!t;c=!0){s=u.value,c=!1;const h=s;h.sender&&((a=h.sender.transport)===null||a===void 0?void 0:a.state)!=="closed"&&(h.mediaStreamTrack=this.mediaStreamTrack.clone(),yield h.sender.replaceTrack(h.mediaStreamTrack))}}catch(h){n={error:h}}finally{try{!c&&!t&&(r=d.return)&&(yield r.call(d))}finally{if(n)throw n.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return m(this,arguments,void 0,function(n){var r=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var a,o,c,d,u,h;if(yield t.setProcessor.call(r,n,s),!((u=r.processor)===null||u===void 0)&&u.processedTrack)try{for(var f=!0,g=Yt(r.simulcastCodecs.values()),y;y=yield g.next(),a=y.done,!a;f=!0)d=y.value,f=!1,yield(h=d.sender)===null||h===void 0?void 0:h.replaceTrack(r.processor.processedTrack)}catch(v){o={error:v}}finally{try{!f&&!a&&(c=g.return)&&(yield c.call(g))}finally{if(o)throw o.error}}}()})}setDegradationPreference(e){return m(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){const n=this.simulcastCodecs.get(e);n&&(n.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},xm))}setPublishingCodecs(e){return m(this,void 0,void 0,function*(){var t,n,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(e[0].qualities),[];this.subscribedCodecs=e;const d=[];try{for(t=!0,n=Yt(e);r=yield n.next(),s=r.done,!s;t=!0){c=r.value,t=!1;const u=c;if(!this.codec||this.codec===u.codec)yield this.setPublishingLayers(u.qualities);else{const h=this.simulcastCodecs.get(u.codec);if(this.log.debug("try setPublishingCodec for ".concat(u.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:h})),!h||!h.sender){for(const f of u.qualities)if(f.enabled){d.push(u.codec);break}}else h.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(u.codec),this.logContext),yield nu(h.sender,h.encodings,u.qualities,this.senderLock,this.log,this.logContext))}}}catch(u){a={error:u}}finally{try{!t&&!s&&(o=n.return)&&(yield o.call(n))}finally{if(a)throw a.error}}return d})}setPublishingLayers(e){return m(this,void 0,void 0,function*(){this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:e})),!(!this.sender||!this.encodings)&&(yield nu(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return m(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),wd()&&this.isInBackground&&this.source===R.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function nu(i,e,t,n,r,s){return m(this,void 0,void 0,function*(){const a=yield n.lock();r.debug("setPublishingLayersForSender",Object.assign(Object.assign({},s),{sender:i,qualities:t,senderEncodings:e}));try{const o=i.getParameters(),{encodings:c}=o;if(!c)return;if(c.length!==e.length){r.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},s),{encodings:c,senderEncodings:e}));return}let d=!1;const u=gt();if((u==null?void 0:u.name)==="Chrome"&&wn(u==null?void 0:u.version,"133")>0&&c[0].scalabilityMode){const f=c[0],g=new Vr(f.scalabilityMode);let y=zn.OFF;if(t.forEach(v=>{v.enabled&&(y===zn.OFF||v.quality>y)&&(y=v.quality)}),y===zn.OFF)f.active&&(f.active=!1,d=!0);else if(!f.active||g.spatial!==y+1){d=!0,f.active=!0;const v=new Vr(e[0].scalabilityMode);g.spatial=y+1,g.suffix=v.suffix,g.spatial===1&&(g.suffix=void 0),f.scalabilityMode=g.toString(),f.scaleResolutionDownBy=Math.pow(2,2-y),e[0].maxBitrate&&(f.maxBitrate=e[0].maxBitrate/(f.scaleResolutionDownBy*f.scaleResolutionDownBy))}}else c.forEach((f,g)=>{var y;let v=(y=f.rid)!==null&&y!==void 0?y:"";v===""&&(v="q");const _=iu(v),w=t.find(N=>N.quality===_);w&&f.active!==w.enabled&&(d=!0,f.active=w.enabled,r.debug("setting layer ".concat(w.quality," to ").concat(f.active?"enabled":"disabled"),s),Yn()&&(w.enabled?(f.scaleResolutionDownBy=e[g].scaleResolutionDownBy,f.maxBitrate=e[g].maxBitrate,f.maxFrameRate=e[g].maxFrameRate):(f.scaleResolutionDownBy=4,f.maxBitrate=10,f.maxFrameRate=2)))});d&&(o.encodings=c,r.debug("setting encodings",Object.assign(Object.assign({},s),{encodings:o.encodings})),yield i.setParameters(o))}finally{a()}})}function iu(i){switch(i){case"f":return ot.HIGH;case"h":return ot.MEDIUM;case"q":return ot.LOW;default:return ot.HIGH}}function ru(i,e,t,n){if(!t)return[new Cn({quality:ot.HIGH,width:i,height:e,bitrate:0,ssrc:0})];if(n){const r=t[0].scalabilityMode,s=new Vr(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 Cn({quality:Math.min(ot.HIGH,s.spatial-1)-d,width:Math.ceil(i/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;const c=(s=r.scaleResolutionDownBy)!==null&&s!==void 0?s:1;let d=iu((a=r.rid)!==null&&a!==void 0?a:"");return new Cn({quality:d,width:Math.ceil(i/c),height:Math.ceil(e/c),bitrate:(o=r.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const su="_lossy",au="_reliable",Im=2*1e3,Aa="leave-reconnect";var yt;(function(i){i[i.New=0]="New",i[i.Connected=1]="Connected",i[i.Disconnected=2]="Disconnected",i[i.Reconnecting=3]="Reconnecting",i[i.Closed=4]="Closed"})(yt||(yt={}));class Om extends Rt.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=wa.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=yt.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=re,this.handleDataChannel=n=>m(this,[n],void 0,function(r){var s=this;let{channel:a}=r;return function*(){if(a){if(a.label===au)s.reliableDCSub=a;else if(a.label===su)s.lossyDCSub=a;else return;s.log.debug("on data channel ".concat(a.id,", ").concat(a.label),s.logContext),a.onmessage=s.handleDataMessage}}()}),this.handleDataMessage=n=>m(this,void 0,void 0,function*(){var r,s;const a=yield this.dataProcessLock.lock();try{let o;if(n.data instanceof ArrayBuffer)o=n.data;else if(n.data instanceof Blob)o=yield n.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:n.data}));return}const c=Ye.fromBinary(new Uint8Array(o));((r=c.value)===null||r===void 0?void 0:r.case)==="speaker"?this.emit(L.ActiveSpeakersUpdate,c.value.value.speakers):(((s=c.value)===null||s===void 0?void 0:s.case)==="user"&&Dm(c,c.value.value),this.emit(L.DataPacketReceived,c))}finally{a()}}),this.handleDataError=n=>{const s=n.currentTarget.maxRetransmits===0?"lossy":"reliable";if(n instanceof ErrorEvent&&n.error){const{error:a}=n.error;this.log.error("DataChannel error on ".concat(s,": ").concat(n.message),Object.assign(Object.assign({},this.logContext),{error:a}))}else this.log.error("Unknown DataChannel error on ".concat(s),Object.assign(Object.assign({},this.logContext),{event:n}))},this.handleBufferedAmountLow=n=>{const s=n.currentTarget.maxRetransmits===0?le.LOSSY:le.RELIABLE;this.updateAndEmitDCBufferStatus(s)},this.handleDisconnect=(n,r)=>{if(this._isClosed)return;this.log.warn("".concat(n," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const s=c=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(c,"ms. giving up"),this.logContext),this.emit(L.Disconnected),this.close()},a=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:a,retryCount:this.reconnectAttempts});if(o===null){s(a);return}n===Aa&&(o=0),this.log.debug("reconnecting in ".concat(o,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Be.setTimeout(()=>this.attemptReconnect(r).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((n,r)=>{this.pcState===yt.Connected&&n();const s=()=>{this.off(L.Disconnected,a),n()},a=()=>{this.off(L.Restarted,s),r()};this.once(L.Restarted,s),this.once(L.Disconnected,a)}),this.updateAndEmitDCBufferStatus=n=>{const r=this.isBufferStatusLow(n);typeof r<"u"&&r!==this.dcBufferStatus.get(n)&&(this.dcBufferStatus.set(n,r),this.emit(L.DCBufferStatusChanged,r,n))},this.isBufferStatusLow=n=>{const r=this.dataChannelForKind(n);if(r)return r.bufferedAmount<=r.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===Se.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(Wn.RR_SIGNAL_DISCONNECTED))},this.log=jt((t=e.loggerName)!==null&&t!==void 0?t:mt.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new ba(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Ze,this.dataProcessLock=new Ze,this.dcBufferStatus=new Map([[le.LOSSY,!0],[le.RELIABLE,!0]]),this.client.onParticipantUpdate=n=>this.emit(L.ParticipantUpdate,n),this.client.onConnectionQuality=n=>this.emit(L.ConnectionQualityUpdate,n),this.client.onRoomUpdate=n=>this.emit(L.RoomUpdate,n),this.client.onSubscriptionError=n=>this.emit(L.SubscriptionError,n),this.client.onSubscriptionPermissionUpdate=n=>this.emit(L.SubscriptionPermissionUpdate,n),this.client.onSpeakersChanged=n=>this.emit(L.SpeakersChanged,n),this.client.onStreamStateUpdate=n=>this.emit(L.StreamStateChanged,n),this.client.onRequestResponse=n=>this.emit(L.SignalRequestResponse,n)}get logContext(){var e,t,n,r,s,a,o,c;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(r=(n=this.latestJoinResponse)===null||n===void 0?void 0:n.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,pID:(c=(o=this.latestJoinResponse)===null||o===void 0?void 0:o.participant)===null||c===void 0?void 0:c.sid}}join(e,t,n,r){return m(this,void 0,void 0,function*(){this.url=e,this.token=t,this.signalOpts=n,this.maxJoinAttempts=n.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const s=yield this.client.join(e,t,n,r);return this._isClosed=!1,this.latestJoinResponse=s,this.subscriberPrimary=s.subscriberPrimary,this.pcManager||(yield this.configure(s)),(!this.subscriberPrimary||s.fastPublish)&&this.negotiate(),this.clientConfiguration=s.clientConfiguration,setTimeout(()=>{this.emit(L.SignalConnected)},10),s}catch(s){if(s instanceof ye&&s.reason===oe.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,n,r);throw s}})}close(){return m(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(L.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return m(this,void 0,void 0,function*(){var e;yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0;const t=n=>{n&&(n.close(),n.onbufferedamountlow=null,n.onclose=null,n.onclosing=null,n.onerror=null,n.onmessage=null,n.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0})}cleanupClient(){return m(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Ft("a track with the same ID has already been published");return new Promise((t,n)=>{const r=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(new ye("publication of local track timed out, no response from server",oe.InternalError))},1e4);this.pendingTrackResolvers[e.cid]={resolve:s=>{clearTimeout(r),t(s)},reject:()=>{clearTimeout(r),n(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return m(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){return m(this,void 0,void 0,function*(){var t,n;if(this.pcManager&&this.pcManager.currentState!==Ae.NEW)return;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new gm(r,e.subscriberPrimary,this.loggerOptions),this.emit(L.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(s,a)=>{this.client.sendIceCandidate(s,a)},this.pcManager.onPublisherOffer=s=>{this.client.sendOffer(s)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(s,a,o)=>m(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(s),this.logContext),["closed","disconnected","failed"].includes(a)&&(this.publisherConnectionPromise=void 0),s===Ae.CONNECTED){const u=this.pcState===yt.New;this.pcState=yt.Connected,u&&this.emit(L.Connected,e)}else s===Ae.FAILED&&this.pcState===yt.Connected&&(this.pcState=yt.Disconnected,this.handleDisconnect("peerconnection failed",o==="failed"?Wn.RR_SUBSCRIBER_FAILED:Wn.RR_PUBLISHER_FAILED));const c=this.client.isDisconnected||this.client.currentState===Se.RECONNECTING,d=[Ae.FAILED,Ae.CLOSING,Ae.CLOSED].includes(s);c&&d&&!this._isClosed&&this.emit(L.Offline)}),this.pcManager.onTrack=s=>{this.emit(L.MediaTrackAdded,s.track,s.streams[0],s.receiver)},Am((n=e.serverInfo)===null||n===void 0?void 0:n.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=e=>m(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=e=>m(this,void 0,void 0,function*(){if(!this.pcManager)return;const t=yield this.pcManager.createSubscriberAnswerFromOffer(e);this.client.sendAnswer(t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(t=e.track)===null||t===void 0?void 0:t.sid})),!this.pendingTrackResolvers[e.cid]){this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}const{resolve:n}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],n(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(L.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(L.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(L.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(L.SubscribedQualityUpdate,e)},this.client.onClose=()=>{this.handleDisconnect("signal",Wn.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e==null?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(e.regions)),e.action){case Kn.DISCONNECT:this.emit(L.Disconnected,e==null?void 0:e.reason),this.close();break;case Kn.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Aa);break;case Kn.RESUME:this.handleDisconnect(Aa)}}}makeRTCConfiguration(e){var t;const n=Object.assign({},this.rtcConfig);if(!((t=this.signalOpts)===null||t===void 0)&&t.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),n.encodedInsertableStreams=!0),e.iceServers&&!n.iceServers){const r=[];e.iceServers.forEach(s=>{const a={urls:s.urls};s.username&&(a.username=s.username),s.credential&&(a.credential=s.credential),r.push(a)}),n.iceServers=r}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Ii.ENABLED&&(n.iceTransportPolicy="relay"),n.sdpSemantics="unified-plan",n.continualGatheringPolicy="gather_continually",n}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(su,{ordered:!0,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(au,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}createSender(e,t,n){return m(this,void 0,void 0,function*(){if(aa())return yield this.createTransceiverRTCRtpSender(e,t,n);if(oa())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new Fe("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,n,r){return m(this,void 0,void 0,function*(){if(aa())return this.createSimulcastTransceiverSender(e,t,n,r);if(oa())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new Fe("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,n){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new Fe("publisher is closed");const r=[];e.mediaStream&&r.push(e.mediaStream),Xn(e)&&(e.codec=t.videoCodec);const s={direction:"sendonly",streams:r};return n&&(s.sendEncodings=n),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender})}createSimulcastTransceiverSender(e,t,n,r){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new Fe("publisher is closed");const s={direction:"sendonly"};r&&(s.sendEncodings=r);const a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s);if(n.videoCodec)return e.setSimulcastTrackSender(n.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new Fe("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return m(this,void 0,void 0,function*(){var t,n,r;if(!this._isClosed){if(this.attemptingReconnect){re.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===Ii.DISABLED||((r=(n=this.pcManager)===null||n===void 0?void 0:n.currentState)!==null&&r!==void 0?r:Ae.NEW)===Ae.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(s){this.reconnectAttempts+=1;let a=!0;s instanceof Fe?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:s})),a=!1):s instanceof ti||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",Wn.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(L.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(e){return m(this,void 0,void 0,function*(){var t,n,r;try{if(!this.url||!this.token)throw new Fe("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(L.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let s;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new ti;s=yield this.join(e??this.url,this.token,this.signalOpts)}catch(a){throw a instanceof ye&&a.reason===oe.NotAllowed?new Fe("could not reconnect, token might be expired"):new ti}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(L.SignalRestarted,s),yield this.waitForPCReconnected(),this.client.currentState!==Se.CONNECTED)throw new ti("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(L.Restarted)}catch(s){const a=yield(n=this.regionUrlProvider)===null||n===void 0?void 0:n.getNextBestRegionUrl();if(a){yield this.restartConnection(a);return}else throw(r=this.regionUrlProvider)===null||r===void 0||r.resetAttempts(),s}})}resumeConnection(e){return m(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new Fe("could not reconnect, url or token not saved");if(!this.pcManager)throw new Fe("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(L.Resuming);let n;try{this.setupSignalClientCallbacks(),n=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,Object.assign(Object.assign({},this.logContext),{error:r}))),r instanceof ye&&r.reason===oe.NotAllowed?new Fe("could not reconnect, token might be expired"):r instanceof ye&&r.reason===oe.LeaveRequest?r:new ti(s)}if(this.emit(L.SignalResumed),n){const r=this.makeRTCConfiguration(n);this.pcManager.updateConfiguration(r)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==Se.CONNECTED)throw new ti("Signal connection got severed during reconnect");this.client.setReconnected(),((t=this.reliableDC)===null||t===void 0?void 0:t.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),this.emit(L.Resumed)})}waitForPCInitialConnection(e,t){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new Fe("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return m(this,void 0,void 0,function*(){this.pcState=yt.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Qe(Im),!this.pcManager)throw new Fe("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=yt.Connected}catch(e){throw this.pcState=yt.Disconnected,new ye("could not establish PC connection, ".concat(e.message),oe.InternalError)}})}publishRpcResponse(e,t,n,r){return m(this,void 0,void 0,function*(){const s=new Ye({destinationIdentities:[e],kind:le.RELIABLE,value:{case:"rpcResponse",value:new lc({requestId:t,value:r?{case:"error",value:r.toProto()}:{case:"payload",value:n??""}})}});yield this.sendDataPacket(s,le.RELIABLE)})}publishRpcAck(e,t){return m(this,void 0,void 0,function*(){const n=new Ye({destinationIdentities:[e],kind:le.RELIABLE,value:{case:"rpcAck",value:new uc({requestId:t})}});yield this.sendDataPacket(n,le.RELIABLE)})}sendDataPacket(e,t){return m(this,void 0,void 0,function*(){const n=e.toBinary();yield this.ensurePublisherConnected(t);const r=this.dataChannelForKind(t);r&&r.send(n),this.updateAndEmitDCBufferStatus(t)})}waitForBufferStatusLow(e){return new Promise((t,n)=>m(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const r=()=>n("Engine closed");for(this.once(L.Closing,r);!this.dcBufferStatus.get(e);)yield Qe(10);this.off(L.Closing,r),t()}}))}ensureDataTransportConnected(e){return m(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){var s;if(!n.pcManager)throw new Fe("PC manager is closed");const a=r?n.pcManager.subscriber:n.pcManager.publisher,o=r?"Subscriber":"Publisher";if(!a)throw new ye("".concat(o," connection not set"),oe.InternalError);let c=!1;!r&&!n.dataChannelForKind(t,r)&&(n.createDataChannels(),c=!0),!c&&!r&&!n.pcManager.publisher.isICEConnected&&n.pcManager.publisher.getICEConnectionState()!=="checking"&&(c=!0),c&&n.negotiate();const d=n.dataChannelForKind(t,r);if((d==null?void 0:d.readyState)==="open")return;const u=new Date().getTime()+n.peerConnectionTimeout;for(;new Date().getTime()<u;){if(a.isICEConnected&&((s=n.dataChannelForKind(t,r))===null||s===void 0?void 0:s.readyState)==="open")return;yield Qe(50)}throw new ye("could not establish ".concat(o," connection, state: ").concat(a.getICEConnectionState()),oe.InternalError)}()})}ensurePublisherConnected(e){return m(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==Ae.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return m(this,void 0,void 0,function*(){return new Promise((e,t)=>m(this,void 0,void 0,function*(){if(!this.pcManager){t(new Xs("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const n=new AbortController,r=()=>{n.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(L.Closing,r),this.pcManager.publisher.once(ei.RTPVideoPayloadTypes,s=>{const a=new Map;s.forEach(o=>{const c=o.codec.toLowerCase();Bp(c)&&a.set(o.payload,c)}),this.emit(L.RTPVideoMapUpdate,a)});try{yield this.pcManager.negotiate(n),e()}catch(s){s instanceof Xs&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Wn.RR_UNKNOWN),t(s)}finally{this.off(L.Closing,r)}}))})}dataChannelForKind(e,t){if(t){if(e===le.LOSSY)return this.lossyDCSub;if(e===le.RELIABLE)return this.reliableDCSub}else{if(e===le.LOSSY)return this.lossyDC;if(e===le.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var n,r;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const s=this.pcManager.subscriber.getLocalDescription(),a=this.pcManager.subscriber.getRemoteDescription(),o=(r=(n=this.signalOpts)===null||n===void 0?void 0:n.autoSubscribe)!==null&&r!==void 0?r:!0,c=new Array,d=new Array;e.forEach(u=>{u.isDesired!==o&&c.push(u.trackSid),u.isEnabled||d.push(u.trackSid)}),this.client.sendSyncState(new xc({answer:s?Fr({sdp:s.sdp,type:s.type}):void 0,offer:a?Fr({sdp:a.sdp,type:a.type}):void 0,subscription:new Cr({trackSids:c,subscribe:!o,participantTracks:[]}),publishTracks:Jp(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:d}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(n,r)=>{(n==null?void 0:n.id)!==void 0&&n.id!==null&&e.push(new Ic({label:n.label,id:n.id,target:r}))};return t(this.dataChannelForKind(le.LOSSY),pt.PUBLISHER),t(this.dataChannelForKind(le.RELIABLE),pt.PUBLISHER),t(this.dataChannelForKind(le.LOSSY,!0),pt.SUBSCRIBER),t(this.dataChannelForKind(le.RELIABLE,!0),pt.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Be.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Xe()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){Xe()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class ti extends Error{}function Am(i){return i!==void 0&&i>13}function Dm(i,e){const t=i.participantIdentity?i.participantIdentity:e.participantIdentity;i.participantIdentity=t,e.participantIdentity=t;const n=i.destinationIdentities.length!==0?i.destinationIdentities:e.destinationIdentities;i.destinationIdentities=n,e.destinationIdentities=n}class Da{constructor(e,t){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return da(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return m(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(e));const t=this.regionSettings.regions.filter(n=>!this.attemptedRegions.find(r=>r.url===n.url));if(t.length>0){const n=t[0];return this.attemptedRegions.push(n),re.debug("next region: ".concat(n.region)),n.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return m(this,void 0,void 0,function*(){const t=yield fetch("".concat(Mm(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(t.ok){const n=yield t.json();return this.lastUpdateAt=Date.now(),n}else throw new ye("Could not fetch region settings: ".concat(t.statusText),t.status===401?oe.NotAllowed:oe.InternalError,t.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function Mm(i){return"".concat(i.protocol.replace("ws","http"),"//").concat(i.host,"/settings")}class ou{get info(){return this._info}constructor(e,t,n){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0}}class Nm extends ou{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength;const n=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,n)}[Symbol.asyncIterator](){const e=this.reader.getReader();return{next:()=>m(this,void 0,void 0,function*(){try{const{done:t,value:n}=yield e.read();return t?{done:!0,value:void 0}:(this.handleChunkReceived(n),{done:!1,value:n.content})}catch{return{done:!0,value:void 0}}}),return(){return m(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return m(this,void 0,void 0,function*(){var e,t,n,r;let s=new Set;try{for(var a=!0,o=Yt(this),c;c=yield o.next(),e=c.done,!e;a=!0){r=c.value,a=!1;const d=r;s.add(d)}}catch(d){t={error:d}}finally{try{!a&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(t)throw t.error}}return Array.from(s)})}}class Lm extends ou{constructor(e,t,n){super(e,t,n),this.receivedChunks=new Map}handleChunkReceived(e){var t;const n=Ur(e.chunkIndex),r=this.receivedChunks.get(n);if(r&&r.version>e.version)return;this.receivedChunks.set(n,e),this.bytesReceived+=e.content.byteLength;const s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,s)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder;return{next:()=>m(this,void 0,void 0,function*(){try{const{done:n,value:r}=yield e.read();return n?{done:!0,value:void 0}:(this.handleChunkReceived(r),{done:!1,value:t.decode(r.content)})}catch{return{done:!0,value:void 0}}}),return(){return m(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return m(this,void 0,void 0,function*(){var e,t,n,r;let s="";try{for(var a=!0,o=Yt(this),c;c=yield o.next(),e=c.done,!e;a=!0)r=c.value,a=!1,s+=r}catch(d){t={error:d}}finally{try{!a&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(t)throw t.error}}return s})}}class cu{constructor(e,t,n){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=n,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return m(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)===null||e===void 0||e.call(this)})}}class Um extends cu{}class jm extends cu{}class du extends R{constructor(e,t,n,r,s){super(e,n,s),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;const t=n=>{n.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(M.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return m(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(),Ra)),Yp()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const n=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(n){const{timestamp:r,rtpTimestamp:s}=n;s&&this.rtpTimestamp!==s&&(this.emit(M.TimeSyncUpdate,{timestamp:r,rtpTimestamp:s}),this.rtpTimestamp=s)}};e()}}class Fm extends du{constructor(e,t,n,r,s,a){super(e,t,R.Kind.Audio,n,a),this.monitorReceiver=()=>m(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=$r(o,this.prevStats)),this.prevStats=o}),this.audioContext=r,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(const n of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):n.volume=e;xt()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(xt())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return m(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(ca(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&ca(e)&&e.setSinkId(this.sinkId),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let n=this.sourceNode;this.webAudioPluginNodes.forEach(r=>{n.connect(r),n=r}),this.gainNode=e.createGain(),n.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(M.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(r=>{this.emit(M.AudioPlaybackFailed,r)})}disconnectWebAudio(){var e,t;(e=this.gainNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return m(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(n=>{n.type==="inbound-rtp"&&(t={type:"audio",streamId:n.id,timestamp:n.timestamp,jitter:n.jitter,bytesReceived:n.bytesReceived,concealedSamples:n.concealedSamples,concealmentEvents:n.concealmentEvents,silentConcealedSamples:n.silentConcealedSamples,silentConcealmentEvents:n.silentConcealmentEvents,totalAudioEnergy:n.totalAudioEnergy,totalSamplesDuration:n.totalSamplesDuration})}),t})}}const Ma=100;class $m extends du{constructor(e,t,n,r,s){super(e,t,R.Kind.Video,n,s),this.elementInfos=[],this.monitorReceiver=()=>m(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=$r(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=_a(()=>{this.updateDimensions()},Ma),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?Jn(this._mediaStreamTrack,t):Zn(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){const t=new Bm(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const t=this.elementInfos.filter(n=>n===e);for(const n of t)n.stopObserving();this.elementInfos=this.elementInfos.filter(n=>n!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const n of t)this.stopObservingElement(n);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return m(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,n="",r=new Map;return e.forEach(s=>{s.type==="inbound-rtp"?(n=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&&n!==""&&r.get(n)&&(t.mimeType=r.get(n).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(n=>n.element===e);for(const n of t)this.stopObservingElementInfo(n)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return m(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(){var e,t;const n=this.elementInfos.reduce((o,c)=>Math.max(o,c.visibilityChangedAt||0),0),r=!((t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pauseVideoInBackground)!==null&&t!==void 0)||t?this.isInBackground:!1,s=this.elementInfos.some(o=>o.pictureInPicture),a=this.elementInfos.some(o=>o.visible)&&!r||s;if(this.lastVisible!==a){if(!a&&Date.now()-n<Ma){Be.setTimeout(()=>{this.updateVisibility()},Ma);return}this.lastVisible=a,this.emit(M.VisibilityChanged,a,this)}}updateDimensions(){var e,t;let n=0,r=0;const s=this.getPixelDensity();for(const a of this.elementInfos){const o=a.width()*s,c=a.height()*s;o+c>n+r&&(n=o,r=c)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===n&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===r||(this.lastDimensions={width:n,height:r},this.emit(M.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?xd():t||(xd()>2?2:1)}}class Bm{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=n=>{var r;const{target:s,isIntersecting:a}=n;s===this.element&&(this.isIntersecting=a,this.isPiP=ji(this.element),this.visibilityChangedAt=Date.now(),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this))},this.onEnterPiP=()=>{var n,r,s;(r=(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window)===null||r===void 0||r.addEventListener("pagehide",this.onLeavePiP),this.isPiP=ji(this.element),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this)},this.onLeavePiP=()=>{var n;this.isPiP=ji(this.element),(n=this.handleVisibilityChanged)===null||n===void 0||n.call(this)},this.element=e,this.isIntersecting=t??Na(e),this.isPiP=Xe()&&ji(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,n;this.isIntersecting=Na(this.element),this.isPiP=ji(this.element),this.element.handleResize=()=>{var r;(r=this.handleResize)===null||r===void 0||r.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Od().observe(this.element),Id().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(n=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||n===void 0||n.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,n,r,s;(e=Od())===null||e===void 0||e.unobserve(this.element),(t=Id())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(n=window.documentPictureInPicture)===null||n===void 0||n.removeEventListener("enter",this.onEnterPiP),(s=(r=window.documentPictureInPicture)===null||r===void 0?void 0:r.window)===null||s===void 0||s.removeEventListener("pagehide",this.onLeavePiP)}}function ji(i){var e,t;return document.pictureInPictureElement===i?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?Na(i,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function Na(i,e){const t=e||window;let n=i.offsetTop,r=i.offsetLeft;const s=i.offsetWidth,a=i.offsetHeight,{hidden:o}=i,{display:c}=getComputedStyle(i);for(;i.offsetParent;)i=i.offsetParent,n+=i.offsetTop,r+=i.offsetLeft;return n<t.pageYOffset+t.innerHeight&&r<t.pageXOffset+t.innerWidth&&n+a>t.pageYOffset&&r+s>t.pageXOffset&&!o&&c!=="none"}class Bt extends Rt.EventEmitter{constructor(e,t,n,r){var s;super(),this.metadataMuted=!1,this.encryption=it.NONE,this.log=re,this.handleMuted=()=>{this.emit(M.Muted)},this.handleUnmuted=()=>{this.emit(M.Unmuted)},this.log=jt((s=r==null?void 0:r.loggerName)!==null&&s!==void 0?s:mt.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=n,this.source=R.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)),pe(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==it.NONE}get audioTrack(){if($t(this.track))return this.track}get videoTrack(){if(Xn(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=R.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===R.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(i){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(i.SubscriptionStatus||(i.SubscriptionStatus={})),function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"}(i.PermissionStatus||(i.PermissionStatus={}))})(Bt||(Bt={}));class La extends Bt{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,n,r){super(e,t.sid,t.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(M.Ended)},this.updateInfo(t),this.setTrack(n)}setTrack(e){this.track&&this.track.off(M.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(M.Ended,this.handleTrackEnded)}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return m(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return m(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return m(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return m(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if($t(this.track)){const t=this.track.getSourceTrackSettings(),n=new Set;return t.autoGainControl&&n.add(wt.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&n.add(wt.TF_ECHO_CANCELLATION),t.noiseSuppression&&n.add(wt.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&n.add(wt.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||n.add(wt.TF_NO_DTX),this.track.enhancedNoiseCancellation&&n.add(wt.TF_ENHANCED_NOISE_CANCELLATION),Array.from(n.values())}else return[]}}function zr(i,e){return m(this,void 0,void 0,function*(){i??(i={});let t=!1;const{audioProcessor:n,videoProcessor:r,optionsWithoutProcessor:s}=Fd(i);let a=s.audio,o=s.video;if(n&&typeof s.audio=="object"&&(s.audio.processor=n),r&&typeof s.video=="object"&&(s.video.processor=r),i.audio&&typeof s.audio=="object"&&typeof s.audio.deviceId=="string"){const h=s.audio.deviceId;s.audio.deviceId={exact:h},t=!0,a=Object.assign(Object.assign({},s.audio),{deviceId:{ideal:h}})}if(s.video&&typeof s.video=="object"&&typeof s.video.deviceId=="string"){const h=s.video.deviceId;s.video.deviceId={exact:h},t=!0,o=Object.assign(Object.assign({},s.video),{deviceId:{ideal:h}})}(s.audio===!0||typeof s.audio=="object"&&!s.audio.deviceId)&&(s.audio={deviceId:"default"}),(s.video===!0||typeof s.video=="object"&&!s.video.deviceId)&&(s.video={deviceId:"default"});const c=Nd(s,Zd,Jd),d=va(c),u=navigator.mediaDevices.getUserMedia(d);s.audio&&($e.userMediaPromiseMap.set("audioinput",u),u.catch(()=>$e.userMediaPromiseMap.delete("audioinput"))),s.video&&($e.userMediaPromiseMap.set("videoinput",u),u.catch(()=>$e.userMediaPromiseMap.delete("videoinput")));try{const h=yield u;return yield Promise.all(h.getTracks().map(f=>m(this,void 0,void 0,function*(){const g=f.kind==="audio";let y=g?c.audio:c.video;(typeof y=="boolean"||!y)&&(y={});let v;const _=g?d.audio:d.video;typeof _!="boolean"&&(v=_);const w=f.getSettings().deviceId;v!=null&&v.deviceId&&nn(v.deviceId)!==w?v.deviceId=w:v||(v={deviceId:w});const N=ym(f,v,e);return N.kind===R.Kind.Video?N.source=R.Source.Camera:N.kind===R.Kind.Audio&&(N.source=R.Source.Microphone),N.mediaStream=h,$t(N)&&n?yield N.setProcessor(n):Xn(N)&&r&&(yield N.setProcessor(r)),N})))}catch(h){if(!t)throw h;return zr(Object.assign(Object.assign({},i),{audio:a,video:o}),e)}})}function Vm(i){return m(this,void 0,void 0,function*(){return(yield zr({audio:!1,video:i??!0}))[0]})}function qm(i){return m(this,void 0,void 0,function*(){return(yield zr({audio:i??!0,video:!1}))[0]})}var an;(function(i){i.Excellent="excellent",i.Good="good",i.Poor="poor",i.Lost="lost",i.Unknown="unknown"})(an||(an={}));function zm(i){switch(i){case xi.EXCELLENT:return an.Excellent;case xi.GOOD:return an.Good;case xi.POOR:return an.Poor;case xi.LOST:return an.Lost;default:return an.Unknown}}class uu extends Rt.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===Tr.AGENT}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,n,r,s,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Tr.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=an.Unknown,this.log=re,this.log=jt((c=a==null?void 0:a.loggerName)!==null&&c!==void 0?c:mt.Participant),this.loggerOptions=a,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=n,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(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(R.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(R.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(R.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,this.log.trace("update participant info",Object.assign(Object.assign({},this.logContext),{info:e})),!0)}_setMetadata(e){const t=this.metadata!==e,n=this.metadata;this.metadata=e,t&&this.emit($.ParticipantMetadataChanged,n)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit($.ParticipantNameChanged,e)}_setAttributes(e){const t=Qp(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit($.AttributesChanged,t)}setPermissions(e){var t,n,r,s,a,o;const c=this.permissions,d=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((n=this.permissions)===null||n===void 0?void 0:n.canSubscribe)||e.canPublishData!==((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((u,h)=>{var f;return u!==((f=this.permissions)===null||f===void 0?void 0:f.canPublishSources[h])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,d&&this.emit($.ParticipantPermissionsChanged,c),d}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit($.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=zm(e),t!==this._connectionQuality&&this.emit($.ConnectionQualityChanged,this._connectionQuality)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>$t(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(M.Muted,()=>{this.emit($.TrackMuted,e)}),e.on(M.Unmuted,()=>{this.emit($.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case R.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case R.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function Wm(i){var e,t,n;if(!i.participantSid&&!i.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Pc({participantIdentity:(e=i.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=i.participantSid)!==null&&t!==void 0?t:"",allTracks:(n=i.allowAll)!==null&&n!==void 0?n:!1,trackSids:i.allowedTrackSids||[]})}const lu=15e3;class Gm extends uu{constructor(e,t,n,r,s){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.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=it.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Dd)},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.handleDisconnected=()=>{var a,o;this.reconnectFuture&&(this.reconnectFuture.promise.catch(c=>this.log.warn(c.message,this.logContext)),(o=(a=this.reconnectFuture)===null||a===void 0?void 0:a.reject)===null||o===void 0||o.call(a,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.handleSignalRequestResponse=a=>{const{requestId:o,reason:c,message:d}=a,u=this.pendingSignalRequests.get(o);u&&(c!==Bs.OK&&u.reject(new Td(d,c)),this.pendingSignalRequests.delete(o))},this.handleDataPacket=a=>{switch(a.value.case){case"rpcResponse":let o=a.value.value,c=null,d=null;o.value.case==="payload"?c=o.value.value:o.value.case==="error"&&(d=De.fromProto(o.value.value)),this.handleIncomingRpcResponse(o.requestId,c,d);break;case"rpcAck":let u=a.value.value;this.handleIncomingRpcAck(u.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(a=>Wm(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",Object.assign(Object.assign({},this.logContext),pe(a)));return}this.engine.updateMuteStatus(a.sid,o)},this.onTrackUpstreamPaused=a=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),pe(a))),this.onTrackMuted(a,!0)},this.onTrackUpstreamResumed=a=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),pe(a))),this.onTrackMuted(a,a.isMuted)},this.onTrackFeatureUpdate=a=>{const 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),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(o.trackSid,o.getTrackFeatures())},this.handleSubscribedQualityUpdate=a=>m(this,void 0,void 0,function*(){var o,c,d,u,h,f;if(!(!((h=this.roomOptions)===null||h===void 0)&&h.dynacast))return;const g=this.videoTrackPublications.get(a.trackSid);if(!g){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}if(a.subscribedCodecs.length>0){if(!g.videoTrack)return;const w=yield g.videoTrack.setPublishingCodecs(a.subscribedCodecs);try{for(var y=!0,v=Yt(w),_;_=yield v.next(),o=_.done,!o;y=!0){u=_.value,y=!1;const N=u;Ip(N)&&(this.log.debug("publish ".concat(N," for ").concat(g.videoTrack.sid),Object.assign(Object.assign({},this.logContext),pe(g))),yield this.publishAdditionalCodecForTrack(g.videoTrack,N,g.options))}}catch(N){c={error:N}}finally{try{!y&&!o&&(d=v.return)&&(yield d.call(v))}finally{if(c)throw c.error}}}else a.subscribedQualities.length>0&&(yield(f=g.videoTrack)===null||f===void 0?void 0:f.setPublishingLayers(a.subscribedQualities))}),this.handleLocalTrackUnpublished=a=>{const o=this.trackPublications.get(a.trackSid);if(!o){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}this.unpublishTrack(o.track)},this.handleTrackEnded=a=>m(this,void 0,void 0,function*(){if(a.source===R.Source.ScreenShare||a.source===R.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),pe(a))),this.unpublishTrack(a);else if(a.isUserProvided)yield a.mute();else if(Rn(a)||rn(a))try{if(Xe())try{const o=yield navigator==null?void 0:navigator.permissions.query({name:a.source===R.Source.Camera?"camera":"microphone"});if(o&&o.state==="denied")throw this.log.warn("user has revoked access to ".concat(a.source),Object.assign(Object.assign({},this.logContext),pe(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",Object.assign(Object.assign({},this.logContext),pe(a))),Rn(a)?yield a.restartTrack({deviceId:"default"}):yield a.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),pe(a))),yield a.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=n,this.roomOptions=r,this.setupEngine(n),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=s}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==it.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){this.engine=e,this.engine.on(L.RemoteMute,(t,n)=>{const r=this.trackPublications.get(t);!r||!r.track||(n?r.mute():r.unmute())}),this.engine.on(L.Connected,this.handleReconnected).on(L.SignalRestarted,this.handleReconnected).on(L.SignalResumed,this.handleReconnected).on(L.Restarting,this.handleReconnecting).on(L.Resuming,this.handleReconnecting).on(L.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(L.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(L.Disconnected,this.handleDisconnected).on(L.SignalRequestResponse,this.handleSignalRequestResponse).on(L.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return m(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return m(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return m(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return m(this,arguments,void 0,function(t){var n=this;let{metadata:r,name:s,attributes:a}=t;return function*(){return new Promise((o,c)=>m(n,void 0,void 0,function*(){var d,u;try{let h=!1;const f=yield this.engine.client.sendUpdateLocalMetadata((d=r??this.metadata)!==null&&d!==void 0?d:"",(u=s??this.name)!==null&&u!==void 0?u:"",a),g=performance.now();for(this.pendingSignalRequests.set(f,{resolve:o,reject:y=>{c(y),h=!0},values:{name:s,metadata:r,attributes:a}});performance.now()-g<5e3&&!h;){if((!s||this.name===s)&&(!r||this.metadata===r)&&(!a||Object.entries(a).every(y=>{let[v,_]=y;return this.attributes[v]===_||_===""&&!this.attributes[v]}))){this.pendingSignalRequests.delete(f),o();return}yield Qe(50)}c(new Td("Request to update local metadata timed out","TimeoutError"))}catch(h){h instanceof Error&&c(h)}}))}()})}setCameraEnabled(e,t,n){return this.setTrackEnabled(R.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(R.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(R.Source.ScreenShare,e,t,n)}setPermissions(e){const t=this.permissions,n=super.setPermissions(e);return n&&t&&this.emit($.ParticipantPermissionsChanged,t),n}setE2EEEnabled(e){return m(this,void 0,void 0,function*(){this.encryptionType=e?it.GCM:it.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,n,r){return m(this,void 0,void 0,function*(){var s,a;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(t)if(o)yield o.unmute();else{let c;if(this.pendingPublishing.has(e)){const d=yield this.waitForPendingPublicationOfSource(e);return d||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield d==null?void 0:d.unmute(),d}this.pendingPublishing.add(e);try{switch(e){case R.Source.Camera:c=yield this.createTracks({video:(s=n)!==null&&s!==void 0?s:!0});break;case R.Source.Microphone:c=yield this.createTracks({audio:(a=n)!==null&&a!==void 0?a:!0});break;case R.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},n));break;default:throw new Ft(e)}}catch(d){throw c==null||c.forEach(u=>{u.stop()}),d instanceof Error&&this.emit($.MediaDevicesError,d),this.pendingPublishing.delete(e),d}try{const d=[];for(const h of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),pe(h))),d.push(this.publishTrack(h,r));[o]=yield Promise.all(d)}catch(d){throw c==null||c.forEach(u=>{u.stop()}),d}finally{this.pendingPublishing.delete(e)}}else if(!(o!=null&&o.track)&&this.pendingPublishing.has(e)&&(o=yield this.waitForPendingPublicationOfSource(e),o||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),o&&o.track)if(e===R.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const c=this.getTrackPublication(R.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return m(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(R.Source.Camera)||this.pendingPublishing.has(R.Source.Microphone))){this.pendingPublishing.add(R.Source.Camera),this.pendingPublishing.add(R.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(t=>this.publishTrack(t)))}finally{this.pendingPublishing.delete(R.Source.Camera),this.pendingPublishing.delete(R.Source.Microphone)}}})}createTracks(e){return m(this,void 0,void 0,function*(){var t,n;e??(e={});const r=Nd(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(n=this.roomOptions)===null||n===void 0?void 0:n.videoCaptureDefaults);try{return(yield zr(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>($t(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=R.Source.Microphone,this.emit($.AudioStreamAcquired)),Xn(o)&&(this.cameraError=void 0,o.source=R.Source.Camera),o))}catch(s){throw s instanceof Error&&(e.audio&&(this.microphoneError=s),e.video&&(this.cameraError=s)),s}})}createScreenTracks(e){return m(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Qs("getDisplayMedia not supported");e.resolution===void 0&&!Lp()&&(e.resolution=sa.h1080fps30.resolution);const t=Zp(e),n=yield navigator.mediaDevices.getDisplayMedia(t),r=n.getVideoTracks();if(r.length===0)throw new Ft("no video track found");const s=new qr(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=R.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);const a=[s];if(n.getAudioTracks().length>0){this.emit($.AudioStreamAcquired);const o=new Br(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=R.Source.ScreenShareAudio,a.push(o)}return a})}publishTrack(e,t){return m(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return m(this,arguments,void 0,function(n,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var o,c,d,u;Rn(n)&&n.setAudioContext(s.audioContext),yield(o=s.reconnectFuture)===null||o===void 0?void 0:o.promise,s.republishPromise&&!a&&(yield s.republishPromise),Qn(n)&&s.pendingPublishPromises.has(n)&&(yield s.pendingPublishPromises.get(n));let h;if(n instanceof MediaStreamTrack)h=n.getConstraints();else{h=n.constraints;let w;switch(n.source){case R.Source.Microphone:w="audioinput";break;case R.Source.Camera:w="videoinput"}w&&s.activeDeviceMap.has(w)&&(h=Object.assign(Object.assign({},h),{deviceId:s.activeDeviceMap.get(w)}))}if(n instanceof MediaStreamTrack)switch(n.kind){case"audio":n=new Br(n,h,!0,s.audioContext,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;case"video":n=new qr(n,h,!0,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;default:throw new Ft("unsupported MediaStreamTrack kind ".concat(n.kind))}else n.updateLoggerOptions({loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});let f;if(s.trackPublications.forEach(w=>{w.track&&w.track===n&&(f=w)}),f)return s.log.warn("track has already been published, skipping",Object.assign(Object.assign({},s.logContext),pe(f))),f;const g="channelCount"in n.mediaStreamTrack.getSettings()&&n.mediaStreamTrack.getSettings().channelCount===2||n.mediaStreamTrack.getConstraints().channelCount===2,y=(c=r==null?void 0:r.forceStereo)!==null&&c!==void 0?c:g;y&&(r||(r={}),r.dtx===void 0&&s.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},s.logContext),pe(n))),r.red===void 0&&s.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(d=r.dtx)!==null&&d!==void 0||(r.dtx=!1),(u=r.red)!==null&&u!==void 0||(r.red=!1));const v=Object.assign(Object.assign({},s.roomOptions.publishDefaults),r);!Up()&&s.roomOptions.e2ee&&(s.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},s.logContext)),v.simulcast=!1),v.source&&(n.source=v.source);const _=new Promise((w,N)=>m(s,void 0,void 0,function*(){try{if(this.engine.client.currentState!==Se.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:pe(n)}));const U=()=>m(this,void 0,void 0,function*(){try{const b=yield this.publish(n,v,y);w(b)}catch(b){N(b)}});setTimeout(()=>{this.engine.off(L.SignalConnected,U),N(new ea("publishing rejected as engine not connected within timeout",408))},15e3),this.engine.once(L.SignalConnected,U),this.engine.on(L.Closing,()=>{this.engine.off(L.SignalConnected,U),N(new ea("publishing rejected as engine closed",499))})}else try{const U=yield this.publish(n,v,y);w(U)}catch(U){N(U)}}catch(U){N(U)}}));s.pendingPublishPromises.set(n,_);try{return yield _}catch(w){throw w}finally{s.pendingPublishPromises.delete(n)}}()})}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),pe(e))),!1;const{canPublish:t,canPublishSources:n}=this.permissions;return t&&(n.length===0||n.map(r=>Xp(r)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),pe(e))),!1)}publish(e,t,n){return m(this,void 0,void 0,function*(){var r,s,a,o,c,d,u,h,f,g;if(!this.hasPermissionsToPublish(e))throw new ea("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(k=>Qn(e)&&k.source===e.source)&&e.source!==R.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),pe(e))),t.stopMicTrackOnMute&&$t(e)&&(e.stopOnMute=!0),e.source===R.Source.ScreenShare&&Yn()&&(t.simulcast=!1),t.videoCodec==="av1"&&!Dp()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!Mp()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=Ea),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(k=>t.videoCodec===jr(k.mime))||(t.videoCodec=jr(this.enabledPublishVideoCodecs[0].mime)));const v=t.videoCodec;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);const _=new Ls({cid:e.mediaStreamTrack.id,name:t.name,type:R.kindToProto(e.kind),muted:e.isMuted,source:R.sourceToProto(e.source),disableDtx:!(!((r=t.dtx)!==null&&r!==void 0)||r),encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(!((s=t.red)!==null&&s!==void 0)||s),stream:t==null?void 0:t.stream,backupCodecPolicy:t==null?void 0:t.backupCodecPolicy});let w;if(e.kind===R.Kind.Video){let k={width:0,height:0};try{k=yield e.waitForDimensions()}catch{const F=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:Mi.h720.resolution;k={width:F.width,height:F.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),pe(e)),{dims:k}))}_.width=k.width,_.height=k.height,rn(e)&&(Ni(v)&&(e.source===R.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),pe(e))))),t.scalabilityMode=(c=t.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),_.simulcastCodecs=[new Ns({codec:v,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:Ea}),t.backupCodec&&v!==t.backupCodec.codec&&_.encryption===it.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),_.simulcastCodecs.push(new Ns({codec:t.backupCodec.codec,cid:""})))),w=Ia(e.source===R.Source.ScreenShare,_.width,_.height,t),_.layers=ru(_.width,_.height,w,Ni(t.videoCodec))}else e.kind===R.Kind.Audio&&(w=[{maxBitrate:(d=t.audioPreset)===null||d===void 0?void 0:d.maxBitrate,priority:(h=(u=t.audioPreset)===null||u===void 0?void 0:u.priority)!==null&&h!==void 0?h:"high",networkPriority:(g=(f=t.audioPreset)===null||f===void 0?void 0:f.priority)!==null&&g!==void 0?g:"high"}]);if(!this.engine||this.engine.isClosed)throw new Fe("cannot publish track when not connected");const N=()=>m(this,void 0,void 0,function*(){var k,x,F;if(!this.engine.pcManager)throw new Fe("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,w),rn(e)&&((k=t.degradationPreference)!==null&&k!==void 0||(t.degradationPreference=Rm(e)),e.setDegradationPreference(t.degradationPreference)),w)if(Yn()&&e.kind===R.Kind.Audio){let q;for(const te of this.engine.pcManager.publisher.getTransceivers())if(te.sender===e.sender){q=te;break}q&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:q,codec:"opus",maxbr:!((x=w[0])===null||x===void 0)&&x.maxBitrate?w[0].maxBitrate/1e3:0})}else e.codec&&Ni(e.codec)&&(!((F=w[0])===null||F===void 0)&&F.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:_.cid,codec:e.codec,maxbr:w[0].maxBitrate/1e3});yield this.engine.negotiate()});let U;if(this.enabledPublishVideoCodecs.length>0)U=(yield Promise.all([this.engine.addTrack(_),N()]))[0];else{U=yield this.engine.addTrack(_);let k;if(U.codecs.forEach(x=>{k===void 0&&(k=x.mimeType)}),k&&e.kind===R.Kind.Video){const x=jr(k);x!==v&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),pe(e)),{codec:x})),t.videoCodec=x,w=Ia(e.source===R.Source.ScreenShare,_.width,_.height,t))}yield N()}const b=new La(e.kind,U,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return b.options=t,e.sid=U.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:w,trackInfo:U})),rn(e)?e.startMonitor(this.engine.client):Rn(e)&&e.startMonitor(),this.addTrackPublication(b),this.emit($.LocalTrackPublished,b),b})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return m(this,void 0,void 0,function*(){var r;if(this.encryptionType!==it.NONE)return;let s;if(this.trackPublications.forEach(g=>{g.track&&g.track===e&&(s=g)}),!s)throw new Ft("track is not published");if(!rn(e))throw new Ft("track is not a video track");const a=Object.assign(Object.assign({},(r=this.roomOptions)===null||r===void 0?void 0:r.publishDefaults),n),o=Em(e,t,a);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),pe(e)));return}const c=e.addSimulcastTrack(t,o);if(!c)return;const d=new Ls({cid:c.mediaStreamTrack.id,type:R.kindToProto(e.kind),muted:e.isMuted,source:R.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:c.mediaStreamTrack.id}]});if(d.layers=ru(d.width,d.height,o),!this.engine||this.engine.isClosed)throw new Fe("cannot publish track when not connected");const u=()=>m(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,c,a,o),yield this.engine.negotiate()}),f=(yield Promise.all([this.engine.addTrack(d),u()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:f}))})}unpublishTrack(e,t){return m(this,void 0,void 0,function*(){var n,r;if(Qn(e)){const d=this.pendingPublishPromises.get(e);d&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),pe(e))),yield d)}const s=this.getPublicationForTrack(e),a=s?pe(s):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),a)),!s||!s.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),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=(n=this.roomOptions)===null||n===void 0?void 0:n.stopLocalTrackOnUnpublish)!==null&&r!==void 0?r:!0),t?e.stop():e.stopMonitor();let o=!1;const c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Ae.FAILED&&c)try{for(const d of this.engine.pcManager.publisher.getTransceivers())d.sender===c&&(d.direction="inactive",o=!0);if(this.engine.removeTrack(c)&&(o=!0),rn(e)){for(const[,d]of e.simulcastCodecs)d.sender&&(this.engine.removeTrack(d.sender)&&(o=!0),d.sender=void 0);e.simulcastCodecs.clear()}}catch(d){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),a),{error:d}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case R.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case R.Kind.Video:this.videoTrackPublications.delete(s.trackSid);break}return this.emit($.LocalTrackUnpublished,s),s.setTrack(void 0),o&&(yield this.engine.negotiate()),s})}unpublishTracks(e){return m(this,void 0,void 0,function*(){return(yield Promise.all(e.map(n=>this.unpublishTrack(n)))).filter(n=>!!n)})}republishAllTracks(e){return m(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){n.republishPromise&&(yield n.republishPromise),n.republishPromise=new Promise((s,a)=>m(n,void 0,void 0,function*(){try{const 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=>m(this,void 0,void 0,function*(){const d=c.track;yield this.unpublishTrack(d,!1),r&&!d.isMuted&&d.source!==R.Source.ScreenShare&&d.source!==R.Source.ScreenShareAudio&&(Rn(d)||rn(d))&&!d.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:c.trackSid})),yield d.restartTrack()),yield this.publishOrRepublishTrack(d,c.options,!0)}))),s()}catch(o){a(o)}finally{this.republishPromise=void 0}})),yield n.republishPromise}()})}publishData(e){return m(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){const s=r.reliable?le.RELIABLE:le.LOSSY,a=r.destinationIdentities,o=r.topic,c=new Ye({kind:s,value:{case:"user",value:new oc({participantIdentity:n.identity,payload:t,destinationIdentities:a,topic:o})}});yield n.engine.sendDataPacket(c,s)}()})}publishDtmf(e,t){return m(this,void 0,void 0,function*(){const n=new Ye({kind:le.RELIABLE,value:{case:"sipDtmf",value:new cc({code:e,digit:t})}});yield this.engine.sendDataPacket(n,le.RELIABLE)})}sendChatMessage(e,t){return m(this,void 0,void 0,function*(){const n={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t==null?void 0:t.attachments},r=new Ye({value:{case:"chatMessage",value:new xs(Object.assign(Object.assign({},n),{timestamp:_e.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(r,le.RELIABLE),this.emit($.ChatMessage,n),n})}editChatMessage(e,t){return m(this,void 0,void 0,function*(){const n=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),r=new Ye({value:{case:"chatMessage",value:new xs(Object.assign(Object.assign({},n),{timestamp:_e.parse(n.timestamp),editTimestamp:_e.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,le.RELIABLE),this.emit($.ChatMessage,n),n})}sendText(e,t){return m(this,void 0,void 0,function*(){var n;const r=crypto.randomUUID(),a=new TextEncoder().encode(e).byteLength,o=(n=t==null?void 0:t.attachments)===null||n===void 0?void 0:n.map(()=>crypto.randomUUID()),c=new Array(o?o.length+1:1).fill(0),d=(h,f)=>{var g;c[f]=h;const y=c.reduce((v,_)=>v+_,0);(g=t==null?void 0:t.onProgress)===null||g===void 0||g.call(t,y)},u=yield this.streamText({streamId:r,totalSize:a,destinationIdentities:t==null?void 0:t.destinationIdentities,topic:t==null?void 0:t.topic,attachedStreamIds:o,attributes:t==null?void 0:t.attributes});return yield u.write(e),d(1,0),yield u.close(),t!=null&&t.attachments&&o&&(yield Promise.all(t.attachments.map((h,f)=>m(this,void 0,void 0,function*(){return this._sendFile(o[f],h,{topic:t.topic,mimeType:h.type,onProgress:g=>{d(g,f+1)}})})))),u.info})}streamText(e){return m(this,void 0,void 0,function*(){var t,n;const r=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),s={id:r,mimeType:"text/plain",timestamp:Date.now(),topic:(n=e==null?void 0:e.topic)!==null&&n!==void 0?n:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes},a=new Os({streamId:r,mimeType:s.mimeType,topic:s.topic,timestamp:Pn(s.timestamp),totalLength:Pn(e==null?void 0:e.totalSize),attributes:s.attributes,contentHeader:{case:"textHeader",value:new bc({version:e==null?void 0:e.version,attachedStreamIds:e==null?void 0:e.attachedStreamIds,replyToStreamId:e==null?void 0:e.replyToStreamId,operationType:(e==null?void 0:e.type)==="update"?Is.UPDATE:Is.CREATE})}}),o=e==null?void 0:e.destinationIdentities,c=new Ye({destinationIdentities:o,value:{case:"streamHeader",value:a}});yield this.engine.sendDataPacket(c,le.RELIABLE);let d=0;const u=this,h=new WritableStream({write(y){return m(this,void 0,void 0,function*(){for(const v of Kp(y,lu)){yield u.engine.waitForBufferStatusLow(le.RELIABLE);const _=new As({content:v,streamId:r,chunkIndex:Pn(d)}),w=new Ye({destinationIdentities:o,value:{case:"streamChunk",value:_}});yield u.engine.sendDataPacket(w,le.RELIABLE),d+=1}})},close(){return m(this,void 0,void 0,function*(){const y=new Ds({streamId:r}),v=new Ye({destinationIdentities:o,value:{case:"streamTrailer",value:y}});yield u.engine.sendDataPacket(v,le.RELIABLE)})},abort(y){console.log("Sink error:",y)}});let f=()=>m(this,void 0,void 0,function*(){yield g.close()});u.engine.once(L.Closing,f);const g=new Um(h,s,()=>this.engine.off(L.Closing,f));return g})}sendFile(e,t){return m(this,void 0,void 0,function*(){const n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}})}_sendFile(e,t,n){return m(this,void 0,void 0,function*(){var r;const s=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(r=n==null?void 0:n.mimeType)!==null&&r!==void 0?r:t.type,topic:n==null?void 0:n.topic,destinationIdentities:n==null?void 0:n.destinationIdentities}),a=t.stream().getReader();for(;;){const{done:o,value:c}=yield a.read();if(o)break;yield s.write(c)}return yield s.close(),s.info})}streamBytes(e){return m(this,void 0,void 0,function*(){var t,n,r,s,a;const o=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),c=e==null?void 0:e.destinationIdentities,d={id:o,mimeType:(n=e==null?void 0:e.mimeType)!==null&&n!==void 0?n:"application/octet-stream",topic:(r=e==null?void 0:e.topic)!==null&&r!==void 0?r:"",timestamp:Date.now(),attributes:e==null?void 0:e.attributes,size:e==null?void 0:e.totalSize,name:(s=e==null?void 0:e.name)!==null&&s!==void 0?s:"unknown"},u=new Os({totalLength:Pn((a=d.size)!==null&&a!==void 0?a:0),mimeType:d.mimeType,streamId:o,topic:d.topic,timestamp:Pn(Date.now()),contentHeader:{case:"byteHeader",value:new kc({name:d.name})}}),h=new Ye({destinationIdentities:c,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(h,le.RELIABLE);let f=0;const g=new Ze,y=this.engine,v=this.log,_=new WritableStream({write(N){return m(this,void 0,void 0,function*(){const U=yield g.lock();let b=0;try{for(;b<N.byteLength;){const k=N.slice(b,b+lu);yield y.waitForBufferStatusLow(le.RELIABLE);const x=new Ye({destinationIdentities:c,value:{case:"streamChunk",value:new As({content:k,streamId:o,chunkIndex:Pn(f)})}});yield y.sendDataPacket(x,le.RELIABLE),f+=1,b+=k.byteLength}}finally{U()}})},close(){return m(this,void 0,void 0,function*(){const N=new Ds({streamId:o}),U=new Ye({destinationIdentities:c,value:{case:"streamTrailer",value:N}});yield y.sendDataPacket(U,le.RELIABLE)})},abort(N){v.error("Sink error:",N)}});return new jm(_,d)})}performRpc(e){return m(this,arguments,void 0,function(t){var n=this;let{destinationIdentity:r,method:s,payload:a,responseTimeout:o=1e4}=t;return function*(){return new Promise((d,u)=>m(n,void 0,void 0,function*(){var h,f,g,y;if(Pa(a)>Yd){u(De.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((f=(h=this.engine.latestJoinResponse)===null||h===void 0?void 0:h.serverInfo)===null||f===void 0)&&f.version&&wn((y=(g=this.engine.latestJoinResponse)===null||g===void 0?void 0:g.serverInfo)===null||y===void 0?void 0:y.version,"1.8.0")<0){u(De.builtIn("UNSUPPORTED_SERVER"));return}const v=crypto.randomUUID();yield this.publishRpcRequest(r,v,s,a,o-2e3);const _=setTimeout(()=>{this.pendingAcks.delete(v),u(De.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(v),clearTimeout(w)},2e3);this.pendingAcks.set(v,{resolve:()=>{clearTimeout(_)},participantIdentity:r});const w=setTimeout(()=>{this.pendingResponses.delete(v),u(De.builtIn("RESPONSE_TIMEOUT"))},o);this.pendingResponses.set(v,{resolve:(N,U)=>{clearTimeout(w),this.pendingAcks.has(v)&&(console.warn("RPC response received before ack",v),this.pendingAcks.delete(v),clearTimeout(_)),U?u(U):d(N??"")},participantIdentity:r})}))}()})}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,n){const r=this.pendingResponses.get(e);r?(r.resolve(t,n),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,n,r,s){return m(this,void 0,void 0,function*(){const a=new Ye({destinationIdentities:[e],kind:le.RELIABLE,value:{case:"rpcRequest",value:new dc({id:t,method:n,payload:r,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(a,le.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:n}]of this.pendingAcks)n===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:n,resolve:r}]of this.pendingResponses)n===e&&(r(null,De.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return e.sid!==this.sid||!super.updateInfo(e)?!1:(e.tracks.forEach(t=>{var n,r;const s=this.trackPublications.get(t.sid);if(s){const a=s.isMuted||((r=(n=s.track)===null||n===void 0?void 0:n.isUpstreamPaused)!==null&&r!==void 0?r:!1);a!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),pe(s)),{mutedOnServer:a})),this.engine.client.sendMuteTrack(t.sid,a))}}),!0)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(n=>{const r=n.track;r&&(e instanceof MediaStreamTrack?(Rn(r)||rn(r))&&r.mediaStreamTrack===e&&(t=n):e===r&&(t=n))}),t}waitForPendingPublicationOfSource(e){return m(this,void 0,void 0,function*(){const n=Date.now();for(;Date.now()<n+1e4;){const r=Array.from(this.pendingPublishPromises.entries()).find(s=>{let[a]=s;return a.source===e});if(r)return r[1];yield Qe(20)}})}}class Km extends Bt{constructor(e,t,n,r){super(e,t.sid,t.name,r),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=ot.HIGH,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.disabled=!s,this.emitTrackUpdate()},this.handleVideoDimensionsChange=s=>{this.log.debug("adaptivestream video dimensions ".concat(s.width,"x").concat(s.height),this.logContext),this.videoDimensions=s,this.emitTrackUpdate()},this.subscribed=n,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const r=new Cr({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new fc({participantSid:"",trackSids:[this.trackSid]})]});this.emit(M.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?Bt.SubscriptionStatus.Unsubscribed:super.isSubscribed?Bt.SubscriptionStatus.Subscribed:Bt.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Bt.PermissionStatus.Allowed:Bt.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return!this.disabled}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.disabled===!e||(this.disabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.currentVideoQuality===e||(this.currentVideoQuality=e,this.videoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,n;this.isManualOperationAllowed()&&(((t=this.videoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((n=this.videoDimensions)===null||n===void 0?void 0:n.height)===e.height||(ma(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&ma(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const t=this.subscriptionStatus,n=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(n),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(M.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?M.Muted:M.Unmuted)}emitSubscriptionUpdateIfChanged(e){const 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.kind===R.Kind.Video&&this.isAdaptiveStream?(this.log.warn("adaptive stream is enabled, cannot change video track settings",this.logContext),!1):this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return ma(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Tc({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(e.width=Math.ceil(this.videoDimensions.width),e.height=Math.ceil(this.videoDimensions.height)):this.currentVideoQuality!==void 0?e.quality=this.currentVideoQuality:e.quality=ot.HIGH,this.emit(M.UpdateSettings,e)}}class Wr extends uu{static fromParticipantInfo(e,t,n){return new Wr(e,t.sid,t.identity,t.name,t.metadata,t.attributes,n,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,r,s,a,o){let c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Tr.STANDARD;super(t,n||"",r,s,a,o,c),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(M.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),pe(e))),this.signalClient.sendUpdateTrackSettings(t)}),e.on(M.UpdateSubscription,t=>{t.participantTracks.forEach(n=>{n.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(M.SubscriptionPermissionChanged,t=>{this.emit($.TrackSubscriptionPermissionChanged,e,t)}),e.on(M.SubscriptionStatusChanged,t=>{this.emit($.TrackSubscriptionStatusChanged,e,t)}),e.on(M.Subscribed,t=>{this.emit($.TrackSubscribed,t,e)}),e.on(M.Unsubscribed,t=>{this.emit($.TrackUnsubscribed,t,e)}),e.on(M.SubscriptionFailed,t=>{this.emit($.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:R.Source.Microphone;this.volumeMap.set(t,e);const n=this.getTrackPublication(t);n&&n.track&&n.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:R.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,n,r,s,a){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(u=>{!o&&e.kind===u.kind.toString()&&(o=u)}),!o){if(a===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit($.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,n,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),pe(o))),this.emit($.TrackSubscriptionFailed,t);return}const c=e.kind==="video";let d;return c?d=new $m(e,t,r,s):d=new Fm(e,t,r,this.audioContext,this.audioOutput),d.source=o.source,d.isMuted=o.isMuted,d.setMediaStream(n),d.start(),o.setTrack(d),this.volumeMap.has(o.source)&&pa(d)&&$t(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;const t=new Map,n=new Map;return e.tracks.forEach(r=>{var s,a;let o=this.getTrackPublicationBySid(r.sid);if(o)o.updateInfo(r);else{const c=R.kindFromProto(r.type);if(!c)return;o=new Km(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),n.set(r.sid,o);const d=Array.from(this.trackPublications.values()).find(u=>u.source===(o==null?void 0:o.source));d&&o.source!==R.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:pe(d),newTrack:pe(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),pe(r))),this.unpublishTrack(r.trackSid,!0))}),n.forEach(r=>{this.emit($.TrackPublished,r)}),!0}unpublishTrack(e,t){const n=this.trackPublications.get(e);if(!n)return;const{track:r}=n;switch(r&&(r.stop(),n.setTrack(void 0)),this.trackPublications.delete(e),n.kind){case R.Kind.Audio:this.audioTrackPublications.delete(e);break;case R.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit($.TrackUnpublished,n)}setAudioOutput(e){return m(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(n=>{var r;$t(n.track)&&pa(n.track)&&t.push(n.track.setSinkId((r=e.deviceId)!==null&&r!==void 0?r:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:n})),super.emit(e,...n)}}var fe;(function(i){i.Disconnected="disconnected",i.Connecting="connecting",i.Connected="connected",i.Reconnecting="reconnecting",i.SignalReconnecting="signalReconnecting"})(fe||(fe={}));const Hm=4*1e3;class ni extends Rt.EventEmitter{constructor(e){var t,n,r,s;if(super(),t=this,this.state=fe.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=re,this.bufferedEvents=[],this.isResuming=!1,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.rpcHandlers=new Map,this.connect=(a,o,c)=>m(this,void 0,void 0,function*(){var d;if(!Np())throw xt()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const u=yield this.disconnectLock.lock();if(this.state===fe.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),u(),Promise.resolve();if(this.connectFuture)return u(),this.connectFuture.promise;this.setAndEmitConnectionState(fe.Connecting),((d=this.regionUrlProvider)===null||d===void 0?void 0:d.getServerUrl().toString())!==a&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),da(new URL(a))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new Da(a,o):this.regionUrlProvider.updateToken(o),this.regionUrlProvider.fetchRegionSettings().then(g=>{var y;(y=this.regionUrlProvider)===null||y===void 0||y.setServerReportedRegions(g)}).catch(g=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:g}))}));const h=(g,y,v)=>m(this,void 0,void 0,function*(){var _,w;this.abortController&&this.abortController.abort();const N=new AbortController;this.abortController=N,u==null||u();try{yield this.attemptConnection(v??a,o,c,N),this.abortController=void 0,g()}catch(U){if(this.regionUrlProvider&&U instanceof ye&&U.reason!==oe.Cancelled&&U.reason!==oe.NotAllowed){let b=null;try{b=yield this.regionUrlProvider.getNextBestRegionUrl((_=this.abortController)===null||_===void 0?void 0:_.signal)}catch(k){if(k instanceof ye&&(k.status===401||k.reason===oe.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),y(k);return}}b&&!(!((w=this.abortController)===null||w===void 0)&&w.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(U.message,". Retrying with another region: ").concat(b),this.logContext),this.recreateEngine(),yield h(g,y,b)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Md(U)),y(U))}else{let b=ft.UNKNOWN_REASON;U instanceof ye&&(b=Md(U)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,b),y(U)}}}),f=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Dd((g,y)=>{h(g,y,f)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(a,o,c,d,u,h)=>m(this,void 0,void 0,function*(){var f,g,y;const v=yield c.join(a,o,{autoSubscribe:d.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:d.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:d.websocketTimeout},h.signal);let _=v.serverInfo;if(_||(_={version:v.serverVersion,region:v.serverRegion}),this.serverInfo=_,this.log.debug("connected to Livekit Server ".concat(Object.entries(_).map(w=>{let[N,U]=w;return"".concat(N,": ").concat(U)}).join(", ")),{room:(f=v.room)===null||f===void 0?void 0:f.name,roomSid:(g=v.room)===null||g===void 0?void 0:g.sid,identity:(y=v.participant)===null||y===void 0?void 0:y.identity}),!_.version)throw new kp("unknown server version");return _.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),u.dynacast=!1),v}),this.applyJoinResponse=a=>{const o=a.participant;if(this.localParticipant.sid=o.sid,this.localParticipant.identity=o.identity,this.localParticipant.setEnabledPublishCodecs(a.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(a.sifTrailer)}catch(c){this.log.error(c instanceof Error?c.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:c}))}this.handleParticipantUpdates([o,...a.otherParticipants]),a.room&&this.handleRoomUpdate(a.room)},this.attemptConnection=(a,o,c,d)=>m(this,void 0,void 0,function*(){var u,h;this.state===fe.Reconnecting||this.isResuming||!((u=this.engine)===null||u===void 0)&&u.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((h=this.regionUrlProvider)===null||h===void 0)&&h.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},wa),c),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const f=yield this.connectSignal(a,o,this.engine,this.connOptions,this.options,d);this.applyJoinResponse(f),this.setupLocalParticipantEvents(),this.emit(O.SignalConnected)}catch(f){yield this.engine.close(),this.recreateEngine();const g=new ye("could not establish signal connection",oe.ServerUnreachable);throw f instanceof Error&&(g.message="".concat(g.message,": ").concat(f.message)),f instanceof ye&&(g.reason=f.reason,g.status=f.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:f})),g}if(d.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new ye("Connection attempt aborted",oe.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,d)}catch(f){throw yield this.engine.close(),this.recreateEngine(),f}Xe()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Xe()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(fe.Connected),this.emit(O.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var a=arguments.length,o=new Array(a),c=0;c<a;c++)o[c]=arguments[c];return m(t,[...o],void 0,function(){var d=this;let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var h,f,g,y;const v=yield d.disconnectLock.lock();try{if(d.state===fe.Disconnected){d.log.debug("already disconnected",d.logContext);return}d.log.info("disconnect from room",Object.assign({},d.logContext)),(d.state===fe.Connecting||d.state===fe.Reconnecting||d.isResuming)&&(d.log.warn("abort connection attempt",d.logContext),(h=d.abortController)===null||h===void 0||h.abort(),(g=(f=d.connectFuture)===null||f===void 0?void 0:f.reject)===null||g===void 0||g.call(f,new ye("Client initiated disconnect",oe.Cancelled)),d.connectFuture=void 0),!((y=d.engine)===null||y===void 0)&&y.client.isDisconnected||(yield d.engine.client.sendLeave()),d.engine&&(yield d.engine.close()),d.handleDisconnect(u,ft.CLIENT_INITIATED),d.engine=void 0}finally{v()}}()})},this.onPageLeave=()=>m(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>m(this,void 0,void 0,function*(){const a=[],o=gt();if(o&&o.os==="iOS"){const c="livekit-dummy-audio-el";let d=document.getElementById(c);if(!d){d=document.createElement("audio"),d.id=c,d.autoplay=!0,d.hidden=!0;const u=ha();u.enabled=!0;const h=new MediaStream([u]);d.srcObject=h,document.addEventListener("visibilitychange",()=>{d&&(d.srcObject=document.hidden?null:h,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(d),this.once(O.Disconnected,()=>{d==null||d.remove(),d=null})}a.push(d)}this.remoteParticipants.forEach(c=>{c.audioTrackPublications.forEach(d=>{d.track&&d.track.attachedElements.forEach(u=>{a.push(u)})})});try{yield Promise.all([this.acquireAudioContext(),...a.map(c=>(c.muted=!1,c.play()))]),this.handleAudioPlaybackStarted()}catch(c){throw this.handleAudioPlaybackFailed(c),c}}),this.startVideo=()=>m(this,void 0,void 0,function*(){const a=[];for(const o of this.remoteParticipants.values())o.videoTrackPublications.forEach(c=>{var d;(d=c.track)===null||d===void 0||d.attachedElements.forEach(u=>{a.includes(u)||a.push(u)})});yield Promise.all(a.map(o=>o.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(o=>{o.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const a of this.remoteParticipants.values())this.handleParticipantDisconnected(a.identity,a);this.setAndEmitConnectionState(fe.Reconnecting)&&this.emit(O.Reconnecting)},this.handleSignalRestarted=a=>m(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(a.serverRegion),Object.assign(Object.assign({},this.logContext),{region:a.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(a);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(o){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:o}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:a.serverRegion}))}catch{return}this.setAndEmitConnectionState(fe.Connected),this.emit(O.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=a=>{a.forEach(o=>{var c;if(o.identity===this.localParticipant.identity){this.localParticipant.updateInfo(o);return}o.identity===""&&(o.identity=(c=this.sidToIdentity.get(o.sid))!==null&&c!==void 0?c:"");let d=this.remoteParticipants.get(o.identity);o.state===Rs.DISCONNECTED?this.handleParticipantDisconnected(o.identity,d):d=this.getOrCreateParticipant(o.identity,o)})},this.handleActiveSpeakersUpdate=a=>{const o=[],c={};a.forEach(d=>{if(c[d.sid]=!0,d.sid===this.localParticipant.sid)this.localParticipant.audioLevel=d.level,this.localParticipant.setIsSpeaking(!0),o.push(this.localParticipant);else{const u=this.getRemoteParticipantBySid(d.sid);u&&(u.audioLevel=d.level,u.setIsSpeaking(!0),o.push(u))}}),c[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(d=>{c[d.sid]||(d.audioLevel=0,d.setIsSpeaking(!1))}),this.activeSpeakers=o,this.emitWhenConnected(O.ActiveSpeakersChanged,o)},this.handleSpeakersChanged=a=>{const o=new Map;this.activeSpeakers.forEach(d=>{const u=this.remoteParticipants.get(d.identity);u&&u.sid!==d.sid||o.set(d.sid,d)}),a.forEach(d=>{let u=this.getRemoteParticipantBySid(d.sid);d.sid===this.localParticipant.sid&&(u=this.localParticipant),u&&(u.audioLevel=d.level,u.setIsSpeaking(d.active),d.active?o.set(d.sid,u):o.delete(d.sid))});const c=Array.from(o.values());c.sort((d,u)=>u.audioLevel-d.audioLevel),this.activeSpeakers=c,this.emitWhenConnected(O.ActiveSpeakersChanged,c)},this.handleStreamStateUpdate=a=>{a.streamStates.forEach(o=>{const c=this.getRemoteParticipantBySid(o.participantSid);if(!c)return;const d=c.getTrackPublicationBySid(o.trackSid);if(!d||!d.track)return;const u=R.streamStateFromProto(o.state);u!==d.track.streamState&&(d.track.streamState=u,c.emit($.TrackStreamStateChanged,d,d.track.streamState),this.emitWhenConnected(O.TrackStreamStateChanged,d,d.track.streamState,c))})},this.handleSubscriptionPermissionUpdate=a=>{const o=this.getRemoteParticipantBySid(a.participantSid);if(!o)return;const c=o.getTrackPublicationBySid(a.trackSid);c&&c.setAllowed(a.allowed)},this.handleSubscriptionError=a=>{const o=Array.from(this.remoteParticipants.values()).find(d=>d.trackPublications.has(a.trackSid));if(!o)return;const c=o.getTrackPublicationBySid(a.trackSid);c&&c.setSubscriptionError(a.err)},this.handleDataPacket=a=>{const o=this.remoteParticipants.get(a.participantIdentity);if(a.value.case==="user")this.handleUserPacket(o,a.value.value,a.kind);else if(a.value.case==="transcription")this.handleTranscription(o,a.value.value);else if(a.value.case==="sipDtmf")this.handleSipDtmf(o,a.value.value);else if(a.value.case==="chatMessage")this.handleChatMessage(o,a.value.value);else if(a.value.case==="metrics")this.handleMetrics(a.value.value,o);else if(a.value.case==="streamHeader")this.handleStreamHeader(a.value.value,a.participantIdentity);else if(a.value.case==="streamChunk")this.handleStreamChunk(a.value.value);else if(a.value.case==="streamTrailer")this.handleStreamTrailer(a.value.value);else if(a.value.case==="rpcRequest"){const c=a.value.value;this.handleIncomingRpcRequest(a.participantIdentity,c.id,c.method,c.payload,c.responseTimeoutMs,c.version)}},this.handleUserPacket=(a,o,c)=>{this.emit(O.DataReceived,o.payload,a,c,o.topic),a==null||a.emit($.DataReceived,o.payload,c)},this.handleSipDtmf=(a,o)=>{this.emit(O.SipDTMFReceived,o,a),a==null||a.emit($.SipDTMFReceived,o)},this.bufferedSegments=new Map,this.handleTranscription=(a,o)=>{const c=o.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(o.transcribedParticipantIdentity),d=c==null?void 0:c.trackPublications.get(o.trackId),u=qp(o,this.transcriptionReceivedTimes);d==null||d.emit(M.TranscriptionReceived,u),c==null||c.emit($.TranscriptionReceived,u,d),this.emit(O.TranscriptionReceived,u,c,d)},this.handleChatMessage=(a,o)=>{const c=zp(o);this.emit(O.ChatMessage,c,a)},this.handleMetrics=(a,o)=>{this.emit(O.MetricsReceived,a,o)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(O.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=a=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:a})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(O.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(O.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(O.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>m(this,void 0,void 0,function*(){var a,o,c;const d=$e.getInstance().previousDevices,u=yield $e.getInstance().getDevices(void 0,!1),h=gt();if((h==null?void 0:h.name)==="Chrome"&&h.os!=="iOS")for(let g of u){const y=d.find(v=>v.deviceId===g.deviceId);y&&y.label!==""&&y.kind===g.kind&&y.label!==g.label&&this.getActiveDevice(g.kind)==="default"&&this.emit(O.ActiveDeviceChanged,g.kind,g.deviceId)}const f=["audiooutput","audioinput","videoinput"];for(let g of f){const y=Hp(g),v=this.localParticipant.getTrackPublication(y);if(v&&(!((a=v.track)===null||a===void 0)&&a.isUserProvided))continue;const _=u.filter(N=>N.kind===g),w=this.getActiveDevice(g);if(w===((o=d.filter(N=>N.kind===g)[0])===null||o===void 0?void 0:o.deviceId)&&_.length>0&&((c=_[0])===null||c===void 0?void 0:c.deviceId)!==w){yield this.switchActiveDevice(g,_[0].deviceId);continue}g==="audioinput"&&!tn()||g==="videoinput"||_.length>0&&!_.find(N=>N.deviceId===this.getActiveDevice(g))&&(yield this.switchActiveDevice(g,_[0].deviceId))}this.emit(O.MediaDevicesChanged)}),this.handleRoomUpdate=a=>{const o=this.roomInfo;this.roomInfo=a,o&&o.metadata!==a.metadata&&this.emitWhenConnected(O.RoomMetadataChanged,a.metadata),(o==null?void 0:o.activeRecording)!==a.activeRecording&&this.emitWhenConnected(O.RecordingStatusChanged,a.activeRecording)},this.handleConnectionQualityUpdate=a=>{a.updates.forEach(o=>{if(o.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(o.quality);return}const c=this.getRemoteParticipantBySid(o.participantSid);c&&c.setConnectionQuality(o.quality)})},this.onLocalParticipantMetadataChanged=a=>{this.emit(O.ParticipantMetadataChanged,a,this.localParticipant)},this.onLocalParticipantNameChanged=a=>{this.emit(O.ParticipantNameChanged,a,this.localParticipant)},this.onLocalAttributesChanged=a=>{this.emit(O.ParticipantAttributesChanged,a,this.localParticipant)},this.onLocalTrackMuted=a=>{this.emit(O.TrackMuted,a,this.localParticipant)},this.onLocalTrackUnmuted=a=>{this.emit(O.TrackUnmuted,a,this.localParticipant)},this.onTrackProcessorUpdate=a=>{var o;(o=a==null?void 0:a.onPublish)===null||o===void 0||o.call(a,this)},this.onLocalTrackPublished=a=>m(this,void 0,void 0,function*(){var o,c,d,u,h,f;(o=a.track)===null||o===void 0||o.on(M.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=a.track)===null||c===void 0||c.on(M.Restarted,this.onLocalTrackRestarted),(h=(u=(d=a.track)===null||d===void 0?void 0:d.getProcessor())===null||u===void 0?void 0:u.onPublish)===null||h===void 0||h.call(u,this),this.emit(O.LocalTrackPublished,a,this.localParticipant),Rn(a.track)&&(yield a.track.checkForSilence())&&this.emit(O.LocalAudioSilenceDetected,a);const g=yield(f=a.track)===null||f===void 0?void 0:f.getDeviceId(!1),y=jd(a.source);y&&g&&g!==this.localParticipant.activeDeviceMap.get(y)&&(this.localParticipant.activeDeviceMap.set(y,g),this.emit(O.ActiveDeviceChanged,y,g))}),this.onLocalTrackUnpublished=a=>{var o,c;(o=a.track)===null||o===void 0||o.off(M.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=a.track)===null||c===void 0||c.off(M.Restarted,this.onLocalTrackRestarted),this.emit(O.LocalTrackUnpublished,a,this.localParticipant)},this.onLocalTrackRestarted=a=>m(this,void 0,void 0,function*(){const o=yield a.getDeviceId(!1),c=jd(a.source);c&&o&&o!==this.localParticipant.activeDeviceMap.get(c)&&(this.log.debug("local track restarted, setting ".concat(c," ").concat(o," active"),this.logContext),this.localParticipant.activeDeviceMap.set(c,o),this.emit(O.ActiveDeviceChanged,c,o))}),this.onLocalConnectionQualityChanged=a=>{this.emit(O.ConnectionQualityChanged,a,this.localParticipant)},this.onMediaDevicesError=a=>{this.emit(O.MediaDevicesError,a)},this.onLocalParticipantPermissionsChanged=a=>{this.emit(O.ParticipantPermissionsChanged,a,this.localParticipant)},this.onLocalChatMessageSent=a=>{this.emit(O.ChatMessage,a,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},mm),e),this.log=jt((n=this.options.loggerName)!==null&&n!==void 0?n:mt.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Zd),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Jd),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},pm),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Ze,this.localParticipant=new Gm("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",nn(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",nn(this.options.audioCaptureDefaults.deviceId)),!((r=this.options.audioOutput)===null||r===void 0)&&r.deviceId&&this.switchActiveDevice("audiooutput",nn(this.options.audioOutput.deviceId)).catch(a=>this.log.warn("Could not set audio output: ".concat(a.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),Xe()){const a=new AbortController;(s=navigator.mediaDevices)===null||s===void 0||s.addEventListener("devicechange",this.handleDeviceChange,{signal:a.signal}),ni.cleanupRegistry&&ni.cleanupRegistry.register(this,()=>{a.abort()})}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new TypeError('A text stream handler for topic "'.concat(e,'" has already been set.'));this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new TypeError('A byte stream handler for topic "'.concat(e,'" has already been set.'));this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}handleIncomingRpcRequest(e,t,n,r,s,a){return m(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),a!==1){yield this.engine.publishRpcResponse(e,t,null,De.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(n);if(!o){yield this.engine.publishRpcResponse(e,t,null,De.builtIn("UNSUPPORTED_METHOD"));return}let c=null,d=null;try{const u=yield o({requestId:t,callerIdentity:e,payload:r,responseTimeout:s});Pa(u)>Yd?(c=De.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(n))):d=u}catch(u){u instanceof De?c=u:(console.warn("Uncaught error returned by RPC handler for ".concat(n,". Returning APPLICATION_ERROR instead."),u),c=De.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,d,c)})}setE2EEEnabled(e){return m(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity);else throw Error("e2ee not configured, please set e2ee settings within the room options")})}setupE2EE(){var e;this.options.e2ee&&("e2eeManager"in this.options.e2ee?this.e2eeManager=this.options.e2ee.e2eeManager:this.e2eeManager=new em(this.options.e2ee),this.e2eeManager.on(Xt.ParticipantEncryptionStatusChanged,(t,n)=>{Gp(n)&&(this.isE2EEEnabled=t),this.emit(O.ParticipantEncryptionStatusChanged,t,n)}),this.e2eeManager.on(Xt.EncryptionError,t=>this.emit(O.EncryptionError,t)),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&t!==void 0?t:!1}getSid(){return m(this,void 0,void 0,function*(){return this.state===fe.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,t)=>{const n=r=>{r.sid!==""&&(this.engine.off(L.RoomUpdate,n),e(r.sid))};this.engine.on(L.RoomUpdate,n),this.once(O.Disconnected,()=>{this.engine.off(L.RoomUpdate,n),t("Room disconnected before room server id was available")})})})}get name(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&t!==void 0?t:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&t!==void 0?t:0}get numPublishers(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&t!==void 0?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new Om(this.options),this.engine.on(L.ParticipantUpdate,this.handleParticipantUpdates).on(L.RoomUpdate,this.handleRoomUpdate).on(L.SpeakersChanged,this.handleSpeakersChanged).on(L.StreamStateChanged,this.handleStreamStateUpdate).on(L.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(L.SubscriptionError,this.handleSubscriptionError).on(L.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(L.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(L.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(L.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(L.DataPacketReceived,this.handleDataPacket).on(L.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(fe.SignalReconnecting)&&this.emit(O.SignalReconnecting)}).on(L.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(fe.Connected)&&this.emit(O.Reconnected)}).on(L.SignalResumed,()=>{this.bufferedEvents=[],(this.state===fe.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(L.Restarting,this.handleRestarting).on(L.SignalRestarted,this.handleSignalRestarted).on(L.Offline,()=>{this.setAndEmitConnectionState(fe.Reconnecting)&&this.emit(O.Reconnecting)}).on(L.DCBufferStatusChanged,(e,t)=>{this.emit(O.DCBufferStatusChanged,e,t)}).on(L.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(n=>{let{trackSid:r}=n;return r===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit($.LocalTrackSubscribed,t),this.emitWhenConnected(O.LocalTrackSubscribed,t,this.localParticipant)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine))}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return $e.getInstance().getDevices(e,t)}prepareConnection(e,t){return m(this,void 0,void 0,function*(){if(this.state===fe.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(da(new URL(e))&&t){this.regionUrlProvider=new Da(e,t);const n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===fe.Disconnected&&(this.regionUrl=n,yield fetch(fa(n),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(n),this.logContext))}else yield fetch(fa(e),{method:"HEAD"})}catch(n){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:n}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return m(this,void 0,void 0,function*(){let n=()=>{},r;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":r=new Pt({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":r=new Pt({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":r=new Pt({scenario:{case:"serverLeave",value:!0}});break;case"migration":r=new Pt({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":n=()=>m(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new Pt({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>m(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new Pt({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 Pt({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),n=()=>m(this,void 0,void 0,function*(){const s=this.engine.client.onLeave;s&&s(new _r({reason:ft.CLIENT_INITIATED,action:Kn.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");r=new Pt({scenario:{case:"subscriberBandwidth",value:Pn(t)}});break;case"leave-full-reconnect":r=new Pt({scenario:{case:"leaveRequestFullReconnect",value:!0}})}r&&(yield this.engine.client.sendSimulateScenario(r),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return m(this,arguments,void 0,function(n,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var o,c,d,u,h,f,g,y;let v=!0,_=!1;const w=a?{exact:r}:r;if(n==="audioinput"){_=s.localParticipant.audioTrackPublications.size===0;const N=(o=s.getActiveDevice(n))!==null&&o!==void 0?o:s.options.audioCaptureDefaults.deviceId;s.options.audioCaptureDefaults.deviceId=w;const U=Array.from(s.localParticipant.audioTrackPublications.values()).filter(b=>b.source===R.Source.Microphone);try{v=(yield Promise.all(U.map(b=>{var k;return(k=b.audioTrack)===null||k===void 0?void 0:k.setDeviceId(w)}))).every(b=>b===!0)}catch(b){throw s.options.audioCaptureDefaults.deviceId=N,b}}else if(n==="videoinput"){_=s.localParticipant.videoTrackPublications.size===0;const N=(c=s.getActiveDevice(n))!==null&&c!==void 0?c:s.options.videoCaptureDefaults.deviceId;s.options.videoCaptureDefaults.deviceId=w;const U=Array.from(s.localParticipant.videoTrackPublications.values()).filter(b=>b.source===R.Source.Camera);try{v=(yield Promise.all(U.map(b=>{var k;return(k=b.videoTrack)===null||k===void 0?void 0:k.setDeviceId(w)}))).every(b=>b===!0)}catch(b){throw s.options.videoCaptureDefaults.deviceId=N,b}}else if(n==="audiooutput"){if(!ca()&&!s.options.webAudioMix||s.options.webAudioMix&&s.audioContext&&!("setSinkId"in s.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");s.options.webAudioMix&&(r=(d=yield $e.getInstance().normalizeDeviceId("audiooutput",r))!==null&&d!==void 0?d:""),(u=(y=s.options).audioOutput)!==null&&u!==void 0||(y.audioOutput={});const N=(h=s.getActiveDevice(n))!==null&&h!==void 0?h:s.options.audioOutput.deviceId;s.options.audioOutput.deviceId=r;try{s.options.webAudioMix&&((f=s.audioContext)===null||f===void 0||f.setSinkId(r)),yield Promise.all(Array.from(s.remoteParticipants.values()).map(U=>U.setAudioOutput({deviceId:r})))}catch(U){throw s.options.audioOutput.deviceId=N,U}}return(_||n==="audiooutput")&&(s.localParticipant.activeDeviceMap.set(n,n==="audiooutput"&&((g=s.options.audioOutput)===null||g===void 0?void 0:g.deviceId)||r),s.emit(O.ActiveDeviceChanged,n,r)),v}()})}setupLocalParticipantEvents(){this.localParticipant.on($.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on($.ParticipantNameChanged,this.onLocalParticipantNameChanged).on($.AttributesChanged,this.onLocalAttributesChanged).on($.TrackMuted,this.onLocalTrackMuted).on($.TrackUnmuted,this.onLocalTrackUnmuted).on($.LocalTrackPublished,this.onLocalTrackPublished).on($.LocalTrackUnpublished,this.onLocalTrackUnpublished).on($.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on($.MediaDevicesError,this.onMediaDevicesError).on($.AudioStreamAcquired,this.startAudio).on($.ChatMessage,this.onLocalChatMessageSent).on($.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,n){if(this.state===fe.Connecting||this.state===fe.Reconnecting){const u=()=>{this.onTrackAdded(e,t,n),h()},h=()=>{this.off(O.Reconnected,u),this.off(O.Connected,u),this.off(O.Disconnected,h)};this.once(O.Reconnected,u),this.once(O.Connected,u),this.once(O.Disconnected,h);return}if(this.state===fe.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if(e.readyState==="ended"){this.log.info("skipping incoming track as it already ended",this.logContext);return}const r=Ap(t.id),s=r[0];let a=r[1],o=e.id;if(a&&a.startsWith("TR")&&(o=a),s===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const c=Array.from(this.remoteParticipants.values()).find(u=>u.sid===s);if(!c){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);return}let d;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?d=this.options.adaptiveStream:d={}),c.addSubscribedMediaTrack(e,o,t,n,d)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var n;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==fe.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{r.unpublishTrack(s.trackSid)})}),this.localParticipant.trackPublications.forEach(r=>{var s,a,o;r.track&&this.localParticipant.unpublishTrack(r.track,e),e?((s=r.track)===null||s===void 0||s.detach(),(a=r.track)===null||a===void 0||a.stop()):(o=r.track)===null||o===void 0||o.stopMonitor()}),this.localParticipant.off($.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off($.ParticipantNameChanged,this.onLocalParticipantNameChanged).off($.AttributesChanged,this.onLocalAttributesChanged).off($.TrackMuted,this.onLocalTrackMuted).off($.TrackUnmuted,this.onLocalTrackUnmuted).off($.LocalTrackPublished,this.onLocalTrackPublished).off($.LocalTrackUnpublished,this.onLocalTrackUnpublished).off($.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off($.MediaDevicesError,this.onMediaDevicesError).off($.AudioStreamAcquired,this.startAudio).off($.ChatMessage,this.onLocalChatMessageSent).off($.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix=="boolean"&&(this.audioContext.close(),this.audioContext=void 0),Xe()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(n=navigator.mediaDevices)===null||n===void 0||n.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(fe.Disconnected),this.emit(O.Disconnected,t)}}}handleParticipantDisconnected(e,t){var n;this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach(r=>{t.unpublishTrack(r.trackSid,!0)}),this.emit(O.ParticipantDisconnected,t),(n=this.localParticipant)===null||n===void 0||n.handleParticipantDisconnected(t.identity))}handleStreamHeader(e,t){return m(this,void 0,void 0,function*(){var n;if(e.contentHeader.case==="byteHeader"){const r=this.byteStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let s;const a={id:e.streamId,name:(n=e.contentHeader.value.name)!==null&&n!==void 0?n:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Ur(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:c=>{s=c,this.byteStreamControllers.set(e.streamId,{info:a,controller:s,startTime:Date.now()})}});r(new Nm(a,o,Ur(e.totalLength)),{identity:t})}else if(e.contentHeader.case==="textHeader"){const r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let s;const a={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:c=>{s=c,this.textStreamControllers.set(e.streamId,{info:a,controller:s,startTime:Date.now()})}});r(new Lm(a,o,Ur(e.totalLength)),{identity:t})}})}handleStreamChunk(e){const t=this.byteStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e);const n=this.textStreamControllers.get(e.streamId);n&&e.content.length>0&&n.controller.enqueue(e)}handleStreamTrailer(e){const t=this.textStreamControllers.get(e.streamId);t&&(t.info.attributes=Object.assign(Object.assign({},t.info.attributes),e.attributes),t.controller.close(),this.textStreamControllers.delete(e.streamId));const n=this.byteStreamControllers.get(e.streamId);n&&(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close(),this.byteStreamControllers.delete(e.streamId))}acquireAudioContext(){return m(this,void 0,void 0,function*(){var e,t;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=Ud())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(r=>r.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),Qe(200)])}catch(r){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:r}))}const n=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";n!==this.canPlaybackAudio&&(this.audioEnabled=n,this.emit(O.AudioPlaybackStatusChanged,n))})}createParticipant(e,t){var n;let r;return t?r=Wr.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):r=new Wr(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&r.setAudioContext(this.audioContext),!((n=this.options.audioOutput)===null||n===void 0)&&n.deviceId&&r.setAudioOutput(this.options.audioOutput).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message),this.logContext)),r}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const r=this.remoteParticipants.get(e);return t&&r.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),r}const n=this.createParticipant(e,t);return this.remoteParticipants.set(e,n),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(O.ParticipantConnected,n),n.on($.TrackPublished,r=>{this.emitWhenConnected(O.TrackPublished,r,n)}).on($.TrackSubscribed,(r,s)=>{r.kind===R.Kind.Audio?(r.on(M.AudioPlaybackStarted,this.handleAudioPlaybackStarted),r.on(M.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):r.kind===R.Kind.Video&&(r.on(M.VideoPlaybackFailed,this.handleVideoPlaybackFailed),r.on(M.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(O.TrackSubscribed,r,s,n)}).on($.TrackUnpublished,r=>{this.emit(O.TrackUnpublished,r,n)}).on($.TrackUnsubscribed,(r,s)=>{this.emit(O.TrackUnsubscribed,r,s,n)}).on($.TrackMuted,r=>{this.emitWhenConnected(O.TrackMuted,r,n)}).on($.TrackUnmuted,r=>{this.emitWhenConnected(O.TrackUnmuted,r,n)}).on($.ParticipantMetadataChanged,r=>{this.emitWhenConnected(O.ParticipantMetadataChanged,r,n)}).on($.ParticipantNameChanged,r=>{this.emitWhenConnected(O.ParticipantNameChanged,r,n)}).on($.AttributesChanged,r=>{this.emitWhenConnected(O.ParticipantAttributesChanged,r,n)}).on($.ConnectionQualityChanged,r=>{this.emitWhenConnected(O.ConnectionQualityChanged,r,n)}).on($.ParticipantPermissionsChanged,r=>{this.emitWhenConnected(O.ParticipantPermissionsChanged,r,n)}).on($.TrackSubscriptionStatusChanged,(r,s)=>{this.emitWhenConnected(O.TrackSubscriptionStatusChanged,r,s,n)}).on($.TrackSubscriptionFailed,(r,s)=>{this.emit(O.TrackSubscriptionFailed,r,n,s)}).on($.TrackSubscriptionPermissionChanged,(r,s)=>{this.emitWhenConnected(O.TrackSubscriptionPermissionChanged,r,s,n)}),t&&n.updateInfo(t),n}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((n,r)=>(n.push(...r.getTrackPublications()),n),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&Wp(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Be.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,ft.STATE_MISMATCH))):e=0},Hm)}clearConnectionReconcile(){this.connectionReconcileInterval&&Be.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(O.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,n]=e;this.emit(t,...n)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];if(this.state===fe.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,n]);else if(this.state===fe.Connected)return this.emit(e,...n);return!1}simulateParticipants(e){return m(this,void 0,void 0,function*(){var t,n;const r=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),s=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Ps({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:_e.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Oi({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(O.SignalConnected),this.emit(O.Connected),this.setAndEmitConnectionState(fe.Connected),r.video){const a=new La(R.Kind.Video,new Gn({source:Le.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:ht.AUDIO,name:"video-dummy"}),new qr(r.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Ad(160*((t=s.aspectRatios[0])!==null&&t!==void 0?t:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(a),this.localParticipant.emit($.LocalTrackPublished,a)}if(r.audio){const a=new La(R.Kind.Audio,new Gn({source:Le.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:ht.AUDIO}),new Br(r.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:ha(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(a),this.localParticipant.emit($.LocalTrackPublished,a)}for(let a=0;a<s.count-1;a+=1){let o=new Oi({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(a),state:Rs.ACTIVE,tracks:[],joinedAt:_e.parse(Date.now())});const c=this.getOrCreateParticipant(o.identity,o);if(s.video){const d=Ad(160*((n=s.aspectRatios[a%s.aspectRatios.length])!==null&&n!==void 0?n:1),160,!1,!0),u=new Gn({source:Le.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:ht.AUDIO});c.addSubscribedMediaTrack(d,u.sid,new MediaStream([d]),new RTCRtpReceiver),o.tracks=[...o.tracks,u]}if(s.audio){const d=ha(),u=new Gn({source:Le.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:ht.AUDIO});c.addSubscribedMediaTrack(d,u.sid,new MediaStream([d]),new RTCRtpReceiver),o.tracks=[...o.tracks,u]}c.updateInfo(o)}})}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];if(e!==O.ActiveSpeakersChanged&&e!==O.TranscriptionReceived){const s=hu(n).filter(a=>a!==void 0);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:s}))}return super.emit(e,...n)}}ni.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(i=>{i()});function hu(i){return i.map(e=>{if(e)return Array.isArray(e)?hu(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var bt;(function(i){i[i.IDLE=0]="IDLE",i[i.RUNNING=1]="RUNNING",i[i.SKIPPED=2]="SKIPPED",i[i.SUCCESS=3]="SUCCESS",i[i.FAILED=4]="FAILED"})(bt||(bt={}));class on extends Rt.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=bt.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new ni(n.roomOptions),this.connectOptions=n.connectOptions,this.options=n}run(e){return m(this,void 0,void 0,function*(){if(this.status!==bt.IDLE)throw Error("check is running already");this.setStatus(bt.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!==bt.SKIPPED&&this.setStatus(this.isSuccess()?bt.SUCCESS:bt.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return m(this,void 0,void 0,function*(){return this.room.state===fe.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return m(this,void 0,void 0,function*(){this.room&&this.room.state!==fe.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(bt.SKIPPED)}switchProtocol(e){return m(this,void 0,void 0,function*(){let t=!1,n=!1;if(this.room.on(O.Reconnecting,()=>{t=!0}),this.room.once(O.Reconnected,()=>{n=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(s=>setTimeout(s,1e3)),!t)return;const r=Date.now()+1e4;for(;Date.now()<r;){if(n)return;yield Qe(100)}throw new Error("Could not reconnect using ".concat(e," protocol after 10 seconds"))})}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return(e=this.room)===null||e===void 0?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class Zm extends on{get description(){return"Cloud regions"}perform(){return m(this,void 0,void 0,function*(){const e=new Da(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],n=new Set;for(let s=0;s<3;s++){const a=yield e.getNextBestRegionUrl();if(!a)break;if(n.has(a))continue;n.add(a);const 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);const r=t[0];this.bestStats=r,this.appendMessage("best Cloud region: ".concat(r.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return m(this,void 0,void 0,function*(){var t,n;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const r=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!r)throw new Error("Region not found");const s=yield this.room.localParticipant.streamText({topic:"test"}),a=1e3,c=1e6/a,d="A".repeat(a),u=Date.now();for(let y=0;y<c;y++)yield s.write(d);yield s.close();const h=Date.now(),f=yield(n=this.room.engine.pcManager)===null||n===void 0?void 0:n.publisher.getStats(),g={region:r,rtt:1e4,duration:h-u};return f==null||f.forEach(y=>{y.type==="candidate-pair"&&y.nominated&&(g.rtt=y.currentRoundTripTime*1e3)}),yield this.disconnect(),g})}}const Ua=1e4;class Jm extends on{get description(){return"Connection via UDP vs TCP"}perform(){return m(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):this.appendMessage("best connection quality via udp");const n=this.bestStats;this.appendMessage("upstream bitrate: ".concat((n.bitrateTotal/n.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((n.rttTotal/n.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((n.jitterTotal/n.count*1e3).toFixed(2)," ms")),n.packetsLost>0&&this.appendWarning("packets lost: ".concat((n.packetsLost/n.packetsSent*100).toFixed(2),"%")),n.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((n.qualityLimitationDurations.bandwidth/(Ua/1e3)*100).toFixed(2),"%")),n.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((n.qualityLimitationDurations.cpu/(Ua/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return m(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const n=t.getContext("2d");if(!n)throw new Error("Could not get canvas context");let r=0;const s=()=>{r=(r+1)%360,n.fillStyle="hsl(".concat(r,", 100%, 50%)"),n.fillRect(0,0,t.width,t.height),requestAnimationFrame(s)};s();const o=t.captureStream(30).getVideoTracks()[0],d=(yield this.room.localParticipant.publishTrack(o,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,u={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},h=setInterval(()=>m(this,void 0,void 0,function*(){const f=yield d.getRTCStatsReport();f==null||f.forEach(g=>{g.type==="outbound-rtp"?(u.packetsSent=g.packetsSent,u.qualityLimitationDurations=g.qualityLimitationDurations,u.bitrateTotal+=g.targetBitrate,u.count++):g.type==="remote-inbound-rtp"&&(u.packetsLost=g.packetsLost,u.rttTotal+=g.roundTripTime,u.jitterTotal+=g.jitter)})}),1e3);return yield new Promise(f=>setTimeout(f,Ua)),clearInterval(h),o.stop(),t.remove(),yield this.disconnect(),u})}}class Ym extends on{get description(){return"Can publish audio"}perform(){return m(this,void 0,void 0,function*(){var e;const t=yield this.connect(),n=yield qm();if(yield Ld(n,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(n),yield new Promise(o=>setTimeout(o,3e3));const s=yield(e=n.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"))})}}class Qm extends on{get description(){return"Can publish video"}perform(){return m(this,void 0,void 0,function*(){var e;const t=yield this.connect(),n=yield Vm();yield this.checkForVideo(n.mediaStreamTrack),t.localParticipant.publishTrack(n),yield new Promise(a=>setTimeout(a,5e3));const r=yield(e=n.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 m(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const n=document.createElement("video");n.srcObject=t,n.muted=!0,yield new Promise(r=>{n.onplay=()=>{setTimeout(()=>{var s,a,o,c;const d=document.createElement("canvas"),u=e.getSettings(),h=(a=(s=u.width)!==null&&s!==void 0?s:n.videoWidth)!==null&&a!==void 0?a:1280,f=(c=(o=u.height)!==null&&o!==void 0?o:n.videoHeight)!==null&&c!==void 0?c:720;d.width=h,d.height=f;const g=d.getContext("2d");g.drawImage(n,0,0);const v=g.getImageData(0,0,d.width,d.height).data;let _=!0;for(let w=0;w<v.length;w+=4)if(v[w]!==0||v[w+1]!==0||v[w+2]!==0){_=!1;break}_?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),r()},1e3)},n.play()}),n.remove()})}}class Xm extends on{get description(){return"Resuming connection after interruption"}perform(){return m(this,void 0,void 0,function*(){var e;const t=yield this.connect();let n=!1,r=!1,s;const a=new Promise(d=>{setTimeout(d,5e3),s=d}),o=()=>{n=!0};t.on(O.SignalReconnecting,o).on(O.Reconnecting,o).on(O.Reconnected,()=>{r=!0,s(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const c=t.engine.client.onClose;if(c&&c(""),yield a,n){if(!r||t.state!==fe.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}else throw new Error("Did not attempt to reconnect")})}}class eg extends on{get description(){return"Can connect via TURN"}perform(){return m(this,void 0,void 0,function*(){var e,t;const n=new ba,r=yield n.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let s=!1,a=!1,o=!1;for(let c of r.iceServers)for(let d of c.urls)d.startsWith("turn:")?(a=!0,o=!0):d.startsWith("turns:")&&(a=!0,o=!0,s=!0),d.startsWith("stun:")&&(o=!0);o?a&&!s&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield n.close(),!((t=(e=this.connectOptions)===null||e===void 0?void 0:e.rtcConfig)===null||t===void 0)&&t.iceServers||a?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(c=>setTimeout(c,0)))})}}class tg extends on{get description(){return"Establishing WebRTC connection"}perform(){return m(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(O.SignalConnected,()=>{const n=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(r,s)=>{if(r.candidate){const a=new RTCIceCandidate(r);let o="".concat(a.protocol," ").concat(a.address,":").concat(a.port," ").concat(a.type);a.address&&(ng(a.address)?o+=" (private)":a.protocol==="tcp"&&a.tcpType==="passive"?(e=!0,o+=" (passive)"):a.protocol==="udp"&&(t=!0)),this.appendMessage(o)}n&&n(r,s)},this.room.engine.pcManager&&(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(),re.info("now the room is connected")}catch(n){throw this.appendWarning("ports need to be open on firewall in order to connect."),n}e||this.appendWarning("Server is not configured for ICE/TCP"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function ng(i){const e=i.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}class ig extends on{get description(){return"Connecting to signal connection via WebSocket"}perform(){return m(this,void 0,void 0,function*(){var e,t,n;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let r=new ba;const s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(s.serverVersion,".")),((e=s.serverInfo)===null||e===void 0?void 0:e.edition)===pc.Cloud&&(!((t=s.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((n=s.serverInfo)===null||n===void 0?void 0:n.region)),yield r.close()})}}class eb extends Rt.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=n}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:bt.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!==bt.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return m(this,void 0,void 0,function*(){const t=this.getNextCheckId(),n=new e(this.url,this.token,this.options),r=a=>{this.updateCheck(t,a)};n.on("update",r);const s=yield n.run();return n.off("update",r),s})}checkWebsocket(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(ig)})}checkWebRTC(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(tg)})}checkTURN(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(eg)})}checkReconnect(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Xm)})}checkPublishAudio(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Ym)})}checkPublishVideo(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Qm)})}checkConnectionProtocol(){return m(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(Jm);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Zm)})}}const et=Symbol.for("@ts-pattern/matcher"),fu=Symbol.for("@ts-pattern/isVariadic"),Gr="@ts-pattern/anonymous-select-key",ja=i=>!!(i&&typeof i=="object"),Kr=i=>i&&!!i[et],Ve=(i,e,t)=>{if(Kr(i)){const n=i[et](),{matched:r,selections:s}=n.match(e);return r&&s&&Object.keys(s).forEach(a=>t(a,s[a])),r}if(ja(i)){if(!ja(e))return!1;if(Array.isArray(i)){if(!Array.isArray(e))return!1;let n=[],r=[],s=[];for(const a of i.keys()){const o=i[a];Kr(o)&&o[fu]?s.push(o):s.length?r.push(o):n.push(o)}if(s.length){if(s.length>1)throw new Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed.");if(e.length<n.length+r.length)return!1;const a=e.slice(0,n.length),o=r.length===0?[]:e.slice(-r.length),c=e.slice(n.length,r.length===0?1/0:-r.length);return n.every((d,u)=>Ve(d,a[u],t))&&r.every((d,u)=>Ve(d,o[u],t))&&(s.length===0||Ve(s[0],c,t))}return i.length===e.length&&i.every((a,o)=>Ve(a,e[o],t))}return Reflect.ownKeys(i).every(n=>{const r=i[n];return(n in e||Kr(s=r)&&s[et]().matcherType==="optional")&&Ve(r,e[n],t);var s})}return Object.is(e,i)},rt=i=>{var e,t,n;return ja(i)?Kr(i)?(e=(t=(n=i[et]()).getSelectionKeys)==null?void 0:t.call(n))!=null?e:[]:Array.isArray(i)?Fi(i,rt):Fi(Object.values(i),rt):[]},Fi=(i,e)=>i.reduce((t,n)=>t.concat(e(n)),[]);function rg(...i){if(i.length===1){const[e]=i;return t=>Ve(e,t,()=>{})}if(i.length===2){const[e,t]=i;return Ve(e,t,()=>{})}throw new Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${i.length}.`)}function qe(i){return Object.assign(i,{optional:()=>$a(i),and:e=>Te(i,e),or:e=>pu(i,e),select:e=>e===void 0?$i(i):$i(e,i)})}function Fa(i){return Object.assign((e=>Object.assign(e,{[Symbol.iterator](){let t=0;const n=[{value:Object.assign(e,{[fu]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var r;return(r=n[t++])!=null?r:n.at(-1)}}}}))(i),{optional:()=>Fa($a(i)),select:e=>Fa(e===void 0?$i(i):$i(e,i))})}function $a(i){return qe({[et]:()=>({match:e=>{let t={};const n=(r,s)=>{t[r]=s};return e===void 0?(rt(i).forEach(r=>n(r,void 0)),{matched:!0,selections:t}):{matched:Ve(i,e,n),selections:t}},getSelectionKeys:()=>rt(i),matcherType:"optional"})})}const sg=(i,e)=>{for(const t of i)if(!e(t))return!1;return!0},ag=(i,e)=>{for(const[t,n]of i.entries())if(!e(n,t))return!1;return!0};function Te(...i){return qe({[et]:()=>({match:e=>{let t={};const n=(r,s)=>{t[r]=s};return{matched:i.every(r=>Ve(r,e,n)),selections:t}},getSelectionKeys:()=>Fi(i,rt),matcherType:"and"})})}function pu(...i){return qe({[et]:()=>({match:e=>{let t={};const n=(r,s)=>{t[r]=s};return Fi(i,rt).forEach(r=>n(r,void 0)),{matched:i.some(r=>Ve(r,e,n)),selections:t}},getSelectionKeys:()=>Fi(i,rt),matcherType:"or"})})}function ce(i){return{[et]:()=>({match:e=>({matched:!!i(e)})})}}function $i(...i){const e=typeof i[0]=="string"?i[0]:void 0,t=i.length===2?i[1]:typeof i[0]=="string"?void 0:i[0];return qe({[et]:()=>({match:n=>{let r={[e??Gr]:n};return{matched:t===void 0||Ve(t,n,(s,a)=>{r[s]=a}),selections:r}},getSelectionKeys:()=>[e??Gr].concat(t===void 0?[]:rt(t))})})}function It(i){return typeof i=="number"}function cn(i){return typeof i=="string"}function dn(i){return typeof i=="bigint"}const mu=qe(ce(function(i){return!0})),og=mu,un=i=>Object.assign(qe(i),{startsWith:e=>{return un(Te(i,(t=e,ce(n=>cn(n)&&n.startsWith(t)))));var t},endsWith:e=>{return un(Te(i,(t=e,ce(n=>cn(n)&&n.endsWith(t)))));var t},minLength:e=>un(Te(i,(t=>ce(n=>cn(n)&&n.length>=t))(e))),length:e=>un(Te(i,(t=>ce(n=>cn(n)&&n.length===t))(e))),maxLength:e=>un(Te(i,(t=>ce(n=>cn(n)&&n.length<=t))(e))),includes:e=>{return un(Te(i,(t=e,ce(n=>cn(n)&&n.includes(t)))));var t},regex:e=>{return un(Te(i,(t=e,ce(n=>cn(n)&&!!n.match(t)))));var t}}),cg=un(ce(cn)),Ot=i=>Object.assign(qe(i),{between:(e,t)=>Ot(Te(i,((n,r)=>ce(s=>It(s)&&n<=s&&r>=s))(e,t))),lt:e=>Ot(Te(i,(t=>ce(n=>It(n)&&n<t))(e))),gt:e=>Ot(Te(i,(t=>ce(n=>It(n)&&n>t))(e))),lte:e=>Ot(Te(i,(t=>ce(n=>It(n)&&n<=t))(e))),gte:e=>Ot(Te(i,(t=>ce(n=>It(n)&&n>=t))(e))),int:()=>Ot(Te(i,ce(e=>It(e)&&Number.isInteger(e)))),finite:()=>Ot(Te(i,ce(e=>It(e)&&Number.isFinite(e)))),positive:()=>Ot(Te(i,ce(e=>It(e)&&e>0))),negative:()=>Ot(Te(i,ce(e=>It(e)&&e<0)))}),dg=Ot(ce(It)),ln=i=>Object.assign(qe(i),{between:(e,t)=>ln(Te(i,((n,r)=>ce(s=>dn(s)&&n<=s&&r>=s))(e,t))),lt:e=>ln(Te(i,(t=>ce(n=>dn(n)&&n<t))(e))),gt:e=>ln(Te(i,(t=>ce(n=>dn(n)&&n>t))(e))),lte:e=>ln(Te(i,(t=>ce(n=>dn(n)&&n<=t))(e))),gte:e=>ln(Te(i,(t=>ce(n=>dn(n)&&n>=t))(e))),positive:()=>ln(Te(i,ce(e=>dn(e)&&e>0))),negative:()=>ln(Te(i,ce(e=>dn(e)&&e<0)))}),ug=ln(ce(dn)),lg=qe(ce(function(i){return typeof i=="boolean"})),hg=qe(ce(function(i){return typeof i=="symbol"})),fg=qe(ce(function(i){return i==null})),pg=qe(ce(function(i){return i!=null}));var mg={__proto__:null,matcher:et,optional:$a,array:function(...i){return Fa({[et]:()=>({match:e=>{if(!Array.isArray(e))return{matched:!1};if(i.length===0)return{matched:!0};const t=i[0];let n={};if(e.length===0)return rt(t).forEach(s=>{n[s]=[]}),{matched:!0,selections:n};const r=(s,a)=>{n[s]=(n[s]||[]).concat([a])};return{matched:e.every(s=>Ve(t,s,r)),selections:n}},getSelectionKeys:()=>i.length===0?[]:rt(i[0])})})},set:function(...i){return qe({[et]:()=>({match:e=>{if(!(e instanceof Set))return{matched:!1};let t={};if(e.size===0)return{matched:!0,selections:t};if(i.length===0)return{matched:!0};const n=(s,a)=>{t[s]=(t[s]||[]).concat([a])},r=i[0];return{matched:sg(e,s=>Ve(r,s,n)),selections:t}},getSelectionKeys:()=>i.length===0?[]:rt(i[0])})})},map:function(...i){return qe({[et]:()=>({match:e=>{if(!(e instanceof Map))return{matched:!1};let t={};if(e.size===0)return{matched:!0,selections:t};const n=(o,c)=>{t[o]=(t[o]||[]).concat([c])};if(i.length===0)return{matched:!0};var r;if(i.length===1)throw new Error(`\`P.map\` wasn't given enough arguments. Expected (key, value), received ${(r=i[0])==null?void 0:r.toString()}`);const[s,a]=i;return{matched:ag(e,(o,c)=>{const d=Ve(s,c,n),u=Ve(a,o,n);return d&&u}),selections:t}},getSelectionKeys:()=>i.length===0?[]:[...rt(i[0]),...rt(i[1])]})})},intersection:Te,union:pu,not:function(i){return qe({[et]:()=>({match:e=>({matched:!Ve(i,e,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:ce,select:$i,any:mu,_:og,string:cg,number:dg,bigint:ug,boolean:lg,symbol:hg,nullish:fg,nonNullable:pg,instanceOf:function(i){return qe(ce(function(e){return t=>t instanceof e}(i)))},shape:function(i){return qe(ce(rg(i)))}};class gg extends Error{constructor(e){let t;try{t=JSON.stringify(e)}catch{t=e}super(`Pattern matching error: no pattern matches value ${t}`),this.input=void 0,this.input=e}}const Ba={matched:!1,value:void 0};function Bi(i){return new vg(i,Ba)}let vg=class uo{constructor(e,t){this.input=void 0,this.state=void 0,this.input=e,this.state=t}with(...e){if(this.state.matched)return this;const t=e[e.length-1],n=[e[0]];let r;e.length===3&&typeof e[1]=="function"?r=e[1]:e.length>2&&n.push(...e.slice(1,e.length-1));let s=!1,a={};const o=(d,u)=>{s=!0,a[d]=u},c=!n.some(d=>Ve(d,this.input,o))||r&&!r(this.input)?Ba:{matched:!0,value:t(s?Gr in a?a[Gr]:a:this.input,this.input)};return new uo(this.input,c)}when(e,t){if(this.state.matched)return this;const n=!!e(this.input);return new uo(this.input,n?{matched:!0,value:t(this.input,this.input)}:Ba)}otherwise(e){return this.state.matched?this.state.value:e(this.input)}exhaustive(e=yg){return this.state.matched?this.state.value:e(this.input)}run(){return this.exhaustive()}returnType(){return this}};function yg(i){throw new gg(i)}class gu{constructor(e={}){this.currentState=G.READY,this.assistantAudioContext=null,this.userAudioContext=null,this.emitter=Eo(),this.apiBaseUrl=e.apiBaseUrl||"/api",this.token=e.token}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}async connect(e={}){if(this.token=e.token??this.token??new URLSearchParams(window.location.search).get("token")??void 0,!this.token){console.error("No token found"),this.emitter.emit("error",{session:this,error:new Error("No session token provided")});return}await this.requestMicrophone();try{this.room=new ni({adaptiveStream:!0,dynacast:!0}),this.room.on(O.LocalTrackUnpublished,r=>{console.log("Local track unpublished",r.source),r.source===R.Source.ScreenShare&&(this.screenStream=void 0)}),this.room.on(O.Disconnected,()=>{console.log("LiveKit room disconnected"),this.disconnect()}),this.room.on(O.ParticipantDisconnected,()=>{this.disconnect()}),this.room.on(O.TrackSubscribed,(r,s,a)=>{if(r.kind==="audio"&&r.attach(),r.source===R.Source.Microphone&&a.identity.includes("agent-")){const o=r.mediaStream;if(!o){console.error("No media stream available for assistant track");return}const c=new AudioContext,d=c.createAnalyser();c.createMediaStreamSource(o).connect(d),d.fftSize=2048;const h=new Uint8Array(d.frequencyBinCount);this.analyzeAudio(d,h,"ASSISTANT"),this.assistantAudioContext=c}}),this.room.on(O.ParticipantAttributesChanged,r=>{if(!r["lk.agent.state"]||this.currentState===G.RESEARCHING||this.currentState===G.PAUSED)return;const s=r["lk.agent.state"],a=Bi(s).with("listening",()=>G.USER_SPEAKING).with("speaking",()=>G.AGENT_SPEAKING).with("thinking",()=>G.AGENT_SPEAKING).otherwise(()=>{});a&&this.setState(a)}),this.room.on(O.DataReceived,async r=>{try{const s=JSON.parse(new TextDecoder().decode(r)),a=s.status||s.request;Bi(a).with("using_tool",()=>{const o=this.currentState;this.currentState=G.RESEARCHING,this.emitter.emit("stateChanged",{session:this,newState:this.currentState,oldState:o})}).with("using_tool_ended",()=>{const o=this.currentState;this.currentState=G.AGENT_SPEAKING,this.emitter.emit("stateChanged",{session:this,newState:this.currentState,oldState:o})}).with("share_screen",()=>{this.shareScreen()}).with("prompt_user",()=>{this.promptContinue()}).with("capture_page_html",()=>{this.emitter.emit("capturePageHTML",{session:this})}).otherwise(()=>{console.warn("Unknown data received:",s)})}catch(s){console.error("Error parsing data:",s)}});const t=`${this.apiBaseUrl}/join-token?token=${this.token}`,n=await fetch(t).then(r=>r.json());if(await this.room.connect(n.url,n.token),this.microphoneStream){const r=this.microphoneStream.getAudioTracks()[0];await this.room.localParticipant.publishTrack(r,{name:"microphone",source:R.Source.Microphone})}}catch(t){throw console.error("Failed to connect to LiveKit:",t),this.disconnect(),this.emitter.emit("error",{session:this,error:t instanceof Error?t:new Error(String(t))}),t}}disconnect(){var e;this.room&&this.room.disconnect(!0),(e=this.screenStream)!=null&&e.track&&this.screenStream.track.stop(),this.microphoneStream&&this.microphoneStream.getTracks().forEach(t=>t.stop()),this.setState(G.READY)}setState(e){if(e===this.currentState)return;const t=this.currentState;this.currentState=e,this.emitter.emit("stateChanged",{session:this,newState:e,oldState:t})}async requestMicrophone(){try{const e=await navigator.mediaDevices.getUserMedia({audio:!0});this.microphoneStream=e;const t=new AudioContext;this.userAudioContext=t;const n=t.createAnalyser(),r=t.createMediaStreamSource(e),s=t.createGain();s.gain.value=1.5,r.connect(s),s.connect(n),n.fftSize=2048;const a=new Uint8Array(n.frequencyBinCount);this.analyzeAudio(n,a,"USER")}catch(e){throw console.error("Microphone permission denied:",e),new Error("Microphone permission denied")}}async shareScreen(){this.emitter.emit("preScreenShare",{session:this});try{if(this.screenStream=await this.room.localParticipant.setScreenShareEnabled(!0,{video:{displaySurface:"window"}}),!this.screenStream){console.warn("Failed to share screen");return}await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({request:"share_screen",success:!0})),{reliable:!0})}catch(e){console.error("Error sharing screen:",e),this.emitter.emit("error",{session:this,error:e instanceof Error?e:new Error(String(e))})}}pauseRecording(){var e,t,n;this.room&&(this.setState(G.PAUSED),this.room.localParticipant.getTrackPublications().forEach(r=>{var s,a;r.handleMuted(),(a=(s=r.track)==null?void 0:s.mediaStream)==null||a.getTracks().forEach(o=>o.enabled=!1)}),(e=this.microphoneStream)==null||e.getTracks().forEach(r=>r.enabled=!1),(n=(t=this.screenStream)==null?void 0:t.track)==null||n.mute(),this.userAudioContext&&this.userAudioContext.resume(),this.assistantAudioContext&&this.assistantAudioContext.resume())}resumeRecording(){var e,t,n;this.room&&(this.setState(G.USER_SPEAKING),this.room.localParticipant.getTrackPublications().forEach(r=>{var s,a;r.handleUnmuted(),(a=(s=r.track)==null?void 0:s.mediaStream)==null||a.getTracks().forEach(o=>o.enabled=!0)}),(e=this.microphoneStream)==null||e.getTracks().forEach(r=>r.enabled=!0),(n=(t=this.screenStream)==null?void 0:t.track)==null||n.unmute())}async promptContinue(){await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({request:"prompt_user",success:!0})),{reliable:!0})}async analyzeAudio(e,t,n){e.getByteFrequencyData(t);const r=t.reduce((a,o)=>a+o,0)/t.length,s=Math.max(.01,Math.min(1,r/128));n==="USER"&&this.currentState===G.USER_SPEAKING?this.emitter.emit("volume",{speaker:"USER",spectrum:Array.from(t),volume:s}):n==="ASSISTANT"&&this.currentState===G.AGENT_SPEAKING&&this.emitter.emit("volume",{speaker:"ASSISTANT",spectrum:Array.from(t),volume:s}),setTimeout(()=>this.analyzeAudio(e,t,n),50)}async sendHTML(e){if(!this.room){console.log("Cannot send HTML: Not connected to LiveKit room");return}try{const t={type:"page_content",html:e,timestamp:new Date().toISOString()},n=JSON.stringify(t),s=new TextEncoder().encode(n);await this.room.localParticipant.publishData(s,{reliable:!0})}catch(t){console.error("Error sending HTML to LiveKit:",t),this.emitter.emit("error",{session:this,error:t instanceof Error?t:new Error(String(t))})}}}const vu=Object.freeze(Object.defineProperty({__proto__:null,ObiSession:gu},Symbol.toStringTag,{value:"Module"}));/**
39
+ * @license
40
+ * Copyright 2019 Google LLC
41
+ * SPDX-License-Identifier: BSD-3-Clause
42
+ */const Hr=globalThis,Va=Hr.ShadowRoot&&(Hr.ShadyCSS===void 0||Hr.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,yu=Symbol(),bu=new WeakMap;let bg=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==yu)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o;const t=this.t;if(Va&&e===void 0){const n=t!==void 0&&t.length===1;n&&(e=bu.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&bu.set(t,e))}return e}toString(){return this.cssText}};const kg=i=>new bg(typeof i=="string"?i:i+"",void 0,yu),Sg=(i,e)=>{if(Va)i.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(const t of e){const n=document.createElement("style"),r=Hr.litNonce;r!==void 0&&n.setAttribute("nonce",r),n.textContent=t.cssText,i.appendChild(n)}},ku=Va?i=>i:i=>i instanceof CSSStyleSheet?(e=>{let t="";for(const n of e.cssRules)t+=n.cssText;return kg(t)})(i):i;/**
43
+ * @license
44
+ * Copyright 2017 Google LLC
45
+ * SPDX-License-Identifier: BSD-3-Clause
46
+ */const{is:Tg,defineProperty:Cg,getOwnPropertyDescriptor:_g,getOwnPropertyNames:Eg,getOwnPropertySymbols:wg,getPrototypeOf:Pg}=Object,hn=globalThis,Su=hn.trustedTypes,Rg=Su?Su.emptyScript:"",qa=hn.reactiveElementPolyfillSupport,Vi=(i,e)=>i,Zr={toAttribute(i,e){switch(e){case Boolean:i=i?Rg:null;break;case Object:case Array:i=i==null?i:JSON.stringify(i)}return i},fromAttribute(i,e){let t=i;switch(e){case Boolean:t=i!==null;break;case Number:t=i===null?null:Number(i);break;case Object:case Array:try{t=JSON.parse(i)}catch{t=null}}return t}},za=(i,e)=>!Tg(i,e),Tu={attribute:!0,type:String,converter:Zr,reflect:!1,useDefault:!1,hasChanged:za};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),hn.litPropertyMetadata??(hn.litPropertyMetadata=new WeakMap);class qi extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??(this.l=[])).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=Tu){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){const n=Symbol(),r=this.getPropertyDescriptor(e,n,t);r!==void 0&&Cg(this.prototype,e,r)}}static getPropertyDescriptor(e,t,n){const{get:r,set:s}=_g(this.prototype,e)??{get(){return this[t]},set(a){this[t]=a}};return{get:r,set(a){const o=r==null?void 0:r.call(this);s==null||s.call(this,a),this.requestUpdate(e,o,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??Tu}static _$Ei(){if(this.hasOwnProperty(Vi("elementProperties")))return;const e=Pg(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(Vi("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Vi("properties"))){const t=this.properties,n=[...Eg(t),...wg(t)];for(const r of n)this.createProperty(r,t[r])}const e=this[Symbol.metadata];if(e!==null){const t=litPropertyMetadata.get(e);if(t!==void 0)for(const[n,r]of t)this.elementProperties.set(n,r)}this._$Eh=new Map;for(const[t,n]of this.elementProperties){const r=this._$Eu(t,n);r!==void 0&&this._$Eh.set(r,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const n=new Set(e.flat(1/0).reverse());for(const r of n)t.unshift(ku(r))}else e!==void 0&&t.push(ku(e));return t}static _$Eu(e,t){const n=t.attribute;return n===!1?void 0:typeof n=="string"?n:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){var e;this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),(e=this.constructor.l)==null||e.forEach(t=>t(this))}addController(e){var t;(this._$EO??(this._$EO=new Set)).add(e),this.renderRoot!==void 0&&this.isConnected&&((t=e.hostConnected)==null||t.call(e))}removeController(e){var t;(t=this._$EO)==null||t.delete(e)}_$E_(){const e=new Map,t=this.constructor.elementProperties;for(const n of t.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Sg(e,this.constructor.elementStyles),e}connectedCallback(){var e;this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(e=this._$EO)==null||e.forEach(t=>{var n;return(n=t.hostConnected)==null?void 0:n.call(t)})}enableUpdating(e){}disconnectedCallback(){var e;(e=this._$EO)==null||e.forEach(t=>{var n;return(n=t.hostDisconnected)==null?void 0:n.call(t)})}attributeChangedCallback(e,t,n){this._$AK(e,n)}_$ET(e,t){var s;const n=this.constructor.elementProperties.get(e),r=this.constructor._$Eu(e,n);if(r!==void 0&&n.reflect===!0){const a=(((s=n.converter)==null?void 0:s.toAttribute)!==void 0?n.converter:Zr).toAttribute(t,n.type);this._$Em=e,a==null?this.removeAttribute(r):this.setAttribute(r,a),this._$Em=null}}_$AK(e,t){var s,a;const n=this.constructor,r=n._$Eh.get(e);if(r!==void 0&&this._$Em!==r){const o=n.getPropertyOptions(r),c=typeof o.converter=="function"?{fromAttribute:o.converter}:((s=o.converter)==null?void 0:s.fromAttribute)!==void 0?o.converter:Zr;this._$Em=r,this[r]=c.fromAttribute(t,o.type)??((a=this._$Ej)==null?void 0:a.get(r))??null,this._$Em=null}}requestUpdate(e,t,n){var r;if(e!==void 0){const s=this.constructor,a=this[e];if(n??(n=s.getPropertyOptions(e)),!((n.hasChanged??za)(a,t)||n.useDefault&&n.reflect&&a===((r=this._$Ej)==null?void 0:r.get(e))&&!this.hasAttribute(s._$Eu(e,n))))return;this.C(e,t,n)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(e,t,{useDefault:n,reflect:r,wrapped:s},a){n&&!(this._$Ej??(this._$Ej=new Map)).has(e)&&(this._$Ej.set(e,a??t??this[e]),s!==!0||a!==void 0)||(this._$AL.has(e)||(this.hasUpdated||n||(t=void 0),this._$AL.set(e,t)),r===!0&&this._$Em!==e&&(this._$Eq??(this._$Eq=new Set)).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}const e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var n;if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(const[s,a]of this._$Ep)this[s]=a;this._$Ep=void 0}const r=this.constructor.elementProperties;if(r.size>0)for(const[s,a]of r){const{wrapped:o}=a,c=this[s];o!==!0||this._$AL.has(s)||c===void 0||this.C(s,void 0,a,c)}}let e=!1;const t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),(n=this._$EO)==null||n.forEach(r=>{var s;return(s=r.hostUpdate)==null?void 0:s.call(r)}),this.update(t)):this._$EM()}catch(r){throw e=!1,this._$EM(),r}e&&this._$AE(t)}willUpdate(e){}_$AE(e){var t;(t=this._$EO)==null||t.forEach(n=>{var r;return(r=n.hostUpdated)==null?void 0:r.call(n)}),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&(this._$Eq=this._$Eq.forEach(t=>this._$ET(t,this[t]))),this._$EM()}updated(e){}firstUpdated(e){}}qi.elementStyles=[],qi.shadowRootOptions={mode:"open"},qi[Vi("elementProperties")]=new Map,qi[Vi("finalized")]=new Map,qa==null||qa({ReactiveElement:qi}),(hn.reactiveElementVersions??(hn.reactiveElementVersions=[])).push("2.1.0");/**
47
+ * @license
48
+ * Copyright 2017 Google LLC
49
+ * SPDX-License-Identifier: BSD-3-Clause
50
+ */const xg={attribute:!0,type:String,converter:Zr,reflect:!1,hasChanged:za},Ig=(i=xg,e,t)=>{const{kind:n,metadata:r}=t;let s=globalThis.litPropertyMetadata.get(r);if(s===void 0&&globalThis.litPropertyMetadata.set(r,s=new Map),n==="setter"&&((i=Object.create(i)).wrapped=!0),s.set(t.name,i),n==="accessor"){const{name:a}=t;return{set(o){const c=e.get.call(this);e.set.call(this,o),this.requestUpdate(a,c,i)},init(o){return o!==void 0&&this.C(a,void 0,i,o),o}}}if(n==="setter"){const{name:a}=t;return function(o){const c=this[a];e.call(this,o),this.requestUpdate(a,c,i)}}throw Error("Unsupported decorator location: "+n)};function se(i){return(e,t)=>typeof t=="object"?Ig(i,e,t):((n,r,s)=>{const a=r.hasOwnProperty(s);return r.constructor.createProperty(s,n),a?Object.getOwnPropertyDescriptor(r,s):void 0})(i,e,t)}/**
51
+ * @license
52
+ * Copyright 2017 Google LLC
53
+ * SPDX-License-Identifier: BSD-3-Clause
54
+ */function Vt(i){return se({...i,state:!0,attribute:!1})}var Og=Object.defineProperty,Ag=Object.getOwnPropertyDescriptor,Jr=(i,e,t,n)=>{for(var r=n>1?void 0:n?Ag(e,t):e,s=i.length-1,a;s>=0;s--)(a=i[s])&&(r=(n?a(e,t,r):a(r))||r);return n&&r&&Og(e,t,r),r};class fn extends W.LitElement{constructor(){super(...arguments),this.id="",this.isActive=!1,this.isSpecial=!1}handleClick(e){e.preventDefault(),e.stopPropagation();const t=new CustomEvent("click",{detail:{id:this.id,isActive:!this.isActive},bubbles:!0,composed:!0});this.dispatchEvent(t),this.onClick&&this.onClick(this.id,!this.isActive)}render(){return W.html`
55
+ <button
56
+ id="obi-nav-${this.id}"
57
+ class=${this.isSpecial?"special":""}
58
+ ?active=${this.isActive}
59
+ @click=${this.handleClick}
60
+ aria-label="${this.id} control"
61
+ >
62
+ <slot></slot>
63
+ </button>
64
+ `}}fn.styles=W.css`
65
+ :host {
66
+ display: block;
67
+ }
68
+
69
+ button {
70
+ display: flex;
71
+ height: 40px;
72
+ width: 40px;
73
+ align-items: center;
74
+ justify-content: center;
75
+ border-radius: 2px;
76
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
77
+ transition: all 0.2s;
78
+ cursor: pointer;
79
+ margin: 4px 0;
80
+ padding: 0;
81
+ border: none;
82
+ color: black;
83
+ }
84
+
85
+ button.special {
86
+ color: #fff;
87
+ background-color: #000;
88
+ }
89
+
90
+ button.special svg {
91
+ stroke: #fff;
92
+ }
93
+
94
+ button.special.active {
95
+ background-color: black;
96
+ color: white;
97
+ }
98
+
99
+ button.special.active:hover {
100
+ background-color: #27272a;
101
+ }
102
+
103
+ button:not(.special) {
104
+ background-color: white;
105
+ color: black;
106
+ }
107
+
108
+ button:not(.special):hover {
109
+ background-color: #e5e5e5;
110
+ }
111
+
112
+ ::slotted(*) {
113
+ width: 18px;
114
+ height: 18px;
115
+ }
116
+ `,Jr([se({type:String})],fn.prototype,"id",2),Jr([se({type:Boolean})],fn.prototype,"isActive",2),Jr([se({type:Boolean})],fn.prototype,"isSpecial",2),Jr([se({type:Function})],fn.prototype,"onClick",2),customElements.get("obi-nav-icon")||customElements.define("obi-nav-icon",fn);const Dg=Object.freeze(Object.defineProperty({__proto__:null,NavIcon:fn},Symbol.toStringTag,{value:"Module"})),zi=i=>W.html`
117
+ <svg
118
+ xmlns="http://www.w3.org/2000/svg"
119
+ width="24"
120
+ height="24"
121
+ viewBox="0 0 24 24"
122
+ fill="none"
123
+ stroke="currentColor"
124
+ stroke-width="2"
125
+ stroke-linecap="round"
126
+ stroke-linejoin="round"
127
+ class="lucide"
128
+ style="display: block;"
129
+ >
130
+ ${i}
131
+ </svg>
132
+ `,Mg=zi(W.svg`
133
+ <rect x="14" y="4" width="4" height="16" rx="1"/><rect x="6" y="4" width="4" height="16" rx="1"/>
134
+ `),Ng=zi(W.svg`<polygon points="6 3 20 12 6 21 6 3"/>`),Lg=zi(W.svg`
135
+ <path d="M12 2v10"/><path d="M18.4 6.6a9 9 0 1 1-12.77.04"/>
136
+ `),Ug=zi(W.svg`
137
+ <path d="M18 6 6 18"/><path d="m6 6 12 12"/>
138
+ `),jg=zi(W.svg`
139
+ <path d="M12 7v14" />
140
+ <path
141
+ d="M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z"
142
+ />
143
+ `),Cu=W.html`
144
+ <img
145
+ class="widget-icon"
146
+ src="data:image/svg+xml;base64,${btoa(`<?xml version="1.0" encoding="UTF-8"?>
147
+ <svg width="32" height="32" viewBox="0 0 32 34" fill="none" xmlns="http://www.w3.org/2000/svg">
148
+ <g id="obi-icon">
149
+ <g id="Subtract">
150
+ <path d="M15.5845 9.29177L8.20527 5.00637L8.20527 13.4502L15.5845 17.7356L15.5845 9.29177Z" fill="white" />
151
+ <path d="M15.5896 27.7146L8.21035 31.9994L8.21032 23.4698L15.5896 19.1843L15.5896 27.7146Z" fill="white" />
152
+ <path d="M16.4104 27.7146L16.4104 19.1786L23.7897 23.4641L23.7897 32L16.4104 27.7146Z" fill="white" />
153
+ <path d="M32 27.7142L24.6207 31.9996L24.6207 23.47L32 19.1846L32 27.7142Z" fill="white" />
154
+ <path d="M24.2048 22.748L31.5911 18.4585L24.2845 14.2154L16.8983 18.5048L24.2048 22.748Z" fill="white" />
155
+ <path d="M23.7948 5.01235L23.7948 13.4564L16.4156 17.7418L16.4156 9.29775L23.7948 5.01235Z" fill="white" />
156
+ <path d="M16.0052 0L23.3865 4.2866L16.0003 8.57606L8.61897 4.28946L16.0052 0Z" fill="white" />
157
+ <path d="M7.72042 14.2182L15.1017 18.5048L7.79445 22.7477L0.413699 18.4615L7.72042 14.2182Z" fill="white" />
158
+ <path d="M7.37926 31.9997L7.37926 23.4638L0 19.1784L3.79636e-05 27.7143L7.37926 31.9997Z" fill="white" />
159
+ </g>
160
+ </g>
161
+ </svg>`)}"
162
+ alt="Obi Icon"
163
+ />
164
+ `;var Fg=Object.defineProperty,$g=Object.getOwnPropertyDescriptor,ii=(i,e,t,n)=>{for(var r=n>1?void 0:n?$g(e,t):e,s=i.length-1,a;s>=0;s--)(a=i[s])&&(r=(n?a(e,t,r):a(r))||r);return n&&r&&Fg(e,t,r),r};class At extends W.LitElement{constructor(){super(),this.isActive=!1,this.isScreenActive=!1,this.position={top:0,left:0},this.currentState=G.READY,this.direction="up"}connectedCallback(){super.connectedCallback()}handleIconClick(e,t){this.onItemSelect&&this.onItemSelect(e,t)}render(){return W.html`
165
+ ${this.isActive?W.html`
166
+ <obi-nav-icon
167
+ id="pause"
168
+ ?isActive=${this.currentState===G.PAUSED}
169
+ @click=${()=>this.handleIconClick("pause",this.currentState!==G.PAUSED)}
170
+ >
171
+ ${this.currentState===G.PAUSED?Ng:Mg}
172
+ </obi-nav-icon>
173
+ <obi-nav-icon
174
+ id="activate"
175
+ ?isActive=${this.isActive}
176
+ ?isSpecial=${!0}
177
+ @click=${()=>this.handleIconClick("activate",!this.isActive)}
178
+ >
179
+ ${this.isActive?Ug:Lg}
180
+ </obi-nav-icon>
181
+ `:W.html`
182
+ <obi-nav-icon
183
+ id="experiences"
184
+ @click=${()=>this.handleIconClick("experiences",!0)}
185
+ >
186
+ ${jg}
187
+ </obi-nav-icon>
188
+ `}
189
+ `}}At.styles=W.css`
190
+ :host {
191
+ display: flex;
192
+ position: absolute;
193
+ z-index: 10000;
194
+ width: 40px;
195
+ transition: all 0.2s ease-in-out;
196
+ opacity: 1;
197
+ transform: scale(1);
198
+ pointer-events: auto;
199
+ background-color: #fff;
200
+ }
201
+
202
+ :host([data-direction="up"]) {
203
+ bottom: 64px;
204
+ top: auto;
205
+ flex-direction: column-reverse;
206
+ }
207
+
208
+ :host([data-direction="down"]) {
209
+ top: 64px;
210
+ bottom: auto;
211
+ flex-direction: column;
212
+ }
213
+ `,ii([se({type:Boolean})],At.prototype,"isActive",2),ii([se({type:Boolean})],At.prototype,"isScreenActive",2),ii([se({type:Object})],At.prototype,"position",2),ii([se({type:String})],At.prototype,"currentState",2),ii([se({type:String})],At.prototype,"direction",2),ii([se({type:Function})],At.prototype,"onItemSelect",2),customElements.get("obi-navigation-bar")||customElements.define("obi-navigation-bar",At);const Bg=Object.freeze(Object.defineProperty({__proto__:null,NavigationBar:At},Symbol.toStringTag,{value:"Module"}));var Vg=Object.defineProperty,qg=Object.getOwnPropertyDescriptor,qt=(i,e,t,n)=>{for(var r=n>1?void 0:n?qg(e,t):e,s=i.length-1,a;s>=0;s--)(a=i[s])&&(r=(n?a(e,t,r):a(r))||r);return n&&r&&Vg(e,t,r),r};class zt extends W.LitElement{constructor(){super(...arguments),this.id="",this.name="",this.description="",this.imageSrc=""}handleClick(){this.onSelect&&this.onSelect(this.id),this.dispatchEvent(new CustomEvent("course-select",{detail:{id:this.id},bubbles:!0,composed:!0}))}render(){return W.html`
214
+ <div class="course-container" @click=${this.handleClick}>
215
+ <img src=${this.imageSrc} alt="Course Preview" class="course-image" />
216
+ <h2 class="course-title">${this.name}</h2>
217
+ ${this.description?W.html`<p class="course-description">${this.description}</p>`:""}
218
+ </div>
219
+ `}}zt.styles=W.css`
220
+ :host {
221
+ display: block;
222
+ }
223
+
224
+ .course-container {
225
+ padding: 16px 12px;
226
+ gap: 12px;
227
+ border-radius: 4px;
228
+ border: 1px solid #e5e7eb;
229
+ cursor: pointer;
230
+ transition: all 0.2s;
231
+ }
232
+
233
+ .course-container:hover {
234
+ background-color: #f9fafb;
235
+ border-color: #d1d5db;
236
+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
237
+ }
238
+
239
+ .course-container:active {
240
+ transform: scale(0.98);
241
+ }
242
+
243
+ .course-image {
244
+ max-height: 160px;
245
+ border-radius: 2px;
246
+ border: 1px solid #e5e7eb;
247
+ object-fit: cover;
248
+ width: 100%;
249
+ margin-bottom: 12px;
250
+ }
251
+
252
+ .course-title {
253
+ font-size: 14px;
254
+ font-weight: bold;
255
+ margin: 0;
256
+ margin-bottom: 12px;
257
+ }
258
+
259
+ .course-description {
260
+ font-size: 14px;
261
+ color: #71717a;
262
+ margin: 0;
263
+ }
264
+ `,qt([se({type:String})],zt.prototype,"id",2),qt([se({type:String})],zt.prototype,"name",2),qt([se({type:String})],zt.prototype,"description",2),qt([se({type:String})],zt.prototype,"imageSrc",2),qt([se({type:Function})],zt.prototype,"onSelect",2);class pn extends W.LitElement{constructor(){super(...arguments),this.courses=[],this.loading=!1,this.error=""}handleCourseSelect(e){this.onCourseSelect&&this.onCourseSelect(e.detail.id)}render(){if(this.loading)return W.html`<div class="loading">Loading...</div>`;if(this.error)return W.html`<div class="error">${this.error}</div>`;if(!this.courses||this.courses.length===0)return W.html`<div class="empty">No courses available</div>`;const e=this.courses.length===1?"grid-cols-1":this.courses.length===2?"grid-cols-2":"grid-cols-3";return W.html`
265
+ <div class="course-grid ${e}">
266
+ ${this.courses.map(t=>W.html`
267
+ <obi-course
268
+ id=${t.id}
269
+ name=${t.name}
270
+ description=${t.description||""}
271
+ imageSrc=${t.imageSrc}
272
+ @course-select=${this.handleCourseSelect}
273
+ ></obi-course>
274
+ `)}
275
+ </div>
276
+ `}}pn.styles=W.css`
277
+ :host {
278
+ display: block;
279
+ }
280
+
281
+ .course-grid {
282
+ display: grid;
283
+ gap: 12px;
284
+ margin-top: 24px;
285
+ }
286
+
287
+ .course-grid.grid-cols-1 {
288
+ grid-template-columns: 1fr;
289
+ }
290
+
291
+ .course-grid.grid-cols-2 {
292
+ grid-template-columns: 1fr 1fr;
293
+ }
294
+
295
+ .course-grid.grid-cols-3 {
296
+ grid-template-columns: 1fr 1fr 1fr;
297
+ }
298
+
299
+ .loading,
300
+ .error,
301
+ .empty {
302
+ display: flex;
303
+ justify-content: center;
304
+ align-items: center;
305
+ margin-top: 16px;
306
+ }
307
+
308
+ .error {
309
+ color: #ef4444;
310
+ }
311
+ `,qt([se({type:Array})],pn.prototype,"courses",2),qt([se({type:Boolean})],pn.prototype,"loading",2),qt([se({type:String})],pn.prototype,"error",2),qt([se({type:Function})],pn.prototype,"onCourseSelect",2),customElements.get("obi-course")||customElements.define("obi-course",zt),customElements.get("obi-course-list")||customElements.define("obi-course-list",pn);const zg=Object.freeze(Object.defineProperty({__proto__:null,Course:zt,CourseList:pn},Symbol.toStringTag,{value:"Module"}));var Wg=Object.defineProperty,Gg=Object.getOwnPropertyDescriptor,xn=(i,e,t,n)=>{for(var r=n>1?void 0:n?Gg(e,t):e,s=i.length-1,a;s>=0;s--)(a=i[s])&&(r=(n?a(e,t,r):a(r))||r);return n&&r&&Wg(e,t,r),r};class kt extends W.LitElement{constructor(){super(...arguments),this.courses=[],this.loading=!0,this.error="",this.apiBaseUrl="",this.apiKey=""}handleCourseSelect(e){this.onCourseSelect&&this.onCourseSelect(e.detail.id)}handleClose(){this.onClose&&this.onClose()}async fetchCourses(){try{this.loading=!0;const r=(await(await fetch(`${this.apiBaseUrl}/sessions?token=${this.apiKey}`)).json()).map(s=>({id:s.uuid,name:s.onboarding_plan.name,description:s.onboarding_plan.description,imageSrc:s.onboarding_plan.screen_url||"https://corproductionsydney-storagebucket5cb7c8ea-atg4gmftc6sk.s3.amazonaws.com/static/generic-course.png"})).filter(s=>!!s.name);this.courses=[...r],this.requestUpdate()}catch(e){console.error("Fetch error:",e),this.error="Failed to fetch courses"}finally{this.loading=!1,this.requestUpdate()}}connectedCallback(){var e,t;super.connectedCallback(),(e=window.obiWidgetConfig)!=null&&e.apiKey&&(this.apiKey=window.obiWidgetConfig.apiKey),(t=window.obiWidgetConfig)!=null&&t.apiBaseUrl&&(this.apiBaseUrl=window.obiWidgetConfig.apiBaseUrl),this.apiBaseUrl&&this.apiKey?this.fetchCourses():(this.loading=!1,this.error="API base URL or API key is missing")}render(){return W.html`
312
+ <div class="backdrop" @click=${this.handleClose}></div>
313
+ <div class="container">
314
+ <button class="close-button" @click=${this.handleClose}>×</button>
315
+ <div class="header">
316
+ <h1>Give Obi a try!</h1>
317
+ <p class="subtitle">Pick a tour, share your screen, and Obi will take it from there.</p>
318
+ </div>
319
+
320
+ <obi-course-list
321
+ .courses=${this.courses}
322
+ .loading=${this.loading}
323
+ .error=${this.error}
324
+ @course-select=${this.handleCourseSelect}
325
+ ></obi-course-list>
326
+ </div>
327
+ `}}kt.styles=W.css`
328
+ :host {
329
+ display: block;
330
+ font-family: "Syne", sans-serif;
331
+ }
332
+
333
+ .backdrop {
334
+ position: fixed;
335
+ top: 0;
336
+ right: 0;
337
+ bottom: 0;
338
+ left: 0;
339
+ background-color: black;
340
+ opacity: 0.7;
341
+ z-index: 40;
342
+ }
343
+
344
+ .container {
345
+ position: fixed;
346
+ background-color: white;
347
+ color: black;
348
+ border: 1px solid #e5e7eb;
349
+ width: 640px;
350
+ max-height: 80vh;
351
+ overflow-y: auto;
352
+ padding: 48px;
353
+ gap: 12px;
354
+ top: 50%;
355
+ left: 50%;
356
+ transform: translate(-50%, -50%);
357
+ border-radius: 4px;
358
+ z-index: 50;
359
+ display: flex;
360
+ flex-direction: column;
361
+ text-align: center;
362
+ }
363
+
364
+ .container:hover {
365
+ cursor: auto;
366
+ }
367
+
368
+ .container::-webkit-scrollbar {
369
+ width: 0.5rem;
370
+ }
371
+
372
+ .container::-webkit-scrollbar-track {
373
+ background-color: #f3f4f6;
374
+ border-radius: 9999px;
375
+ }
376
+
377
+ .container::-webkit-scrollbar-thumb {
378
+ background-color: #d1d5db;
379
+ border-radius: 9999px;
380
+ }
381
+
382
+ .header {
383
+ margin-bottom: 24px;
384
+ text-align: center;
385
+ }
386
+
387
+ h1 {
388
+ font-size: 32px;
389
+ font-weight: 700;
390
+ margin: 0;
391
+ margin-bottom: 8px;
392
+ }
393
+
394
+ .subtitle {
395
+ font-size: 20px;
396
+ color: rgb(113 113 122 / 1);
397
+ margin: 0;
398
+ }
399
+
400
+ .close-button {
401
+ position: absolute;
402
+ top: 16px;
403
+ right: 16px;
404
+ background: none;
405
+ border: none;
406
+ cursor: pointer;
407
+ font-size: 24px;
408
+ color: #6b7280;
409
+ }
410
+ `,xn([se({type:Array})],kt.prototype,"courses",2),xn([se({type:Boolean})],kt.prototype,"loading",2),xn([se({type:String})],kt.prototype,"error",2),xn([se({type:String})],kt.prototype,"apiBaseUrl",2),xn([se({type:String})],kt.prototype,"apiKey",2),xn([se({type:Function})],kt.prototype,"onCourseSelect",2),xn([se({type:Function})],kt.prototype,"onClose",2),customElements.get("obi-course-modal")||customElements.define("obi-course-modal",kt);const Kg=Object.freeze(Object.defineProperty({__proto__:null,CourseModal:kt},Symbol.toStringTag,{value:"Module"}));/**
411
+ * @license
412
+ * Copyright 2017 Google LLC
413
+ * SPDX-License-Identifier: BSD-3-Clause
414
+ */const Wi=globalThis,Yr=Wi.trustedTypes,_u=Yr?Yr.createPolicy("lit-html",{createHTML:i=>i}):void 0,Eu="$lit$",mn=`lit$${Math.random().toFixed(9).slice(2)}$`,wu="?"+mn,Hg=`<${wu}>`,In=document,Qr=()=>In.createComment(""),Gi=i=>i===null||typeof i!="object"&&typeof i!="function",Wa=Array.isArray,Zg=i=>Wa(i)||typeof(i==null?void 0:i[Symbol.iterator])=="function",Ga=`[
415
+ \f\r]`,Ki=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Pu=/-->/g,Ru=/>/g,On=RegExp(`>|${Ga}(?:([^\\s"'>=/]+)(${Ga}*=${Ga}*(?:[^
416
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),xu=/'/g,Iu=/"/g,Ou=/^(?:script|style|textarea|title)$/i,Hi=Symbol.for("lit-noChange"),Ue=Symbol.for("lit-nothing"),Au=new WeakMap,An=In.createTreeWalker(In,129);function Du(i,e){if(!Wa(i)||!i.hasOwnProperty("raw"))throw Error("invalid template strings array");return _u!==void 0?_u.createHTML(e):e}const Jg=(i,e)=>{const t=i.length-1,n=[];let r,s=e===2?"<svg>":e===3?"<math>":"",a=Ki;for(let o=0;o<t;o++){const c=i[o];let d,u,h=-1,f=0;for(;f<c.length&&(a.lastIndex=f,u=a.exec(c),u!==null);)f=a.lastIndex,a===Ki?u[1]==="!--"?a=Pu:u[1]!==void 0?a=Ru:u[2]!==void 0?(Ou.test(u[2])&&(r=RegExp("</"+u[2],"g")),a=On):u[3]!==void 0&&(a=On):a===On?u[0]===">"?(a=r??Ki,h=-1):u[1]===void 0?h=-2:(h=a.lastIndex-u[2].length,d=u[1],a=u[3]===void 0?On:u[3]==='"'?Iu:xu):a===Iu||a===xu?a=On:a===Pu||a===Ru?a=Ki:(a=On,r=void 0);const g=a===On&&i[o+1].startsWith("/>")?" ":"";s+=a===Ki?c+Hg:h>=0?(n.push(d),c.slice(0,h)+Eu+c.slice(h)+mn+g):c+mn+(h===-2?o:g)}return[Du(i,s+(i[t]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),n]};class Zi{constructor({strings:e,_$litType$:t},n){let r;this.parts=[];let s=0,a=0;const o=e.length-1,c=this.parts,[d,u]=Jg(e,t);if(this.el=Zi.createElement(d,n),An.currentNode=this.el.content,t===2||t===3){const h=this.el.content.firstChild;h.replaceWith(...h.childNodes)}for(;(r=An.nextNode())!==null&&c.length<o;){if(r.nodeType===1){if(r.hasAttributes())for(const h of r.getAttributeNames())if(h.endsWith(Eu)){const f=u[a++],g=r.getAttribute(h).split(mn),y=/([.?@])?(.*)/.exec(f);c.push({type:1,index:s,name:y[2],strings:g,ctor:y[1]==="."?Qg:y[1]==="?"?Xg:y[1]==="@"?ev:es}),r.removeAttribute(h)}else h.startsWith(mn)&&(c.push({type:6,index:s}),r.removeAttribute(h));if(Ou.test(r.tagName)){const h=r.textContent.split(mn),f=h.length-1;if(f>0){r.textContent=Yr?Yr.emptyScript:"";for(let g=0;g<f;g++)r.append(h[g],Qr()),An.nextNode(),c.push({type:2,index:++s});r.append(h[f],Qr())}}}else if(r.nodeType===8)if(r.data===wu)c.push({type:2,index:s});else{let h=-1;for(;(h=r.data.indexOf(mn,h+1))!==-1;)c.push({type:7,index:s}),h+=mn.length-1}s++}}static createElement(e,t){const n=In.createElement("template");return n.innerHTML=e,n}}function ri(i,e,t=i,n){var a,o;if(e===Hi)return e;let r=n!==void 0?(a=t._$Co)==null?void 0:a[n]:t._$Cl;const s=Gi(e)?void 0:e._$litDirective$;return(r==null?void 0:r.constructor)!==s&&((o=r==null?void 0:r._$AO)==null||o.call(r,!1),s===void 0?r=void 0:(r=new s(i),r._$AT(i,t,n)),n!==void 0?(t._$Co??(t._$Co=[]))[n]=r:t._$Cl=r),r!==void 0&&(e=ri(i,r._$AS(i,e.values),r,n)),e}class Yg{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){const{el:{content:t},parts:n}=this._$AD,r=((e==null?void 0:e.creationScope)??In).importNode(t,!0);An.currentNode=r;let s=An.nextNode(),a=0,o=0,c=n[0];for(;c!==void 0;){if(a===c.index){let d;c.type===2?d=new Xr(s,s.nextSibling,this,e):c.type===1?d=new c.ctor(s,c.name,c.strings,this,e):c.type===6&&(d=new tv(s,this,e)),this._$AV.push(d),c=n[++o]}a!==(c==null?void 0:c.index)&&(s=An.nextNode(),a++)}return An.currentNode=In,r}p(e){let t=0;for(const n of this._$AV)n!==void 0&&(n.strings!==void 0?(n._$AI(e,n,t),t+=n.strings.length-2):n._$AI(e[t])),t++}}class Xr{get _$AU(){var e;return((e=this._$AM)==null?void 0:e._$AU)??this._$Cv}constructor(e,t,n,r){this.type=2,this._$AH=Ue,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=n,this.options=r,this._$Cv=(r==null?void 0:r.isConnected)??!0}get parentNode(){let e=this._$AA.parentNode;const t=this._$AM;return t!==void 0&&(e==null?void 0:e.nodeType)===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=ri(this,e,t),Gi(e)?e===Ue||e==null||e===""?(this._$AH!==Ue&&this._$AR(),this._$AH=Ue):e!==this._$AH&&e!==Hi&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):Zg(e)?this.k(e):this._(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==Ue&&Gi(this._$AH)?this._$AA.nextSibling.data=e:this.T(In.createTextNode(e)),this._$AH=e}$(e){var s;const{values:t,_$litType$:n}=e,r=typeof n=="number"?this._$AC(e):(n.el===void 0&&(n.el=Zi.createElement(Du(n.h,n.h[0]),this.options)),n);if(((s=this._$AH)==null?void 0:s._$AD)===r)this._$AH.p(t);else{const a=new Yg(r,this),o=a.u(this.options);a.p(t),this.T(o),this._$AH=a}}_$AC(e){let t=Au.get(e.strings);return t===void 0&&Au.set(e.strings,t=new Zi(e)),t}k(e){Wa(this._$AH)||(this._$AH=[],this._$AR());const t=this._$AH;let n,r=0;for(const s of e)r===t.length?t.push(n=new Xr(this.O(Qr()),this.O(Qr()),this,this.options)):n=t[r],n._$AI(s),r++;r<t.length&&(this._$AR(n&&n._$AB.nextSibling,r),t.length=r)}_$AR(e=this._$AA.nextSibling,t){var n;for((n=this._$AP)==null?void 0:n.call(this,!1,!0,t);e&&e!==this._$AB;){const r=e.nextSibling;e.remove(),e=r}}setConnected(e){var t;this._$AM===void 0&&(this._$Cv=e,(t=this._$AP)==null||t.call(this,e))}}class es{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,n,r,s){this.type=1,this._$AH=Ue,this._$AN=void 0,this.element=e,this.name=t,this._$AM=r,this.options=s,n.length>2||n[0]!==""||n[1]!==""?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=Ue}_$AI(e,t=this,n,r){const s=this.strings;let a=!1;if(s===void 0)e=ri(this,e,t,0),a=!Gi(e)||e!==this._$AH&&e!==Hi,a&&(this._$AH=e);else{const o=e;let c,d;for(e=s[0],c=0;c<s.length-1;c++)d=ri(this,o[n+c],t,c),d===Hi&&(d=this._$AH[c]),a||(a=!Gi(d)||d!==this._$AH[c]),d===Ue?e=Ue:e!==Ue&&(e+=(d??"")+s[c+1]),this._$AH[c]=d}a&&!r&&this.j(e)}j(e){e===Ue?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class Qg extends es{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===Ue?void 0:e}}class Xg extends es{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==Ue)}}class ev extends es{constructor(e,t,n,r,s){super(e,t,n,r,s),this.type=5}_$AI(e,t=this){if((e=ri(this,e,t,0)??Ue)===Hi)return;const n=this._$AH,r=e===Ue&&n!==Ue||e.capture!==n.capture||e.once!==n.once||e.passive!==n.passive,s=e!==Ue&&(n===Ue||r);r&&this.element.removeEventListener(this.name,this,n),s&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){var t;typeof this._$AH=="function"?this._$AH.call(((t=this.options)==null?void 0:t.host)??this.element,e):this._$AH.handleEvent(e)}}class tv{constructor(e,t,n){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=n}get _$AU(){return this._$AM._$AU}_$AI(e){ri(this,e)}}const Ka=Wi.litHtmlPolyfillSupport;Ka==null||Ka(Zi,Xr),(Wi.litHtmlVersions??(Wi.litHtmlVersions=[])).push("3.3.0");/**
417
+ * @license
418
+ * Copyright 2020 Google LLC
419
+ * SPDX-License-Identifier: BSD-3-Clause
420
+ */const nv=i=>i.strings===void 0;/**
421
+ * @license
422
+ * Copyright 2017 Google LLC
423
+ * SPDX-License-Identifier: BSD-3-Clause
424
+ */const iv={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},rv=i=>(...e)=>({_$litDirective$:i,values:e});class sv{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,n){this._$Ct=e,this._$AM=t,this._$Ci=n}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}}/**
425
+ * @license
426
+ * Copyright 2017 Google LLC
427
+ * SPDX-License-Identifier: BSD-3-Clause
428
+ */const Ji=(i,e)=>{var n;const t=i._$AN;if(t===void 0)return!1;for(const r of t)(n=r._$AO)==null||n.call(r,e,!1),Ji(r,e);return!0},ts=i=>{let e,t;do{if((e=i._$AM)===void 0)break;t=e._$AN,t.delete(i),i=e}while((t==null?void 0:t.size)===0)},Mu=i=>{for(let e;e=i._$AM;i=e){let t=e._$AN;if(t===void 0)e._$AN=t=new Set;else if(t.has(i))break;t.add(i),cv(e)}};function av(i){this._$AN!==void 0?(ts(this),this._$AM=i,Mu(this)):this._$AM=i}function ov(i,e=!1,t=0){const n=this._$AH,r=this._$AN;if(r!==void 0&&r.size!==0)if(e)if(Array.isArray(n))for(let s=t;s<n.length;s++)Ji(n[s],!1),ts(n[s]);else n!=null&&(Ji(n,!1),ts(n));else Ji(this,i)}const cv=i=>{i.type==iv.CHILD&&(i._$AP??(i._$AP=ov),i._$AQ??(i._$AQ=av))};class dv extends sv{constructor(){super(...arguments),this._$AN=void 0}_$AT(e,t,n){super._$AT(e,t,n),Mu(this),this.isConnected=e._$AU}_$AO(e,t=!0){var n,r;e!==this.isConnected&&(this.isConnected=e,e?(n=this.reconnected)==null||n.call(this):(r=this.disconnected)==null||r.call(this)),t&&(Ji(this,e),ts(this))}setValue(e){if(nv(this._$Ct))this._$Ct._$AI(e,this);else{const t=[...this._$Ct._$AH];t[this._$Ci]=e,this._$Ct._$AI(t,this,0)}}disconnected(){}reconnected(){}}/**
429
+ * @license
430
+ * Copyright 2020 Google LLC
431
+ * SPDX-License-Identifier: BSD-3-Clause
432
+ */const uv=()=>new lv;class lv{}const Ha=new WeakMap,hv=rv(class extends dv{render(i){return Ue}update(i,[e]){var n;const t=e!==this.G;return t&&this.G!==void 0&&this.rt(void 0),(t||this.lt!==this.ct)&&(this.G=e,this.ht=(n=i.options)==null?void 0:n.host,this.rt(this.ct=i.element)),Ue}rt(i){if(this.isConnected||(i=void 0),typeof this.G=="function"){const e=this.ht??globalThis;let t=Ha.get(e);t===void 0&&(t=new WeakMap,Ha.set(e,t)),t.get(this.G)!==void 0&&this.G.call(this.ht,void 0),t.set(this.G,i),i!==void 0&&this.G.call(this.ht,i)}else this.G.value=i}get lt(){var i,e;return typeof this.G=="function"?(i=Ha.get(this.ht??globalThis))==null?void 0:i.get(this.G):(e=this.G)==null?void 0:e.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}});var fv=Object.defineProperty,pv=Object.getOwnPropertyDescriptor,Nu=(i,e,t,n)=>{for(var r=n>1?void 0:n?pv(e,t):e,s=i.length-1,a;s>=0;s--)(a=i[s])&&(r=(n?a(e,t,r):a(r))||r);return n&&r&&fv(e,t,r),r};class si extends W.LitElement{constructor(){super(...arguments),this.volume={speaker:"ASSISTANT",volume:0,spectrum:[]},this.canvasRef=uv(),this.barCount=8,this.animationFrame=null}connectedCallback(){super.connectedCallback(),this.startAnimation()}disconnectedCallback(){super.disconnectedCallback(),this.stopAnimation()}startAnimation(){const e=()=>{this.drawEqualizer(),this.animationFrame=requestAnimationFrame(e)};this.animationFrame=requestAnimationFrame(e)}stopAnimation(){this.animationFrame&&(cancelAnimationFrame(this.animationFrame),this.animationFrame=null)}drawEqualizer(){const e=this.canvasRef.value;if(!e)return;const t=e.getContext("2d");if(!t)return;const n=window.devicePixelRatio||1,r=e.clientWidth,s=e.clientHeight;e.width=r*n,e.height=s*n,t.scale(n,n),t.clearRect(0,0,r,s);const a=3,o=Math.max(1,(r-(this.barCount-1)*a)/this.barCount),c=s/2,d=this.volume.speaker==="USER"?this.volume.volume:this.volume.volume,u=this.volume.speaker==="USER"?this.volume.spectrum:this.volume.spectrum;if(d===0)return;let h=[];if(u&&u.length>0){const f=u.length,g=Math.ceil(f/10);let y=[];for(let b=0;b<10;b++){const k=b*g,x=Math.min((b+1)*g,f);let F=0;for(let q=k;q<x;q++)F+=u[q]||0;y.push({region:b,startIdx:k,endIdx:x,energy:F})}y.sort((b,k)=>k.energy-b.energy);const v=y.slice(0,3),_=Math.min(...v.map(b=>b.startIdx)),w=Math.max(...v.map(b=>b.endIdx));if(w>_)for(let b=0;b<this.barCount;b++){const k=_+b/(this.barCount-1)*(w-_),x=Math.min(f-1,Math.floor(k));h[b]=u[x]||0}else for(let b=0;b<this.barCount;b++){const k=b/(this.barCount-1)*(f/2),x=Math.min(f-1,Math.floor(k));h[b]=u[x]||0}const N=Math.max(...h,1),U=this.volume.speaker==="USER"?.7:.6;h=h.map((b,k)=>{const x=b/N,F=U+k/(this.barCount-1)*.3;return Math.min(1,x*F)})}else if(this.volume.speaker!=="USER")for(let f=0;f<this.barCount;f++){const g=Date.now()*.002,y=.3+.2*Math.sin(g+f*.7);h[f]=y}for(let f=0;f<this.barCount;f++){const g=h.length>0&&h[f]!==void 0?h[f]:d;this.volume.speaker==="USER"?t.fillStyle=`rgba(109, 40, 217, ${g*.5+.5})`:t.fillStyle=`rgba(255, 255, 255, ${g*.5+.5})`;const y=Math.max(2,g*.8*c),v=r-(this.barCount-f)*(o+a),_=o/2;t.beginPath(),t.moveTo(v+_,s/2-y),t.lineTo(v+o-_,s/2-y),t.quadraticCurveTo(v+o,s/2-y,v+o,s/2-y+_),t.lineTo(v+o,s/2),t.lineTo(v,s/2),t.lineTo(v,s/2-y+_),t.quadraticCurveTo(v,s/2-y,v+_,s/2-y),t.fill(),t.beginPath(),t.moveTo(v,s/2),t.lineTo(v+o,s/2),t.lineTo(v+o,s/2+y-_),t.quadraticCurveTo(v+o,s/2+y,v+o-_,s/2+y),t.lineTo(v+_,s/2+y),t.quadraticCurveTo(v,s/2+y,v,s/2+y-_),t.lineTo(v,s/2),t.fill()}}render(){return W.html` <canvas ${hv(this.canvasRef)} width="52" height="52"></canvas> `}}si.styles=W.css`
433
+ :host {
434
+ display: block;
435
+ width: 40px;
436
+ height: 40px;
437
+ margin: 4px;
438
+ }
439
+
440
+ canvas {
441
+ width: 100%;
442
+ height: 100%;
443
+ }
444
+ `,Nu([se({type:Object})],si.prototype,"volume",2),Nu([Vt()],si.prototype,"canvasRef",2),customElements.get("obi-audio-equalizer")||customElements.define("obi-audio-equalizer",si);const mv=Object.freeze(Object.defineProperty({__proto__:null,AudioEqualizer:si},Symbol.toStringTag,{value:"Module"}));var gv=Object.defineProperty,vv=Object.getOwnPropertyDescriptor,yv=(i,e,t,n)=>{for(var r=n>1?void 0:n?vv(e,t):e,s=i.length-1,a;s>=0;s--)(a=i[s])&&(r=(n?a(e,t,r):a(r))||r);return n&&r&&gv(e,t,r),r};class Yi extends W.LitElement{constructor(){super(...arguments),this.activeDots=Array(5).fill(!1),this.numDots=5,this.containerWidth=32,this.dotSize=2,this.bounceHeight=12,this.animationDuration=200,this.pauseDuration=300,this.overlapFactor=.7,this.color="#FFF",this.timeoutIds=[]}connectedCallback(){super.connectedCallback(),this.startAnimation(),this.style.setProperty("--dot-loader-width",`${this.containerWidth}px`),this.style.setProperty("--dot-size",`${this.dotSize}px`),this.style.setProperty("--dot-color",this.color)}disconnectedCallback(){super.disconnectedCallback(),this.stopAnimation()}startAnimation(){this.animateSequence()}stopAnimation(){this.timeoutIds.forEach(e=>window.clearTimeout(e)),this.timeoutIds=[]}animateSequence(){this.activeDots=Array(this.numDots).fill(!1);for(let t=0;t<this.numDots;t++){const n=t*(this.animationDuration*this.overlapFactor),r=window.setTimeout(()=>{this.activeDots=[...this.activeDots],this.activeDots[t]=!0;const s=window.setTimeout(()=>{this.activeDots=[...this.activeDots],this.activeDots[t]=!1},this.animationDuration);this.timeoutIds.push(s)},n);this.timeoutIds.push(r)}const e=window.setTimeout(()=>{this.animateSequence()},this.numDots*this.animationDuration*this.overlapFactor+this.pauseDuration);this.timeoutIds.push(e)}render(){return W.html`
445
+ <div class="dot-loader">
446
+ ${this.activeDots.map(e=>W.html`
447
+ <div
448
+ class="dot"
449
+ style="transform: ${e?`translateY(-${this.bounceHeight}px)`:"translateY(0)"}"
450
+ ></div>
451
+ `)}
452
+ </div>
453
+ `}}Yi.styles=W.css`
454
+ :host {
455
+ display: block;
456
+ }
457
+
458
+ .dot-loader {
459
+ display: flex;
460
+ flex-direction: row;
461
+ width: var(--dot-loader-width, 32px);
462
+ height: 14px;
463
+ justify-content: center;
464
+ align-items: center;
465
+ padding: 0;
466
+ margin: 0;
467
+ gap: 4px;
468
+ }
469
+
470
+ .dot {
471
+ width: var(--dot-size, 2px);
472
+ height: var(--dot-size, 2px);
473
+ border-radius: 50%;
474
+ background-color: var(--dot-color, #fff);
475
+ margin: 0;
476
+ padding: 0;
477
+ transition: transform 0.2s ease-in-out;
478
+ opacity: 1;
479
+ }
480
+ `,yv([Vt()],Yi.prototype,"activeDots",2),customElements.get("obi-dot-loader")||customElements.define("obi-dot-loader",Yi);const bv=Object.freeze(Object.defineProperty({__proto__:null,DotLoader:Yi},Symbol.toStringTag,{value:"Module"}));class ns extends W.LitElement{render(){return W.html`
481
+ <obi-dot-loader loading style="margin-left: 2px"></obi-dot-loader>
482
+ <span class="text">Searching the knowledge base</span>
483
+ `}}ns.styles=W.css`
484
+ :host {
485
+ display: flex;
486
+ align-items: center;
487
+ gap: 12px;
488
+ background-color: #7c3aed;
489
+ border-radius: 12px;
490
+ padding: 8px 12px;
491
+ }
492
+
493
+ .text {
494
+ color: white;
495
+ font-weight: 500;
496
+ font-size: 14px;
497
+ }
498
+ `,customElements.get("obi-searching-loader")||customElements.define("obi-searching-loader",ns);const kv=Object.freeze(Object.defineProperty({__proto__:null,SearchingLoader:ns},Symbol.toStringTag,{value:"Module"}));var Sv=Object.defineProperty,Tv=Object.getOwnPropertyDescriptor,Dt=(i,e,t,n)=>{for(var r=n>1?void 0:n?Tv(e,t):e,s=i.length-1,a;s>=0;s--)(a=i[s])&&(r=(n?a(e,t,r):a(r))||r);return n&&r&&Sv(e,t,r),r};const Cv="https://iamobi.ai/api";class tt extends W.LitElement{constructor(){super(),this.apiBaseUrl=Cv,this.apiKey="",this.position="bottom-right",this.state=G.READY,this.showCourseModal=!1,this.isHovering=!1,this.navVisible=!1,this.activeSession=null,this.volume={speaker:"ASSISTANT",volume:0,spectrum:[]},this.screenPosition=this.calculateScreenPosition(),this.closeNavTimeoutRef=null,this.handleResize=()=>{this.screenPosition=this.calculateScreenPosition()},window.obiWidgetConfig&&(window.obiWidgetConfig.apiKey&&(this.apiKey=window.obiWidgetConfig.apiKey),window.obiWidgetConfig.apiBaseUrl&&(this.apiBaseUrl=window.obiWidgetConfig.apiBaseUrl),window.obiWidgetConfig.position&&(this.position=window.obiWidgetConfig.position))}calculateScreenPosition(){return Bi(this.position).with("top-right",()=>({top:20,left:window.innerWidth-100})).with("bottom-right",()=>({top:window.innerHeight-100,left:window.innerWidth-100})).with("top-left",()=>({top:20,left:20})).with("bottom-left",()=>({top:window.innerHeight-100,left:20})).otherwise(()=>({top:window.innerHeight-100,left:window.innerWidth-100}))}connectedCallback(){super.connectedCallback(),window.addEventListener("resize",this.handleResize),window.obiWidgetConfig||(window.obiWidgetConfig={}),window.obiWidgetConfig.apiBaseUrl=this.apiBaseUrl,this.apiKey&&(window.obiWidgetConfig.apiKey=this.apiKey)}disconnectedCallback(){super.disconnectedCallback(),window.removeEventListener("resize",this.handleResize),this.closeNavTimeoutRef!==null&&window.clearTimeout(this.closeNavTimeoutRef),this.activeSession&&(this.activeSession.disconnect(),this.activeSession=null)}handleMouseEnter(){this.isHovering=!0,this.navVisible=!0}handleMouseLeave(){this.isHovering=!1,this.closeNavTimeoutRef!==null&&window.clearTimeout(this.closeNavTimeoutRef),this.closeNavTimeoutRef=window.setTimeout(()=>{this.isHovering||(this.navVisible=!1),this.closeNavTimeoutRef=null},300)}handleItemSelect(e,t){if(e==="experiences"){this.showCourseModal=!0;return}Bi([e,t]).with(["pause",!0],()=>{var n;(n=this.activeSession)==null||n.pauseRecording()}).with(["pause",!1],()=>{var n;(n=this.activeSession)==null||n.resumeRecording()}).with(["activate",!1],()=>{var n;(n=this.activeSession)==null||n.disconnect()}).otherwise(()=>{})}async handleSessionStart(e){this.showCourseModal=!1,this.state=G.LOADING;try{const{ObiSession:t}=await Promise.resolve().then(()=>vu),n=new t({token:e,apiBaseUrl:this.apiBaseUrl});n.on("stateChanged",r=>{this.state=r.newState}),n.on("volume",r=>{this.volume=r}),n.on("error",r=>{console.error("Session error:",r.error),this.state=G.ERROR,this.activeSession=null}),await n.connect(),this.activeSession=n}catch(t){console.error("Failed to connect to session:",t),this.state=G.ERROR}}render(){const{top:e,left:t}=this.screenPosition,n=this.state===G.RESEARCHING?t-265+56:t,r=Bi(this.state).with(G.LOADING,()=>W.html`<obi-dot-loader></obi-dot-loader>`).with(G.RESEARCHING,()=>W.html`<obi-searching-loader></obi-searching-loader>`).with(mg.union(G.USER_SPEAKING,G.AGENT_SPEAKING),()=>W.html`<obi-audio-equalizer .volume=${this.volume}></obi-audio-equalizer>`).with(G.PAUSED,()=>Cu).otherwise(()=>Cu);return W.html`
499
+ <div
500
+ class="widget-container ${this.state===G.USER_SPEAKING||this.state===G.AGENT_SPEAKING?"pulse":""} ${this.state!==G.READY||this.navVisible?"rounded":""} ${this.state===G.RESEARCHING?"researching":""} ${this.state===G.USER_SPEAKING?"user-speaking":""}"
501
+ style="top: ${e}px; left: ${n}px;"
502
+ @mouseenter=${this.handleMouseEnter}
503
+ @mouseleave=${this.handleMouseLeave}
504
+ >
505
+ ${r}
506
+ ${this.navVisible&&this.state!==G.RESEARCHING?W.html`
507
+ <obi-navigation-bar
508
+ ?isActive=${this.state!==G.READY}
509
+ .position=${{top:e,left:n}}
510
+ data-direction="up"
511
+ .currentState=${this.state}
512
+ .onItemSelect=${this.handleItemSelect.bind(this)}
513
+ ></obi-navigation-bar>
514
+ `:W.nothing}
515
+ </div>
516
+ ${this.showCourseModal?W.html`<obi-course-modal
517
+ .onClose=${()=>this.showCourseModal=!1}
518
+ .onCourseSelect=${this.handleSessionStart.bind(this)}
519
+ .apiBaseUrl=${this.apiBaseUrl}
520
+ .apiKey=${this.apiKey}
521
+ ></obi-course-modal>`:W.nothing}
522
+ `}}tt.styles=W.css`
523
+ :host {
524
+ display: block;
525
+ position: fixed;
526
+ z-index: 9999;
527
+ font-family: Arial, sans-serif;
528
+ --obi-primary: #7c3aed;
529
+ --obi-danger: #ef4444;
530
+ --obi-gray: #6b7280;
531
+ }
532
+
533
+ .widget-container {
534
+ position: fixed;
535
+ width: 56px;
536
+ height: 56px;
537
+ border-radius: 28px;
538
+ border-color: transparent;
539
+ background-color: var(--obi-primary);
540
+ display: flex;
541
+ align-items: center;
542
+ justify-content: center;
543
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
544
+ transition: all 0.2s ease-out;
545
+ }
546
+
547
+ .widget-container.user-speaking {
548
+ background:
549
+ linear-gradient(0deg, #c4b5fd, #c4b5fd),
550
+ linear-gradient(195.84deg, rgba(192, 132, 252, 0) 11.05%, #c084fc 117.01%);
551
+ }
552
+
553
+ .widget-container:hover {
554
+ border-radius: 12px;
555
+ }
556
+
557
+ .widget-container.rounded {
558
+ border-radius: 12px;
559
+ }
560
+
561
+ .widget-container.researching {
562
+ width: 265px;
563
+ border-radius: 12px;
564
+ }
565
+
566
+ .widget-icon {
567
+ width: 32px;
568
+ height: 32px;
569
+ transition: transform 0.5s ease-in-out;
570
+ }
571
+
572
+ .widget-container.rounded .widget-icon {
573
+ transform: rotate(110deg);
574
+ }
575
+
576
+ @keyframes pulse-shadow {
577
+ 0% {
578
+ box-shadow: 0 0 0 0 rgba(124, 58, 237, 0.4);
579
+ }
580
+ 70% {
581
+ box-shadow: 0 0 0 10px rgba(124, 58, 237, 0);
582
+ }
583
+ 100% {
584
+ box-shadow: 0 0 0 0 rgba(124, 58, 237, 0);
585
+ }
586
+ }
587
+
588
+ .pulse {
589
+ animation: pulse-shadow 2s ease-in-out infinite;
590
+ }
591
+ `,Dt([se({type:String})],tt.prototype,"apiBaseUrl",2),Dt([se({type:String})],tt.prototype,"apiKey",2),Dt([se({type:String})],tt.prototype,"position",2),Dt([Vt()],tt.prototype,"state",2),Dt([Vt()],tt.prototype,"showCourseModal",2),Dt([Vt()],tt.prototype,"isHovering",2),Dt([Vt()],tt.prototype,"navVisible",2),Dt([Vt()],tt.prototype,"activeSession",2),Dt([Vt()],tt.prototype,"volume",2),Dt([Vt()],tt.prototype,"screenPosition",2),customElements.get("obi-widget")||customElements.define("obi-widget",tt);const _v=Object.freeze(Object.defineProperty({__proto__:null,ObiWidget:tt},Symbol.toStringTag,{value:"Module"}));function Ev(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Za={exports:{}},ie={};/**
592
+ * @license React
593
+ * react.production.min.js
594
+ *
595
+ * Copyright (c) Facebook, Inc. and its affiliates.
596
+ *
597
+ * This source code is licensed under the MIT license found in the
598
+ * LICENSE file in the root directory of this source tree.
599
+ */var Lu;function wv(){if(Lu)return ie;Lu=1;var i=Symbol.for("react.element"),e=Symbol.for("react.portal"),t=Symbol.for("react.fragment"),n=Symbol.for("react.strict_mode"),r=Symbol.for("react.profiler"),s=Symbol.for("react.provider"),a=Symbol.for("react.context"),o=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),d=Symbol.for("react.memo"),u=Symbol.for("react.lazy"),h=Symbol.iterator;function f(S){return S===null||typeof S!="object"?null:(S=h&&S[h]||S["@@iterator"],typeof S=="function"?S:null)}var g={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},y=Object.assign,v={};function _(S,A,de){this.props=S,this.context=A,this.refs=v,this.updater=de||g}_.prototype.isReactComponent={},_.prototype.setState=function(S,A){if(typeof S!="object"&&typeof S!="function"&&S!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,S,A,"setState")},_.prototype.forceUpdate=function(S){this.updater.enqueueForceUpdate(this,S,"forceUpdate")};function w(){}w.prototype=_.prototype;function N(S,A,de){this.props=S,this.context=A,this.refs=v,this.updater=de||g}var U=N.prototype=new w;U.constructor=N,y(U,_.prototype),U.isPureReactComponent=!0;var b=Array.isArray,k=Object.prototype.hasOwnProperty,x={current:null},F={key:!0,ref:!0,__self:!0,__source:!0};function q(S,A,de){var he,me={},Me=null,Re=null;if(A!=null)for(he in A.ref!==void 0&&(Re=A.ref),A.key!==void 0&&(Me=""+A.key),A)k.call(A,he)&&!F.hasOwnProperty(he)&&(me[he]=A[he]);var xe=arguments.length-2;if(xe===1)me.children=de;else if(1<xe){for(var Ce=Array(xe),Ke=0;Ke<xe;Ke++)Ce[Ke]=arguments[Ke+2];me.children=Ce}if(S&&S.defaultProps)for(he in xe=S.defaultProps,xe)me[he]===void 0&&(me[he]=xe[he]);return{$$typeof:i,type:S,key:Me,ref:Re,props:me,_owner:x.current}}function te(S,A){return{$$typeof:i,type:S.type,key:A,ref:S.ref,props:S.props,_owner:S._owner}}function Y(S){return typeof S=="object"&&S!==null&&S.$$typeof===i}function ne(S){var A={"=":"=0",":":"=2"};return"$"+S.replace(/[=:]/g,function(de){return A[de]})}var be=/\/+/g;function st(S,A){return typeof S=="object"&&S!==null&&S.key!=null?ne(""+S.key):A.toString(36)}function St(S,A,de,he,me){var Me=typeof S;(Me==="undefined"||Me==="boolean")&&(S=null);var Re=!1;if(S===null)Re=!0;else switch(Me){case"string":case"number":Re=!0;break;case"object":switch(S.$$typeof){case i:case e:Re=!0}}if(Re)return Re=S,me=me(Re),S=he===""?"."+st(Re,0):he,b(me)?(de="",S!=null&&(de=S.replace(be,"$&/")+"/"),St(me,A,de,"",function(Ke){return Ke})):me!=null&&(Y(me)&&(me=te(me,de+(!me.key||Re&&Re.key===me.key?"":(""+me.key).replace(be,"$&/")+"/")+S)),A.push(me)),1;if(Re=0,he=he===""?".":he+":",b(S))for(var xe=0;xe<S.length;xe++){Me=S[xe];var Ce=he+st(Me,xe);Re+=St(Me,A,de,Ce,me)}else if(Ce=f(S),typeof Ce=="function")for(S=Ce.call(S),xe=0;!(Me=S.next()).done;)Me=Me.value,Ce=he+st(Me,xe++),Re+=St(Me,A,de,Ce,me);else if(Me==="object")throw A=String(S),Error("Objects are not valid as a React child (found: "+(A==="[object Object]"?"object with keys {"+Object.keys(S).join(", ")+"}":A)+"). If you meant to render a collection of children, use an array instead.");return Re}function at(S,A,de){if(S==null)return S;var he=[],me=0;return St(S,he,"","",function(Me){return A.call(de,Me,me++)}),he}function gn(S){if(S._status===-1){var A=S._result;A=A(),A.then(function(de){(S._status===0||S._status===-1)&&(S._status=1,S._result=de)},function(de){(S._status===0||S._status===-1)&&(S._status=2,S._result=de)}),S._status===-1&&(S._status=0,S._result=A)}if(S._status===1)return S._result.default;throw S._result}var J={current:null},Mn={transition:null},is={ReactCurrentDispatcher:J,ReactCurrentBatchConfig:Mn,ReactCurrentOwner:x};function ai(){throw Error("act(...) is not supported in production builds of React.")}return ie.Children={map:at,forEach:function(S,A,de){at(S,function(){A.apply(this,arguments)},de)},count:function(S){var A=0;return at(S,function(){A++}),A},toArray:function(S){return at(S,function(A){return A})||[]},only:function(S){if(!Y(S))throw Error("React.Children.only expected to receive a single React element child.");return S}},ie.Component=_,ie.Fragment=t,ie.Profiler=r,ie.PureComponent=N,ie.StrictMode=n,ie.Suspense=c,ie.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=is,ie.act=ai,ie.cloneElement=function(S,A,de){if(S==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+S+".");var he=y({},S.props),me=S.key,Me=S.ref,Re=S._owner;if(A!=null){if(A.ref!==void 0&&(Me=A.ref,Re=x.current),A.key!==void 0&&(me=""+A.key),S.type&&S.type.defaultProps)var xe=S.type.defaultProps;for(Ce in A)k.call(A,Ce)&&!F.hasOwnProperty(Ce)&&(he[Ce]=A[Ce]===void 0&&xe!==void 0?xe[Ce]:A[Ce])}var Ce=arguments.length-2;if(Ce===1)he.children=de;else if(1<Ce){xe=Array(Ce);for(var Ke=0;Ke<Ce;Ke++)xe[Ke]=arguments[Ke+2];he.children=xe}return{$$typeof:i,type:S.type,key:me,ref:Me,props:he,_owner:Re}},ie.createContext=function(S){return S={$$typeof:a,_currentValue:S,_currentValue2:S,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},S.Provider={$$typeof:s,_context:S},S.Consumer=S},ie.createElement=q,ie.createFactory=function(S){var A=q.bind(null,S);return A.type=S,A},ie.createRef=function(){return{current:null}},ie.forwardRef=function(S){return{$$typeof:o,render:S}},ie.isValidElement=Y,ie.lazy=function(S){return{$$typeof:u,_payload:{_status:-1,_result:S},_init:gn}},ie.memo=function(S,A){return{$$typeof:d,type:S,compare:A===void 0?null:A}},ie.startTransition=function(S){var A=Mn.transition;Mn.transition={};try{S()}finally{Mn.transition=A}},ie.unstable_act=ai,ie.useCallback=function(S,A){return J.current.useCallback(S,A)},ie.useContext=function(S){return J.current.useContext(S)},ie.useDebugValue=function(){},ie.useDeferredValue=function(S){return J.current.useDeferredValue(S)},ie.useEffect=function(S,A){return J.current.useEffect(S,A)},ie.useId=function(){return J.current.useId()},ie.useImperativeHandle=function(S,A,de){return J.current.useImperativeHandle(S,A,de)},ie.useInsertionEffect=function(S,A){return J.current.useInsertionEffect(S,A)},ie.useLayoutEffect=function(S,A){return J.current.useLayoutEffect(S,A)},ie.useMemo=function(S,A){return J.current.useMemo(S,A)},ie.useReducer=function(S,A,de){return J.current.useReducer(S,A,de)},ie.useRef=function(S){return J.current.useRef(S)},ie.useState=function(S){return J.current.useState(S)},ie.useSyncExternalStore=function(S,A,de){return J.current.useSyncExternalStore(S,A,de)},ie.useTransition=function(){return J.current.useTransition()},ie.version="18.3.1",ie}var Qi={exports:{}};/**
600
+ * @license React
601
+ * react.development.js
602
+ *
603
+ * Copyright (c) Facebook, Inc. and its affiliates.
604
+ *
605
+ * This source code is licensed under the MIT license found in the
606
+ * LICENSE file in the root directory of this source tree.
607
+ */Qi.exports;var Uu;function Pv(){return Uu||(Uu=1,function(i,e){process.env.NODE_ENV!=="production"&&function(){typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error);var t="18.3.1",n=Symbol.for("react.element"),r=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),a=Symbol.for("react.strict_mode"),o=Symbol.for("react.profiler"),c=Symbol.for("react.provider"),d=Symbol.for("react.context"),u=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),f=Symbol.for("react.suspense_list"),g=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),v=Symbol.for("react.offscreen"),_=Symbol.iterator,w="@@iterator";function N(l){if(l===null||typeof l!="object")return null;var p=_&&l[_]||l[w];return typeof p=="function"?p:null}var U={current:null},b={transition:null},k={current:null,isBatchingLegacy:!1,didScheduleLegacyUpdate:!1},x={current:null},F={},q=null;function te(l){q=l}F.setExtraStackFrame=function(l){q=l},F.getCurrentStack=null,F.getStackAddendum=function(){var l="";q&&(l+=q);var p=F.getCurrentStack;return p&&(l+=p()||""),l};var Y=!1,ne=!1,be=!1,st=!1,St=!1,at={ReactCurrentDispatcher:U,ReactCurrentBatchConfig:b,ReactCurrentOwner:x};at.ReactDebugCurrentFrame=F,at.ReactCurrentActQueue=k;function gn(l){{for(var p=arguments.length,T=new Array(p>1?p-1:0),E=1;E<p;E++)T[E-1]=arguments[E];Mn("warn",l,T)}}function J(l){{for(var p=arguments.length,T=new Array(p>1?p-1:0),E=1;E<p;E++)T[E-1]=arguments[E];Mn("error",l,T)}}function Mn(l,p,T){{var E=at.ReactDebugCurrentFrame,D=E.getStackAddendum();D!==""&&(p+="%s",T=T.concat([D]));var H=T.map(function(V){return String(V)});H.unshift("Warning: "+p),Function.prototype.apply.call(console[l],console,H)}}var is={};function ai(l,p){{var T=l.constructor,E=T&&(T.displayName||T.name)||"ReactClass",D=E+"."+p;if(is[D])return;J("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",p,E),is[D]=!0}}var S={isMounted:function(l){return!1},enqueueForceUpdate:function(l,p,T){ai(l,"forceUpdate")},enqueueReplaceState:function(l,p,T,E){ai(l,"replaceState")},enqueueSetState:function(l,p,T,E){ai(l,"setState")}},A=Object.assign,de={};Object.freeze(de);function he(l,p,T){this.props=l,this.context=p,this.refs=de,this.updater=T||S}he.prototype.isReactComponent={},he.prototype.setState=function(l,p){if(typeof l!="object"&&typeof l!="function"&&l!=null)throw new Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,l,p,"setState")},he.prototype.forceUpdate=function(l){this.updater.enqueueForceUpdate(this,l,"forceUpdate")};{var me={isMounted:["isMounted","Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."],replaceState:["replaceState","Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."]},Me=function(l,p){Object.defineProperty(he.prototype,l,{get:function(){gn("%s(...) is deprecated in plain JavaScript React classes. %s",p[0],p[1])}})};for(var Re in me)me.hasOwnProperty(Re)&&Me(Re,me[Re])}function xe(){}xe.prototype=he.prototype;function Ce(l,p,T){this.props=l,this.context=p,this.refs=de,this.updater=T||S}var Ke=Ce.prototype=new xe;Ke.constructor=Ce,A(Ke,he.prototype),Ke.isPureReactComponent=!0;function Bv(){var l={current:null};return Object.seal(l),l}var Vv=Array.isArray;function rs(l){return Vv(l)}function qv(l){{var p=typeof Symbol=="function"&&Symbol.toStringTag,T=p&&l[Symbol.toStringTag]||l.constructor.name||"Object";return T}}function zv(l){try{return Fu(l),!1}catch{return!0}}function Fu(l){return""+l}function ss(l){if(zv(l))return J("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",qv(l)),Fu(l)}function Wv(l,p,T){var E=l.displayName;if(E)return E;var D=p.displayName||p.name||"";return D!==""?T+"("+D+")":T}function $u(l){return l.displayName||"Context"}function vn(l){if(l==null)return null;if(typeof l.tag=="number"&&J("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof l=="function")return l.displayName||l.name||null;if(typeof l=="string")return l;switch(l){case s:return"Fragment";case r:return"Portal";case o:return"Profiler";case a:return"StrictMode";case h:return"Suspense";case f:return"SuspenseList"}if(typeof l=="object")switch(l.$$typeof){case d:var p=l;return $u(p)+".Consumer";case c:var T=l;return $u(T._context)+".Provider";case u:return Wv(l,l.render,"ForwardRef");case g:var E=l.displayName||null;return E!==null?E:vn(l.type)||"Memo";case y:{var D=l,H=D._payload,V=D._init;try{return vn(V(H))}catch{return null}}}return null}var tr=Object.prototype.hasOwnProperty,Bu={key:!0,ref:!0,__self:!0,__source:!0},Vu,qu,Ya;Ya={};function zu(l){if(tr.call(l,"ref")){var p=Object.getOwnPropertyDescriptor(l,"ref").get;if(p&&p.isReactWarning)return!1}return l.ref!==void 0}function Wu(l){if(tr.call(l,"key")){var p=Object.getOwnPropertyDescriptor(l,"key").get;if(p&&p.isReactWarning)return!1}return l.key!==void 0}function Gv(l,p){var T=function(){Vu||(Vu=!0,J("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",p))};T.isReactWarning=!0,Object.defineProperty(l,"key",{get:T,configurable:!0})}function Kv(l,p){var T=function(){qu||(qu=!0,J("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",p))};T.isReactWarning=!0,Object.defineProperty(l,"ref",{get:T,configurable:!0})}function Hv(l){if(typeof l.ref=="string"&&x.current&&l.__self&&x.current.stateNode!==l.__self){var p=vn(x.current.type);Ya[p]||(J('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref',p,l.ref),Ya[p]=!0)}}var Qa=function(l,p,T,E,D,H,V){var Q={$$typeof:n,type:l,key:p,ref:T,props:V,_owner:H};return Q._store={},Object.defineProperty(Q._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(Q,"_self",{configurable:!1,enumerable:!1,writable:!1,value:E}),Object.defineProperty(Q,"_source",{configurable:!1,enumerable:!1,writable:!1,value:D}),Object.freeze&&(Object.freeze(Q.props),Object.freeze(Q)),Q};function Zv(l,p,T){var E,D={},H=null,V=null,Q=null,ue=null;if(p!=null){zu(p)&&(V=p.ref,Hv(p)),Wu(p)&&(ss(p.key),H=""+p.key),Q=p.__self===void 0?null:p.__self,ue=p.__source===void 0?null:p.__source;for(E in p)tr.call(p,E)&&!Bu.hasOwnProperty(E)&&(D[E]=p[E])}var ke=arguments.length-2;if(ke===1)D.children=T;else if(ke>1){for(var Ee=Array(ke),we=0;we<ke;we++)Ee[we]=arguments[we+2];Object.freeze&&Object.freeze(Ee),D.children=Ee}if(l&&l.defaultProps){var Ie=l.defaultProps;for(E in Ie)D[E]===void 0&&(D[E]=Ie[E])}if(H||V){var je=typeof l=="function"?l.displayName||l.name||"Unknown":l;H&&Gv(D,je),V&&Kv(D,je)}return Qa(l,H,V,Q,ue,x.current,D)}function Jv(l,p){var T=Qa(l.type,p,l.ref,l._self,l._source,l._owner,l.props);return T}function Yv(l,p,T){if(l==null)throw new Error("React.cloneElement(...): The argument must be a React element, but you passed "+l+".");var E,D=A({},l.props),H=l.key,V=l.ref,Q=l._self,ue=l._source,ke=l._owner;if(p!=null){zu(p)&&(V=p.ref,ke=x.current),Wu(p)&&(ss(p.key),H=""+p.key);var Ee;l.type&&l.type.defaultProps&&(Ee=l.type.defaultProps);for(E in p)tr.call(p,E)&&!Bu.hasOwnProperty(E)&&(p[E]===void 0&&Ee!==void 0?D[E]=Ee[E]:D[E]=p[E])}var we=arguments.length-2;if(we===1)D.children=T;else if(we>1){for(var Ie=Array(we),je=0;je<we;je++)Ie[je]=arguments[je+2];D.children=Ie}return Qa(l.type,H,V,Q,ue,ke,D)}function oi(l){return typeof l=="object"&&l!==null&&l.$$typeof===n}var Gu=".",Qv=":";function Xv(l){var p=/[=:]/g,T={"=":"=0",":":"=2"},E=l.replace(p,function(D){return T[D]});return"$"+E}var Ku=!1,ey=/\/+/g;function Hu(l){return l.replace(ey,"$&/")}function Xa(l,p){return typeof l=="object"&&l!==null&&l.key!=null?(ss(l.key),Xv(""+l.key)):p.toString(36)}function as(l,p,T,E,D){var H=typeof l;(H==="undefined"||H==="boolean")&&(l=null);var V=!1;if(l===null)V=!0;else switch(H){case"string":case"number":V=!0;break;case"object":switch(l.$$typeof){case n:case r:V=!0}}if(V){var Q=l,ue=D(Q),ke=E===""?Gu+Xa(Q,0):E;if(rs(ue)){var Ee="";ke!=null&&(Ee=Hu(ke)+"/"),as(ue,p,Ee,"",function(Gy){return Gy})}else ue!=null&&(oi(ue)&&(ue.key&&(!Q||Q.key!==ue.key)&&ss(ue.key),ue=Jv(ue,T+(ue.key&&(!Q||Q.key!==ue.key)?Hu(""+ue.key)+"/":"")+ke)),p.push(ue));return 1}var we,Ie,je=0,ze=E===""?Gu:E+Qv;if(rs(l))for(var ps=0;ps<l.length;ps++)we=l[ps],Ie=ze+Xa(we,ps),je+=as(we,p,T,Ie,D);else{var co=N(l);if(typeof co=="function"){var bl=l;co===bl.entries&&(Ku||gn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),Ku=!0);for(var zy=co.call(bl),kl,Wy=0;!(kl=zy.next()).done;)we=kl.value,Ie=ze+Xa(we,Wy++),je+=as(we,p,T,Ie,D)}else if(H==="object"){var Sl=String(l);throw new Error("Objects are not valid as a React child (found: "+(Sl==="[object Object]"?"object with keys {"+Object.keys(l).join(", ")+"}":Sl)+"). If you meant to render a collection of children, use an array instead.")}}return je}function os(l,p,T){if(l==null)return l;var E=[],D=0;return as(l,E,"","",function(H){return p.call(T,H,D++)}),E}function ty(l){var p=0;return os(l,function(){p++}),p}function ny(l,p,T){os(l,function(){p.apply(this,arguments)},T)}function iy(l){return os(l,function(p){return p})||[]}function ry(l){if(!oi(l))throw new Error("React.Children.only expected to receive a single React element child.");return l}function sy(l){var p={$$typeof:d,_currentValue:l,_currentValue2:l,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null};p.Provider={$$typeof:c,_context:p};var T=!1,E=!1,D=!1;{var H={$$typeof:d,_context:p};Object.defineProperties(H,{Provider:{get:function(){return E||(E=!0,J("Rendering <Context.Consumer.Provider> is not supported and will be removed in a future major release. Did you mean to render <Context.Provider> instead?")),p.Provider},set:function(V){p.Provider=V}},_currentValue:{get:function(){return p._currentValue},set:function(V){p._currentValue=V}},_currentValue2:{get:function(){return p._currentValue2},set:function(V){p._currentValue2=V}},_threadCount:{get:function(){return p._threadCount},set:function(V){p._threadCount=V}},Consumer:{get:function(){return T||(T=!0,J("Rendering <Context.Consumer.Consumer> is not supported and will be removed in a future major release. Did you mean to render <Context.Consumer> instead?")),p.Consumer}},displayName:{get:function(){return p.displayName},set:function(V){D||(gn("Setting `displayName` on Context.Consumer has no effect. You should set it directly on the context with Context.displayName = '%s'.",V),D=!0)}}}),p.Consumer=H}return p._currentRenderer=null,p._currentRenderer2=null,p}var nr=-1,eo=0,Zu=1,ay=2;function oy(l){if(l._status===nr){var p=l._result,T=p();if(T.then(function(H){if(l._status===eo||l._status===nr){var V=l;V._status=Zu,V._result=H}},function(H){if(l._status===eo||l._status===nr){var V=l;V._status=ay,V._result=H}}),l._status===nr){var E=l;E._status=eo,E._result=T}}if(l._status===Zu){var D=l._result;return D===void 0&&J(`lazy: Expected the result of a dynamic import() call. Instead received: %s
608
+
609
+ Your code should look like:
610
+ const MyComponent = lazy(() => import('./MyComponent'))
611
+
612
+ Did you accidentally put curly braces around the import?`,D),"default"in D||J(`lazy: Expected the result of a dynamic import() call. Instead received: %s
613
+
614
+ Your code should look like:
615
+ const MyComponent = lazy(() => import('./MyComponent'))`,D),D.default}else throw l._result}function cy(l){var p={_status:nr,_result:l},T={$$typeof:y,_payload:p,_init:oy};{var E,D;Object.defineProperties(T,{defaultProps:{configurable:!0,get:function(){return E},set:function(H){J("React.lazy(...): It is not supported to assign `defaultProps` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."),E=H,Object.defineProperty(T,"defaultProps",{enumerable:!0})}},propTypes:{configurable:!0,get:function(){return D},set:function(H){J("React.lazy(...): It is not supported to assign `propTypes` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."),D=H,Object.defineProperty(T,"propTypes",{enumerable:!0})}}})}return T}function dy(l){l!=null&&l.$$typeof===g?J("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."):typeof l!="function"?J("forwardRef requires a render function but was given %s.",l===null?"null":typeof l):l.length!==0&&l.length!==2&&J("forwardRef render functions accept exactly two parameters: props and ref. %s",l.length===1?"Did you forget to use the ref parameter?":"Any additional parameter will be undefined."),l!=null&&(l.defaultProps!=null||l.propTypes!=null)&&J("forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?");var p={$$typeof:u,render:l};{var T;Object.defineProperty(p,"displayName",{enumerable:!1,configurable:!0,get:function(){return T},set:function(E){T=E,!l.name&&!l.displayName&&(l.displayName=E)}})}return p}var Ju;Ju=Symbol.for("react.module.reference");function Yu(l){return!!(typeof l=="string"||typeof l=="function"||l===s||l===o||St||l===a||l===h||l===f||st||l===v||Y||ne||be||typeof l=="object"&&l!==null&&(l.$$typeof===y||l.$$typeof===g||l.$$typeof===c||l.$$typeof===d||l.$$typeof===u||l.$$typeof===Ju||l.getModuleId!==void 0))}function uy(l,p){Yu(l)||J("memo: The first argument must be a component. Instead received: %s",l===null?"null":typeof l);var T={$$typeof:g,type:l,compare:p===void 0?null:p};{var E;Object.defineProperty(T,"displayName",{enumerable:!1,configurable:!0,get:function(){return E},set:function(D){E=D,!l.name&&!l.displayName&&(l.displayName=D)}})}return T}function He(){var l=U.current;return l===null&&J(`Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
616
+ 1. You might have mismatching versions of React and the renderer (such as React DOM)
617
+ 2. You might be breaking the Rules of Hooks
618
+ 3. You might have more than one copy of React in the same app
619
+ See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.`),l}function ly(l){var p=He();if(l._context!==void 0){var T=l._context;T.Consumer===l?J("Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be removed in a future major release. Did you mean to call useContext(Context) instead?"):T.Provider===l&&J("Calling useContext(Context.Provider) is not supported. Did you mean to call useContext(Context) instead?")}return p.useContext(l)}function hy(l){var p=He();return p.useState(l)}function fy(l,p,T){var E=He();return E.useReducer(l,p,T)}function py(l){var p=He();return p.useRef(l)}function my(l,p){var T=He();return T.useEffect(l,p)}function gy(l,p){var T=He();return T.useInsertionEffect(l,p)}function vy(l,p){var T=He();return T.useLayoutEffect(l,p)}function yy(l,p){var T=He();return T.useCallback(l,p)}function by(l,p){var T=He();return T.useMemo(l,p)}function ky(l,p,T){var E=He();return E.useImperativeHandle(l,p,T)}function Sy(l,p){{var T=He();return T.useDebugValue(l,p)}}function Ty(){var l=He();return l.useTransition()}function Cy(l){var p=He();return p.useDeferredValue(l)}function _y(){var l=He();return l.useId()}function Ey(l,p,T){var E=He();return E.useSyncExternalStore(l,p,T)}var ir=0,Qu,Xu,el,tl,nl,il,rl;function sl(){}sl.__reactDisabledLog=!0;function wy(){{if(ir===0){Qu=console.log,Xu=console.info,el=console.warn,tl=console.error,nl=console.group,il=console.groupCollapsed,rl=console.groupEnd;var l={configurable:!0,enumerable:!0,value:sl,writable:!0};Object.defineProperties(console,{info:l,log:l,warn:l,error:l,group:l,groupCollapsed:l,groupEnd:l})}ir++}}function Py(){{if(ir--,ir===0){var l={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:A({},l,{value:Qu}),info:A({},l,{value:Xu}),warn:A({},l,{value:el}),error:A({},l,{value:tl}),group:A({},l,{value:nl}),groupCollapsed:A({},l,{value:il}),groupEnd:A({},l,{value:rl})})}ir<0&&J("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var to=at.ReactCurrentDispatcher,no;function cs(l,p,T){{if(no===void 0)try{throw Error()}catch(D){var E=D.stack.trim().match(/\n( *(at )?)/);no=E&&E[1]||""}return`
620
+ `+no+l}}var io=!1,ds;{var Ry=typeof WeakMap=="function"?WeakMap:Map;ds=new Ry}function al(l,p){if(!l||io)return"";{var T=ds.get(l);if(T!==void 0)return T}var E;io=!0;var D=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var H;H=to.current,to.current=null,wy();try{if(p){var V=function(){throw Error()};if(Object.defineProperty(V.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(V,[])}catch(ze){E=ze}Reflect.construct(l,[],V)}else{try{V.call()}catch(ze){E=ze}l.call(V.prototype)}}else{try{throw Error()}catch(ze){E=ze}l()}}catch(ze){if(ze&&E&&typeof ze.stack=="string"){for(var Q=ze.stack.split(`
621
+ `),ue=E.stack.split(`
622
+ `),ke=Q.length-1,Ee=ue.length-1;ke>=1&&Ee>=0&&Q[ke]!==ue[Ee];)Ee--;for(;ke>=1&&Ee>=0;ke--,Ee--)if(Q[ke]!==ue[Ee]){if(ke!==1||Ee!==1)do if(ke--,Ee--,Ee<0||Q[ke]!==ue[Ee]){var we=`
623
+ `+Q[ke].replace(" at new "," at ");return l.displayName&&we.includes("<anonymous>")&&(we=we.replace("<anonymous>",l.displayName)),typeof l=="function"&&ds.set(l,we),we}while(ke>=1&&Ee>=0);break}}}finally{io=!1,to.current=H,Py(),Error.prepareStackTrace=D}var Ie=l?l.displayName||l.name:"",je=Ie?cs(Ie):"";return typeof l=="function"&&ds.set(l,je),je}function xy(l,p,T){return al(l,!1)}function Iy(l){var p=l.prototype;return!!(p&&p.isReactComponent)}function us(l,p,T){if(l==null)return"";if(typeof l=="function")return al(l,Iy(l));if(typeof l=="string")return cs(l);switch(l){case h:return cs("Suspense");case f:return cs("SuspenseList")}if(typeof l=="object")switch(l.$$typeof){case u:return xy(l.render);case g:return us(l.type,p,T);case y:{var E=l,D=E._payload,H=E._init;try{return us(H(D),p,T)}catch{}}}return""}var ol={},cl=at.ReactDebugCurrentFrame;function ls(l){if(l){var p=l._owner,T=us(l.type,l._source,p?p.type:null);cl.setExtraStackFrame(T)}else cl.setExtraStackFrame(null)}function Oy(l,p,T,E,D){{var H=Function.call.bind(tr);for(var V in l)if(H(l,V)){var Q=void 0;try{if(typeof l[V]!="function"){var ue=Error((E||"React class")+": "+T+" type `"+V+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof l[V]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw ue.name="Invariant Violation",ue}Q=l[V](p,V,E,T,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(ke){Q=ke}Q&&!(Q instanceof Error)&&(ls(D),J("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",E||"React class",T,V,typeof Q),ls(null)),Q instanceof Error&&!(Q.message in ol)&&(ol[Q.message]=!0,ls(D),J("Failed %s type: %s",T,Q.message),ls(null))}}}function ci(l){if(l){var p=l._owner,T=us(l.type,l._source,p?p.type:null);te(T)}else te(null)}var ro;ro=!1;function dl(){if(x.current){var l=vn(x.current.type);if(l)return`
624
+
625
+ Check the render method of \``+l+"`."}return""}function Ay(l){if(l!==void 0){var p=l.fileName.replace(/^.*[\\\/]/,""),T=l.lineNumber;return`
626
+
627
+ Check your code at `+p+":"+T+"."}return""}function Dy(l){return l!=null?Ay(l.__source):""}var ul={};function My(l){var p=dl();if(!p){var T=typeof l=="string"?l:l.displayName||l.name;T&&(p=`
628
+
629
+ Check the top-level render call using <`+T+">.")}return p}function ll(l,p){if(!(!l._store||l._store.validated||l.key!=null)){l._store.validated=!0;var T=My(p);if(!ul[T]){ul[T]=!0;var E="";l&&l._owner&&l._owner!==x.current&&(E=" It was passed a child from "+vn(l._owner.type)+"."),ci(l),J('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',T,E),ci(null)}}}function hl(l,p){if(typeof l=="object"){if(rs(l))for(var T=0;T<l.length;T++){var E=l[T];oi(E)&&ll(E,p)}else if(oi(l))l._store&&(l._store.validated=!0);else if(l){var D=N(l);if(typeof D=="function"&&D!==l.entries)for(var H=D.call(l),V;!(V=H.next()).done;)oi(V.value)&&ll(V.value,p)}}}function fl(l){{var p=l.type;if(p==null||typeof p=="string")return;var T;if(typeof p=="function")T=p.propTypes;else if(typeof p=="object"&&(p.$$typeof===u||p.$$typeof===g))T=p.propTypes;else return;if(T){var E=vn(p);Oy(T,l.props,"prop",E,l)}else if(p.PropTypes!==void 0&&!ro){ro=!0;var D=vn(p);J("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",D||"Unknown")}typeof p.getDefaultProps=="function"&&!p.getDefaultProps.isReactClassApproved&&J("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function Ny(l){{for(var p=Object.keys(l.props),T=0;T<p.length;T++){var E=p[T];if(E!=="children"&&E!=="key"){ci(l),J("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",E),ci(null);break}}l.ref!==null&&(ci(l),J("Invalid attribute `ref` supplied to `React.Fragment`."),ci(null))}}function pl(l,p,T){var E=Yu(l);if(!E){var D="";(l===void 0||typeof l=="object"&&l!==null&&Object.keys(l).length===0)&&(D+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var H=Dy(p);H?D+=H:D+=dl();var V;l===null?V="null":rs(l)?V="array":l!==void 0&&l.$$typeof===n?(V="<"+(vn(l.type)||"Unknown")+" />",D=" Did you accidentally export a JSX literal instead of a component?"):V=typeof l,J("React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",V,D)}var Q=Zv.apply(this,arguments);if(Q==null)return Q;if(E)for(var ue=2;ue<arguments.length;ue++)hl(arguments[ue],l);return l===s?Ny(Q):fl(Q),Q}var ml=!1;function Ly(l){var p=pl.bind(null,l);return p.type=l,ml||(ml=!0,gn("React.createFactory() is deprecated and will be removed in a future major release. Consider using JSX or use React.createElement() directly instead.")),Object.defineProperty(p,"type",{enumerable:!1,get:function(){return gn("Factory.type is deprecated. Access the class directly before passing it to createFactory."),Object.defineProperty(this,"type",{value:l}),l}}),p}function Uy(l,p,T){for(var E=Yv.apply(this,arguments),D=2;D<arguments.length;D++)hl(arguments[D],E.type);return fl(E),E}function jy(l,p){var T=b.transition;b.transition={};var E=b.transition;b.transition._updatedFibers=new Set;try{l()}finally{if(b.transition=T,T===null&&E._updatedFibers){var D=E._updatedFibers.size;D>10&&gn("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."),E._updatedFibers.clear()}}}var gl=!1,hs=null;function Fy(l){if(hs===null)try{var p=("require"+Math.random()).slice(0,7),T=i&&i[p];hs=T.call(i,"timers").setImmediate}catch{hs=function(D){gl===!1&&(gl=!0,typeof MessageChannel>"u"&&J("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."));var H=new MessageChannel;H.port1.onmessage=D,H.port2.postMessage(void 0)}}return hs(l)}var di=0,vl=!1;function yl(l){{var p=di;di++,k.current===null&&(k.current=[]);var T=k.isBatchingLegacy,E;try{if(k.isBatchingLegacy=!0,E=l(),!T&&k.didScheduleLegacyUpdate){var D=k.current;D!==null&&(k.didScheduleLegacyUpdate=!1,oo(D))}}catch(Ie){throw fs(p),Ie}finally{k.isBatchingLegacy=T}if(E!==null&&typeof E=="object"&&typeof E.then=="function"){var H=E,V=!1,Q={then:function(Ie,je){V=!0,H.then(function(ze){fs(p),di===0?so(ze,Ie,je):Ie(ze)},function(ze){fs(p),je(ze)})}};return!vl&&typeof Promise<"u"&&Promise.resolve().then(function(){}).then(function(){V||(vl=!0,J("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"))}),Q}else{var ue=E;if(fs(p),di===0){var ke=k.current;ke!==null&&(oo(ke),k.current=null);var Ee={then:function(Ie,je){k.current===null?(k.current=[],so(ue,Ie,je)):Ie(ue)}};return Ee}else{var we={then:function(Ie,je){Ie(ue)}};return we}}}}function fs(l){l!==di-1&&J("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "),di=l}function so(l,p,T){{var E=k.current;if(E!==null)try{oo(E),Fy(function(){E.length===0?(k.current=null,p(l)):so(l,p,T)})}catch(D){T(D)}else p(l)}}var ao=!1;function oo(l){if(!ao){ao=!0;var p=0;try{for(;p<l.length;p++){var T=l[p];do T=T(!0);while(T!==null)}l.length=0}catch(E){throw l=l.slice(p+1),E}finally{ao=!1}}}var $y=pl,By=Uy,Vy=Ly,qy={map:os,forEach:ny,count:ty,toArray:iy,only:ry};e.Children=qy,e.Component=he,e.Fragment=s,e.Profiler=o,e.PureComponent=Ce,e.StrictMode=a,e.Suspense=h,e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=at,e.act=yl,e.cloneElement=By,e.createContext=sy,e.createElement=$y,e.createFactory=Vy,e.createRef=Bv,e.forwardRef=dy,e.isValidElement=oi,e.lazy=cy,e.memo=uy,e.startTransition=jy,e.unstable_act=yl,e.useCallback=yy,e.useContext=ly,e.useDebugValue=Sy,e.useDeferredValue=Cy,e.useEffect=my,e.useId=_y,e.useImperativeHandle=ky,e.useInsertionEffect=gy,e.useLayoutEffect=vy,e.useMemo=by,e.useReducer=fy,e.useRef=py,e.useState=hy,e.useSyncExternalStore=Ey,e.useTransition=Ty,e.version=t,typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error)}()}(Qi,Qi.exports)),Qi.exports}process.env.NODE_ENV==="production"?Za.exports=wv():Za.exports=Pv();var Xi=Za.exports;const ju=Ev(Xi);function Rv(i){const[e,t]=Xi.useState(null),[n,r]=Xi.useState(G.READY),[s,a]=Xi.useState(null);return Xi.useEffect(()=>{const h=new wo(i);return t(h),h.init().catch(f=>{console.error("Failed to initialize Obi SDK:",f)}),h.on(lt.STATE_CHANGE,f=>{r(f)}),h.on(lt.ERROR,f=>{a(f)}),()=>{h.dispose()}},[]),{sdk:e,state:n,error:s,startVoiceRecording:async()=>{if(e)return e.startVoiceRecording()},stopVoiceRecording:async()=>e?e.stopVoiceRecording():{transcript:void 0},startScreenCapture:async()=>{if(e)return e.startScreenCapture()},stopScreenCapture:async()=>e?e.stopScreenCapture():{screenshot:void 0},isReady:n===G.READY,isActive:n!==G.READY,isError:n===G.ERROR}}var xv=Object.defineProperty,Iv=Object.getOwnPropertyDescriptor,Ov=(i,e,t,n)=>{for(var r=n>1?void 0:n?Iv(e,t):e,s=i.length-1,a;s>=0;s--)(a=i[s])&&(r=(n?a(e,t,r):a(r))||r);return n&&r&&xv(e,t,r),r};class er extends W.LitElement{constructor(){super(...arguments),this.state=G.READY}render(){return W.html`
630
+ <div class="status-container">
631
+ <div class="status-indicator ${this.state}"></div>
632
+ <div class="status-text">${this.getStatusText()}</div>
633
+ </div>
634
+ `}getStatusText(){switch(this.state){case G.READY:return"Ready";case G.ERROR:return"Error";default:return"Unknown"}}}er.styles=W.css`
635
+ :host {
636
+ display: inline-block;
637
+ font-family: Arial, sans-serif;
638
+ }
639
+
640
+ .status-container {
641
+ display: flex;
642
+ align-items: center;
643
+ padding: 8px 12px;
644
+ border-radius: 16px;
645
+ background-color: #f3f4f6;
646
+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
647
+ }
648
+
649
+ .status-indicator {
650
+ width: 10px;
651
+ height: 10px;
652
+ border-radius: 50%;
653
+ margin-right: 8px;
654
+ }
655
+
656
+ .ready {
657
+ background-color: #10b981;
658
+ }
659
+
660
+ .active {
661
+ background-color: #3b82f6;
662
+ }
663
+
664
+ .error {
665
+ background-color: #ef4444;
666
+ }
667
+
668
+ .status-text {
669
+ font-size: 14px;
670
+ font-weight: 500;
671
+ color: #1f2937;
672
+ }
673
+ `,Ov([se({type:String})],er.prototype,"state",2),customElements.get("obi-status-widget")||customElements.define("obi-status-widget",er);const Av=Object.freeze(Object.defineProperty({__proto__:null,ObiStatusWidget:er},Symbol.toStringTag,{value:"Module"}));var Dv=Object.defineProperty,Mv=Object.getOwnPropertyDescriptor,Ja=(i,e,t,n)=>{for(var r=n>1?void 0:n?Mv(e,t):e,s=i.length-1,a;s>=0;s--)(a=i[s])&&(r=(n?a(e,t,r):a(r))||r);return n&&r&&Dv(e,t,r),r};class Dn extends W.LitElement{constructor(){super(...arguments),this.state=G.READY,this.voiceEnabled=!0,this.screenEnabled=!0}render(){const e=this.state===G.AGENT_SPEAKING,t=this.state===G.READY;return W.html`
674
+ <div class="control-container">
675
+ <div class="control-header">Obi Controls</div>
676
+ <div class="control-buttons">
677
+ <button
678
+ class="btn-voice"
679
+ ?disabled=${!t||!this.voiceEnabled}
680
+ @click=${this.handleVoiceClick}
681
+ >
682
+ Start Voice
683
+ </button>
684
+
685
+ <button
686
+ class="btn-screen"
687
+ ?disabled=${!t||!this.screenEnabled}
688
+ @click=${this.handleScreenClick}
689
+ >
690
+ Capture Screen
691
+ </button>
692
+
693
+ <button class="btn-stop" ?disabled=${!e} @click=${this.handleStopClick}>
694
+ Stop
695
+ </button>
696
+ </div>
697
+ </div>
698
+ `}handleVoiceClick(){this.dispatchEvent(new CustomEvent("voice-start"))}handleScreenClick(){this.dispatchEvent(new CustomEvent("screen-start"))}handleStopClick(){this.dispatchEvent(new CustomEvent("stop"))}}Dn.styles=W.css`
699
+ :host {
700
+ display: block;
701
+ font-family: Arial, sans-serif;
702
+ --obi-primary: #3b82f6;
703
+ --obi-danger: #ef4444;
704
+ --obi-gray: #6b7280;
705
+ }
706
+
707
+ .control-container {
708
+ display: flex;
709
+ flex-direction: column;
710
+ padding: 16px;
711
+ border-radius: 8px;
712
+ background-color: #ffffff;
713
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
714
+ max-width: 300px;
715
+ }
716
+
717
+ .control-header {
718
+ margin-bottom: 16px;
719
+ font-size: 16px;
720
+ font-weight: 600;
721
+ color: #111827;
722
+ }
723
+
724
+ .control-buttons {
725
+ display: flex;
726
+ gap: 8px;
727
+ margin-bottom: 16px;
728
+ }
729
+
730
+ button {
731
+ padding: 8px 12px;
732
+ border: none;
733
+ border-radius: 4px;
734
+ font-size: 14px;
735
+ font-weight: 500;
736
+ cursor: pointer;
737
+ transition:
738
+ background-color 0.2s,
739
+ opacity 0.2s;
740
+ }
741
+
742
+ button:disabled {
743
+ opacity: 0.5;
744
+ cursor: not-allowed;
745
+ }
746
+
747
+ .btn-voice {
748
+ background-color: var(--obi-primary);
749
+ color: white;
750
+ }
751
+
752
+ .btn-screen {
753
+ background-color: var(--obi-primary);
754
+ color: white;
755
+ }
756
+
757
+ .btn-stop {
758
+ background-color: var(--obi-danger);
759
+ color: white;
760
+ }
761
+ `,Ja([se({type:String})],Dn.prototype,"state",2),Ja([se({type:Boolean})],Dn.prototype,"voiceEnabled",2),Ja([se({type:Boolean})],Dn.prototype,"screenEnabled",2),customElements.get("obi-control-panel")||customElements.define("obi-control-panel",Dn);const Nv=Object.freeze(Object.defineProperty({__proto__:null,ObiControlPanel:Dn},Symbol.toStringTag,{value:"Module"}));function Lv({state:i=G.READY,className:e}){return ju.createElement("obi-status-widget",{state:i,className:e})}function Uv({state:i=G.READY,voiceEnabled:e=!0,screenEnabled:t=!0,onVoiceStart:n,onScreenStart:r,onStop:s,className:a}){const o=()=>{n&&n()},c=()=>{r&&r()},d=()=>{s&&s()};return ju.createElement("obi-control-panel",{state:i,voiceEnabled:e,screenEnabled:t,onvoicestart:o,onscreenstart:c,onstop:d,className:a})}function jv(){Promise.resolve().then(()=>Av),Promise.resolve().then(()=>Nv),Promise.resolve().then(()=>_v),Promise.resolve().then(()=>mv),Promise.resolve().then(()=>bv),Promise.resolve().then(()=>Dg),Promise.resolve().then(()=>Bg),Promise.resolve().then(()=>kv),Promise.resolve().then(()=>zg),Promise.resolve().then(()=>Kg)}const Fv="0.1.0",$v=async(i={})=>{const{ObiSession:e}=await Promise.resolve().then(()=>vu);return new e(i)};ge.AudioEqualizer=si,ge.Course=zt,ge.CourseList=pn,ge.CourseModal=kt,ge.DotLoader=Yi,ge.EventType=lt,ge.NavIcon=fn,ge.NavigationBar=At,ge.ObiControlPanel=Dn,ge.ObiControlPanelReact=Uv,ge.ObiSDK=wo,ge.ObiSDKConfigSchema=_o,ge.ObiSession=gu,ge.ObiStatusWidget=er,ge.ObiStatusWidgetReact=Lv,ge.ObiWidget=tt,ge.SDKState=G,ge.SearchingLoader=ns,ge.VERSION=Fv,ge.createSession=$v,ge.defineCustomElements=jv,ge.useObiSDK=Rv,Object.defineProperty(ge,Symbol.toStringTag,{value:"Module"})});